Admin token for config changes, licenses, and 1.0.0 #1
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Xexéu image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
|
||||
XEXEU_VERSION=latest
|
||||
# Host address and port of the dashboard. Keep it on loopback unless an
|
||||
# authenticating reverse proxy sits in front of it.
|
||||
XEXEU_PUBLISH=127.0.0.1:8788
|
||||
# Admin token for the dashboard actions that change the configuration (group
|
||||
# CRUD). At least 16 characters, e.g. `openssl rand -hex 32`. Empty: a new one
|
||||
# is generated at each start and printed in `docker compose logs xexeu`.
|
||||
XEXEU_ADMIN_TOKEN=
|
||||
# Xexéu container image repository.
|
||||
XEXEU_IMAGE=git.lucasrguerra.dev.br/ciberfauna/xexeu
|
||||
@@ -15,6 +15,7 @@ env:
|
||||
RUSTFLAGS: -D warnings
|
||||
CARGO_HOME: /opt/hostedtoolcache/cargo
|
||||
RUSTUP_HOME: /opt/hostedtoolcache/rustup
|
||||
NPM_CONFIG_CACHE: /opt/hostedtoolcache/npm-cache
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
@@ -27,6 +28,11 @@ jobs:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
- name: UI translation coverage
|
||||
run: node scripts/check-ui-i18n.mjs
|
||||
- name: Workflows and templates (valid YAML)
|
||||
run: |
|
||||
python3 -c 'import yaml' 2>/dev/null \
|
||||
|
||||
@@ -17,6 +17,10 @@ concurrency:
|
||||
|
||||
env:
|
||||
REGISTRY: git.lucasrguerra.dev.br
|
||||
CARGO_TERM_COLOR: always
|
||||
# Rust toolchains, cargo registry, and caches live on the persistent runner volume.
|
||||
CARGO_HOME: /opt/hostedtoolcache/cargo
|
||||
RUSTUP_HOME: /opt/hostedtoolcache/rustup
|
||||
|
||||
jobs:
|
||||
# The image is built only from these paths, so their tree hashes identify it.
|
||||
@@ -149,10 +153,6 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Build release CLI binary
|
||||
run: |
|
||||
cargo build --release --locked -p xexeu-cli
|
||||
- name: Release
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
@@ -167,14 +167,32 @@ jobs:
|
||||
pre=false; case "$TAG" in *-*) pre=true ;; esac
|
||||
jq -n --arg tag "$TAG" --arg name "Xexéu ${TAG#v}" --rawfile body notes.md --argjson pre "$pre" \
|
||||
'{tag_name:$tag, name:$name, body:$body, prerelease:$pre}' > release.json
|
||||
rel=$(curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" \
|
||||
-H 'Content-Type: application/json' -d @release.json)
|
||||
rel_id=$(echo "$rel" | jq -r .id)
|
||||
if [ -n "$rel_id" ] && [ "$rel_id" != "null" ]; then
|
||||
asset_name="xexeu-${TAG#v}-linux-arm64"
|
||||
cp target/release/xexeu "$asset_name"
|
||||
curl -fsS -X POST "$API/releases/$rel_id/assets?name=$asset_name" \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @"$asset_name" >/dev/null || true
|
||||
fi
|
||||
curl -fsS -X POST "$API/releases" -H "Authorization: token $TOKEN" \
|
||||
-H 'Content-Type: application/json' -d @release.json >/dev/null
|
||||
|
||||
# Standalone CLI for hosts that run Xexéu without Docker, built natively on
|
||||
# each architecture: xexeu-<tag>-<platform>.tar.gz plus its .sha256.
|
||||
cli:
|
||||
name: CLI (${{ matrix.platform }})
|
||||
needs: gitea-release
|
||||
runs-on: ${{ matrix.runner }}
|
||||
env:
|
||||
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/xexeu-release-cli-${{ matrix.platform }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { platform: linux-aarch64, target: aarch64-unknown-linux-gnu, runner: linux-arm64 }
|
||||
- { platform: linux-x86_64, target: x86_64-unknown-linux-gnu, runner: linux-amd64 }
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
- name: Build and package
|
||||
run: scripts/package-cli.sh "${{ gitea.ref_name }}" "${{ matrix.platform }}" "${{ matrix.target }}" | tee packages.txt
|
||||
- name: Upload to release
|
||||
env:
|
||||
TOKEN: ${{ gitea.token }}
|
||||
API: ${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}
|
||||
run: scripts/release-upload.sh "${{ gitea.ref_name }}" $(cat packages.txt)
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
exec "$(git rev-parse --show-toplevel)/scripts/verificar.sh"
|
||||
exec "$(git rev-parse --show-toplevel)/scripts/check.sh"
|
||||
+3
-1
@@ -2,7 +2,9 @@
|
||||
/apps/gui/ui/logo.png
|
||||
*.eml
|
||||
__pycache__/
|
||||
.env*
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.DS_Store
|
||||
/data
|
||||
/config
|
||||
+17
-1
@@ -6,7 +6,16 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.0.0] - 2026-11-03
|
||||
|
||||
### Security
|
||||
- The API routes that change the configuration (`POST`/`PUT`/`DELETE /api/config/groups…`) now require an admin token (`--admin-token`/`XEXEU_ADMIN_TOKEN`, at least 16 characters, compared in constant time) in `Authorization: Bearer` or `X-Xexeu-Token`, and reject a browser `Origin` that does not match `Host`. Without a configured token, `serve` generates a random one at each start and prints a `?token=` link; the dashboard keeps it for the tab and asks for it on a `401`. Reads are unchanged.
|
||||
- `quinn-proto` 0.11.17 → 0.11.19 (RUSTSEC-2026-0338, RUSTSEC-2026-0340, RUSTSEC-2026-0343).
|
||||
|
||||
### Added
|
||||
- `LICENSE-MIT` and `LICENSE-APACHE`: the crates and the image already declared `MIT OR Apache-2.0`, but the license texts were missing.
|
||||
- Releases attach a standalone CLI for `linux-aarch64` and `linux-x86_64` (`xexeu-<tag>-<platform>.tar.gz` plus `.sha256`), built natively on each architecture.
|
||||
- `scripts/check-ui-i18n.mjs`, run by CI and `scripts/check.sh`: every Portuguese dashboard string needs an English translation. It found 38 untranslated strings and a duplicated key, now fixed.
|
||||
- Rust workspace scaffolding (`xexeu-core`, `xexeu-cli`), Docker Compose topology, documentation pairs and configuration examples.
|
||||
- `config`, `targets` and `schedule`: TOML parsing, CIDR/range/DNS target expansion, 5-field cron with jitter and overlap/cadence warnings.
|
||||
- Native scan engines: `nativo-sem-raw` (TCP connect) and `nativo` (raw-socket TCP SYN, `CAP_NET_RAW`), with automatic fallback and the engine actually used recorded in every sweep manifest.
|
||||
@@ -19,10 +28,17 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
- CSV export (`/api/export/*.csv`, `xexeu export`), CSV-injection-safe.
|
||||
- A4, Paged.js-paginated executive report at `/relatorio`.
|
||||
- `xexeu doctor` and `xexeu export` (JSON/CSV) CLI commands.
|
||||
- Gitea CI/CD (`ci.yml`, `release.yml`), `scripts/verificar.sh`, pre-push hook, issue/PR templates.
|
||||
- Gitea CI/CD (`ci.yml`, `release.yml`), `scripts/check.sh`, pre-push hook, issue/PR templates.
|
||||
- Full `docs/` set (architecture, CLI, configuration, Docker, interface, support) in EN/PT-BR with real dashboard screenshots.
|
||||
|
||||
### Changed
|
||||
- `scripts/verificar.sh` → `scripts/check.sh` (fast by default; `--full` adds the workspace tests and `cargo audit`) and `scripts/instalar-hooks.sh` → `scripts/install-hooks.sh`, the same names as the other Ciberfauna projects.
|
||||
|
||||
### Fixed
|
||||
- The image smoke test started the container without `/config/xexeu.toml`, ran `xexeu doctor` against relative paths, and piped into `grep -q` under `pipefail`, which failed at random through SIGPIPE.
|
||||
- The CI YAML check failed on runners without PyYAML.
|
||||
- `.env.example` was never in the repository (`.env*` in `.gitignore` matched it), although the README tells operators to copy it.
|
||||
- The dashboard sidebar always showed `v0.1.0`; it now shows the running version.
|
||||
- `Dockerfile` didn't copy `apps/` or `logo.png`, so the image never actually built until this was caught by a real `docker build`.
|
||||
- Sweep batch files were written with mode `0600` by `scanner` (uid 0); `xexeu` (uid 10001) couldn't read them through the read-only `xexeu-sweeps` mount. Batches are now written `0644`/directories `0755` explicitly.
|
||||
- Target group names accepted by the config CRUD API weren't validated as safe path components, so an unsafe name would only fail much later when a sweep for that group tried to write its batch; now rejected immediately with a clear error.
|
||||
|
||||
+17
-1
@@ -6,7 +6,16 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Não lançado]
|
||||
|
||||
## [1.0.0] - 2026-11-03
|
||||
|
||||
### Segurança
|
||||
- As rotas da API que mudam a configuração (`POST`/`PUT`/`DELETE /api/config/groups…`) agora exigem um token de administração (`--admin-token`/`XEXEU_ADMIN_TOKEN`, com pelo menos 16 caracteres, comparado em tempo constante) em `Authorization: Bearer` ou `X-Xexeu-Token`, e recusam um `Origin` de navegador que não bata com o `Host`. Sem token configurado, o `serve` gera um aleatório a cada partida e imprime um link `?token=`; o dashboard o guarda na aba e pede o token ao receber `401`. Leituras não mudaram.
|
||||
- `quinn-proto` 0.11.17 → 0.11.19 (RUSTSEC-2026-0338, RUSTSEC-2026-0340, RUSTSEC-2026-0343).
|
||||
|
||||
### Adicionado
|
||||
- `LICENSE-MIT` e `LICENSE-APACHE`: os crates e a imagem já declaravam `MIT OR Apache-2.0`, mas faltavam os textos das licenças.
|
||||
- As releases anexam um CLI avulso para `linux-aarch64` e `linux-x86_64` (`xexeu-<tag>-<plataforma>.tar.gz` mais `.sha256`), compilado nativamente em cada arquitetura.
|
||||
- `scripts/check-ui-i18n.mjs`, rodado pelo CI e pelo `scripts/check.sh`: todo texto em português do dashboard precisa de tradução inglesa. Ele achou 38 textos sem tradução e uma chave duplicada, já corrigidos.
|
||||
- Scaffolding do workspace Rust (`xexeu-core`, `xexeu-cli`), topologia Docker Compose, pares de documentação e exemplos de configuração.
|
||||
- `config`, `targets` e `schedule`: parse de TOML, expansão de alvo CIDR/faixa/DNS, cron de 5 campos com jitter e avisos de sobreposição/cadência.
|
||||
- Motores de varredura nativos: `nativo-sem-raw` (TCP connect) e `nativo` (SYN cru de socket, `CAP_NET_RAW`), com fallback automático e o motor realmente usado registrado em todo manifesto de varredura.
|
||||
@@ -19,10 +28,17 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
- Exportação CSV (`/api/export/*.csv`, `xexeu export`), protegida contra injeção de CSV.
|
||||
- Relatório executivo A4 paginado com Paged.js em `/relatorio`.
|
||||
- Comandos de CLI `xexeu doctor` e `xexeu export` (JSON/CSV).
|
||||
- CI/CD do Gitea (`ci.yml`, `release.yml`), `scripts/verificar.sh`, hook de pre-push, templates de issue/PR.
|
||||
- CI/CD do Gitea (`ci.yml`, `release.yml`), `scripts/check.sh`, hook de pre-push, templates de issue/PR.
|
||||
- Conjunto completo de `docs/` (arquitetura, CLI, configuração, Docker, interface, suporte) em EN/PT-BR com screenshots reais do dashboard.
|
||||
|
||||
### Alterado
|
||||
- `scripts/verificar.sh` → `scripts/check.sh` (rápido por padrão; `--full` acrescenta os testes do workspace e o `cargo audit`) e `scripts/instalar-hooks.sh` → `scripts/install-hooks.sh`, os mesmos nomes dos outros projetos da Ciberfauna.
|
||||
|
||||
### Corrigido
|
||||
- O smoke test da imagem subia o contêiner sem `/config/xexeu.toml`, rodava o `xexeu doctor` em caminhos relativos e usava pipe para `grep -q` sob `pipefail`, o que falhava ao acaso por SIGPIPE.
|
||||
- A checagem de YAML do CI falhava em runners sem PyYAML.
|
||||
- O `.env.example` nunca esteve no repositório (o `.env*` do `.gitignore` o pegava), embora o README mande os operadores copiá-lo.
|
||||
- A barra lateral do dashboard mostrava sempre `v0.1.0`; agora mostra a versão em execução.
|
||||
- O `Dockerfile` não copiava `apps/` nem `logo.png`, então a imagem nunca buildava de verdade até isso ser pego por um `docker build` real.
|
||||
- Arquivos de lote de varredura eram gravados com modo `0600` pelo `scanner` (uid 0); o `xexeu` (uid 10001) não conseguia lê-los pelo mount `xexeu-sweeps` somente leitura. Lotes agora são gravados com `0644`/diretórios com `0755` explicitamente.
|
||||
- Nomes de grupo de alvos aceitos pela API de CRUD de config não eram validados como componentes de caminho seguros, então um nome inseguro só falhava bem mais tarde, quando uma varredura daquele grupo tentava gravar o lote; agora é rejeitado imediatamente com um erro claro.
|
||||
|
||||
+3
-3
@@ -12,11 +12,11 @@ Thanks for helping. Xexéu is a continuous attack surface and vulnerability audi
|
||||
## Workflow
|
||||
|
||||
```bash
|
||||
scripts/instalar-hooks.sh
|
||||
scripts/verificar.sh
|
||||
scripts/install-hooks.sh
|
||||
scripts/check.sh
|
||||
```
|
||||
|
||||
`verificar.sh` validates code formatting, clippy with warnings as errors, UI translation coverage, shell script syntax, workflow YAML files, SemVer consistency, and prohibited terms.
|
||||
`check.sh` validates code formatting, clippy with warnings as errors, UI translation coverage, shell script syntax, workflow YAML files, SemVer consistency and `docker compose config` in about a minute; `scripts/check.sh --full` also runs the workspace tests and `cargo audit`.
|
||||
|
||||
## Interface and translation
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ Obrigado por ajudar. O Xexéu é um motor de auditoria contínua de superfície
|
||||
## Fluxo de trabalho
|
||||
|
||||
```bash
|
||||
scripts/instalar-hooks.sh
|
||||
scripts/verificar.sh
|
||||
scripts/install-hooks.sh
|
||||
scripts/check.sh
|
||||
```
|
||||
|
||||
`verificar.sh` executa formatação, clippy com avisos como erro, cobertura de tradução da UI, sintaxe de shell, YAML de workflows, consistência de SemVer e inspeção de termos proibidos.
|
||||
`check.sh` executa formatação, clippy com avisos como erro, cobertura de tradução da UI, sintaxe de shell, YAML de workflows, consistência de SemVer e `docker compose config` em cerca de um minuto; `scripts/check.sh --full` também roda os testes do workspace e o `cargo audit`.
|
||||
|
||||
## Interface e tradução
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -2245,7 +2245,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "xexeu-cli"
|
||||
version = "0.1.0"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
@@ -2260,7 +2260,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xexeu-core"
|
||||
version = "0.1.0"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-schema",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/xexeu-core", "crates/xexeu-cli"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "1.0.0"
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://git.lucasrguerra.dev.br/ciberfauna/xexeu"
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Xexéu contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -35,7 +35,7 @@ Xexéu is a lightweight continuous attack surface and vulnerability audit daemon
|
||||
| Dashboard & executive report | ✅ embedded vanilla UI (severity palette, SVG charts, group CRUD), A4 Paged.js report at `/relatorio` |
|
||||
| CSV / JSON export | ✅ `/api/export/*.csv`, `xexeu export`, CSV-injection-safe |
|
||||
| Docker Compose topology & hardening | ✅ validated end-to-end against a real target, including the permission boundary between the two containers' users |
|
||||
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/verificar.sh`, pre-push hook |
|
||||
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, pre-push hook |
|
||||
| Bilingual documentation | ✅ EN/PT-BR pairs, with real dashboard screenshots |
|
||||
| `nmap` adapter / `xexeu-scanner-nmap` variant | 🚧 not yet implemented |
|
||||
| Published releases | ❌ none yet — see [ROADMAP.md](ROADMAP.md) |
|
||||
@@ -53,7 +53,7 @@ Xexéu executes an ongoing loop: **schedule → scan → identify → historize
|
||||
|
||||
Xexéu is defensive software designed strictly for networks you own or are explicitly authorized to audit. Scanning third-party infrastructure without permission is illegal. Operators are responsible for scope, compliance, and data retention policies.
|
||||
|
||||
The configuration requires an explicit `[escopo]` block. Any target resolving outside the authorized CIDR ranges is rejected. The API daemon binds to `127.0.0.1` by default; it has no built-in authentication — put it behind an authenticating reverse proxy before exposing it beyond localhost. See [SECURITY.md](SECURITY.md).
|
||||
The configuration requires an explicit `[escopo]` block. Any target resolving outside the authorized CIDR ranges is rejected. The API daemon binds to `127.0.0.1` by default; reads are open, and the routes that change the configuration need an admin token (`XEXEU_ADMIN_TOKEN`, or the one-off link printed at startup). Put it behind an authenticating reverse proxy before exposing it beyond localhost. See [SECURITY.md](SECURITY.md).
|
||||
|
||||
## Install
|
||||
|
||||
@@ -63,8 +63,11 @@ Run via Docker Compose (recommended for operators):
|
||||
cp .env.example .env
|
||||
mkdir -p config && cp examples/xexeu.toml config/xexeu.toml
|
||||
docker compose pull && docker compose up -d
|
||||
docker compose logs xexeu | grep token # one-off admin link, unless XEXEU_ADMIN_TOKEN is set
|
||||
```
|
||||
|
||||
The image is public: `docker pull git.lucasrguerra.dev.br/ciberfauna/xexeu:latest`.
|
||||
|
||||
Or build and run locally with Docker:
|
||||
|
||||
```bash
|
||||
@@ -78,6 +81,13 @@ cargo build --release -p xexeu-cli
|
||||
./target/release/xexeu --help
|
||||
```
|
||||
|
||||
Or download the standalone CLI from the [releases page](https://git.lucasrguerra.dev.br/ciberfauna/xexeu/releases) (`linux-x86_64` and `linux-aarch64`) and check it against its `.sha256`:
|
||||
|
||||
```bash
|
||||
sha256sum -c xexeu-v1.0.0-linux-x86_64.tar.gz.sha256
|
||||
tar xzf xexeu-v1.0.0-linux-x86_64.tar.gz
|
||||
```
|
||||
|
||||
Supported platform matrix for container images: `linux/amd64` and `linux/arm64`.
|
||||
|
||||
## Getting started
|
||||
@@ -106,7 +116,7 @@ See [docs/cli.md](docs/cli.md) for the full command reference.
|
||||
```bash
|
||||
cargo test --workspace
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
scripts/verificar.sh
|
||||
scripts/check.sh
|
||||
```
|
||||
|
||||
See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/architecture.md)**.
|
||||
@@ -117,7 +127,6 @@ See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/arc
|
||||
- Authenticated scans (SSH/WinRM) and active exploit validation are non-goals.
|
||||
- The `nativo-sem-raw` degraded mode is restricted to TCP connect and lacks ICMP/ARP discovery.
|
||||
- IPv6 target expansion is limited to prefixes up to `/112` or explicit host lists; the raw SYN engine itself only scans IPv4 targets (IPv6 ones fall back to `nativo-sem-raw` automatically).
|
||||
- No published releases/container images yet — build from source or `docker compose up -d --build` until the first tagged release.
|
||||
|
||||
## Where it's going
|
||||
|
||||
@@ -125,9 +134,9 @@ Summary of the [ROADMAP](ROADMAP.md):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Done** | 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, CI/CD |
|
||||
| **Next** | First tagged release and published container image |
|
||||
| **Later** | `nmap` adapter and the `xexeu-scanner-nmap` variant, authenticated scanning, notifications |
|
||||
| **Done (1.0.0)** | Workspace crates, native SYN/connect scan engines, fingerprinting, CVE/KEV correlation, scoped diffs, SQLite+Parquet storage, dashboard, executive report, CSV export, config CRUD with scanner hot-reload behind an admin token, CI/CD with published image and CLI |
|
||||
| **Next** | Fuzzing and property tests, webhook alerts, Prometheus metrics |
|
||||
| **Later** | `nmap` adapter and the `xexeu-scanner-nmap` variant, email alerts, OSV and distribution backport mapping |
|
||||
| **Not planned** | Exploitation payloads, NASL engine, mandatory cloud services, desktop Tauri wrapper |
|
||||
|
||||
## License
|
||||
|
||||
+16
-7
@@ -35,7 +35,7 @@ A Xexéu é um daemon leve e contínuo de auditoria de superfície de ataque e v
|
||||
| Dashboard e relatório executivo | ✅ interface embutida em HTML/JS puro (paleta por severidade, gráficos SVG, CRUD de grupos), relatório A4 com Paged.js em `/relatorio` |
|
||||
| Exportação CSV / JSON | ✅ `/api/export/*.csv`, `xexeu export`, protegido contra injeção de fórmula em CSV |
|
||||
| Topologia Docker Compose e hardening | ✅ validado de ponta a ponta contra um alvo real, incluindo o limite de permissão entre os usuários dos dois containers |
|
||||
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/verificar.sh`, hook de pre-push |
|
||||
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, hook de pre-push |
|
||||
| Documentação bilíngue | ✅ pares EN/PT-BR, com screenshots reais do dashboard |
|
||||
| Adaptador `nmap` / variante `xexeu-scanner-nmap` | 🚧 ainda não implementado |
|
||||
| Releases publicados | ❌ nenhum ainda — veja [ROADMAP.pt-BR.md](ROADMAP.pt-BR.md) |
|
||||
@@ -53,7 +53,7 @@ A Xexéu executa um ciclo contínuo: **agendar → varrer → identificar → hi
|
||||
|
||||
A Xexéu é software defensivo desenhado estritamente pra redes que você possui ou tem autorização explícita pra auditar. Varrer infraestrutura de terceiros sem permissão é ilegal. Operadores são responsáveis pelo escopo, conformidade e políticas de retenção de dados.
|
||||
|
||||
A configuração exige um bloco `[escopo]` explícito. Qualquer alvo que resolva fora das faixas CIDR autorizadas é rejeitado. O daemon de API vincula em `127.0.0.1` por padrão; não tem autenticação embutida — coloque atrás de um proxy reverso autenticador antes de expor além do localhost. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
|
||||
A configuração exige um bloco `[escopo]` explícito. Qualquer alvo que resolva fora das faixas CIDR autorizadas é rejeitado. O daemon de API vincula em `127.0.0.1` por padrão; leituras são abertas, e as rotas que mudam a configuração exigem um token de administração (`XEXEU_ADMIN_TOKEN`, ou o link avulso impresso na partida). Coloque atrás de um proxy reverso autenticador antes de expor além do localhost. Veja [SECURITY.pt-BR.md](SECURITY.pt-BR.md).
|
||||
|
||||
## Instalação
|
||||
|
||||
@@ -63,8 +63,11 @@ Rode via Docker Compose (recomendado pra operadores):
|
||||
cp .env.example .env
|
||||
mkdir -p config && cp examples/xexeu.toml config/xexeu.toml
|
||||
docker compose pull && docker compose up -d
|
||||
docker compose logs xexeu | grep token # link avulso de admin, se XEXEU_ADMIN_TOKEN não estiver definido
|
||||
```
|
||||
|
||||
A imagem é pública: `docker pull git.lucasrguerra.dev.br/ciberfauna/xexeu:latest`.
|
||||
|
||||
Ou builde e rode localmente com Docker:
|
||||
|
||||
```bash
|
||||
@@ -78,6 +81,13 @@ cargo build --release -p xexeu-cli
|
||||
./target/release/xexeu --help
|
||||
```
|
||||
|
||||
Ou baixe o CLI avulso na [página de releases](https://git.lucasrguerra.dev.br/ciberfauna/xexeu/releases) (`linux-x86_64` e `linux-aarch64`) e confira com o `.sha256`:
|
||||
|
||||
```bash
|
||||
sha256sum -c xexeu-v1.0.0-linux-x86_64.tar.gz.sha256
|
||||
tar xzf xexeu-v1.0.0-linux-x86_64.tar.gz
|
||||
```
|
||||
|
||||
Matriz de plataforma suportada pras imagens de container: `linux/amd64` e `linux/arm64`.
|
||||
|
||||
## Primeiros passos
|
||||
@@ -106,7 +116,7 @@ Veja [docs/pt-BR/cli.md](docs/pt-BR/cli.md) pra referência completa de comandos
|
||||
```bash
|
||||
cargo test --workspace
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
scripts/verificar.sh
|
||||
scripts/check.sh
|
||||
```
|
||||
|
||||
Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e **[docs/pt-BR/arquitetura.md](docs/pt-BR/arquitetura.md)**.
|
||||
@@ -117,7 +127,6 @@ Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e **[docs/pt-BR/arquitet
|
||||
- Varreduras autenticadas (SSH/WinRM) e validação ativa de exploit são não-objetivos.
|
||||
- O modo degradado `nativo-sem-raw` é restrito a TCP connect e não tem descoberta ICMP/ARP.
|
||||
- Expansão de alvo IPv6 é limitada a prefixos até `/112` ou listas explícitas de host; o próprio motor SYN cru só varre alvos IPv4 (os IPv6 recorrem automaticamente ao `nativo-sem-raw`).
|
||||
- Sem releases/imagens de container publicados ainda — builde a partir do código-fonte ou `docker compose up -d --build` até o primeiro release com tag.
|
||||
|
||||
## Pra onde está indo
|
||||
|
||||
@@ -125,9 +134,9 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feito** | 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, CI/CD |
|
||||
| **Próximo** | Primeiro release com tag e imagem de container publicada |
|
||||
| **Depois** | Adaptador `nmap` e a variante `xexeu-scanner-nmap`, varredura autenticada, notificações |
|
||||
| **Feito (1.0.0)** | Crates do workspace, motores de varredura SYN/connect nativos, fingerprint, correlação CVE/KEV, diffs por escopo, armazenamento SQLite+Parquet, dashboard, relatório executivo, exportação CSV, CRUD de config com hot-reload do scanner protegido por token de administração, CI/CD com imagem e CLI publicados |
|
||||
| **Próximo** | Fuzzing e testes de propriedade, alertas por webhook, métricas Prometheus |
|
||||
| **Depois** | Adaptador `nmap` e a variante `xexeu-scanner-nmap`, alertas por e-mail, OSV e mapeamento de backports de distribuição |
|
||||
| **Não planejado** | Payloads de exploração, motor NASL, serviços de nuvem obrigatórios, wrapper desktop Tauri |
|
||||
|
||||
## Licença
|
||||
|
||||
+9
-5
@@ -2,9 +2,11 @@
|
||||
|
||||
**English** · [Português](ROADMAP.pt-BR.md)
|
||||
|
||||
This roadmap outlines the implementation plan for Xexéu based on the approved specification (`openspec/changes/criar-xexeu/`).
|
||||
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
|
||||
## Done (1.0.0)
|
||||
|
||||
- **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`).
|
||||
- **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.
|
||||
@@ -13,17 +15,19 @@ This roadmap outlines the implementation plan for Xexéu based on the approved s
|
||||
- **Non-intrusive vulnerability identification:** local NVD CVE JSON 2.0 + CISA KEV caching, offline import or live sync (one-shot or periodic background, independent of image/binary updates); deterministic CPE → CVE matcher with confidence levels (`alta`/`média`/`baixa`); safe configuration checks (expired/soon-to-expire TLS certificates, unencrypted administrative ports).
|
||||
- **Storage, diff engine & change history:** embedded SQLite (state) + Parquet (immutable sweep batches) — see `docs/architecture.md` for why SQLite instead of the originally-specified DuckDB; idempotent batch ingestion; scoped diff computation that never produces a false disappearance from a partial sweep; debounced state transitions (`ausencias_para_sumir`).
|
||||
- **API, dashboard & executive report:** Axum API (`/api/health`, `/api/status`, `/api/hosts`, `/api/changes`, `/api/config*`, `/api/export/*.csv`); embedded vanilla HTML/CSS/JS dashboard with a CVSS-severity palette, SVG charts and group CRUD; an A4, Paged.js-paginated executive report at `/relatorio`.
|
||||
- **CI/CD & hardening:** Gitea `ci.yml`/`release.yml`, `scripts/verificar.sh` and a pre-push hook, a multi-stage `Dockerfile`, and `docker-compose.yml` — all validated end-to-end against a real scan target (DVWA) through the actual hardened containers, not just the host binary.
|
||||
- **CI/CD & hardening:** Gitea `ci.yml`/`release.yml`, `scripts/check.sh` and a pre-push hook, a multi-stage `Dockerfile`, and `docker-compose.yml` — all validated end-to-end against a real scan target (DVWA) through the actual hardened containers, not just the host binary.
|
||||
- **Bilingual documentation:** `README`, `CHANGELOG`, `CONTRIBUTING`, `SECURITY`, `ROADMAP` and the full `docs/` set (architecture, CLI, configuration, Docker, interface, support), EN/PT-BR pairs, with real dashboard screenshots.
|
||||
|
||||
## Next
|
||||
|
||||
- **First tagged release:** cut `v1.0.0` and publish the container image to the Gitea registry via `release.yml`.
|
||||
- **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.
|
||||
|
||||
## Later
|
||||
|
||||
- **`nmap` adapter & `xexeu-scanner-nmap` variant:** optional integration with the external `nmap` binary for richer service fingerprinting on profiles that opt in.
|
||||
- **Alert notifications:** outbound webhooks and email alerting for critical new findings or surface changes.
|
||||
- **Email alerting:** the same events as the webhooks, delivered by SMTP.
|
||||
- **Distribution backport mapping:** automated detection of backported vulnerability fixes in Debian/Ubuntu packages, to reduce false positives in version-based CVE matching.
|
||||
- **OSV feed integration:** Open Source Vulnerabilities database correlation for exposed application dependencies.
|
||||
- **Advanced network topologies:** coordinated multi-scanner worker pools reporting to a centralized aggregator daemon.
|
||||
|
||||
+9
-5
@@ -2,9 +2,11 @@
|
||||
|
||||
[English](ROADMAP.md) · **Português**
|
||||
|
||||
Este roadmap detalha o plano de implementação do Xexéu com base na especificação aprovada (`openspec/changes/criar-xexeu/`).
|
||||
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
|
||||
## Concluído (1.0.0)
|
||||
|
||||
- **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`).
|
||||
- **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.
|
||||
@@ -13,17 +15,19 @@ Este roadmap detalha o plano de implementação do Xexéu com base na especifica
|
||||
- **Identificação não intrusiva de vulnerabilidades:** cache local do NVD CVE JSON 2.0 + CISA KEV, importação offline ou sync ao vivo (único ou periódico em segundo plano, independente de atualização de imagem/binário); correlacionador determinístico CPE → CVE com níveis de confiança (`alta`/`média`/`baixa`); checagens seguras de configuração (certificados TLS expirados ou prestes a expirar, portas administrativas sem criptografia).
|
||||
- **Armazenamento, motor de diff e histórico de mudanças:** SQLite embutido (estado) + Parquet (lotes de varredura imutáveis) — veja `docs/pt-BR/arquitetura.md` pro motivo de SQLite em vez do DuckDB originalmente especificado; ingestão idempotente de lotes; cálculo de diff por escopo que nunca gera um falso desaparecimento a partir de uma varredura parcial; amortecimento de transições de estado (`ausencias_para_sumir`).
|
||||
- **API, dashboard e relatório executivo:** API Axum (`/api/health`, `/api/status`, `/api/hosts`, `/api/changes`, `/api/config*`, `/api/export/*.csv`); dashboard embutido em HTML/CSS/JS puro com paleta por severidade CVSS, gráficos SVG e CRUD de grupos; relatório executivo A4 paginado com Paged.js em `/relatorio`.
|
||||
- **CI/CD e hardening:** `ci.yml`/`release.yml` do Gitea, `scripts/verificar.sh` e hook de pre-push, `Dockerfile` multi-stage, e `docker-compose.yml` — tudo validado de ponta a ponta contra um alvo real de varredura (DVWA) através dos containers hardened de verdade, não só do binário no host.
|
||||
- **CI/CD e hardening:** `ci.yml`/`release.yml` do Gitea, `scripts/check.sh` e hook de pre-push, `Dockerfile` multi-stage, e `docker-compose.yml` — tudo validado de ponta a ponta contra um alvo real de varredura (DVWA) através dos containers hardened de verdade, não só do binário no host.
|
||||
- **Documentação bilíngue:** `README`, `CHANGELOG`, `CONTRIBUTING`, `SECURITY`, `ROADMAP` e todo o conjunto `docs/` (arquitetura, CLI, configuração, Docker, interface, suporte), pares EN/PT-BR, com screenshots reais do dashboard.
|
||||
|
||||
## Próximo
|
||||
|
||||
- **Primeiro release com tag:** cortar a `v1.0.0` e publicar a imagem de container no registro do Gitea via `release.yml`.
|
||||
- **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.
|
||||
|
||||
## Depois
|
||||
|
||||
- **Adaptador `nmap` e variante `xexeu-scanner-nmap`:** integração opcional com o binário externo `nmap` pra fingerprint de serviço mais rico em perfis que optarem por isso.
|
||||
- **Notificações de alerta:** webhooks externos e alertas por e-mail pra novas vulnerabilidades críticas ou mudanças de superfície.
|
||||
- **Alertas por e-mail:** os mesmos eventos dos webhooks, entregues por SMTP.
|
||||
- **Mapeamento de backports de distribuições:** dedução automática de correções retroportadas em pacotes Debian/Ubuntu, pra reduzir falsos positivos na correlação de CVE por versão.
|
||||
- **Integração com feeds OSV:** correlação contra a base Open Source Vulnerabilities pra dependências de aplicações expostas.
|
||||
- **Topologias distribuídas:** agrupamentos de múltiplos scanners reportando pra um daemon agregador centralizado.
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
|
||||
- **Strict authorized scope:** Target expansion enforces the `[escopo]` configuration boundary. Any target or DNS resolution resolving outside authorized CIDR blocks is rejected at validation time, preventing accidental or unauthorized scanning.
|
||||
- **Safe vulnerability identification:** Xexéu does not execute exploit payloads, perform credential brute-forcing, or execute denial-of-service tests. Checks are limited to passive banner matching and standard cryptographic handshakes.
|
||||
- **Input and batch parsing:** Malformed packets, banner responses, and Parquet batch files must not panic the engine or cause memory exhaustion.
|
||||
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Exposing it on an external network interface requires an authenticating reverse proxy.
|
||||
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Configuration changes require the admin token (`XEXEU_ADMIN_TOKEN`, compared in constant time) and a same-origin request; reads are not authenticated, so exposing it on an external network interface still requires an authenticating reverse proxy.
|
||||
- **Evidence integrity:** Findings and diff events must be reproducible from the same observations and feeds. Nondeterministic behavior is treated as a correctness and security defect.
|
||||
- **Privacy & local-first:** There is no telemetry. Vulnerability feeds are cached locally in SQLite/Parquet; air-gapped offline import (`xexeu feeds import`) is fully supported.
|
||||
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
|
||||
- **Escopo autorizado estrito:** A expansão de alvos impõe a barreira definida em `[escopo]`. Qualquer alvo ou resolução DNS que caia fora das faixas CIDR autorizadas é rejeitado na validação, prevenindo varreduras acidentais ou não autorizadas.
|
||||
- **Identificação segura de vulnerabilidades:** O Xexéu não executa payloads de exploração, força bruta de credenciais ou testes de negação de serviço. As checagens se limitam a correlação passiva de banners e handshakes criptográficos padronizados.
|
||||
- **Parsing de entradas e lotes:** Pacotes malformados, respostas anômalas de banner e arquivos de lote Parquet corrompidos não devem causar panic no motor nem exaustão de recursos.
|
||||
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Expô-lo externamente exige um proxy reverso com autenticação.
|
||||
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Mudanças de configuração exigem o token de administração (`XEXEU_ADMIN_TOKEN`, comparado em tempo constante) e requisição de mesma origem; leituras não são autenticadas, então expô-lo externamente ainda exige um proxy reverso com autenticação.
|
||||
- **Integridade da evidência:** Achados e eventos de diff devem ser reproduzíveis a partir das mesmas observações e bases de feeds. Nãodeterminismo é tratado como falha de corretude e segurança.
|
||||
- **Privacidade e local-first:** Não há telemetria. Os feeds de vulnerabilidades são armazenados localmente em SQLite/Parquet; importação offline para redes isoladas (`xexeu feeds import`) é suportada nativamente.
|
||||
|
||||
|
||||
+34
-3
@@ -4,6 +4,36 @@ const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
const $$ = (selector) => document.querySelectorAll(selector);
|
||||
|
||||
// Admin token for the routes that change state. `xexeu serve` prints a link
|
||||
// with `?token=`; it is kept for this tab only and dropped from the address bar.
|
||||
const TOKEN_KEY = 'xexeu.adminToken';
|
||||
{
|
||||
const params = new URLSearchParams(location.search);
|
||||
if (params.has('token')) {
|
||||
sessionStorage.setItem(TOKEN_KEY, params.get('token'));
|
||||
params.delete('token');
|
||||
const query = params.toString();
|
||||
history.replaceState(null, '', location.pathname + (query ? `?${query}` : '') + location.hash);
|
||||
}
|
||||
}
|
||||
|
||||
// fetch() for writes: sends the admin token and, on 401, asks for it once and retries.
|
||||
async function adminFetch(url, options = {}) {
|
||||
const send = () => fetch(url, {
|
||||
...options,
|
||||
headers: { ...options.headers, Authorization: `Bearer ${sessionStorage.getItem(TOKEN_KEY) || ''}` },
|
||||
});
|
||||
let res = await send();
|
||||
if (res.status === 401) {
|
||||
const token = window.prompt(t('Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):'));
|
||||
if (token && token.trim()) {
|
||||
sessionStorage.setItem(TOKEN_KEY, token.trim());
|
||||
res = await send();
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// DOM Elements
|
||||
const connection = $('#connection');
|
||||
const connectionText = $('#connectionText');
|
||||
@@ -253,6 +283,7 @@ async function fetchData() {
|
||||
connectionText.textContent = t('Conectado');
|
||||
if (state.health && state.health.version) {
|
||||
versionEl.textContent = `Xexéu v${state.health.version}`;
|
||||
$('#versionPill').textContent = `v${state.health.version}`;
|
||||
}
|
||||
if (state.status) {
|
||||
feedsStatusEl.textContent = `${formatInt(state.status.feeds_cve_count || 0)} CVEs`;
|
||||
@@ -1211,13 +1242,13 @@ async function handleGroupFormSubmit(e) {
|
||||
try {
|
||||
let res;
|
||||
if (editingGroupName) {
|
||||
res = await fetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
||||
res = await adminFetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} else {
|
||||
res = await fetch('/api/config/groups', {
|
||||
res = await adminFetch('/api/config/groups', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
@@ -1246,7 +1277,7 @@ async function deleteGroup(name) {
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
||||
const res = await adminFetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!res.ok) {
|
||||
|
||||
+40
-1
@@ -90,7 +90,6 @@ export const EN = {
|
||||
'Baixo (0.1-3.9)': 'Low (0.1-3.9)',
|
||||
'No KEV': 'In KEV',
|
||||
'Ordenar': 'Sort by',
|
||||
'Maior CVSS': 'Highest CVSS',
|
||||
'Menor CVSS': 'Lowest CVSS',
|
||||
'KEV primeiro': 'KEV first',
|
||||
'ID (CVE / Check)': 'ID (CVE / Check)',
|
||||
@@ -175,4 +174,44 @@ export const EN = {
|
||||
'Tem certeza que deseja remover o grupo': 'Are you sure you want to remove the group',
|
||||
'Pelo menos um alvo autorizado é obrigatório.': 'At least one authorized target is required.',
|
||||
'Nome do grupo é obrigatório.': 'Group name is required.',
|
||||
'Hosts e Superfície': 'Hosts and Surface',
|
||||
'Ativos identificados no escopo autorizado e portas abertas observadas': 'Assets found within the authorized scope and the open ports observed',
|
||||
'Inventário de Vulnerabilidades': 'Vulnerability Inventory',
|
||||
'Correlação de versões com feeds NVD, checagens de configuração e CISA KEV': 'Version correlation with NVD feeds, configuration checks and CISA KEV',
|
||||
'Alvos configurados, perfis de portas e cadência contínua': 'Configured targets, port profiles and continuous cadence',
|
||||
'Mudanças na Superfície': 'Surface Changes',
|
||||
'Linha do tempo de novas portas, hosts sumidos e alterações observadas': 'Timeline of new ports, vanished hosts and observed changes',
|
||||
'{n}s atrás': '{n}s ago',
|
||||
'{n}min atrás': '{n}min ago',
|
||||
'{n}h atrás': '{n}h ago',
|
||||
'{n}d atrás': '{n}d ago',
|
||||
'Falha ao comunicar com a API do Xexéu': 'Could not reach the Xexéu API',
|
||||
'Contém vulnerabilidade no CISA KEV!': 'Has a vulnerability in CISA KEV!',
|
||||
'Clique para abrir na tabela de hosts': 'Click to open it in the hosts table',
|
||||
'Serviço desconhecido': 'Unknown service',
|
||||
'Serviço': 'Service',
|
||||
'Versão': 'Version',
|
||||
'Confiança': 'Confidence',
|
||||
'Catálogo KEV': 'KEV catalog',
|
||||
'Sim (Ativamente explorado)': 'Yes (actively exploited)',
|
||||
'Não': 'No',
|
||||
'Erro ao salvar grupo': 'Could not save the group',
|
||||
'Erro de rede ao salvar grupo': 'Network error while saving the group',
|
||||
'Erro ao remover grupo': 'Could not remove the group',
|
||||
'Erro de rede ao remover grupo': 'Network error while removing the group',
|
||||
'Xexéu — Auditoria Contínua de Superfície de Ataque': 'Xexéu — Continuous Attack Surface Auditing',
|
||||
'superfície de risco': 'risk surface',
|
||||
'Informações de sincronização incremental NVD e catálogo CISA KEV.': 'Incremental NVD sync and CISA KEV catalog status.',
|
||||
'Média': 'Medium',
|
||||
'Crítica': 'Critical',
|
||||
'Navegação principal': 'Main navigation',
|
||||
'Top hosts por maior CVSS': 'Top hosts by highest CVSS',
|
||||
'IP, grupo ou serviço...': 'IP, group or service...',
|
||||
'Filtrar por status': 'Filter by status',
|
||||
'Filtrar por severidade': 'Filter by severity',
|
||||
'Filtrar por período': 'Filter by period',
|
||||
'Filtrar por IP ou tipo de evento...': 'Filter by IP or event type...',
|
||||
'Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):': 'Admin token (shown in the xexeu serve log or set in XEXEU_ADMIN_TOKEN):',
|
||||
'token de administração ausente ou inválido': 'admin token missing or invalid',
|
||||
'origem da requisição não confere': 'request origin does not match',
|
||||
};
|
||||
@@ -49,10 +49,10 @@
|
||||
<div class="side-foot">
|
||||
<div class="status-row">
|
||||
<span id="connection" class="pill"><span class="dot"></span><span id="connectionText">Conectando…</span></span>
|
||||
<span class="pill muted">v0.1.0</span>
|
||||
<span id="versionPill" class="pill muted">—</span>
|
||||
</div>
|
||||
<div class="status-row">
|
||||
<span id="version" class="mono">Xexéu v0.1.0</span>
|
||||
<span id="version" class="mono">Xexéu</span>
|
||||
<span class="mono" id="feedsStatus">—</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ path = "src/main.rs"
|
||||
xexeu-core = { path = "../xexeu-core" }
|
||||
axum = "0.8"
|
||||
chrono = { version = "0.4", features = ["clock"] }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
libc = "0.2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Admin token for the API routes that change state (group CRUD).
|
||||
//!
|
||||
//! Reads stay open, as before: the dashboard is meant to sit on loopback or
|
||||
//! behind a reverse proxy. Writes decide what the scanner sweeps, so they need
|
||||
//! the admin token in `Authorization: Bearer <token>` or `X-Xexeu-Token`, and a
|
||||
//! browser `Origin`, when sent, must match `Host` (CSRF).
|
||||
//!
|
||||
//! The token comes from `--admin-token`/`XEXEU_ADMIN_TOKEN`; without one, a
|
||||
//! random token is generated at startup and printed once, the same way
|
||||
//! `sabia ui` hands out its session token.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::{header, HeaderMap, Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
/// Shortest token accepted from configuration; shorter ones are guessable.
|
||||
pub const MIN_TOKEN_LEN: usize = 16;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AdminToken(Arc<str>);
|
||||
|
||||
impl AdminToken {
|
||||
pub fn new(token: &str) -> Self {
|
||||
Self(Arc::from(token))
|
||||
}
|
||||
|
||||
/// 32 random bytes from the kernel, hex-encoded.
|
||||
pub fn generate() -> std::io::Result<Self> {
|
||||
let mut bytes = [0u8; 32];
|
||||
File::open("/dev/urandom")?.read_exact(&mut bytes)?;
|
||||
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
Ok(Self::new(&hex))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Constant-time comparison: the time taken does not reveal how many
|
||||
/// leading characters of a guess were right.
|
||||
pub fn matches(&self, candidate: &str) -> bool {
|
||||
let expected = self.0.as_bytes();
|
||||
let candidate = candidate.as_bytes();
|
||||
let mut diff = expected.len() ^ candidate.len();
|
||||
for (index, byte) in expected.iter().enumerate() {
|
||||
diff |= usize::from(byte ^ candidate.get(index).copied().unwrap_or(0));
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Token sent by the client, from `Authorization: Bearer` or `X-Xexeu-Token`.
|
||||
fn presented_token(headers: &HeaderMap) -> Option<&str> {
|
||||
if let Some(value) = headers.get("x-xexeu-token").and_then(|v| v.to_str().ok()) {
|
||||
return Some(value.trim());
|
||||
}
|
||||
headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
}
|
||||
|
||||
/// `true` when there is no `Origin` (non-browser client) or its host matches `Host`.
|
||||
fn same_origin(headers: &HeaderMap) -> bool {
|
||||
let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {
|
||||
return true;
|
||||
};
|
||||
let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
let origin_host = origin
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or(origin)
|
||||
.trim_end_matches('/');
|
||||
origin_host.eq_ignore_ascii_case(host)
|
||||
}
|
||||
|
||||
fn is_write(method: &Method) -> bool {
|
||||
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
|
||||
}
|
||||
|
||||
pub async fn require_admin(
|
||||
State(token): State<AdminToken>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if is_write(request.method()) {
|
||||
let headers = request.headers();
|
||||
if !same_origin(headers) {
|
||||
return (StatusCode::FORBIDDEN, "origem da requisição não confere").into_response();
|
||||
}
|
||||
match presented_token(headers) {
|
||||
Some(candidate) if token.matches(candidate) => {}
|
||||
_ => {
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Bearer")],
|
||||
"token de administração ausente ou inválido",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
#[test]
|
||||
fn matches_only_the_exact_token() {
|
||||
let token = AdminToken::new("abcdef0123456789");
|
||||
assert!(token.matches("abcdef0123456789"));
|
||||
assert!(!token.matches("abcdef012345678"));
|
||||
assert!(!token.matches("abcdef01234567890"));
|
||||
assert!(!token.matches("Abcdef0123456789"));
|
||||
assert!(!token.matches(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_long_and_distinct() {
|
||||
let a = AdminToken::generate().unwrap();
|
||||
let b = AdminToken::generate().unwrap();
|
||||
assert_eq!(a.as_str().len(), 64);
|
||||
assert_ne!(a.as_str(), b.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bearer_and_custom_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer xyz"),
|
||||
);
|
||||
assert_eq!(presented_token(&headers), Some("xyz"));
|
||||
headers.insert("x-xexeu-token", HeaderValue::from_static("abc"));
|
||||
assert_eq!(presented_token(&headers), Some("abc"));
|
||||
headers.clear();
|
||||
headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Basic xyz"));
|
||||
assert_eq!(presented_token(&headers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origin_must_match_host() {
|
||||
let mut headers = HeaderMap::new();
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(header::HOST, HeaderValue::from_static("127.0.0.1:8788"));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("http://127.0.0.1:8788"),
|
||||
);
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("https://evil.example"),
|
||||
);
|
||||
assert!(!same_origin(&headers));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
mod auth;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::fs;
|
||||
use std::net::IpAddr;
|
||||
@@ -56,6 +58,10 @@ enum Command {
|
||||
sweeps: PathBuf,
|
||||
#[arg(long, default_value = "data/xexeu")]
|
||||
data_dir: PathBuf,
|
||||
/// Token required by the API routes that change state. Without it, a
|
||||
/// random token is generated at startup and printed once.
|
||||
#[arg(long, env = "XEXEU_ADMIN_TOKEN", hide_env_values = true)]
|
||||
admin_token: Option<String>,
|
||||
},
|
||||
/// Run the continuous scheduler and scan engine, writing sweep batches.
|
||||
Scanner {
|
||||
@@ -175,7 +181,8 @@ async fn main() -> ExitCode {
|
||||
config,
|
||||
sweeps,
|
||||
data_dir,
|
||||
} => match run_serve(&bind, &config, &sweeps, &data_dir).await {
|
||||
admin_token,
|
||||
} => match run_serve(&bind, &config, &sweeps, &data_dir, admin_token.as_deref()).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
@@ -1460,8 +1467,25 @@ async fn run_serve(
|
||||
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)
|
||||
@@ -1595,7 +1619,11 @@ async fn run_serve(
|
||||
.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);
|
||||
.with_state(state)
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
admin_token.clone(),
|
||||
auth::require_admin,
|
||||
));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(bind)
|
||||
.await
|
||||
@@ -1606,6 +1634,13 @@ async fn run_serve(
|
||||
.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())
|
||||
|
||||
@@ -15,7 +15,21 @@ impl Drop for ChildGuard {
|
||||
}
|
||||
}
|
||||
|
||||
const ADMIN_TOKEN: &str = "e2e-admin-token-0123456789";
|
||||
|
||||
fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
|
||||
let auth = format!("Authorization: Bearer {ADMIN_TOKEN}\r\n");
|
||||
http_request_with(addr, method, path, body, &auth)
|
||||
}
|
||||
|
||||
/// `extra_headers` is a raw block of `Name: value\r\n` lines.
|
||||
fn http_request_with(
|
||||
addr: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&str>,
|
||||
extra_headers: &str,
|
||||
) -> (u16, String, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
@@ -23,7 +37,7 @@ fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u1
|
||||
|
||||
let payload = body.unwrap_or("");
|
||||
let request = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
|
||||
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{extra_headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
|
||||
payload.len()
|
||||
);
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
@@ -87,6 +101,7 @@ alvos = ["127.0.0.1/32"]
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.env("XEXEU_ADMIN_TOKEN", ADMIN_TOKEN)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
@@ -118,6 +133,46 @@ alvos = ["127.0.0.1/32"]
|
||||
assert!(body.contains("\"escopo\""));
|
||||
assert!(body.contains("\"inicial\""));
|
||||
|
||||
// Writes need the admin token; a browser Origin must match Host.
|
||||
let group = r#"{"nome": "sem-token", "alvos": ["127.0.0.1"]}"#;
|
||||
let (code, headers, _) =
|
||||
http_request_with(&addr, "POST", "/api/config/groups", Some(group), "");
|
||||
assert_eq!(code, 401);
|
||||
assert!(headers.contains("www-authenticate: Bearer"));
|
||||
let wrong = "Authorization: Bearer e2e-admin-token-0123456788\r\n";
|
||||
let (code, _, _) = http_request_with(&addr, "POST", "/api/config/groups", Some(group), wrong);
|
||||
assert_eq!(code, 401);
|
||||
let (code, _, _) = http_request_with(&addr, "DELETE", "/api/config/groups/inicial", None, "");
|
||||
assert_eq!(code, 401);
|
||||
let cross_site =
|
||||
format!("Authorization: Bearer {ADMIN_TOKEN}\r\nOrigin: https://evil.example\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(group),
|
||||
&cross_site,
|
||||
);
|
||||
assert_eq!(code, 403);
|
||||
let same_site = format!("X-Xexeu-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(r#"{"nome": "fora", "alvos": ["192.168.1.1"]}"#),
|
||||
&same_site,
|
||||
);
|
||||
assert_eq!(
|
||||
code, 400,
|
||||
"same-origin request with the custom header reaches the handler"
|
||||
);
|
||||
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(
|
||||
!body.contains("sem-token"),
|
||||
"rejected writes must not change the config"
|
||||
);
|
||||
|
||||
// 3. Test POST /api/config/groups - out of scope rejection
|
||||
let (code, _, body) = http_request(
|
||||
&addr,
|
||||
|
||||
@@ -29,6 +29,9 @@ services:
|
||||
build: .
|
||||
command: ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/xexeu.toml",
|
||||
"--sweeps", "/data/sweeps", "--data-dir", "/data/xexeu"]
|
||||
environment:
|
||||
# Empty: a token is generated at each start and printed in `docker compose logs xexeu`.
|
||||
XEXEU_ADMIN_TOKEN: ${XEXEU_ADMIN_TOKEN:-}
|
||||
ports:
|
||||
- "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788"
|
||||
volumes:
|
||||
|
||||
+17
-7
@@ -15,14 +15,24 @@ dashboard/executive report.
|
||||
Usage: xexeu serve [OPTIONS]
|
||||
|
||||
Options:
|
||||
--bind <BIND> [default: 0.0.0.0:8788]
|
||||
--config <CONFIG> [default: config/xexeu.toml]
|
||||
--sweeps <SWEEPS> [default: data/sweeps]
|
||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||
--bind <BIND> [default: 0.0.0.0:8788]
|
||||
--config <CONFIG> [default: config/xexeu.toml]
|
||||
--sweeps <SWEEPS> [default: data/sweeps]
|
||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
|
||||
Without it, a random token is generated at startup
|
||||
and printed once [env: XEXEU_ADMIN_TOKEN]
|
||||
```
|
||||
|
||||
This is the `xexeu` Compose service's entrypoint.
|
||||
|
||||
Reads (`GET`) are open; the routes that change the configuration
|
||||
(`POST`/`PUT`/`DELETE /api/config/groups…`) need the admin token in
|
||||
`Authorization: Bearer <token>` or `X-Xexeu-Token`, and a browser `Origin`, when
|
||||
present, must match `Host`. Without `XEXEU_ADMIN_TOKEN`, `serve` prints a fresh
|
||||
`http://…/?token=…` link at each start; opening it logs the dashboard in for
|
||||
that tab.
|
||||
|
||||
## `xexeu scanner`
|
||||
|
||||
Runs the continuous scheduler and scan engine, writing sweep batches —
|
||||
@@ -75,7 +85,7 @@ Options:
|
||||
```
|
||||
|
||||
Exits non-zero on an invalid configuration — safe to use in a pre-push hook
|
||||
or CI step, which is exactly what `scripts/verificar.sh` does.
|
||||
or CI step, which is exactly what `scripts/check.sh` does.
|
||||
|
||||
## `xexeu feeds sync` / `xexeu feeds import`
|
||||
|
||||
@@ -142,11 +152,11 @@ Options:
|
||||
|
||||
```
|
||||
$ xexeu doctor
|
||||
Xexéu v0.1.0 - Diagnóstico do Ambiente
|
||||
Xexéu v1.0.0 - Diagnóstico do Ambiente
|
||||
================================================================================
|
||||
Item Status Detalhe
|
||||
--------------------------------------------------------------------------------
|
||||
versao ok xexeu v0.1.0
|
||||
versao ok xexeu v1.0.0
|
||||
config ok configuração válida (4 grupo(s))
|
||||
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
||||
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
||||
|
||||
+5
-1
@@ -38,7 +38,11 @@ docker compose up -d --build
|
||||
```
|
||||
|
||||
The dashboard comes up at `http://127.0.0.1:8788` by default (`XEXEU_PUBLISH`
|
||||
in `.env` to change the bind address/port).
|
||||
in `.env` to change the bind address/port). To add, edit or remove groups from
|
||||
it, set `XEXEU_ADMIN_TOKEN` in `.env` (`openssl rand -hex 32`) or, leaving it
|
||||
empty, take the one-off link from `docker compose logs xexeu`; inside the
|
||||
container it reads `http://0.0.0.0:8788/?token=…`, so swap the host for the
|
||||
published address.
|
||||
|
||||
## Why `scanner` runs as `uid 0` restricted to `NET_RAW`
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ cron, port profile, criticality) without touching `xexeu.toml` by hand —
|
||||
see [`configuration.md`](configuration.md#editing-a-group-from-the-dashboard)
|
||||
for how the change reaches the running `scanner`.
|
||||
|
||||
Changing groups needs the admin token: open the `?token=` link printed by
|
||||
`xexeu serve` (or `docker compose logs xexeu`), or type the token when the
|
||||
dashboard asks for it. It is kept for the browser tab only.
|
||||
|
||||
## Executive report
|
||||
|
||||
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Xexéu executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
|
||||
|
||||
+17
-7
@@ -15,14 +15,24 @@ dashboard/relatório executivo embutidos.
|
||||
Usage: xexeu serve [OPTIONS]
|
||||
|
||||
Options:
|
||||
--bind <BIND> [default: 0.0.0.0:8788]
|
||||
--config <CONFIG> [default: config/xexeu.toml]
|
||||
--sweeps <SWEEPS> [default: data/sweeps]
|
||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||
--bind <BIND> [default: 0.0.0.0:8788]
|
||||
--config <CONFIG> [default: config/xexeu.toml]
|
||||
--sweeps <SWEEPS> [default: data/sweeps]
|
||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
|
||||
Without it, a random token is generated at startup
|
||||
and printed once [env: XEXEU_ADMIN_TOKEN]
|
||||
```
|
||||
|
||||
Esse é o entrypoint do serviço `xexeu` do Compose.
|
||||
|
||||
Leituras (`GET`) são abertas; as rotas que mudam a configuração
|
||||
(`POST`/`PUT`/`DELETE /api/config/groups…`) exigem o token de administração em
|
||||
`Authorization: Bearer <token>` ou `X-Xexeu-Token`, e um `Origin` de navegador,
|
||||
quando presente, precisa bater com o `Host`. Sem `XEXEU_ADMIN_TOKEN`, o `serve`
|
||||
imprime um link `http://…/?token=…` novo a cada partida; abri-lo autentica o
|
||||
dashboard naquela aba.
|
||||
|
||||
## `xexeu scanner`
|
||||
|
||||
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
|
||||
@@ -78,7 +88,7 @@ Options:
|
||||
|
||||
Sai com código não-zero numa configuração inválida — seguro de usar num
|
||||
hook de pre-push ou passo de CI, que é exatamente o que
|
||||
`scripts/verificar.sh` faz.
|
||||
`scripts/check.sh` faz.
|
||||
|
||||
## `xexeu feeds sync` / `xexeu feeds import`
|
||||
|
||||
@@ -147,11 +157,11 @@ Options:
|
||||
|
||||
```
|
||||
$ xexeu doctor
|
||||
Xexéu v0.1.0 - Diagnóstico do Ambiente
|
||||
Xexéu v1.0.0 - Diagnóstico do Ambiente
|
||||
================================================================================
|
||||
Item Status Detalhe
|
||||
--------------------------------------------------------------------------------
|
||||
versao ok xexeu v0.1.0
|
||||
versao ok xexeu v1.0.0
|
||||
config ok configuração válida (4 grupo(s))
|
||||
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
||||
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
||||
|
||||
@@ -38,7 +38,11 @@ docker compose up -d --build
|
||||
```
|
||||
|
||||
O dashboard sobe em `http://127.0.0.1:8788` por padrão (`XEXEU_PUBLISH` no
|
||||
`.env` pra trocar endereço/porta).
|
||||
`.env` pra trocar endereço/porta). Pra adicionar, editar ou remover grupos
|
||||
por ele, defina `XEXEU_ADMIN_TOKEN` no `.env` (`openssl rand -hex 32`) ou,
|
||||
deixando vazio, pegue o link avulso em `docker compose logs xexeu`; dentro do
|
||||
contêiner ele aparece como `http://0.0.0.0:8788/?token=…`, então troque o host
|
||||
pelo endereço publicado.
|
||||
|
||||
## Por que o `scanner` roda como `uid 0` restrito a `NET_RAW`
|
||||
|
||||
|
||||
@@ -43,6 +43,10 @@ exclusões, cron, perfil de portas, criticidade) sem mexer no
|
||||
[`configuracao.md`](configuracao.md#editando-um-grupo-pelo-dashboard) pra
|
||||
como a mudança chega no `scanner` em execução.
|
||||
|
||||
Mexer em grupos exige o token de administração: abra o link `?token=` impresso
|
||||
pelo `xexeu serve` (ou `docker compose logs xexeu`), ou digite o token quando o
|
||||
dashboard pedir. Ele fica guardado só naquela aba do navegador.
|
||||
|
||||
## Relatório executivo
|
||||
|
||||
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Xexéu: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
|
||||
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs apt packages in CI without depending on fast mirrors: reuses cached .deb
|
||||
# archives when present and retries with per-attempt timeouts if apt stalls or fails.
|
||||
#
|
||||
# Usage: scripts/apt-install.sh <cache-dir> <package>...
|
||||
set -euo pipefail
|
||||
[ $# -ge 2 ] || { echo "usage: $0 <cache-dir> <package>..." >&2; exit 2; }
|
||||
cache="$1"; shift
|
||||
pkgs=("$@")
|
||||
mkdir -p "$cache/partial"
|
||||
# apt runs as root and leaves files (lock, .deb) unreadable by non-root runner users;
|
||||
# restore ownership on exit so cache directories remain accessible.
|
||||
trap 'sudo chown -R "$(id -u):$(id -g)" "$cache" 2>/dev/null || true; rm -f "$cache/lock"' EXIT
|
||||
opts=(-o "Dir::Cache::archives=$cache" -y)
|
||||
|
||||
# 1) With cached .deb files and package index present: install directly without updating apt lists
|
||||
if [ -z "$(dpkg --print-foreign-architectures)" ] && ls "$cache"/*.deb >/dev/null 2>&1 && ls /var/lib/apt/lists/*Packages* >/dev/null 2>&1 && timeout 300 sudo apt-get "${opts[@]}" install "${pkgs[@]}"; then
|
||||
echo "installed from cache"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 2) Cache miss (or multiarch / incomplete): update and install, up to 3 attempts with timeout
|
||||
for attempt in 1 2 3; do
|
||||
if timeout 240 sudo apt-get update && { [ -z "$(dpkg --print-foreign-architectures)" ] || timeout 600 sudo apt-get "${opts[@]}" upgrade; } && timeout 600 sudo apt-get "${opts[@]}" install "${pkgs[@]}"; then
|
||||
echo "installed (attempt $attempt)"
|
||||
exit 0
|
||||
fi
|
||||
echo "apt failed or timed out (attempt $attempt of 3)" >&2
|
||||
sleep $((attempt * 10))
|
||||
done
|
||||
echo "failed to install: ${pkgs[*]}" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env node
|
||||
// Verifies that the English dictionary covers all user-facing interface strings.
|
||||
//
|
||||
// Static zero-dependency scanner: reads the UI files (JS and HTML) and the
|
||||
// pt-BR messages emitted by the Rust core (errors, diagnostics, engine status),
|
||||
// failing whenever a string looks like Portuguese and lacks a translation. Also
|
||||
// rejects duplicate keys in the dictionary (in a JS object literal the last key wins silently).
|
||||
//
|
||||
// Usage: node scripts/check-ui-i18n.mjs
|
||||
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(fileURLToPath(new URL('.', import.meta.url)), '..');
|
||||
const rel = (p) => relative(root, p).replaceAll('\\', '/');
|
||||
|
||||
// ---------------------------------------------------------------- dictionary
|
||||
|
||||
const dictPath = join(root, 'apps/gui/ui/i18n-en.js');
|
||||
const dictSource = readFileSync(dictPath, 'utf8');
|
||||
|
||||
const keyRe = /^\s*(['"])((?:(?!\1).)*)\1\s*:/gm;
|
||||
const seen = new Map();
|
||||
const duplicates = [];
|
||||
let m;
|
||||
while ((m = keyRe.exec(dictSource))) {
|
||||
const key = m[2];
|
||||
const line = dictSource.slice(0, m.index).split('\n').length;
|
||||
if (seen.has(key)) duplicates.push({ key, first: seen.get(key), again: line });
|
||||
else seen.set(key, line);
|
||||
}
|
||||
|
||||
if (duplicates.length) {
|
||||
console.error('Duplicate keys in apps/gui/ui/i18n-en.js:');
|
||||
for (const d of duplicates) console.error(` ${JSON.stringify(d.key)} (lines ${d.first} and ${d.again})`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
const { EN } = await import(new URL('../apps/gui/ui/i18n-en.js', import.meta.url).href);
|
||||
|
||||
const exact = new Set(Object.keys(EN).filter((k) => !k.includes('{n}')));
|
||||
const patterns = Object.keys(EN)
|
||||
.filter((k) => k.includes('{n}'))
|
||||
.map((k) => {
|
||||
const parts = k.split('{n}').map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
return new RegExp('^' + parts.join('(.+?)') + '$', 's');
|
||||
});
|
||||
|
||||
function translated(text) {
|
||||
if (exact.has(text)) return true;
|
||||
return patterns.some((re) => re.test(text));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- heuristic
|
||||
|
||||
const ACCENT = /[áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ]/;
|
||||
const WORDS = [
|
||||
'pilar', 'pilares', 'ameaças', 'escopo', 'autorizado', 'tema', 'idioma', 'esqueleto', 'analisar',
|
||||
'atualizar', 'status', 'alerta', 'alertas', 'registros', 'detector', 'protocolo', 'anomalias',
|
||||
'fusão', 'evidências', 'conexões', 'sessões', 'persistentes', 'desenvolvimento', 'prova', 'opaca',
|
||||
'pesquisa', 'determinística', 'armazenamento', 'implementados', 'matemáticos', 'quatro', 'pacote',
|
||||
'enviado', 'fora', 'próprias', 'autorização', 'explícita', 'serviço', 'indisponível', 'selecionado',
|
||||
'analisando', 'concluída', 'falha', 'verificando', 'versão', 'recente', 'disponível', 'possível',
|
||||
'carregados', 'navegação', 'principal', 'recentes', 'futuro', 'carregará', 'sustenta', 'motor',
|
||||
'detecção', 'próximas', 'specs', 'fechar', 'claro', 'escuro', 'rede', 'redes', 'interface', 'interfaces', 'captura', 'capturar', 'modo', 'ativar', 'ativa',
|
||||
'desativar', 'iniciar', 'parar', 'nenhum', 'nenhuma', 'selecione', 'selecionada', 'canal',
|
||||
'sinal', 'segurança', 'clientes', 'cliente', 'oculta', 'oculto', 'privilégio', 'administrador',
|
||||
'necessário', 'pra', 'própria', 'próprias', 'autorização', 'responsável', 'sessão', 'trilha',
|
||||
'auditoria', 'registrada', 'registrado', 'local', 'adaptador', 'compatível', 'recarregue',
|
||||
'escutando', 'levar', 'segundos', 'enquanto', 'canais', 'varridos', 'erro', 'desconhecido',
|
||||
'desconhecida', 'não', 'sim', 'mais', 'menos', 'uma', 'uns', 'umas', 'aqui', 'onde', 'quando',
|
||||
'como', 'qual', 'para', 'com', 'sem', 'dos', 'das', 'por', 'que', 'checando', 'checar',
|
||||
'atualização', 'atualizado', 'trocar', 'possível', 'quebrável', 'quebrado', 'rompida',
|
||||
'corrompida', 'inválido', 'inválida', 'entrada', 'dicionário', 'quadros', 'quantidade',
|
||||
'injetar', 'encontrado', 'encontrada', 'suportada', 'permissão', 'insuficiente', 'instale',
|
||||
'root', 'indisponível', 'plataforma', 'criada', 'ainda', 'ferramenta', 'ferramentas',
|
||||
'exportar', 'importar', 'imprimir', 'baixar', 'recomendado', 'recomendada', 'aberta',
|
||||
'aberto', 'inconclusivo', 'inconclusiva', 'capturado', 'capturada', 'conhecido',
|
||||
'conhecida', 'opcional', 'opcionais', 'fechar', 'motivo', 'linha', 'tempo', 'quadro',
|
||||
'tentativas', 'ambas',
|
||||
];
|
||||
|
||||
const BRAND = /Xexéu|Xexeu|Português|English/gi;
|
||||
const isPortuguese = (raw) => {
|
||||
const s = raw.replace(BRAND, ' ');
|
||||
return ACCENT.test(s) || WORDS.some((w) => new RegExp(`(^|[^a-zà-ú])${w}([^a-zà-ú]|$)`, 'i').test(s));
|
||||
};
|
||||
|
||||
const ALLOW = new Set([
|
||||
'Xexéu', 'Português', 'English', 'Auto', 'Wi-Fi', 'Zeek', 'DuckDB', 'API', 'JSON', 'CLI',
|
||||
'MIT', 'Apache-2.0', 'OK', 'status-indicator {n}',
|
||||
]);
|
||||
const ALLOW_PREFIX = ['http://', 'https://', 'data:', 'file:', '#', '.', '/'];
|
||||
const ALLOW_EXACT = new Set(['—', '-', '·']);
|
||||
|
||||
function suspicious(text) {
|
||||
const s = text.replace(/\s+/g, ' ').trim();
|
||||
if (!s || s.length < 2) return false;
|
||||
if (ALLOW.has(s) || ALLOW_EXACT.has(s)) return false;
|
||||
if (ALLOW_PREFIX.some((p) => s.startsWith(p))) return false;
|
||||
if (!isPortuguese(s)) return false;
|
||||
// Technical tokens: CSS selectors, classes, extensions, expressions
|
||||
if (/^[.#\w-]+(\s*[,>+~]\s*[.#\w-]+)+$/.test(s)) return false;
|
||||
if (/^[a-z0-9_.:/@%{}$-]+$/i.test(s) && !ACCENT.test(s)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- extractors
|
||||
|
||||
function jsStrings(source, file, baseLine = 1) {
|
||||
const out = [];
|
||||
let i = 0;
|
||||
let line = baseLine;
|
||||
let prev = '';
|
||||
const skipRegex = () => {
|
||||
i++;
|
||||
let inClass = false;
|
||||
while (i < source.length) {
|
||||
const ch = source[i];
|
||||
if (ch === '\\') { i += 2; continue; }
|
||||
if (ch === '[') inClass = true;
|
||||
else if (ch === ']') inClass = false;
|
||||
else if (ch === '/' && !inClass) { i++; break; }
|
||||
else if (ch === '\n') line++;
|
||||
i++;
|
||||
}
|
||||
while (i < source.length && /[a-z]/i.test(source[i])) i++;
|
||||
};
|
||||
while (i < source.length) {
|
||||
const c = source[i];
|
||||
if (c === '\n') { line++; i++; prev = '\n'; continue; }
|
||||
if (c === ' ' || c === '\t' || c === '\r') { i++; continue; }
|
||||
if (c === '/' && source[i + 1] === '/') {
|
||||
while (i < source.length && source[i] !== '\n') i++;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && source[i + 1] === '*') {
|
||||
i += 2;
|
||||
while (i < source.length && !(source[i] === '*' && source[i + 1] === '/')) { if (source[i] === '\n') line++; i++; }
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && (/[=(:,[!&|?{};+\-*%^~<>]/.test(prev) || prev === 'return')) {
|
||||
skipRegex();
|
||||
prev = ')';
|
||||
continue;
|
||||
}
|
||||
if (c === "'" || c === '"') {
|
||||
const quote = c;
|
||||
const startLine = line;
|
||||
let value = '';
|
||||
i++;
|
||||
while (i < source.length) {
|
||||
const ch = source[i];
|
||||
if (ch === '\\') {
|
||||
const n = source[i + 1];
|
||||
if (n === 'n') value += '\n';
|
||||
else if (n === 't') value += '\t';
|
||||
else if (n === 'r') value += '\r';
|
||||
else if (n === '\n') line++;
|
||||
else value += n ?? '';
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === quote) { i++; break; }
|
||||
if (ch === '\n') line++;
|
||||
value += ch;
|
||||
i++;
|
||||
}
|
||||
out.push({ text: value, file, line: startLine });
|
||||
prev = ')';
|
||||
continue;
|
||||
}
|
||||
if (c === '`') {
|
||||
const startLine = line;
|
||||
let value = '';
|
||||
i++;
|
||||
while (i < source.length) {
|
||||
const ch = source[i];
|
||||
if (ch === '\\') {
|
||||
const n = source[i + 1];
|
||||
if (n === 'n') value += '\n';
|
||||
else if (n === 't') value += '\t';
|
||||
else if (n === '\n') line++;
|
||||
else value += n ?? '';
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '`') { i++; break; }
|
||||
if (ch === '$' && source[i + 1] === '{') {
|
||||
value += '{n}';
|
||||
i += 2;
|
||||
const exprStart = i;
|
||||
const exprLine = line;
|
||||
let depth = 1;
|
||||
while (i < source.length && depth > 0) {
|
||||
if (source[i] === '{') depth++;
|
||||
else if (source[i] === '}') depth--;
|
||||
else if (source[i] === '\n') line++;
|
||||
i++;
|
||||
}
|
||||
out.push(...jsStrings(source.slice(exprStart, i - 1), file, exprLine));
|
||||
continue;
|
||||
}
|
||||
if (ch === '\n') line++;
|
||||
value += ch;
|
||||
i++;
|
||||
}
|
||||
out.push({ text: value, file, line: startLine });
|
||||
prev = ')';
|
||||
continue;
|
||||
}
|
||||
prev = c;
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function htmlStrings(source, file, baseLine = 1) {
|
||||
const out = [];
|
||||
const lineAt = (idx) => baseLine + source.slice(0, idx).split('\n').length - 1;
|
||||
// Text between tags (including leading and trailing text nodes)
|
||||
let last = 0;
|
||||
for (const m of source.matchAll(/<[^>]*>/g)) {
|
||||
out.push({ text: source.slice(last, m.index), file, line: lineAt(last) });
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
out.push({ text: source.slice(last), file, line: lineAt(last) });
|
||||
// Translatable attributes (single or double quotes)
|
||||
for (const m of source.matchAll(/\b(placeholder|title|aria-label|alt|data-empty)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
|
||||
out.push({ text: m[2] ?? m[3], file, line: lineAt(m.index) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Extracts pt-BR messages from the Rust core: #[error("...")], .push("...".into()),
|
||||
// "...".into(), and format!("...", ...). Placeholders ({name}, {0}, {} etc.) are
|
||||
// normalized to {n}, matching the dictionary format.
|
||||
function rustLabels(source, file) {
|
||||
const out = [];
|
||||
const lineAt = (idx) => source.slice(0, idx).split('\n').length;
|
||||
const norm = (s) => s.replace(/\{[^}]*\}/g, '{n}');
|
||||
const grab = (re) => {
|
||||
for (const m of source.matchAll(re)) {
|
||||
out.push({ text: norm(m[1]), file, line: lineAt(m.index) });
|
||||
}
|
||||
};
|
||||
grab(/#\[error\(\s*"((?:[^"\\]|\\.)*)"\s*\)\]/g);
|
||||
grab(/"((?:[^"\\]|\\.)*)"\s*\.into\(\)/g);
|
||||
grab(/format!\(\s*"((?:[^"\\]|\\.)*)"/g);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- collection
|
||||
|
||||
const uiFiles = readdirSync(join(root, 'apps/gui/ui'))
|
||||
.filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor' && !f.endsWith('.min.js'))
|
||||
.map((f) => join(root, 'apps/gui/ui', f));
|
||||
uiFiles.push(join(root, 'apps/gui/ui/index.html'));
|
||||
|
||||
// The Rust core's messages reach only the CLI, never the dashboard.
|
||||
const rustFiles = [].map((f) => join(root, f));
|
||||
|
||||
const found = [];
|
||||
for (const file of uiFiles) {
|
||||
const source = readFileSync(file, 'utf8');
|
||||
if (file.endsWith('.html')) found.push(...htmlStrings(source, file));
|
||||
else {
|
||||
for (const str of jsStrings(source, file)) {
|
||||
if (/<[a-z!/][^>]*>/i.test(str.text)) found.push(...htmlStrings(str.text, file, str.line));
|
||||
else found.push(str);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const file of rustFiles) found.push(...rustLabels(readFileSync(file, 'utf8'), file));
|
||||
|
||||
const missing = [];
|
||||
const seenMissing = new Set();
|
||||
for (const { text, file, line } of found) {
|
||||
if (!suspicious(text)) continue;
|
||||
const key = text.replace(/\s+/g, ' ').trim();
|
||||
if (translated(key)) continue;
|
||||
const id = `${key}\u0000${rel(file)}\u0000${line}`;
|
||||
if (seenMissing.has(id)) continue;
|
||||
seenMissing.add(id);
|
||||
missing.push({ text: key, file: rel(file), line });
|
||||
}
|
||||
|
||||
if (missing.length) {
|
||||
console.error('Untranslated Portuguese strings in apps/gui/ui/i18n-en.js:\n');
|
||||
for (const x of missing) console.error(` ${x.file}:${x.line} ${JSON.stringify(x.text)}`);
|
||||
console.error(`\n${missing.length} untranslated string(s).`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (!process.exitCode) {
|
||||
console.log(`i18n ok: ${found.length} strings checked, ${Object.keys(EN).length} dictionary keys.`);
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Verificação local: executa as mesmas checagens do CI antes do push.
|
||||
# Local verification: runs the same fast checks as CI before pushing.
|
||||
#
|
||||
# scripts/verificar.sh completo: fmt, clippy, scripts, workflows, semver, compose, testes
|
||||
# scripts/verificar.sh --rapido pula a suíte de testes do workspace
|
||||
# scripts/check.sh fast (~1 min): fmt, clippy, i18n, scripts, workflows, semver
|
||||
# scripts/check.sh --full also runs workspace tests and cargo audit
|
||||
#
|
||||
# CI takes 5 to 30 minutes per run; almost everything that breaks CI is caught
|
||||
# here in seconds.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
rapido=0
|
||||
[ "${1:-}" = "--rapido" ] || [ "${1:-}" = "--fast" ] && rapido=1
|
||||
full=0
|
||||
[ "${1:-}" = "--full" ] || [ "${1:-}" = "--completo" ] && full=1
|
||||
failures=()
|
||||
step() { # step "name" command...
|
||||
local name="$1"; shift
|
||||
@@ -16,18 +18,22 @@ step() { # step "name" command...
|
||||
}
|
||||
|
||||
step "formatting (cargo fmt)" cargo fmt --all -- --check
|
||||
# Same flags as CI: warnings are treated as errors across all targets, including tests
|
||||
step "clippy (workspace, all targets)" env RUSTFLAGS="-D warnings" cargo clippy --workspace --all-targets
|
||||
|
||||
step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do [ -f "$f" ] || continue; bash -n "$f" || exit 1; done'
|
||||
|
||||
step "UI translation coverage" node scripts/check-ui-i18n.mjs
|
||||
step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do bash -n "$f" || exit 1; done'
|
||||
step "workflows and templates (valid YAML)" python3 -c "
|
||||
import sys
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
sys.exit('PyYAML missing: pip install pyyaml')
|
||||
import glob, yaml
|
||||
for f in glob.glob('.gitea/**/*.yml', recursive=True):
|
||||
yaml.safe_load(open(f))
|
||||
"
|
||||
|
||||
step "brand assets" test -s logo.png
|
||||
|
||||
step "consistent Semantic Versioning 2.0.0" python3 -c "
|
||||
import re, sys
|
||||
from pathlib import Path
|
||||
@@ -56,8 +62,9 @@ else
|
||||
printf '\n(docker compose config: skipped, docker compose not available)\n'
|
||||
fi
|
||||
|
||||
if [ "$rapido" = 0 ]; then
|
||||
if [ "$full" = 1 ]; then
|
||||
step "tests (cargo test --workspace)" cargo test --workspace
|
||||
step "dependency audit (cargo audit)" cargo audit
|
||||
fi
|
||||
|
||||
printf '\n'
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Ativa os Git hooks do repositório (.githooks/pre-push e .githooks/commit-msg).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
git config core.hooksPath .githooks
|
||||
echo "hooks ativados: git commit valida Conventional Commits e git push executa scripts/verificar.sh (desative com: git config --unset core.hooksPath)"
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Enables the repository Git hooks (.githooks/pre-push and .githooks/commit-msg).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
git config core.hooksPath .githooks
|
||||
echo "hooks enabled: git commit validates Conventional Commits in English and git push runs scripts/check.sh (disable with: git config --unset core.hooksPath)"
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the CLI for a target platform and packages it for a release:
|
||||
# xexeu-<tag>-<platform>.tar.gz alongside a .sha256 checksum file.
|
||||
#
|
||||
# scripts/package-cli.sh v1.0.3 linux-x86_64 x86_64-unknown-linux-gnu
|
||||
#
|
||||
# Supported platforms: linux-x86_64 and linux-aarch64. When cross-compiling
|
||||
# from a non-x86_64 host, uses gcc-x86-64-linux-gnu. Writes the archives to the
|
||||
# repository root and prints their filenames.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
tag=${1:?usage: package-cli.sh <tag> <platform> <rust-target>}
|
||||
platform=${2:?usage: package-cli.sh <tag> <platform> <rust-target>}
|
||||
target=${3:?usage: package-cli.sh <tag> <platform> <rust-target>}
|
||||
|
||||
case "$target" in
|
||||
x86_64-unknown-linux-gnu)
|
||||
if [ "$(uname -m)" != x86_64 ]; then
|
||||
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc
|
||||
export CC_x86_64_unknown_linux_gnu=x86_64-linux-gnu-gcc
|
||||
fi ;;
|
||||
esac
|
||||
|
||||
rustup target add "$target" >/dev/null 2>&1 || true
|
||||
cargo build --release --locked -p xexeu-cli --target "$target"
|
||||
|
||||
name="xexeu-${tag}-${platform}"
|
||||
rm -rf "$name"; mkdir "$name"
|
||||
cp "${CARGO_TARGET_DIR:-target}/${target}/release/xexeu" "$name/"
|
||||
cp README.md LICENSE-MIT LICENSE-APACHE "$name/"
|
||||
|
||||
tar czf "$name.tar.gz" "$name"
|
||||
asset="$name.tar.gz"
|
||||
rm -rf "$name"
|
||||
sha256sum "$asset" > "$asset.sha256"
|
||||
echo "$asset"
|
||||
echo "$asset.sha256"
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Uploads assets to a Gitea release, replacing any existing asset with the same
|
||||
# filename so re-running a CI job never fails on duplicate attachments.
|
||||
#
|
||||
# API=https://git.example.com/api/v1/repos/owner/repo TOKEN=... \
|
||||
# scripts/release-upload.sh v1.2.3 file1 file2
|
||||
set -euo pipefail
|
||||
|
||||
: "${API:?set API (Gitea repository API URL)}"
|
||||
: "${TOKEN:?set TOKEN}"
|
||||
tag=${1:?usage: release-upload.sh <tag> <file>...}
|
||||
shift
|
||||
|
||||
auth=(-H "Authorization: token $TOKEN")
|
||||
id=$(curl -fsS "${auth[@]}" "$API/releases/tags/$tag" | jq -r .id)
|
||||
|
||||
for file in "$@"; do
|
||||
name=$(basename "$file")
|
||||
encoded=$(jq -rn --arg n "$name" '$n|@uri')
|
||||
for old in $(curl -fsS "${auth[@]}" "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
|
||||
curl -fsS -X DELETE "${auth[@]}" "$API/releases/$id/assets/$old"
|
||||
done
|
||||
curl -fsS -X POST "${auth[@]}" -F "attachment=@$file" "$API/releases/$id/assets?name=$encoded" >/dev/null
|
||||
echo "uploaded: $name"
|
||||
done
|
||||
Reference in new issue
Block a user