3 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 2697d15a3e chore(release): 2.1.0
Release / Plan (reuse the published image?) (push) Successful in 5s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and clippy (push) Successful in 8m5s
CI / Dependency audit (push) Successful in 13s
CI / Tests (Linux) (push) Successful in 14m3s
Release / ci (push) Successful in 22m8s
Release / Build image (arm64) (push) Successful in 6m37s
Release / Build image (amd64) (push) Successful in 8m56s
Release / Publish tags (push) Successful in 16s
Release / Gitea release (push) Successful in 6s
Release / CLI (linux-x86_64) (push) Successful in 2m34s
Release / CLI (linux-aarch64) (push) Successful in 5m18s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:26:50 -03:00
Lucas RayanandClaude Opus 5.5 9c0d00a9db feat(report): new cover and layout for the executive report
CI / Tests (Linux) (push) Successful in 1m29s
CI / Dependency audit (push) Successful in 11s
CI / Format and clippy (push) Successful in 5m37s
Release / ci (push) Successful in 5m38s
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Failing after 31s
Release / Build image (amd64) (push) Successful in 8m49s
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:23:57 -03:00
Lucas RayanandClaude Sonnet 5.5 d3c3b91e82 docs: refresh README and screenshots for 2.x, drop em dashes, add scripts/screenshots.sh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 20:44:47 -03:00
35 changed files with 555 additions and 246 deletions

No files matched your search

+11 -1
View File
@@ -4,7 +4,17 @@
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
## [Unreleased]
## [2.1.0] - 2026-11-04
### Changed
- Documentation brought up to date for 2.x (README status, releases, install example) and rewritten without em dashes.
- The executive report title and the dashboard's page title, finding and group-dialog titles no longer use an em dash.
- Executive report redesign: full-bleed navy cover with the Harpia logo as the hero over an orange glow, a data-driven radar (one dot per listed finding, nearer the center means higher CVSS, KEV highlighted), headline numbers and a meta grid; inner pages carry the logo, document title, TLP and page counter in the margins.
### Fixed
- The executive report cover still read "XEXÉU"; it now shows the Harpia name.
- The interface screenshots in `docs/img` still showed the old Xexéu name and v0.1.0; they were retaken from the current build.
## [2.0.1] - 2026-11-03
+11 -1
View File
@@ -4,7 +4,17 @@
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
## [Não lançado]
## [2.1.0] - 2026-11-04
### Alterado
- Documentação atualizada para a série 2.x (status do README, releases, exemplo de instalação) e reescrita sem travessões.
- O título do relatório executivo e os títulos da página, dos achados e do diálogo de grupo no dashboard não usam mais travessão.
- Novo visual do relatório executivo: capa azul-marinho de página inteira com o logo do Harpia em destaque sobre um brilho laranja, um radar guiado pelos dados (um ponto por achado listado, mais perto do centro significa CVSS maior, KEV em destaque), números principais e grade de metadados; as páginas internas trazem logo, título do documento, TLP e contador de páginas nas margens.
### Corrigido
- A capa do relatório executivo ainda mostrava "XEXÉU"; agora mostra o nome Harpia.
- As capturas de tela da interface em `docs/img` ainda mostravam o nome antigo Xexéu e a v0.1.0; foram refeitas a partir da versão atual.
## [2.0.1] - 2026-11-03
+2
View File
@@ -38,6 +38,8 @@ The `Weekly` workflow fuzzes every target for ten minutes on a persistent corpus
Always maintain document pairs: every `*.md` and `docs/*` file has an English version and a Portuguese version (`*.pt-BR.md`, `docs/pt-BR/`). File names are translated only when the word changes (e.g. `architecture.md` → `arquitetura.md`).
The screenshots in `docs/img` are generated, not hand-made: run `scripts/screenshots.sh` to retake them from the current build (a synthetic Apache 2.4.25 service scanned for real, correlated with the real NVD and CISA KEV feeds, which are cached after the first run). Run it again whenever the interface, the name or the version shown on screen changes.
## Commits and releases
Commits follow Conventional Commits 1.0.0 in English (`feat:`, `fix:`, `chore:`, `ci:`, `docs:`, `refactor:`, `test:`, `perf:`, `build:`). Versions follow SemVer 2.0.0.
+2
View File
@@ -38,6 +38,8 @@ O workflow `Weekly` fuzza cada alvo por dez minutos sobre um corpus persistente
Mantenha sempre os pares: todo arquivo `*.md` e `docs/*` possui uma versão em inglês e uma em português (`*.pt-BR.md`, `docs/pt-BR/`). Nomes de arquivo são traduzidos apenas quando a palavra de fato muda (ex: `architecture.md` → `arquitetura.md`).
As capturas de tela em `docs/img` são geradas, não feitas à mão: rode `scripts/screenshots.sh` para refazê-las a partir da versão atual (um serviço Apache 2.4.25 sintético varrido de verdade e correlacionado com os feeds reais da NVD e da CISA KEV, que ficam em cache depois da primeira execução). Rode de novo sempre que a interface, o nome ou a versão exibida na tela mudar.
## Commits e releases
Commits seguem Conventional Commits 1.0.0 em inglês (`feat:`, `fix:`, `chore:`, `ci:`, `docs:`, `refactor:`, `test:`, `perf:`, `build:`). Versões seguem SemVer 2.0.0.
Generated
+2 -2
View File
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "harpia-cli"
version = "2.0.1"
version = "2.1.0"
dependencies = [
"axum",
"chrono",
@@ -751,7 +751,7 @@ dependencies = [
[[package]]
name = "harpia-core"
version = "2.0.1"
version = "2.1.0"
dependencies = [
"arrow-array",
"arrow-schema",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/harpia-core", "crates/harpia-cli"]
[workspace.package]
version = "2.0.1"
version = "2.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://git.lucasrguerra.dev.br/ciberfauna/harpia"
+10 -9
View File
@@ -10,17 +10,17 @@
---
**Status: v1.0 candidate.** The full pipeline — raw-socket SYN scanning, TCP-connect fallback, service fingerprinting, CVE/KEV correlation, scoped diffs, the dashboard, the executive report, CSV export and CI/release — is implemented and has been validated against a real vulnerable target (DVWA) through the actual hardened Docker Compose stack, not just the host binary. See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped and when.
**Status: stable, v2.0.1.** The full pipeline (raw-socket SYN scanning, TCP-connect fallback, service fingerprinting, CVE/KEV correlation, scoped diffs, the dashboard, the executive report, CSV export, webhook alerts, Prometheus metrics and CI/release) is implemented and has been validated against a real vulnerable target (DVWA) through the actual hardened Docker Compose stack, not just the host binary. The project was renamed from Xexéu to Harpia in 2.0.0. See [CHANGELOG.md](CHANGELOG.md) for exactly what shipped and when.
Harpia is a lightweight continuous attack surface and vulnerability audit daemon for authorized networks. Instead of one-off scans and unorganized XML dumps, Harpia runs continuously via Docker Compose, tracking what is exposed, what changed between sweeps, and what vulnerabilities exist.
- **Continuous, not point-in-time:** the primary output is the live deduplicated state of your network surface plus an append-only event log of differences (new hosts, closed ports, altered services, remediated CVEs).
- **Tiered scan cadences:** critical segments (core servers, DMZs) can be scanned frequently (e.g. every 5 minutes), while secondary segments are audited on broader schedules (e.g. daily cron at 03:00) — editable live from the dashboard's Groups view, no file editing required.
- **Tiered scan cadences:** critical segments (core servers, DMZs) can be scanned frequently (e.g. every 5 minutes), while secondary segments are audited on broader schedules (e.g. daily cron at 03:00), editable live from the dashboard's Groups view, no file editing required.
- **Lightweight & local-first:** a single Rust binary, embedded SQLite + Parquet storage. No external database, no Python runtime, and no telemetry.
- **Deterministic & explainable:** every vulnerability finding carries verifiable JSON evidence (raw banner, candidate CPE, matched feed rule, confidence level) — timeouts and network congestion are the only documented source of run-to-run variation, unlike traditional `nmap`'s intermittent flakiness.
- **Deterministic & explainable:** every vulnerability finding carries verifiable JSON evidence (raw banner, candidate CPE, matched feed rule, confidence level); timeouts and network congestion are the only documented source of run-to-run variation, unlike traditional `nmap`'s intermittent flakiness.
- **Least privilege:** containerized with strict privilege separation. Only the packet emitter container receives `NET_RAW` (no `NET_ADMIN`); the API, ingestion, diffing engine and web dashboard run completely unprivileged without capabilities. Falls back to an unprivileged `nativo-sem-raw` TCP-connect engine automatically when `CAP_NET_RAW` isn't usable.
- **Authorized use by design:** explicit authorized scope declaration is mandatory in configuration; out-of-scope targets are strictly rejected.
- **Stays fresh on its own:** the local CVE/KEV database can sync itself periodically, independently of image or binary updates — the same principle Trivy uses for its own vulnerability database.
- **Stays fresh on its own:** the local CVE/KEV database can sync itself periodically, independently of image or binary updates, the same principle Trivy uses for its own vulnerability database.
## What exists today
@@ -34,11 +34,12 @@ Harpia is a lightweight continuous attack surface and vulnerability audit daemon
| Storage | ✅ SQLite (state) + Parquet (immutable sweep batches) |
| Dashboard & executive report | ✅ embedded vanilla UI (severity palette, SVG charts, group CRUD), A4 Paged.js report at `/relatorio` |
| CSV / JSON export | ✅ `/api/export/*.csv`, `harpia export`, CSV-injection-safe |
| Webhook alerts and Prometheus metrics | ✅ HMAC-signed webhooks (JSON, Slack, Discord) and `/metrics` |
| Docker Compose topology & hardening | ✅ validated end-to-end against a real target, including the permission boundary between the two containers' users |
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, pre-push hook |
| Bilingual documentation | ✅ EN/PT-BR pairs, with real dashboard screenshots |
| `nmap` adapter / `harpia-scanner-nmap` variant | 🚧 not yet implemented |
| Published releases | ❌ none yet — see [ROADMAP.md](ROADMAP.md) |
| Published releases | ✅ CLI for `linux-x86_64` and `linux-aarch64` and the container image, on the [releases page](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) |
## Core principles
@@ -74,7 +75,7 @@ Or build and run locally with Docker:
docker compose up -d --build
```
To compile from source natively (just Rust 1.88+ — no external library to fetch, SQLite is bundled):
To compile from source natively (just Rust 1.88+, no external library to fetch, SQLite is bundled):
```bash
cargo build --release -p harpia-cli
@@ -84,8 +85,8 @@ cargo build --release -p harpia-cli
Or download the standalone CLI from the [releases page](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) (`linux-x86_64` and `linux-aarch64`) and check it against its `.sha256`:
```bash
sha256sum -c harpia-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf harpia-v1.0.0-linux-x86_64.tar.gz
sha256sum -c harpia-v2.0.1-linux-x86_64.tar.gz.sha256
tar xzf harpia-v2.0.1-linux-x86_64.tar.gz
```
Supported platform matrix for container images: `linux/amd64` and `linux/arm64`.
@@ -134,7 +135,7 @@ Summary of the [ROADMAP](ROADMAP.md):
| | |
|---|---|
| **Done (1.2.0)** | Workspace crates, native SYN/connect scan engines, fingerprinting, CVE/KEV correlation, scoped diffs, SQLite+Parquet storage, dashboard, executive report, CSV export, config CRUD with scanner hot-reload behind an admin token, CI/CD with published image and CLI, property tests and weekly fuzzing, webhook alerts, Prometheus metrics |
| **Done (2.0.1)** | Workspace crates, native SYN/connect scan engines, fingerprinting, CVE/KEV correlation, scoped diffs, SQLite+Parquet storage, dashboard, executive report, CSV export, config CRUD with scanner hot-reload behind an admin token, CI/CD with published image and CLI, property tests and weekly fuzzing, webhook alerts, Prometheus metrics |
| **Next** | Distribution backport mapping, email alerts |
| **Later** | `nmap` adapter and the `harpia-scanner-nmap` variant, OSV correlation, multi-scanner aggregation |
| **Not planned** | Exploitation payloads, NASL engine, mandatory cloud services, desktop Tauri wrapper |
+10 -9
View File
@@ -10,17 +10,17 @@
---
**Status: candidata a v1.0.** O pipeline completo — varredura SYN de socket cru, fallback TCP connect, fingerprint de serviço, correlação CVE/KEV, diffs por escopo, dashboard, relatório executivo, exportação CSV e CI/release — está implementado e foi validado contra um alvo real vulnerável (DVWA) através da stack Docker Compose hardened de verdade, não só do binário no host. Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) pra saber exatamente o que entrou e quando.
**Status: estável, v2.0.1.** O pipeline completo (varredura SYN de socket cru, fallback TCP connect, fingerprint de serviço, correlação CVE/KEV, diffs por escopo, dashboard, relatório executivo, exportação CSV, alertas por webhook, métricas Prometheus e CI/release) está implementado e foi validado contra um alvo vulnerável real (DVWA) pela stack Docker Compose endurecida de verdade, não só pelo binário no host. O projeto foi renomeado de Xexéu para Harpia na 2.0.0. Veja o [CHANGELOG.pt-BR.md](CHANGELOG.pt-BR.md) pra saber exatamente o que foi entregue e quando.
A Harpia é um daemon leve e contínuo de auditoria de superfície de ataque e vulnerabilidades pra redes autorizadas. Em vez de varreduras pontuais e dumps XML desorganizados, a Harpia roda continuamente via Docker Compose, rastreando o que está exposto, o que mudou entre varreduras, e quais vulnerabilidades existem.
- **Contínuo, não pontual:** o produto principal é o estado atual deduplicado da sua superfície de rede mais um log de eventos de diferenças (hosts novos, portas fechadas, serviços alterados, CVEs corrigidos).
- **Cadências de varredura em níveis:** segmentos críticos (servidores núcleo, DMZs) podem ser varridos com frequência (ex. a cada 5 minutos), enquanto segmentos secundários são auditados em cronogramas mais amplos (ex. cron diário às 03:00) — editável ao vivo pela tela de Grupos do dashboard, sem precisar editar arquivo nenhum.
- **Cadências de varredura em níveis:** segmentos críticos (servidores núcleo, DMZs) podem ser varridos com frequência (ex. a cada 5 minutos), enquanto segmentos secundários são auditados em cronogramas mais amplos (ex. cron diário às 03:00), editável ao vivo pela tela de Grupos do dashboard, sem precisar editar arquivo nenhum.
- **Leve e local-first:** um único binário Rust, armazenamento embutido em SQLite + Parquet. Sem banco externo, sem Python no runtime e sem telemetria.
- **Determinístico e explicável:** todo achado de vulnerabilidade carrega evidência JSON verificável (banner cru, CPE candidato, regra do feed que casou, nível de confiança) — timeouts e congestionamento de rede são a única fonte documentada de variação entre execuções, ao contrário da instabilidade intermitente do `nmap` tradicional.
- **Determinístico e explicável:** todo achado de vulnerabilidade carrega evidência JSON verificável (banner cru, CPE candidato, regra do feed que casou, nível de confiança); timeouts e congestionamento de rede são a única fonte documentada de variação entre execuções, ao contrário da instabilidade intermitente do `nmap` tradicional.
- **Privilégio mínimo:** containerizado com separação estrita de privilégio. Só o container emissor de pacotes recebe `NET_RAW` (sem `NET_ADMIN`); a API, ingestão, motor de diff e dashboard web rodam completamente não privilegiados, sem capabilities. Recorre automaticamente ao motor `nativo-sem-raw` de TCP connect, sem privilégio, quando `CAP_NET_RAW` não está utilizável.
- **Uso autorizado por design:** declaração explícita de escopo autorizado é obrigatória na configuração; alvos fora do escopo são rejeitados sem exceção.
- **Se mantém fresca sozinha:** a base local de CVE/KEV pode se sincronizar periodicamente, de forma independente de atualizações de imagem ou binário — o mesmo princípio que o Trivy usa pro próprio banco de vulnerabilidades.
- **Se mantém fresca sozinha:** a base local de CVE/KEV pode se sincronizar periodicamente, de forma independente de atualizações de imagem ou binário, o mesmo princípio que o Trivy usa pro próprio banco de vulnerabilidades.
## O que existe hoje
@@ -34,11 +34,12 @@ A Harpia é um daemon leve e contínuo de auditoria de superfície de ataque e v
| Armazenamento | ✅ SQLite (estado) + Parquet (lotes de varredura imutáveis) |
| Dashboard e relatório executivo | ✅ interface embutida em HTML/JS puro (paleta por severidade, gráficos SVG, CRUD de grupos), relatório A4 com Paged.js em `/relatorio` |
| Exportação CSV / JSON | ✅ `/api/export/*.csv`, `harpia export`, protegido contra injeção de fórmula em CSV |
| Alertas por webhook e métricas Prometheus | ✅ webhooks assinados com HMAC (JSON, Slack, Discord) e `/metrics` |
| Topologia Docker Compose e hardening | ✅ validado de ponta a ponta contra um alvo real, incluindo o limite de permissão entre os usuários dos dois containers |
| CI/CD (Gitea) | ✅ `ci.yml`, `release.yml`, `scripts/check.sh`, hook de pre-push |
| Documentação bilíngue | ✅ pares EN/PT-BR, com screenshots reais do dashboard |
| Adaptador `nmap` / variante `harpia-scanner-nmap` | 🚧 ainda não implementado |
| Releases publicados | ❌ nenhum ainda — veja [ROADMAP.pt-BR.md](ROADMAP.pt-BR.md) |
| Releases publicados | ✅ CLI para `linux-x86_64` e `linux-aarch64` e a imagem de container, na [página de releases](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) |
## Princípios centrais
@@ -74,7 +75,7 @@ Ou builde e rode localmente com Docker:
docker compose up -d --build
```
Pra compilar a partir do código-fonte nativamente (só Rust 1.88+ — sem biblioteca externa pra buscar, o SQLite vem embutido):
Pra compilar a partir do código-fonte nativamente (só Rust 1.88+, sem biblioteca externa pra buscar, o SQLite vem embutido):
```bash
cargo build --release -p harpia-cli
@@ -84,8 +85,8 @@ cargo build --release -p harpia-cli
Ou baixe o CLI avulso na [página de releases](https://git.lucasrguerra.dev.br/ciberfauna/harpia/releases) (`linux-x86_64` e `linux-aarch64`) e confira com o `.sha256`:
```bash
sha256sum -c harpia-v1.0.0-linux-x86_64.tar.gz.sha256
tar xzf harpia-v1.0.0-linux-x86_64.tar.gz
sha256sum -c harpia-v2.0.1-linux-x86_64.tar.gz.sha256
tar xzf harpia-v2.0.1-linux-x86_64.tar.gz
```
Matriz de plataforma suportada pras imagens de container: `linux/amd64` e `linux/arm64`.
@@ -134,7 +135,7 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
| | |
|---|---|
| **Feito (1.2.0)** | Crates do workspace, motores de varredura SYN/connect nativos, fingerprint, correlação CVE/KEV, diffs por escopo, armazenamento SQLite+Parquet, dashboard, relatório executivo, exportação CSV, CRUD de config com hot-reload do scanner protegido por token de administração, CI/CD com imagem e CLI publicados, testes de propriedade e fuzzing semanal, alertas por webhook, métricas Prometheus |
| **Feito (2.0.1)** | Crates do workspace, motores de varredura SYN/connect nativos, fingerprint, correlação CVE/KEV, diffs por escopo, armazenamento SQLite+Parquet, dashboard, relatório executivo, exportação CSV, CRUD de config com hot-reload do scanner protegido por token de administração, CI/CD com imagem e CLI publicados, testes de propriedade e fuzzing semanal, alertas por webhook, métricas Prometheus |
| **Próximo** | Mapeamento de backports de distribuição, alertas por e-mail |
| **Depois** | Adaptador `nmap` e a variante `harpia-scanner-nmap`, correlação OSV, agregação de vários scanners |
| **Não planejado** | Payloads de exploração, motor NASL, serviços de nuvem obrigatórios, wrapper desktop Tauri |
+3 -2
View File
@@ -6,6 +6,7 @@ Harpia does continuous attack-surface and vulnerability auditing: it sweeps auth
## Done
- **Rename to Harpia (2.0.0):** the project, crates, binary, environment variables, container image and repository were renamed from Xexéu to Harpia, after the harpy eagle. See the [CHANGELOG](CHANGELOG.md) for the migration notes.
- **Webhook alerts (1.2.0):** surface changes posted after each sweep, filtered by kind and group, as JSON or Slack/Discord messages, HMAC-signed, with retries.
- **Prometheus metrics (1.2.0):** `/metrics` with hosts, ports, findings by severity, feed age, per-group last sweep and webhook deliveries.
- **Robustness (1.1.0):** fuzzing of the parsers that read untrusted input (service banners, NVD/KEV feeds, target expansion), property tests for the diff engine's no-false-disappearance guarantee, `harpia-cli` split into modules, and a weekly dependency audit.
@@ -14,9 +15,9 @@ Harpia does continuous attack-surface and vulnerability auditing: it sweeps auth
- **Target & tiered schedule configuration:** `[escopo]`, `[padrao]`, `[perfis.*]`, `[[grupo]]` parsing; CIDR/range/DNS target expansion with rigid `escopo.autorizado` enforcement; 5-field cron with shortcuts, jitter and an aggressive-cadence warning (< 5 min); groups and their cron are editable live from the dashboard (`/api/config/groups`), with `scanner` hot-reloading on the config file's mtime.
- **Scan engine & scheduler:** multi-group scheduler with a shared packet-rate budget and non-overlapping group runs; native raw-socket SYN engine (`nativo`, requires `CAP_NET_RAW`) with automatic fallback to the unprivileged TCP-connect engine (`nativo-sem-raw`); HTTP/SSH/TLS service fingerprinting; atomic Parquet batch writes (`observations.parquet` + `manifest.json`) with file permissions explicit about the two containers running as different, unrelated Linux users.
- **Non-intrusive vulnerability identification:** local NVD CVE JSON 2.0 + CISA KEV caching, offline import or live sync (one-shot or periodic background, independent of image/binary updates); deterministic CPE → CVE matcher with confidence levels (`alta`/`média`/`baixa`); safe configuration checks (expired/soon-to-expire TLS certificates, unencrypted administrative ports).
- **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`).
- **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/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.
- **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
+3 -2
View File
@@ -6,6 +6,7 @@ O Harpia faz auditoria contínua de superfície de ataque e de vulnerabilidades:
## Concluído
- **Renomeação para Harpia (2.0.0):** o projeto, os crates, o binário, as variáveis de ambiente, a imagem de container e o repositório foram renomeados de Xexéu para Harpia, em referência à harpia (gavião-real). Veja o [CHANGELOG](CHANGELOG.pt-BR.md) para as notas de migração.
- **Alertas por webhook (1.2.0):** mudanças de superfície enviadas depois de cada varredura, filtradas por tipo e grupo, como JSON ou mensagem de Slack/Discord, assinadas com HMAC, com novas tentativas.
- **Métricas Prometheus (1.2.0):** `/metrics` com hosts, portas, achados por severidade, idade dos feeds, última varredura por grupo e entregas de webhook.
- **Robustez (1.1.0):** fuzzing dos parsers que leem entrada não confiável (banners de serviço, feeds NVD/KEV, expansão de alvos), testes de propriedade da garantia de nenhum desaparecimento falso do motor de diff, `harpia-cli` dividido em módulos e auditoria semanal de dependências.
@@ -14,9 +15,9 @@ O Harpia faz auditoria contínua de superfície de ataque e de vulnerabilidades:
- **Configuração de alvos e agendamento em níveis:** parse de `[escopo]`, `[padrao]`, `[perfis.*]`, `[[grupo]]`; expansão de alvo CIDR/faixa/DNS com imposição estrita de `escopo.autorizado`; cron de 5 campos com atalhos, jitter e aviso de cadência agressiva (< 5 min); grupos e seu cron são editáveis ao vivo pelo dashboard (`/api/config/groups`), com o `scanner` recarregando sozinho pelo `mtime` do arquivo de config.
- **Motor de varredura e agendador:** agendador multi-grupo com orçamento de taxa de pacotes compartilhado e sem sobreposição de execuções; motor nativo de SYN cru (`nativo`, exige `CAP_NET_RAW`) com fallback automático pro motor TCP connect sem privilégio (`nativo-sem-raw`); fingerprint de serviço HTTP/SSH/TLS; gravação atômica de lotes Parquet (`observations.parquet` + `manifest.json`) com permissões de arquivo explícitas sobre os dois containers rodando como usuários Linux diferentes e sem relação.
- **Identificação não intrusiva de vulnerabilidades:** cache local do NVD CVE JSON 2.0 + CISA KEV, importação offline ou sync ao vivo (único ou periódico em segundo plano, independente de atualização de imagem/binário); correlacionador determinístico CPE → CVE com níveis de confiança (`alta`/`média`/`baixa`); checagens seguras de configuração (certificados TLS expirados ou prestes a expirar, portas administrativas sem criptografia).
- **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`).
- **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/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.
- **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
+2 -2
View File
@@ -980,7 +980,7 @@ function renderFindings() {
const badge = el('span', `sev-badge ${sev}`, `${formatScore(finding.cvss)} ${severityLabel(sev)}`);
const main = el('div', 'alert-main');
const title = el('div', 'alert-title', `${finding.id} — ${finding.title || finding.description || ''}`);
const title = el('div', 'alert-title', `${finding.id}: ${finding.title || finding.description || ''}`);
const meta = el('div', 'alert-meta');
meta.append(
el('span', 'alert-target', `${finding.hostIp}:${finding.port}`),
@@ -1188,7 +1188,7 @@ function openEditGroupDialog(name) {
if (!group) return;
editingGroupName = name;
groupDlgTitle.textContent = `${t('Editar Grupo')} — ${name}`;
groupDlgTitle.textContent = `${t('Editar Grupo')}: ${name}`;
groupFormError.hidden = true;
groupFormError.textContent = '';
groupName.value = group.nome || '';
+1 -1
View File
@@ -199,7 +199,7 @@ export const EN = {
'Erro de rede ao salvar grupo': 'Network error while saving the group',
'Erro ao remover grupo': 'Could not remove the group',
'Erro de rede ao remover grupo': 'Network error while removing the group',
'Harpia — Auditoria Contínua de Superfície de Ataque': 'Harpia — Continuous Attack Surface Auditing',
'Harpia: Auditoria Contínua de Superfície de Ataque': 'Harpia: Continuous Attack Surface Auditing',
'superfície de risco': 'risk surface',
'Informações de sincronização incremental NVD e catálogo CISA KEV.': 'Incremental NVD sync and CISA KEV catalog status.',
'Média': 'Medium',
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Harpia — Auditoria Contínua de Superfície de Ataque</title>
<title>Harpia: Auditoria Contínua de Superfície de Ataque</title>
<link rel="icon" href="/logo.png">
<link rel="stylesheet" href="/app.css">
</head>
@@ -262,7 +262,7 @@ alvos = ["127.0.0.1/32"]
let (code, headers, body) = http_request(&addr, "GET", "/relatorio", None);
assert_eq!(code, 200);
assert!(headers.contains("content-type: text/html; charset=utf-8"));
assert!(body.contains("Relatório Executivo de Segurança — Harpia"));
assert!(body.contains("Relatório Executivo de Segurança: Harpia"));
assert!(body.contains("Indicadores-Chave de Exposição (KPIs)"));
assert!(body.contains("Glossário e Metodologia de Avaliação"));
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+261 -118
View File
@@ -516,7 +516,7 @@ impl ExecutiveReport {
};
ExecutiveReport {
title: "Relatório Executivo de Segurança — Harpia".to_string(),
title: "Relatório Executivo de Segurança: Harpia".to_string(),
subtitle: format!(
"Auditoria contínua de superfície de ataque e catálogo de vulnerabilidades · Emitido em {}",
now.format("%d/%m/%Y às %H:%M UTC")
@@ -550,7 +550,11 @@ impl ExecutiveReport {
"<script src=\"/paged.polyfill.js\"></script>\n<script>window.Paged || document.write('<script src=\"https://unpkg.com/pagedjs/dist/paged.polyfill.js\"><\\/script>')</script>\n",
);
html.push_str("<style>\n");
html.push_str(&REPORT_CSS.replace("HARPIA_REPORT_TLP_MARKER", self.tlp.label()));
html.push_str(
&REPORT_CSS
.replace("HARPIA_REPORT_TLP_MARKER", self.tlp.label())
.replace("HARPIA_REPORT_LOGO_MARKER", &png_data_uri(LOGO_MARK_PNG)),
);
html.push_str("</style>\n</head>\n<body>\n");
// 1. Cover Page
@@ -562,11 +566,16 @@ impl ExecutiveReport {
let emitted_date = self.emitted_at.format("%d/%m/%Y %H:%M UTC").to_string();
let logo = logo_data_uri();
let s = &self.scope_summary;
html.push_str("<div class=\"cover\">\n");
html.push_str(&self.cover_radar_svg());
html.push_str(" <div class=\"cover-glow\"></div>\n");
html.push_str(" <img class=\"cover-hero\" src=\"");
html.push_str(&logo);
html.push_str("\" alt=\"Harpia\">\n");
html.push_str(" <div class=\"cover-top\">\n");
html.push_str(" <div class=\"cover-brand\"><img class=\"cover-logo\" src=\"");
html.push_str(&logo_data_uri());
html.push_str("\" alt=\"\">XEXÉU</div>\n");
html.push_str(" <div class=\"cover-brand\">HARPIA</div>\n");
html.push_str(" <div class=\"cover-badges\">\n");
html.push_str(&format!(
" <div class=\"cover-tlp\" style=\"color:{0};border-color:{0}\">{1}</div>\n",
@@ -577,7 +586,7 @@ impl ExecutiveReport {
html.push_str(" </div>\n");
html.push_str(" </div>\n");
html.push_str(
" <div class=\"cover-eyebrow\">CIBERFAUNA · AUDITORIA CONTÍNUA DE SEGURANÇA</div>\n",
" <div class=\"cover-eyebrow\">CIBERFAUNA · AUDITORIA CONTÍNUA DE SUPERFÍCIE DE ATAQUE</div>\n",
);
html.push_str(" <h1 class=\"cover-title\">");
html.push_str(&html_escape(&self.title));
@@ -586,25 +595,20 @@ impl ExecutiveReport {
html.push_str(&html_escape(&self.subtitle));
html.push_str("</div>\n");
// Cover verdict / severity cards
// Headline numbers strip
html.push_str(" <div class=\"cover-cards\">\n");
html.push_str(&format!(
" <div class=\"cover-card sev-crit\"><span class=\"cc-num\">{}</span><span class=\"cc-lbl\">Críticos (9.0+)</span></div>\n",
self.scope_summary.critical_count
));
html.push_str(&format!(
" <div class=\"cover-card sev-high\"><span class=\"cc-num\">{}</span><span class=\"cc-lbl\">Altos (7.0–8.9)</span></div>\n",
self.scope_summary.high_count
));
html.push_str(&format!(
" <div class=\"cover-card sev-kev\"><span class=\"cc-num\">{}</span><span class=\"cc-lbl\">No CISA KEV</span></div>\n",
self.scope_summary.kev_count
));
html.push_str(&format!(
" <div class=\"cover-card sev-max\"><span class=\"cc-num\">{}</span><span class=\"cc-lbl\">Maior CVSS</span></div>\n",
max_cvss_display
));
for (cls, num, lbl) in [
("sev-crit", s.critical_count.to_string(), "Críticos (9.0+)"),
("sev-high", s.high_count.to_string(), "Altos (7.0 a 8.9)"),
("sev-kev", s.kev_count.to_string(), "No CISA KEV"),
("sev-max", max_cvss_display.clone(), "Maior CVSS"),
] {
html.push_str(&format!(
" <div class=\"cover-card {cls}\"><span class=\"cc-num\">{num}</span><span class=\"cc-lbl\">{lbl}</span></div>\n"
));
}
html.push_str(" </div>\n");
html.push_str(" <p class=\"cover-mark-cap\">Radar: cada ponto é um achado do relatório; quanto mais perto do centro, mais grave. Âmbar com halo: presente no CISA KEV.</p>\n");
// Cover meta footer
html.push_str(" <div class=\"cover-meta\">\n");
@@ -614,12 +618,13 @@ impl ExecutiveReport {
html.push_str(&emitted_date);
html.push_str("</span></div>\n");
html.push_str(&format!(
" <div class=\"cm-col\"><span class=\"cm-dt\">Escopo</span><span class=\"cm-dd\">{} hosts · {} portas</span></div>\n",
self.scope_summary.active_hosts_count, self.scope_summary.open_ports_count
" <div class=\"cm-col\"><span class=\"cm-dt\">Escopo</span><span class=\"cm-dd\">{} · {}</span></div>\n",
plural(s.active_hosts_count, "host", "hosts"),
plural(s.open_ports_count, "porta", "portas")
));
html.push_str(&format!(
" <div class=\"cm-col\"><span class=\"cm-dt\">Achados</span><span class=\"cm-dd\">{} vulnerabilidades</span></div>\n",
self.scope_summary.total_findings_count
s.total_findings_count
));
html.push_str(" <div class=\"cm-col\"><span class=\"cm-dt\">Classificação</span><span class=\"cm-dd\">Restrito / Interno</span></div>\n");
html.push_str(" </div>\n");
@@ -827,6 +832,88 @@ impl ExecutiveReport {
}
}
impl ExecutiveReport {
/// Data-driven radar motif for the cover: one dot per finding listed in the
/// findings table, nearer the center (the logo) means a higher CVSS, KEV
/// entries are amber with a halo. Coordinates are in millimetres (A4).
fn cover_radar_svg(&self) -> String {
let (cx, cy) = (140.0_f64, 158.0_f64);
let radii = [70.0, 82.0, 94.0, 106.0, 118.0];
let mut svg = String::with_capacity(8 * 1024);
svg.push_str(" <svg class=\"cover-radar\" viewBox=\"0 0 210 297\" preserveAspectRatio=\"none\" aria-hidden=\"true\">\n");
svg.push_str(" <defs><linearGradient id=\"sweep\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0\" stop-color=\"#38bdf8\" stop-opacity=\"0\"/><stop offset=\"1\" stop-color=\"#38bdf8\" stop-opacity=\"0.16\"/></linearGradient></defs>\n");
let (sr, sa) = (radii[4], -2.35_f64);
svg.push_str(&format!(
" <path d=\"M {cx} {cy} L {:.1} {:.1} A {sr} {sr} 0 0 1 {:.1} {:.1} Z\" fill=\"url(#sweep)\"/>\n",
cx + sr * (sa - 0.5).cos(), cy + sr * (sa - 0.5).sin(),
cx + sr * sa.cos(), cy + sr * sa.sin()
));
svg.push_str(&format!(" <line x1=\"0\" x2=\"210\" y1=\"{cy}\" y2=\"{cy}\" stroke=\"#38bdf8\" stroke-opacity=\"0.12\" stroke-width=\"0.25\"/>\n"));
svg.push_str(&format!(" <line x1=\"{cx}\" x2=\"{cx}\" y1=\"20\" y2=\"297\" stroke=\"#38bdf8\" stroke-opacity=\"0.12\" stroke-width=\"0.25\"/>\n"));
for (i, r) in radii.iter().enumerate() {
let dash = if i % 2 == 1 {
" stroke-dasharray=\"0.6 1.8\""
} else {
""
};
svg.push_str(&format!(
" <circle cx=\"{cx}\" cy=\"{cy}\" r=\"{r}\" fill=\"none\" stroke=\"#38bdf8\" stroke-opacity=\"{:.2}\" stroke-width=\"0.3\"{dash}/>\n",
0.34 - i as f64 * 0.05
));
}
let rows = self.sections.iter().find_map(|sec| match sec {
ReportSection::Table { id, rows, .. } if id == "achados-criticos" => Some(rows),
_ => None,
});
if let Some(rows) = rows {
for (i, row) in rows.iter().enumerate() {
let cvss: f64 = row.get(2).and_then(|c| c.parse().ok()).unwrap_or(0.0);
let kev = row.get(3).map(|c| c == "SIM").unwrap_or(false);
let (ring, color) = if cvss >= 9.0 {
(0, "#fb7185")
} else if cvss >= 7.0 {
(1, "#fb923c")
} else if cvss >= 4.0 {
(2, "#facc15")
} else {
(3, "#38bdf8")
};
let color = if kev { "#fbbf24" } else { color };
// Golden-angle spread, skipping spots that would sit under the
// title block, the caption, the number strip or off the page.
let r = radii[ring] + if i % 2 == 1 { 5.0 } else { 0.0 };
let free = |x: f64, y: f64| {
(6.0..204.0).contains(&x)
&& (108.0..232.0).contains(&y)
&& !(x < 88.0 && y > 212.0)
};
let mut deg = i as f64 * 137.508 + ring as f64 * 31.0;
let (mut x, mut y) = (cx, cy);
for _ in 0..64 {
let a = deg.to_radians();
(x, y) = (cx + r * a.cos(), cy - r * a.sin());
if free(x, y) {
break;
}
deg += 23.7;
}
svg.push_str(&format!(
" <line x1=\"{cx}\" y1=\"{cy}\" x2=\"{x:.1}\" y2=\"{y:.1}\" stroke=\"{color}\" stroke-opacity=\"0.10\" stroke-width=\"0.25\"/>\n"
));
if kev {
svg.push_str(&format!(" <circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"3.4\" fill=\"none\" stroke=\"{color}\" stroke-opacity=\"0.7\" stroke-width=\"0.35\"/>\n"));
}
svg.push_str(&format!(" <circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"2.2\" fill=\"{color}\" fill-opacity=\"0.18\"/>\n"));
svg.push_str(&format!(
" <circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"1.05\" fill=\"{color}\"/>\n"
));
}
}
svg.push_str(" </svg>\n");
svg
}
}
/// The Harpia logo, embedded so the report renders identically whether it's
/// viewed live from `/relatorio` or saved as a standalone offline HTML file
/// (same reasoning as `Sabiá/crates/sabia-core/src/report.rs`, which this
@@ -836,11 +923,20 @@ const LOGO_PNG: &[u8] = include_bytes!("../../../logo.png");
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Encodes `bytes` as a `data:image/png;base64,...` URI.
/// Encodes the full-size logo as a `data:image/png;base64,...` URI (cover only).
fn logo_data_uri() -> String {
let mut out = String::with_capacity(LOGO_PNG.len().div_ceil(3) * 4 + 22);
png_data_uri(LOGO_PNG)
}
/// 128 px copy of the logo for the running header of the inner pages, so the
/// full-size PNG is embedded only once (on the cover).
const LOGO_MARK_PNG: &[u8] = include_bytes!("../assets/logo-mark.png");
/// Encodes PNG `bytes` as a `data:image/png;base64,...` URI.
fn png_data_uri(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4 + 22);
out.push_str("data:image/png;base64,");
for chunk in LOGO_PNG.chunks(3) {
for chunk in bytes.chunks(3) {
let b0 = chunk[0];
let b1 = chunk.get(1).copied();
let b2 = chunk.get(2).copied();
@@ -858,6 +954,10 @@ fn logo_data_uri() -> String {
out
}
fn plural(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
fn html_escape(raw: &str) -> String {
raw.replace('&', "&amp;")
.replace('<', "&lt;")
@@ -884,7 +984,7 @@ fn format_markdown_bold(raw: &str) -> String {
const REPORT_CSS: &str = r#"
:root {
--primary: #0369a1;
--primary: #0284c7;
--primary-deep: #0c4a6e;
--primary-dark: #072738;
--accent: #38bdf8;
@@ -902,8 +1002,8 @@ const REPORT_CSS: &str = r#"
--med-bg: #fefce8;
--low: #0284c7;
--low-bg: #f0f9ff;
--font-sans: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--font-mono: 'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--font-sans: system-ui, 'Inter', 'Segoe UI', Roboto, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--font-mono: ui-monospace, 'JetBrains Mono', 'IBM Plex Mono', SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
* { box-sizing: border-box; }
@@ -920,26 +1020,37 @@ body {
margin: 24mm 16mm 22mm 16mm;
background: #ffffff;
@top-left {
content: "Harpia · Auditoria Contínua de Segurança";
font-family: var(--font-sans);
font-size: 7.5pt;
content: "";
background: url("HARPIA_REPORT_LOGO_MARKER") no-repeat left bottom / 8mm 8mm;
vertical-align: bottom;
padding-bottom: 3mm;
width: 30mm;
}
@top-center {
content: "HARPIA · RELATÓRIO EXECUTIVO";
font-family: var(--font-mono);
font-size: 6.8pt;
font-weight: 600;
letter-spacing: 0.16em;
color: var(--muted);
vertical-align: bottom;
padding-bottom: 4mm;
padding-bottom: 4.5mm;
}
@top-right {
content: "HARPIA_REPORT_TLP_MARKER · USO AUTORIZADO";
font-family: var(--font-mono);
font-size: 7pt;
font-size: 6.8pt;
font-weight: 700;
letter-spacing: 0.1em;
color: var(--primary);
color: #b45309;
white-space: nowrap;
width: 55mm;
text-align: right;
vertical-align: bottom;
padding-bottom: 4mm;
padding-bottom: 4.5mm;
}
@bottom-left {
content: "Ciberfauna · Inteligência Defensiva e Ofensiva Contínua";
content: "Ciberfauna · Harpia · Auditoria Contínua de Superfície de Ataque";
font-family: var(--font-sans);
font-size: 7.5pt;
color: var(--faint);
@@ -959,8 +1070,9 @@ body {
@page cover {
margin: 0;
background: var(--primary-dark);
@top-left { content: none; }
background: #03101c;
@top-left { content: none; background: none; }
@top-center { content: none; }
@top-right { content: none; }
@bottom-left { content: none; }
@bottom-right { content: none; }
@@ -972,138 +1084,164 @@ body {
break-after: page;
height: 297mm;
width: 210mm;
padding: 24mm 20mm;
display: flex;
flex-direction: column;
justify-content: space-between;
background: linear-gradient(170deg, #072738 0%, #03141f 100%);
background:
radial-gradient(120mm 120mm at 140mm 158mm, #0b3352 0%, rgba(11, 51, 82, 0) 70%),
linear-gradient(165deg, #06213a 0%, #041628 45%, #020b15 100%);
color: #ffffff;
overflow: hidden;
position: relative;
}
.cover-radar {
position: absolute;
inset: 0;
width: 210mm;
height: 297mm;
}
.cover-glow {
position: absolute;
left: 50mm;
top: 68mm;
width: 180mm;
height: 180mm;
border-radius: 50%;
background: radial-gradient(circle, rgba(249, 115, 22, 0.40) 0%, rgba(251, 146, 60, 0.16) 38%, rgba(251, 146, 60, 0) 68%);
}
.cover-hero {
position: absolute;
left: 76mm;
top: 94mm;
width: 128mm;
height: 128mm;
object-fit: contain;
filter: drop-shadow(0 0 6mm rgba(249, 115, 22, 0.35));
}
.cover-top {
position: absolute;
left: 18mm;
right: 18mm;
top: 16mm;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(56, 189, 248, 0.25);
padding-bottom: 5mm;
border-bottom: 1px solid rgba(56, 189, 248, 0.22);
padding-bottom: 4mm;
}
.cover-brand {
display: flex;
align-items: center;
gap: 3mm;
font-family: var(--font-mono);
font-size: 16pt;
font-size: 11pt;
font-weight: 800;
letter-spacing: 0.18em;
color: var(--accent);
letter-spacing: 0.42em;
color: #e0f2fe;
}
.cover-logo {
width: 9mm;
height: 9mm;
object-fit: contain;
}
.cover-badges {
display: flex;
align-items: center;
gap: 2.5mm;
}
.cover-tlp {
.cover-badges { display: flex; align-items: center; gap: 2.5mm; }
.cover-tlp, .cover-classification {
font-family: var(--font-mono);
font-size: 8pt;
font-weight: 800;
letter-spacing: 0.1em;
border: 1.5px solid;
padding: 2px 8px;
border-radius: 4px;
}
.cover-classification {
font-family: var(--font-mono);
font-size: 8pt;
font-size: 7.5pt;
font-weight: 700;
letter-spacing: 0.12em;
color: #fbbf24;
border: 1px solid #fbbf24;
padding: 2px 8px;
border-radius: 4px;
letter-spacing: 0.16em;
border: 1px solid;
padding: 3px 8px;
border-radius: 2px;
}
.cover-classification { color: #cbd5e1; border-color: rgba(203, 213, 225, 0.5); }
.cover-eyebrow, .cover-title, .cover-subtitle { position: relative; margin-left: 18mm; }
.cover-eyebrow {
font-family: var(--font-mono);
font-size: 8pt;
font-weight: 700;
letter-spacing: 0.2em;
font-size: 7.5pt;
font-weight: 600;
letter-spacing: 0.22em;
text-transform: uppercase;
color: var(--accent);
margin-top: 25mm;
color: #38bdf8;
padding-top: 40mm;
}
.cover-title {
font-size: 32pt;
font-size: 38pt;
font-weight: 800;
line-height: 1.1;
letter-spacing: -0.02em;
margin: 4mm 0 3mm;
line-height: 1.02;
letter-spacing: -0.025em;
margin-top: 5mm;
margin-bottom: 0;
max-width: 150mm;
color: #ffffff;
}
.cover-subtitle {
font-size: 11pt;
line-height: 1.5;
color: #cbd5e1;
max-width: 150mm;
margin-bottom: 12mm;
line-height: 1.55;
color: #b9d3e6;
max-width: 100mm;
margin-top: 6mm;
}
.cover-cards {
position: absolute;
left: 18mm;
right: 18mm;
bottom: 40mm;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 3.5mm;
margin: 6mm 0 16mm;
gap: 4mm;
}
.cover-card {
padding: 4mm 3mm;
border-radius: 6px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.12);
padding: 3mm 3.5mm;
background: rgba(3, 16, 28, 0.72);
border-top: 3px solid var(--accent);
display: flex;
flex-direction: column;
gap: 1.5mm;
}
.cover-card.sev-crit { border-left: 3.5px solid var(--crit); }
.cover-card.sev-high { border-left: 3.5px solid var(--high); }
.cover-card.sev-kev { border-left: 3.5px solid #fbbf24; }
.cover-card.sev-max { border-left: 3.5px solid var(--accent); }
.cover-card.sev-crit { border-top-color: #fb7185; }
.cover-card.sev-high { border-top-color: #fb923c; }
.cover-card.sev-kev { border-top-color: #fbbf24; }
.cover-card.sev-max { border-top-color: #38bdf8; }
.cc-num {
font-family: var(--font-mono);
font-size: 18pt;
font-size: 20pt;
font-weight: 800;
color: #ffffff;
line-height: 1;
}
.cc-lbl {
font-size: 7.5pt;
font-family: var(--font-mono);
font-size: 6.6pt;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.1em;
color: #8fb3cc;
}
.cover-mark-cap {
position: absolute;
left: 18mm;
bottom: 64mm;
width: 64mm;
margin: 0;
font: 400 6.5pt/1.5 var(--font-mono);
letter-spacing: 0.06em;
color: #94a3b8;
text-transform: uppercase;
color: #6f93ad;
}
.cover-meta {
position: absolute;
left: 18mm;
right: 18mm;
bottom: 14mm;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4mm;
border-top: 1px solid rgba(255, 255, 255, 0.16);
padding-top: 5mm;
gap: 6mm;
border-top: 1px solid rgba(255, 255, 255, 0.18);
padding-top: 4.5mm;
}
.cm-col { display: flex; flex-direction: column; gap: 1mm; }
.cm-dt {
font-family: var(--font-mono);
font-size: 6.8pt;
font-weight: 700;
letter-spacing: 0.12em;
font-size: 6.6pt;
font-weight: 600;
letter-spacing: 0.16em;
text-transform: uppercase;
color: #64748b;
color: #6f93ad;
}
.cm-dd {
font-size: 8.5pt;
font-weight: 600;
color: #e2e8f0;
font-size: 9pt;
font-weight: 500;
color: #ffffff;
}
/* CHAPTER / PAGE BREAKS */
@@ -1478,9 +1616,14 @@ alvos = ["10.0.0.1/32"]
}
let html = report.render_html();
assert!(html.contains("Relatório Executivo de Segurança — Harpia"));
assert!(html.contains("Relatório Executivo de Segurança: Harpia"));
assert!(html.contains("CVE-2024-CRIT"));
assert!(html.contains("Execução remota crítica"));
assert!(html.contains("paged.polyfill.js"));
// Cover: hero logo, radar with one dot per listed finding, KEV ring.
assert!(html.contains("class=\"cover-hero\" src=\"data:image/png;base64,"));
assert!(html.contains("AUDITORIA CONTÍNUA DE SUPERFÍCIE DE ATAQUE"));
assert_eq!(html.matches("r=\"1.05\"").count(), 3);
assert_eq!(html.matches("r=\"3.4\"").count(), 1);
}
}
+10 -10
View File
@@ -14,9 +14,9 @@ an unprivileged analytical server (`harpia`), sharing one binary and one
|---|---|---|
| Core engine & CLI | Rust 2021 (MSRV 1.88) | Memory safety, native networking performance, single binary deployment. |
| API layer | Axum + Tokio | Asynchronous HTTP service with minimal overhead. |
| Web dashboard | Vanilla HTML/CSS/JS | Zero-dependency frontend embedded directly into the binary via `include_str!`/`include_bytes!` — no `rust-embed`, no build step. |
| Raw-socket engine | `socket2`, hand-built TCP headers | A single `SOCK_RAW`/`IPPROTO_TCP` socket for both sending SYN probes and receiving replies — see [Scan engine](#scan-engine) below. |
| Storage engine | SQLite (`rusqlite`, bundled) + Parquet | Embedded, zero-ops storage. **Not DuckDB**: an early design draft specified DuckDB for its analytical query strengths, but SQLite was chosen instead for v1.0 — no external `libduckdb.so` to link or ship, one less moving part, and the query patterns `harpia serve` actually needs (point lookups by asset key, small aggregate counts) don't benefit from a columnar engine. Sweep batches themselves stay in Parquet (immutable, one file per sweep, not touched by this choice). |
| Web dashboard | Vanilla HTML/CSS/JS | Zero-dependency frontend embedded directly into the binary via `include_str!`/`include_bytes!`, no `rust-embed`, no build step. |
| Raw-socket engine | `socket2`, hand-built TCP headers | A single `SOCK_RAW`/`IPPROTO_TCP` socket for both sending SYN probes and receiving replies, see [Scan engine](#scan-engine) below. |
| Storage engine | SQLite (`rusqlite`, bundled) + Parquet | Embedded, zero-ops storage. **Not DuckDB**: an early design draft specified DuckDB for its analytical query strengths, but SQLite was chosen instead for v1.0: no external `libduckdb.so` to link or ship, one less moving part, and the query patterns `harpia serve` actually needs (point lookups by asset key, small aggregate counts) don't benefit from a columnar engine. Sweep batches themselves stay in Parquet (immutable, one file per sweep, not touched by this choice). |
| Deployment | Docker Compose | Strict privilege isolation, container hardening, immutable batches over named volumes. |
## System topology & data flow
@@ -41,7 +41,7 @@ scanner (NET_RAW, host net, uid 0) harpia (uid 10001, zero capabilities)
- **`scanner`:** emits raw network packets to discover hosts and scan ports,
and writes sweep batches. It requires `network_mode: host` and
`cap_add: [NET_RAW]` (hence `user: "0:0"` — see
`cap_add: [NET_RAW]` (hence `user: "0:0"`, see
[`docker.md`](docker.md#why-scanner-runs-as-uid-0-restricted-to-net_raw)
for why Docker makes that necessary), but drops every other capability
(`cap_drop: [ALL]`), runs with a read-only root filesystem, and only
@@ -61,7 +61,7 @@ either can feed the rest of the pipeline unchanged:
- **`nativo` (raw SYN, `scan::syn_scan`):** one `SOCK_RAW`/`IPPROTO_TCP`
socket per scan, used for both sending and receiving. On Linux, such a
socket needs no `IP_HDRINCL` to send — the kernel fills in the IP header,
socket needs no `IP_HDRINCL` to send; the kernel fills in the IP header,
so each probe is just a hand-built 20-byte TCP segment (SYN flag, correct
checksum over the IPv4 pseudo-header). On receive, the kernel does the
opposite and hands back the full IP+TCP packet, so replies are parsed by
@@ -76,7 +76,7 @@ either can feed the rest of the pipeline unchanged:
`execute_scan_for_group` in `harpia-cli` picks `nativo` whenever a profile
asks for it **and** `CAP_NET_RAW` is actually usable, and falls back to
`nativo-sem-raw` with a logged warning otherwise — the engine that actually
`nativo-sem-raw` with a logged warning otherwise, the engine that actually
ran, not the one requested, is what gets recorded in the sweep manifest, so
an operator reading `/api/status` or a manifest never has to guess.
@@ -94,7 +94,7 @@ filesystem batches, never a network call between the two containers:
### 4. Tiered scheduling & scope boundaries
Target configuration in `harpia.toml` decouples asset definitions from
execution policy — see [`configuration.md`](configuration.md) for the full
execution policy, see [`configuration.md`](configuration.md) for the full
reference:
- **`[escopo]`:** mandatory boundary. Any target or DNS resolution outside
@@ -118,7 +118,7 @@ covered:
- **Scoped diff algorithm:** ports outside a group's scanned profile are
never marked closed by that group's sweep.
- **Oscillation debounce:** a host needs `ausencias_para_sumir` consecutive
missed sweeps before `host_sumiu` fires — one dropped sweep never reads as
missed sweeps before `host_sumiu` fires; one dropped sweep never reads as
a disappearance.
- **Event log:** append-only log of `host_novo`, `porta_aberta`,
`servico_alterado`, `vulnerabilidade_nova`, `vulnerabilidade_corrigida`
@@ -130,7 +130,7 @@ covered:
raw SSH banner, TLS certificate). `vuln::matcher` turns that into a
candidate CPE and matches it against the local CVE/KEV database
(`vuln::feeds`), producing `Finding`s with a CVSS score, KEV status and a
confidence level (`alta`/`média`/`baixa` — lower when a distro backport is
confidence level (`alta`/`média`/`baixa`, lower when a distro backport is
suspected, since a backported security fix can leave an old-looking version
string on an actually-patched package). `vuln::checks` adds a small set of
safe, non-intrusive configuration checks (expired/soon-to-expire TLS
@@ -140,7 +140,7 @@ matching.
### 7. Determinism
Every documented source of variation in a result is explicit, not
incidental — the opposite of the intermittent flakiness traditional `nmap`
incidental, the opposite of the intermittent flakiness traditional `nmap`
runs are known for: timeouts and network congestion are the *only*
documented sources of run-to-run difference (a dropped packet reads as
`Filtered`, never as a silently different `Open`/`Closed` verdict), results
+9 -9
View File
@@ -44,7 +44,7 @@ scanner that stopped.
## `harpia scanner`
Runs the continuous scheduler and scan engine, writing sweep batches —
Runs the continuous scheduler and scan engine, writing sweep batches,
never exits on its own, same lifecycle as a daemon.
```
@@ -58,12 +58,12 @@ Options:
Picks the `nativo` (raw SYN) engine whenever a profile asks for it and
`CAP_NET_RAW` is actually usable, falling back to `nativo-sem-raw`
automatically otherwise — see [`architecture.md`](architecture.md#2-scan-engine).
automatically otherwise, see [`architecture.md`](architecture.md#2-scan-engine).
This is the `scanner` Compose service's entrypoint.
## `harpia scan --group <name> --once`
Runs a single sweep for one group, for diagnostics — writes a batch exactly
Runs a single sweep for one group, for diagnostics; it writes a batch exactly
like `scanner` would, then exits.
```
@@ -93,7 +93,7 @@ Options:
--config <CONFIG> [default: config/harpia.toml]
```
Exits non-zero on an invalid configuration — safe to use in a pre-push hook
Exits non-zero on an invalid configuration, safe to use in a pre-push hook
or CI step, which is exactly what `scripts/check.sh` does.
## `harpia feeds sync` / `harpia feeds import`
@@ -108,7 +108,7 @@ Commands:
```bash
# Live, one-shot sync (also happens automatically inside `serve` if
# padrao.feeds.sincronizar_automaticamente = true — see configuration.md)
# padrao.feeds.sincronizar_automaticamente = true: see configuration.md)
harpia feeds sync --config config/harpia.toml --data-dir data/harpia
# Offline, for air-gapped networks
@@ -118,7 +118,7 @@ harpia feeds import ./nvd-dump --data-dir data/harpia
## `harpia changes --since <duration>`
Prints diff events (new/gone host, new/closed port, new/fixed
vulnerability) from the local state — the same data `/api/changes` serves.
vulnerability) from the local state, the same data `/api/changes` serves.
```bash
harpia changes --since 24h --data-dir data/harpia
@@ -126,7 +126,7 @@ harpia changes --since 24h --data-dir data/harpia
## `harpia export --format json|csv`
Exports the current deduplicated state (hosts, ports, findings) — shares
Exports the current deduplicated state (hosts, ports, findings), shares
its formatting logic with the `/api/export/*.csv` and `/api/hosts`
endpoints, so a terminal export and a dashboard download never drift apart.
@@ -146,7 +146,7 @@ harpia export --format json --data-dir data/harpia # prints to stdout
## `harpia doctor [--json]`
Diagnoses the runtime environment — run this first when something looks
Diagnoses the runtime environment; run this first when something looks
wrong, and always before reporting an issue (see
[`support.md`](support.md)).
@@ -177,7 +177,7 @@ Resultado: OK
Exits `1` if any critical item (`config`, a missing database it needs to
write to) failed; a missing/stale vulnerability database or absent
`CAP_NET_RAW` are reported but don't fail the exit code — both have a
`CAP_NET_RAW` are reported but don't fail the exit code; both have a
documented degraded path (see [`architecture.md`](architecture.md)).
`--json` is meant for scripted health checks and monitoring, not for
humans at a terminal.
+15 -15
View File
@@ -5,7 +5,7 @@
Harpia is configured by a single TOML file, by default `config/harpia.toml`
(override with `--config` on every command). `harpia config check --config
<path>` validates it and prints, per group, the address count, effective
cron and cadence overlaps — run it after every edit, before restarting
cron and cadence overlaps; run it after every edit, before restarting
`serve`/`scanner`.
## Shape of the file
@@ -44,50 +44,50 @@ See [`examples/harpia.toml`](../examples/harpia.toml) for a fully commented
reference covering a corporate network, a DMZ and a core/critical tier with
two cadences (a light 5-minute check and a full 03:00 sweep).
### `[escopo]` — authorized scope (hard limit)
### `[escopo]`: authorized scope (hard limit)
- `autorizado`: list of CIDR ranges every expanded target must fall inside.
A target outside it — including a DNS name that resolves outside it —
A target outside it (including a DNS name that resolves outside it)
is rejected (`config check` fails for static targets; a name is skipped
for that sweep and logged as `alvo_fora_do_escopo` if it only drifts at
resolution time).
- `responsavel`: free-text contact, shown in reports; not validated.
### `[padrao]` — defaults inherited by every group
### `[padrao]`: defaults inherited by every group
- `cron`: 5-field cron expression or a shortcut (`@hourly`, `@daily`,
`@weekly`, `@monthly`). Any group without its own `cron` uses this one.
- `jitter`: percentage of the interval to the next run, applied as a
deterministic (not random) offset — see [`architecture.md`](architecture.md)
deterministic (not random) offset, see [`architecture.md`](architecture.md)
for why.
- `perfil`: which `[perfis.*]` table a group uses when it doesn't set its own.
- `taxa_maxima_pps` / `hosts_simultaneos`: shared rate budget across the
whole scanner process, not per group.
- `ausencias_para_sumir`: consecutive missed sweeps before a host is marked
gone (`host_sumiu`) — protects against a single dropped sweep producing a
gone (`host_sumiu`); this protects against a single dropped sweep producing a
false "host disappeared" event.
- `[padrao.feeds]`: `sincronizar_automaticamente` (bool, default `false`) and
`intervalo_sincronizacao` (default `"24h"`) control the background CVE/KEV
refresh inside `harpia serve` — see [Vulnerability feeds](#vulnerability-feeds) below.
refresh inside `harpia serve`, see [Vulnerability feeds](#vulnerability-feeds) below.
### `[perfis.<nome>]` — port and engine profiles
### `[perfis.<nome>]`: port and engine profiles
- `tcp`: `"top-1000"`, a range (`"1-65535"`), or an explicit list
(`"22,80,443"`).
- `udp`: list of UDP ports to probe (string list).
- `motor`: `"nativo"` (tries the raw-socket SYN engine, falls back to
`nativo-sem-raw` automatically if `CAP_NET_RAW` isn't available — see
`nativo-sem-raw` automatically if `CAP_NET_RAW` isn't available, see
[`docker.md`](docker.md)) or `"nmap"` (requires the `harpia-scanner-nmap`
image variant).
- `vulnerabilidades`: whether CVE/KEV correlation and the safe config checks
(expired TLS cert, unencrypted admin port) run for this profile's findings.
### `[[grupo]]` — target groups
### `[[grupo]]`: target groups
Each `[[grupo]]` block is a named network with its own targets and,
optionally, its own cron/profile/criticality:
- `nome`: unique name (also the asset-identity namespace — see
- `nome`: unique name (also the asset-identity namespace, see
[`architecture.md`](architecture.md)).
- `alvos`: list of CIDR ranges, single IPs, ranges (`"10.0.1.10-10.0.1.20"`)
or DNS names (re-resolved every sweep).
@@ -95,14 +95,14 @@ optionally, its own cron/profile/criticality:
names).
- `cron` / `perfil` / `criticidade`: override the defaults for this group
only. `criticidade` is informational (shown in the dashboard/report), it
does not change scheduling by itself — the cron does.
does not change scheduling by itself; the cron does.
A host can belong to more than one group (e.g. a narrow high-frequency group
and a broad daily one covering the same address). The storage layer
deduplicates by asset identity, and `config check` lists the overlap with
each host's effective (shortest) cadence.
### `[[webhook]]` — change alerts
### `[[webhook]]`: change alerts
After each ingested sweep, `harpia serve` posts the surface changes it found to
every `[[webhook]]` (one request per sweep, only when there is something to
@@ -135,7 +135,7 @@ segredo_env = "HARPIA_WEBHOOK_KEY" # optional HMAC-SHA256 signature
## Editing a group from the dashboard
`harpia serve`'s **Groups** view can create, edit and delete groups without
touching the file by hand (`POST`/`PUT`/`DELETE /api/config/groups`) — every
touching the file by hand (`POST`/`PUT`/`DELETE /api/config/groups`); every
mutation re-runs the same validation as `config check` and persists back to
the TOML file atomically. `harpia scanner`, running as a separate process,
picks up the change on its next tick by comparing the file's mtime; no
@@ -149,6 +149,6 @@ dump and a CISA KEV file with no network access (for air-gapped networks).
and merges them into the existing local database. Setting
`padrao.feeds.sincronizar_automaticamente = true` makes `harpia serve` repeat
that sync on its own, every `intervalo_sincronizacao`, for as long as the
process runs — the CVE database then stays fresh independently of the image
process runs; the CVE database then stays fresh independently of the image
or binary being rebuilt, the same principle Trivy uses for its vulnerability
database.
+4 -4
View File
@@ -25,7 +25,7 @@ scanner (NET_RAW, host net) harpia (no capabilities)
- **`harpia`** never emits traffic at scan targets. It ingests batches
(mounted `:ro`), is SQLite's only writer, serves the API/dashboard, and
makes the only outbound connections the stack has (feed sync, update
check) — both opt-in and both disabled by default.
check), both opt-in and both disabled by default.
## Quick start
@@ -48,7 +48,7 @@ published address.
The raw-socket SYN engine (`nativo`, see [`architecture.md`](architecture.md))
needs `CAP_NET_RAW`. Docker's `cap_add` only grants a capability to a
process that is already root (`uid 0`) inside the container — a non-root
process that is already root (`uid 0`) inside the container; a non-root
user does **not** receive an added capability unless the binary itself
carries it as a *file capability* (`setcap cap_net_raw+ep`), and this image
intentionally doesn't bake that in (a setuid-like file capability is itself
@@ -59,7 +59,7 @@ So the `scanner` service runs as `uid 0` but with **every other** capability
dropped (`cap_drop: [ALL]`, `cap_add: [NET_RAW]` only), a read-only root
filesystem, `tmpfs` for `/tmp`, and `no-new-privileges`. It is still
"root" in the Linux-user sense, but it can do essentially nothing a normal
root process could — no `NET_ADMIN`, no `SYS_ADMIN`, no filesystem writes
root process could, no `NET_ADMIN`, no `SYS_ADMIN`, no filesystem writes
outside the two mounted volumes, nothing privileged except crafting raw TCP
packets.
@@ -73,7 +73,7 @@ If the capability isn't usable for any reason (remapping misconfigured, a
platform that strips it, a profile with `motor = "nativo"` running outside
this compose file at all), `harpia` detects it automatically
(`harpia doctor` reports it, and every sweep manifest records which engine
actually ran) and falls back to `nativo-sem-raw` — never a hard failure.
actually ran) and falls back to `nativo-sem-raw`, never a hard failure.
## Volumes
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 706 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 607 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 537 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 534 KiB

After

Width:  |  Height:  |  Size: 704 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 688 KiB

+8 -6
View File
@@ -3,7 +3,7 @@
# Interface
`harpia serve` embeds a vanilla HTML/CSS/JS dashboard (no build step, no
framework) — the same architectural pattern as Acauã's. It polls the API
framework), the same architectural pattern as Acauã's. It polls the API
every few seconds and never needs a page reload to reflect a new sweep.
## Overview
@@ -36,7 +36,7 @@ searchable, sorted by CVSS by default.
<p align="center"><img src="img/grupos-dark-pt.png" width="900" alt="Harpia groups view: a card per target group with its cron expression and next scheduled run, plus an Add group form for CIDR/host/network targets with a custom cron"></p>
Add, edit and delete target groups (CIDR ranges, single hosts, exclusions,
cron, port profile, criticality) without touching `harpia.toml` by hand —
cron, port profile, criticality) without touching `harpia.toml` by hand,
see [`configuration.md`](configuration.md#editing-a-group-from-the-dashboard)
for how the change reaches the running `scanner`.
@@ -46,11 +46,11 @@ 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="Harpia executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Harpia executive security report cover: the Harpia logo over a radar of findings (nearer the center means more severe), TLP and authorized-use badges, title, headline numbers and the metadata grid"></p>
`GET /relatorio` renders a print-oriented A4 report (cover, table of
contents, KPIs, prioritized findings table, host inventory, glossary),
paginated with Paged.js — open it in a browser and print/"save as PDF" for
paginated with Paged.js; open it in a browser and print/"save as PDF" for
a shareable document. See the dashboard's "Export executive report" link.
## Changes
@@ -62,11 +62,13 @@ fixed vulnerability) from `/api/changes`, the same data `harpia changes
## CSV exports
The Hosts, Findings and Changes views each have an "Export CSV" button that
downloads `/api/export/{hosts,findings,changes}.csv` directly — Portuguese
downloads `/api/export/{hosts,findings,changes}.csv` directly, Portuguese
headers, RFC 4180 quoting, a timestamped filename.
## Settings
Language (PT-BR/English) and theme (light/dark/auto) — the same pattern as
Language (PT-BR/English) and theme (light/dark/auto), the same pattern as
every other Ciberfauna dashboard, including the dark-mode `<select>` fix
documented in the project's own changelog.
The screenshots are regenerated by `scripts/screenshots.sh` (see [CONTRIBUTING.md](../CONTRIBUTING.md)): a synthetic Apache 2.4.25 service on `127.0.0.10`, scanned by Harpia and correlated with the real NVD and CISA KEV feeds. No real data appears.
+10 -10
View File
@@ -14,9 +14,9 @@ privilegiado (`scanner`) e um servidor analítico não privilegiado
|---|---|---|
| Motor principal e CLI | Rust 2021 (MSRV 1.88) | Segurança de memória, performance de rede nativa, implantação em binário único. |
| Camada de API | Axum + Tokio | Serviço HTTP assíncrono com overhead mínimo. |
| Dashboard web | HTML/CSS/JS puro | Frontend sem dependências, embutido direto no binário via `include_str!`/`include_bytes!` — sem `rust-embed`, sem etapa de build. |
| Motor de socket cru | `socket2`, cabeçalhos TCP montados à mão | Um único socket `SOCK_RAW`/`IPPROTO_TCP` tanto pra enviar sondas SYN quanto pra receber respostas — veja [Motor de varredura](#motor-de-varredura) abaixo. |
| Motor de armazenamento | SQLite (`rusqlite`, embutido) + Parquet | Armazenamento embutido, zero operação. **Não é DuckDB**: um rascunho inicial do design especificava DuckDB pelas forças dele em consultas analíticas, mas o SQLite foi escolhido pro v1.0 — sem `libduckdb.so` externo pra linkar ou distribuir, uma peça móvel a menos, e os padrões de consulta que o `harpia serve` realmente precisa (busca pontual por chave de ativo, contagens agregadas pequenas) não se beneficiam de um motor colunar. Os lotes de varredura em si continuam em Parquet (imutáveis, um arquivo por varredura, não afetados por essa escolha). |
| Dashboard web | HTML/CSS/JS puro | Frontend sem dependências, embutido direto no binário via `include_str!`/`include_bytes!`, sem `rust-embed`, sem etapa de build. |
| Motor de socket cru | `socket2`, cabeçalhos TCP montados à mão | Um único socket `SOCK_RAW`/`IPPROTO_TCP` tanto pra enviar sondas SYN quanto pra receber respostas, veja [Motor de varredura](#motor-de-varredura) abaixo. |
| Motor de armazenamento | SQLite (`rusqlite`, embutido) + Parquet | Armazenamento embutido, zero operação. **Não é DuckDB**: um rascunho inicial do design especificava DuckDB pelas forças dele em consultas analíticas, mas o SQLite foi escolhido pro v1.0, sem `libduckdb.so` externo pra linkar ou distribuir, uma peça móvel a menos, e os padrões de consulta que o `harpia serve` realmente precisa (busca pontual por chave de ativo, contagens agregadas pequenas) não se beneficiam de um motor colunar. Os lotes de varredura em si continuam em Parquet (imutáveis, um arquivo por varredura, não afetados por essa escolha). |
| Implantação | Docker Compose | Isolamento estrito de privilégio, hardening de container, lotes imutáveis em volumes nomeados. |
## Topologia do sistema e fluxo de dados
@@ -41,7 +41,7 @@ scanner (NET_RAW, rede do host, uid 0) harpia (uid 10001, zero capabilities)
- **`scanner`:** emite pacotes de rede crus pra descobrir hosts e varrer
portas, e grava lotes de varredura. Precisa de `network_mode: host` e
`cap_add: [NET_RAW]` (por isso `user: "0:0"` — veja
`cap_add: [NET_RAW]` (por isso `user: "0:0"`, veja
[`docker.md`](docker.md#por-que-o-scanner-roda-como-uid-0-restrito-a-net_raw)
pra entender por que o Docker torna isso necessário), mas descarta toda
outra capability (`cap_drop: [ALL]`), roda com sistema de arquivos raiz
@@ -63,7 +63,7 @@ mudança:
- **`nativo` (SYN cru, `scan::syn_scan`):** um socket `SOCK_RAW`/
`IPPROTO_TCP` por varredura, usado tanto pra enviar quanto pra receber.
No Linux, esse socket não precisa de `IP_HDRINCL` pra enviar — o kernel
No Linux, esse socket não precisa de `IP_HDRINCL` pra enviar; o kernel
preenche o cabeçalho IP sozinho, então cada sonda é só um segmento TCP de
20 bytes montado à mão (flag SYN, checksum correto sobre o pseudo-
cabeçalho IPv4). No recebimento, o kernel faz o oposto e devolve o
@@ -79,7 +79,7 @@ mudança:
A função `execute_scan_for_group` em `harpia-cli` escolhe `nativo` sempre
que um perfil pede e `CAP_NET_RAW` está realmente utilizável, e recorre ao
`nativo-sem-raw` com um aviso registrado caso contrário — o motor que
`nativo-sem-raw` com um aviso registrado caso contrário, o motor que
realmente rodou, não o pedido, é o que fica gravado no manifesto do lote,
então um operador lendo `/api/status` ou um manifesto nunca precisa
adivinhar.
@@ -100,7 +100,7 @@ containers:
### 4. Agendamento em níveis e limites de escopo
A configuração de alvos no `harpia.toml` desacopla a definição de ativos da
política de execução — veja [`configuracao.md`](configuracao.md) pra
política de execução, veja [`configuracao.md`](configuracao.md) pra
referência completa:
- **`[escopo]`:** limite obrigatório. Qualquer alvo ou resolução DNS fora
@@ -125,7 +125,7 @@ realmente cobriu:
grupo nunca são marcadas como fechadas por aquela varredura.
- **Amortecimento de oscilação:** um host precisa de
`ausencias_para_sumir` varreduras consecutivas perdidas antes de
`host_sumiu` disparar — uma varredura perdida nunca é lida como um
`host_sumiu` disparar; uma varredura perdida nunca é lida como um
desaparecimento.
- **Log de eventos:** log somente-acréscimo de `host_novo`, `porta_aberta`,
`servico_alterado`, `vulnerabilidade_nova`, `vulnerabilidade_corrigida` e
@@ -137,7 +137,7 @@ O `scan::fingerprint` captura um banner por porta aberta (header `Server`
HTTP, banner SSH cru, certificado TLS). O `vuln::matcher` transforma isso
num CPE candidato e correlaciona contra a base local de CVE/KEV
(`vuln::feeds`), produzindo `Finding`s com score CVSS, status no KEV e um
nível de confiança (`alta`/`média`/`baixa` — menor quando um backport de
nível de confiança (`alta`/`média`/`baixa`, menor quando um backport de
distro é suspeitado, já que uma correção de segurança retroportada pode
deixar uma string de versão com aparência antiga num pacote na verdade já
corrigido). O `vuln::checks` adiciona um conjunto pequeno de checagens de
@@ -148,7 +148,7 @@ independentes da correlação de CVE.
### 7. Determinismo
Toda fonte documentada de variação num resultado é explícita, não
incidental — o oposto da instabilidade intermitente que execuções
incidental, o oposto da instabilidade intermitente que execuções
tradicionais do `nmap` são conhecidas por ter: timeouts e congestionamento
de rede são as **únicas** fontes documentadas de diferença entre
execuções (um pacote perdido vira `Filtrada`, nunca um veredito
+9 -9
View File
@@ -44,7 +44,7 @@ scanner que parou.
## `harpia scanner`
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
Roda o agendador e o motor de varredura contínuos, gravando lotes, nunca
sai sozinho, mesmo ciclo de vida de um daemon.
```
@@ -58,13 +58,13 @@ Options:
Escolhe o motor `nativo` (SYN cru) sempre que um perfil pede e o
`CAP_NET_RAW` está realmente utilizável, recorrendo automaticamente ao
`nativo-sem-raw` caso contrário — veja
`nativo-sem-raw` caso contrário, veja
[`arquitetura.md`](arquitetura.md#2-motor-de-varredura). Esse é o
entrypoint do serviço `scanner` do Compose.
## `harpia scan --group <nome> --once`
Roda uma única varredura de um grupo, pra diagnóstico — grava um lote
Roda uma única varredura de um grupo, pra diagnóstico; grava um lote
exatamente como o `scanner` faria, e sai.
```
@@ -95,7 +95,7 @@ Options:
--config <CONFIG> [default: config/harpia.toml]
```
Sai com código não-zero numa configuração inválida — seguro de usar num
Sai com código não-zero numa configuração inválida, seguro de usar num
hook de pre-push ou passo de CI, que é exatamente o que
`scripts/check.sh` faz.
@@ -111,7 +111,7 @@ Commands:
```bash
# Sync ao vivo, único (também acontece automaticamente dentro do `serve`
# se padrao.feeds.sincronizar_automaticamente = true — veja configuracao.md)
# se padrao.feeds.sincronizar_automaticamente = true: veja configuracao.md)
harpia feeds sync --config config/harpia.toml --data-dir data/harpia
# Offline, pra redes isoladas
@@ -121,7 +121,7 @@ harpia feeds import ./dump-nvd --data-dir data/harpia
## `harpia changes --since <duração>`
Imprime eventos de diff (host novo/sumido, porta nova/fechada,
vulnerabilidade nova/corrigida) do estado local — os mesmos dados que
vulnerabilidade nova/corrigida) do estado local, os mesmos dados que
`/api/changes` serve.
```bash
@@ -130,7 +130,7 @@ harpia changes --since 24h --data-dir data/harpia
## `harpia export --format json|csv`
Exporta o estado atual deduplicado (hosts, portas, achados) —
Exporta o estado atual deduplicado (hosts, portas, achados),
compartilha a lógica de formatação com os endpoints `/api/export/*.csv` e
`/api/hosts`, então uma exportação no terminal e um download pelo
dashboard nunca desalinham.
@@ -151,7 +151,7 @@ harpia export --format json --data-dir data/harpia # imprime no stdout
## `harpia doctor [--json]`
Diagnostica o ambiente de execução — rode isso primeiro quando algo
Diagnostica o ambiente de execução; rode isso primeiro quando algo
parecer errado, e sempre antes de reportar uma issue (veja
[`suporte.md`](suporte.md)).
@@ -182,7 +182,7 @@ Resultado: OK
Sai com `1` se algum item crítico (`config`, um banco ausente que ele
precisa escrever) falhou; uma base de vulnerabilidades ausente/velha ou
`CAP_NET_RAW` ausente são reportados mas não falham o código de saída —
`CAP_NET_RAW` ausente são reportados mas não falham o código de saída;
os dois têm um caminho degradado documentado (veja
[`arquitetura.md`](arquitetura.md)). O `--json` é pensado pra checagens de
saúde automatizadas e monitoramento, não pra humano no terminal.
+15 -15
View File
@@ -6,7 +6,7 @@ A Harpia é configurada por um único arquivo TOML, por padrão
`config/harpia.toml` (troque com `--config` em qualquer comando).
`harpia config check --config <caminho>` valida o arquivo e imprime, por
grupo, a contagem de endereços, o cron efetivo e as sobreposições de
cadência — rode depois de cada edição, antes de reiniciar `serve`/`scanner`.
cadência; rode depois de cada edição, antes de reiniciar `serve`/`scanner`.
## Formato do arquivo
@@ -45,52 +45,52 @@ comentada completa, cobrindo uma rede corporativa, uma DMZ e um núcleo
crítico com duas cadências (checagem leve a cada 5 minutos e varredura
completa às 03:00).
### `[escopo]` — escopo autorizado (limite rígido)
### `[escopo]`: escopo autorizado (limite rígido)
- `autorizado`: faixas CIDR que todo alvo expandido precisa caber dentro.
Um alvo fora disso — inclusive um nome DNS que resolva pra fora — é
Um alvo fora disso (inclusive um nome DNS que resolva pra fora) é
rejeitado (`config check` falha pra alvos estáticos; um nome é pulado
naquela varredura e registrado como `alvo_fora_do_escopo` se só desviar
na hora da resolução).
- `responsavel`: contato livre, aparece nos relatórios; não é validado.
### `[padrao]` — padrões herdados por todo grupo
### `[padrao]`: padrões herdados por todo grupo
- `cron`: expressão cron de 5 campos ou um atalho (`@hourly`, `@daily`,
`@weekly`, `@monthly`). Todo grupo sem `cron` próprio usa este.
- `jitter`: percentual do intervalo até a próxima execução, aplicado como
deslocamento determinístico (não aleatório) — veja
deslocamento determinístico (não aleatório), veja
[`arquitetura.md`](arquitetura.md) pro motivo.
- `perfil`: qual tabela `[perfis.*]` um grupo usa quando não define a sua.
- `taxa_maxima_pps` / `hosts_simultaneos`: orçamento de taxa compartilhado
por todo o processo do scanner, não por grupo.
- `ausencias_para_sumir`: varreduras consecutivas sem resposta antes de um
host ser marcado como sumido (`host_sumiu`) — protege contra uma única
host ser marcado como sumido (`host_sumiu`); isso protege contra uma única
varredura perdida gerar um falso "host sumiu".
- `[padrao.feeds]`: `sincronizar_automaticamente` (bool, padrão `false`) e
`intervalo_sincronizacao` (padrão `"24h"`) controlam a atualização
periódica de CVE/KEV em segundo plano dentro do `harpia serve` — veja
periódica de CVE/KEV em segundo plano dentro do `harpia serve`, veja
[Feeds de vulnerabilidade](#feeds-de-vulnerabilidade) abaixo.
### `[perfis.<nome>]` — perfis de porta e motor
### `[perfis.<nome>]`: perfis de porta e motor
- `tcp`: `"top-1000"`, uma faixa (`"1-65535"`), ou uma lista explícita
(`"22,80,443"`).
- `udp`: lista de portas UDP a sondar (lista de strings).
- `motor`: `"nativo"` (tenta o motor SYN de socket cru, recorrendo
automaticamente a `nativo-sem-raw` se `CAP_NET_RAW` não estiver
disponível — veja [`docker.md`](docker.md)) ou `"nmap"` (exige a variante
disponível, veja [`docker.md`](docker.md)) ou `"nmap"` (exige a variante
de imagem `harpia-scanner-nmap`).
- `vulnerabilidades`: se a correlação de CVE/KEV e as checagens seguras de
configuração (certificado TLS expirado, porta administrativa sem
criptografia) rodam pros achados desse perfil.
### `[[grupo]]` — grupos de alvos
### `[[grupo]]`: grupos de alvos
Cada bloco `[[grupo]]` é uma rede nomeada com seus próprios alvos e,
opcionalmente, seu próprio cron/perfil/criticidade:
- `nome`: nome único (também o namespace de identidade de ativo — veja
- `nome`: nome único (também o namespace de identidade de ativo, veja
[`arquitetura.md`](arquitetura.md)).
- `alvos`: lista de faixas CIDR, IPs isolados, intervalos
(`"10.0.1.10-10.0.1.20"`) ou nomes DNS (resolvidos de novo a cada
@@ -99,14 +99,14 @@ opcionalmente, seu próprio cron/perfil/criticidade:
nomes DNS).
- `cron` / `perfil` / `criticidade`: sobrescrevem os padrões só pra esse
grupo. `criticidade` é informativa (aparece no dashboard/relatório), não
muda o agendamento sozinha — quem faz isso é o cron.
muda o agendamento sozinha; quem faz isso é o cron.
Um host pode pertencer a mais de um grupo (ex: um grupo estreito de alta
frequência e um amplo diário cobrindo o mesmo endereço). A camada de
armazenamento deduplica por identidade de ativo, e `config check` lista a
sobreposição com a cadência efetiva (a mais curta) de cada host.
### `[[webhook]]` — alertas de mudança
### `[[webhook]]`: alertas de mudança
Depois de cada varredura ingerida, o `harpia serve` envia as mudanças de
superfície encontradas para cada `[[webhook]]` (uma requisição por varredura,
@@ -140,7 +140,7 @@ segredo_env = "HARPIA_WEBHOOK_KEY" # assinatura HMAC-SHA256 opcional
## Editando um grupo pelo dashboard
A tela **Grupos** do `harpia serve` cria, edita e remove grupos sem precisar
mexer no arquivo na mão (`POST`/`PUT`/`DELETE /api/config/groups`) — toda
mexer no arquivo na mão (`POST`/`PUT`/`DELETE /api/config/groups`); toda
mutação roda a mesma validação do `config check` e persiste de volta no
TOML de forma atômica. O `harpia scanner`, rodando num processo separado,
pega a mudança no próximo tick comparando o `mtime` do arquivo; não precisa
@@ -154,6 +154,6 @@ isoladas). `harpia feeds sync --config <caminho> --data-dir <caminho>` baixa
os dois ao vivo, uma vez, e funde no banco local existente. Definir
`padrao.feeds.sincronizar_automaticamente = true` faz o `harpia serve`
repetir essa sincronização sozinho, a cada `intervalo_sincronizacao`,
durante toda a vida do processo — o banco de CVEs fica fresco independente
durante toda a vida do processo; o banco de CVEs fica fresco independente
de rebuild de imagem ou binário, o mesmo princípio que o Trivy usa pro
banco de vulnerabilidades dele.
+4 -4
View File
@@ -25,7 +25,7 @@ scanner (NET_RAW, rede do host) harpia (sem capabilities)
- **`harpia`** nunca emite tráfego pros alvos. Ingere lotes (montados
`:ro`), é o único escritor do SQLite, serve a API/dashboard, e faz as
únicas conexões de saída de toda a stack (sync de feeds, checagem de
atualização) — ambas opt-in e desativadas por padrão.
atualização), ambas opt-in e desativadas por padrão.
## Início rápido
@@ -49,7 +49,7 @@ pelo endereço publicado.
O motor de varredura SYN de socket cru (`nativo`, veja
[`arquitetura.md`](arquitetura.md)) precisa de `CAP_NET_RAW`. O `cap_add`
do Docker só concede uma capability a um processo que já seja root
(`uid 0`) dentro do container — um usuário não-root **não** recebe uma
(`uid 0`) dentro do container; um usuário não-root **não** recebe uma
capability adicionada a não ser que o próprio binário a carregue como
*file capability* (`setcap cap_net_raw+ep`), e esta imagem
propositalmente não embute isso (uma file capability é, ela mesma, uma
@@ -61,7 +61,7 @@ Então o serviço `scanner` roda como `uid 0`, mas com **todas as outras**
capabilities descartadas (`cap_drop: [ALL]`, `cap_add: [NET_RAW]` só),
sistema de arquivos raiz somente leitura, `tmpfs` pro `/tmp`, e
`no-new-privileges`. Ele ainda é "root" no sentido de usuário Linux, mas
não consegue praticamente nada que um processo root normal conseguiria —
não consegue praticamente nada que um processo root normal conseguiria,
sem `NET_ADMIN`, sem `SYS_ADMIN`, sem escrita no sistema de arquivos fora
dos dois volumes montados, nada privilegiado além de montar pacotes TCP
crus.
@@ -77,7 +77,7 @@ mal configurado, uma plataforma que remove ela, um perfil com
`motor = "nativo"` rodando fora deste compose de qualquer forma), a Harpia
detecta isso automaticamente (`harpia doctor` reporta, e todo manifesto de
varredura registra qual motor realmente rodou) e recorre ao
`nativo-sem-raw` — nunca uma falha dura.
`nativo-sem-raw`, nunca uma falha dura.
## Volumes
+8 -6
View File
@@ -3,7 +3,7 @@
# Interface
O `harpia serve` embute um dashboard HTML/CSS/JS puro (sem build, sem
framework) — o mesmo padrão arquitetural do Acauã. Ele sonda a API a cada
framework), o mesmo padrão arquitetural do Acauã. Ele sonda a API a cada
poucos segundos e nunca precisa de recarregar a página pra refletir uma
varredura nova.
@@ -39,7 +39,7 @@ ordenado por CVSS por padrão.
Adicione, edite e remova grupos de alvos (faixas CIDR, hosts isolados,
exclusões, cron, perfil de portas, criticidade) sem mexer no
`harpia.toml` na mão — veja
`harpia.toml` na mão, veja
[`configuracao.md`](configuracao.md#editando-um-grupo-pelo-dashboard) pra
como a mudança chega no `scanner` em execução.
@@ -49,11 +49,11 @@ 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 Harpia: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Harpia: o logo da Harpia sobre um radar de achados (mais perto do centro, mais grave), selos TLP e de uso autorizado, título, números principais e a grade de metadados"></p>
`GET /relatorio` renderiza um relatório A4 orientado a impressão (capa,
sumário, KPIs, tabela de achados prioritários, inventário de hosts,
glossário), paginado com Paged.js — abra no navegador e imprima/"salve
glossário), paginado com Paged.js; abra no navegador e imprima/"salve
como PDF" pra um documento compartilhável. Veja o link "Exportar relatório
executivo" no dashboard.
@@ -66,11 +66,13 @@ vulnerabilidade nova/corrigida) de `/api/changes`, os mesmos dados que
## Exportação CSV
As telas de Hosts, Achados e Mudanças têm um botão "Exportar CSV" que
baixa direto `/api/export/{hosts,findings,changes}.csv` — cabeçalhos em
baixa direto `/api/export/{hosts,findings,changes}.csv`, cabeçalhos em
português, aspas RFC 4180, nome de arquivo com timestamp.
## Configurações
Idioma (PT-BR/inglês) e tema (claro/escuro/auto) — o mesmo padrão de todo
Idioma (PT-BR/inglês) e tema (claro/escuro/auto), o mesmo padrão de todo
outro dashboard da Ciberfauna, incluindo a correção do `<select>` no modo
escuro já documentada no changelog do próprio projeto.
As capturas são regeradas por `scripts/screenshots.sh` (veja [CONTRIBUTING.pt-BR.md](../../CONTRIBUTING.pt-BR.md)): um serviço Apache 2.4.25 sintético em `127.0.0.10`, varrido pelo Harpia e correlacionado com os feeds reais da NVD e da CISA KEV. Nenhum dado real aparece.
+4 -4
View File
@@ -14,7 +14,7 @@ Gitea.
3. Rode `harpia config check --config <caminho>` pra descartar um problema
de configuração antes de reportar um de varredura.
4. Revise [`configuracao.md`](configuracao.md), [`arquitetura.md`](arquitetura.md)
e [`docker.md`](docker.md) — principalmente a seção de `CAP_NET_RAW` se
e [`docker.md`](docker.md), principalmente a seção de `CAP_NET_RAW` se
o problema parecer relacionado ao motor de varredura.
## O que incluir
@@ -22,7 +22,7 @@ Gitea.
- SO do host, arquitetura (`uname -m`) e versão/tag da Harpia.
- O `docker-compose.yml` exato (ou a invocação de CLI) usado.
- Logs completos dos containers: `docker compose logs scanner harpia`.
- O `motor` realmente usado na varredura afetada — confira o manifesto do
- O `motor` realmente usado na varredura afetada; confira o manifesto do
lote ou `/api/status`, já que `nativo` recorre silenciosamente a
`nativo-sem-raw` sem `CAP_NET_RAW`, o que muda o que é esperado.
- Um `harpia.toml` redigido (nunca compartilhe faixas de escopo autorizado
@@ -40,9 +40,9 @@ Não inclua detalhes de exploração numa issue pública. Siga o
| Sintoma | O que checar |
|---|---|
| O container `scanner` sai imediatamente | Confirme que `cap_add: [NET_RAW]` e `user: "0:0"` estão definidos — `nativo` sem a capability deveria recorrer ao modo degradado, não travar; um crash é um problema diferente |
| O container `scanner` sai imediatamente | Confirme que `cap_add: [NET_RAW]` e `user: "0:0"` estão definidos; `nativo` sem a capability deveria recorrer ao modo degradado, não travar; um crash é um problema diferente |
| Toda varredura usa `nativo-sem-raw` mesmo com `NET_RAW` concedido | Confira o relatório de capabilities do `harpia doctor`; num host com `--userns-remap`, verifique se o remapeamento mapeia o `uid 0` do container corretamente |
| `serve` fica inacessível de outro host | Vincula em `127.0.0.1:8788` por padrão (`HARPIA_PUBLISH` no `.env`); verifique a configuração do proxy reverso |
| `feeds sync` falha | Verifique conectividade de rede com as APIs do NVD e do CISA KEV; recorra a `feeds import` com um dump baixado manualmente pra redes isoladas |
| Dashboard aparece em português | `Auto` segue o idioma do navegador; selecione inglês nas Configurações |
| Um grupo adicionado pelo dashboard ainda não é varrido | O `scanner` recarrega a config no próximo tick pelo `mtime` do arquivo, não instantaneamente — espere um tick, ou confira os logs dele por um aviso de recarga se a config estava inválida |
| Um grupo adicionado pelo dashboard ainda não é varrido | O `scanner` recarrega a config no próximo tick pelo `mtime` do arquivo, não instantaneamente; espere um tick, ou confira os logs dele por um aviso de recarga se a config estava inválida |
+4 -4
View File
@@ -13,7 +13,7 @@ way to get help is opening an issue in the Gitea repository.
3. Run `harpia config check --config <path>` to rule out a configuration
problem before reporting a scanning one.
4. Review [`configuration.md`](configuration.md), [`architecture.md`](architecture.md)
and [`docker.md`](docker.md) — especially the `CAP_NET_RAW` section if the
and [`docker.md`](docker.md), especially the `CAP_NET_RAW` section if the
issue looks scan-engine related.
## What to include
@@ -21,7 +21,7 @@ way to get help is opening an issue in the Gitea repository.
- Host OS, architecture (`uname -m`) and Harpia version/tag.
- The exact `docker-compose.yml` (or CLI invocation) used.
- Full container logs: `docker compose logs scanner harpia`.
- The `motor` actually used for the affected sweep — check the batch
- The `motor` actually used for the affected sweep, check the batch
manifest or `/api/status`, since `nativo` silently falls back to
`nativo-sem-raw` without `CAP_NET_RAW`, which changes what's expected.
- A redacted `harpia.toml` (never share real authorized-scope ranges or
@@ -39,9 +39,9 @@ Do not include exploit details in a public issue. Follow
| Symptom | What to check |
|---|---|
| `scanner` container exits immediately | Confirm `cap_add: [NET_RAW]` and `user: "0:0"` are both set — `nativo` without the capability should fall back, not crash; a crash means a different problem |
| `scanner` container exits immediately | Confirm `cap_add: [NET_RAW]` and `user: "0:0"` are both set; `nativo` without the capability should fall back, not crash; a crash means a different problem |
| Every sweep uses `nativo-sem-raw` even with `NET_RAW` granted | Check `harpia doctor`'s capability report; on a `--userns-remap` host, verify the remap maps the container's `uid 0` correctly |
| `serve` is unreachable from another host | Binds to `127.0.0.1:8788` by default (`HARPIA_PUBLISH` in `.env`); verify reverse proxy configuration |
| `feeds sync` fails | Check network connectivity to the NVD and CISA KEV APIs; fall back to `feeds import` with a manually downloaded dump for isolated networks |
| Dashboard shows Portuguese | `Auto` follows the browser language; select English in Settings |
| A group added from the dashboard isn't scanned yet | `scanner` reloads the config on its next tick by file `mtime`, not instantly — wait one tick, or check its logs for a reload warning if the config was invalid |
| A group added from the dashboard isn't scanned yet | `scanner` reloads the config on its next tick by file `mtime`, not instantly; wait one tick, or check its logs for a reload warning if the config was invalid |
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Regera as capturas de tela de docs/img a partir da interface real do Harpia.
#
# Dados: um servidor HTTP local que se anuncia como Apache 2.4.25 (nenhum dado de terceiros),
# varrido de verdade por `harpia scan`, correlacionado com os feeds reais NVD (CPE do Apache
# 2.4.25) e CISA KEV. Os feeds são baixados uma vez e ficam em cache.
#
# scripts/screenshots.sh # grava em docs/img
# OUT=/tmp/img scripts/screenshots.sh # grava em outro diretório
#
# Variáveis: HARPIA_BIN (padrão target/release/harpia, compilado se faltar), OUT, APP_PORT
# (porta do serviço sintético, 8080), SERVE_PORT (8788), FEEDS_CACHE, CHROME, PUPPETEER_CORE
# (padrões: Chrome do cache do puppeteer e puppeteer-core em ~/.claude/tools/node_modules).
# Requer: python3, curl, node, Chrome. A primeira execução precisa de internet (NVD/CISA).
set -euo pipefail
root=$(cd "$(dirname "$0")/.." && pwd)
out=${OUT:-$root/docs/img}
app_port=${APP_PORT:-8080}
serve_port=${SERVE_PORT:-8788}
cache=${FEEDS_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/harpia-screenshots}
bin=${HARPIA_BIN:-$root/target/release/harpia}
cpe='cpe:2.3:a:apache:http_server:2.4.25:*:*:*:*:*:*:*'
work=$(mktemp -d)
pids=()
cleanup() { for p in "${pids[@]}"; do kill "$p" 2>/dev/null || true; done; rm -rf "$work"; }
trap cleanup EXIT
[ -x "$bin" ] || (cd "$root" && cargo build --release -p harpia-cli)
# Feeds reais, em cache entre execuções.
mkdir -p "$cache" "$out"
if [ ! -s "$cache/nvd.json" ]; then
echo "baixando CVEs do Apache 2.4.25 (NVD)..."
curl -fsS -m 120 -o "$cache/nvd.json" \
"https://services.nvd.nist.gov/rest/json/cves/2.0?cpeName=${cpe}&resultsPerPage=2000"
fi
if [ ! -s "$cache/kev.json" ]; then
echo "baixando catálogo KEV (CISA)..."
curl -fsS -m 120 -o "$cache/kev.json" \
https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json
fi
mkdir "$work/feeds" && cp "$cache/nvd.json" "$cache/kev.json" "$work/feeds/"
# Serviço sintético que se anuncia como Apache 2.4.25 em 127.0.0.10 (loopback não exige root).
cat > "$work/fake.py" <<PY
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
server_version = "Apache/2.4.25"; sys_version = "(Debian)"
def do_GET(self):
b = b"<html><title>Damn Vulnerable Web Application</title></html>"
self.send_response(200); self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
do_HEAD = do_GET
def log_message(self, *a): pass
HTTPServer(("127.0.0.10", $app_port), H).serve_forever()
PY
python3 "$work/fake.py" & pids+=($!)
cat > "$work/harpia.toml" <<TOML
[escopo]
autorizado = ["127.0.0.0/24"]
responsavel = "Equipe de Seguranca <seguranca@exemplo.org>"
[padrao]
cron = "* * * * *"
[perfis.padrao]
tcp = "$app_port"
motor = "nativo-sem-raw"
vulnerabilidades = true
[[grupo]]
nome = "lab-dvwa"
alvos = ["127.0.0.10"]
TOML
for _ in $(seq 1 30); do curl -fsS "http://127.0.0.10:$app_port/" >/dev/null 2>&1 && break; sleep 0.2; done
cd "$work"
"$bin" feeds import feeds --data-dir data --config harpia.toml
"$bin" scan --group lab-dvwa --once --config harpia.toml --out sweeps --data-dir data
"$bin" serve --bind "127.0.0.1:$serve_port" --config harpia.toml --sweeps sweeps --data-dir data \
> serve.log 2>&1 & pids+=($!)
for _ in $(seq 1 50); do curl -fsS "http://127.0.0.1:$serve_port/api/health" >/dev/null 2>&1 && break; sleep 0.2; done
node "$root/scripts/screenshots/shots.mjs" "http://127.0.0.1:$serve_port/" "$out"
echo "capturas gravadas em $out"
+44
View File
@@ -0,0 +1,44 @@
// Captura as telas do dashboard do Harpia (tema escuro, português) em OUT.
// Uso (chamado por scripts/screenshots.sh): node shots.mjs <url-base> <dir-saída>
import { execFileSync } from "node:child_process";
import { homedir } from "node:os";
const [base, out] = process.argv.slice(2);
const core = process.env.PUPPETEER_CORE || `${homedir()}/.claude/tools/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js`;
const { default: puppeteer } = await import(core);
const chrome = process.env.CHROME || execFileSync("bash", ["-c", `ls -1d "$HOME"/.cache/puppeteer/chrome/*/chrome-linux64/chrome | sort -V | tail -1`], { encoding: "utf8" }).trim();
const size = { width: 1905, height: 2053, deviceScaleFactor: 1 };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const browser = await puppeteer.launch({ executablePath: chrome, args: ["--no-sandbox"], defaultViewport: size });
try {
const page = await browser.newPage();
await page.evaluateOnNewDocument(() => {
try { localStorage.setItem("harpia-lang", "pt"); localStorage.setItem("harpia-theme", "dark"); } catch {}
});
await page.goto(base, { waitUntil: "networkidle0" });
await sleep(2500);
const nav = async (t) => { await page.click(`.nav-item[data-target="${t}"]`); await sleep(1500); };
const save = async (name) => { await page.screenshot({ path: `${out}/${name}.png` }); console.log("ok", name); };
await save("visao-geral-dark-pt");
await nav("hosts");
const row = await page.$("table tbody tr");
if (row) { await row.click(); await sleep(1200); }
await save("hosts-dark-pt");
await nav("findings");
await save("achados-dark-pt");
await nav("groups");
await save("grupos-dark-pt");
// Capa e sumário do relatório executivo (Paged.js).
const rep = await browser.newPage();
await rep.setViewport(size);
await rep.goto(`${base}relatorio`, { waitUntil: "networkidle0" });
await rep.waitForSelector(".pagedjs_page", { timeout: 60000 });
await sleep(4000);
await rep.screenshot({ path: `${out}/relatorio-executivo-pt.png` });
console.log("ok relatorio-executivo-pt");
} finally {
await browser.close();
}