Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
150 lines
8.2 KiB
Markdown
150 lines
8.2 KiB
Markdown
# Architecture
|
|
|
|
**English** · [Português](pt-BR/arquitetura.md)
|
|
|
|
Harpia is a lightweight, continuous attack surface management and
|
|
vulnerability audit system. It follows a decoupled two-service architecture
|
|
distributed via Docker Compose: a privileged packet emitter (`scanner`) and
|
|
an unprivileged analytical server (`harpia`), sharing one binary and one
|
|
`crates/harpia-core` library.
|
|
|
|
## Technology stack
|
|
|
|
| Layer | Component | Rationale |
|
|
|---|---|---|
|
|
| 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). |
|
|
| Deployment | Docker Compose | Strict privilege isolation, container hardening, immutable batches over named volumes. |
|
|
|
|
## System topology & data flow
|
|
|
|
```
|
|
config/harpia.toml (rw from harpia, ro-mounted into scanner)
|
|
│
|
|
┌─────────────────────┴──────────────────────┐
|
|
▼ ▼
|
|
scanner (NET_RAW, host net, uid 0) harpia (uid 10001, zero capabilities)
|
|
- Multi-group scheduler, hot-reload - Batch ingestion (:ro)
|
|
- TCP connect discovery - Scoped diff calculation
|
|
- SYN (nativo) / connect - CPE -> CVE/KEV matching
|
|
(nativo-sem-raw) port scan - SQLite state + CVE database
|
|
- Service banner fingerprinting - Axum API, dashboard, exec. report
|
|
│ - config CRUD (writes harpia.toml)
|
|
▼ ▲
|
|
harpia-sweeps (Parquet batches + manifest.json) ───┘
|
|
```
|
|
|
|
### 1. Privilege separation
|
|
|
|
- **`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
|
|
[`docker.md`](docker.md#why-scanner-runs-as-uid-0-restricted-to-net_raw)
|
|
for why Docker makes that necessary), but drops every other capability
|
|
(`cap_drop: [ALL]`), runs with a read-only root filesystem, and only
|
|
writes to the `harpia-sweeps` volume. It never opens a listening port, has
|
|
no API, and never touches the SQLite database.
|
|
- **`harpia`:** runs as an unprivileged user (uid 10001) with zero
|
|
capabilities. It mounts `harpia-sweeps` read-only, is the **exclusive
|
|
writer** of the SQLite state (`harpia-data`), writes `harpia.toml` back
|
|
when the dashboard's Groups view mutates a group, correlates findings
|
|
against the local vulnerability database, and serves the Axum API,
|
|
dashboard and executive report bound to `127.0.0.1:8788` by default.
|
|
|
|
### 2. Scan engine
|
|
|
|
Two port-scanning engines share one result type (`HostPortScanResult`), so
|
|
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,
|
|
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
|
|
skipping the IP header. A `SYN-ACK` matching the probe's `(peer_ip,
|
|
peer_port)` means `Open`; an `RST` means `Closed`; no reply by the scan's
|
|
deadline means `Filtered`, same semantics as the connect engine. Requires
|
|
`CAP_NET_RAW`, checked at runtime via `caps::has_net_raw()` (reads
|
|
`CapEff` from `/proc/self/status`).
|
|
- **`nativo-sem-raw` (TCP connect, `scan::ports`):** the documented degraded
|
|
mode. No capability needed; every open port is a real, completed TCP
|
|
connection.
|
|
|
|
`execute_scan_for_group` in `harpia-cli` picks `nativo` whenever a profile
|
|
asks for it **and** `CAP_NET_RAW` is actually usable, and falls back to
|
|
`nativo-sem-raw` with a logged warning otherwise, the engine that actually
|
|
ran, not the one requested, is what gets recorded in the sweep manifest, so
|
|
an operator reading `/api/status` or a manifest never has to guess.
|
|
|
|
### 3. Batch contract & idempotency
|
|
|
|
Communication between `scanner` and `harpia` happens entirely through
|
|
filesystem batches, never a network call between the two containers:
|
|
|
|
- Each scan execution writes to `sweeps/<group>/<sweep_id>/observations.parquet`.
|
|
- On successful completion, `scanner` atomically creates `manifest.json`
|
|
(sweep id, group, scope, engine mode actually used, status).
|
|
- `harpia` polls the sweeps volume, ingests batches idempotently by
|
|
`sweep_id`, and `scanner` prunes batches past the retention window.
|
|
|
|
### 4. Tiered scheduling & scope boundaries
|
|
|
|
Target configuration in `harpia.toml` decouples asset definitions from
|
|
execution policy, see [`configuration.md`](configuration.md) for the full
|
|
reference:
|
|
|
|
- **`[escopo]`:** mandatory boundary. Any target or DNS resolution outside
|
|
the authorized CIDR blocks fails validation.
|
|
- **`[padrao]`:** global default cron schedule, jitter, and the shared
|
|
`taxa_maxima_pps` budget.
|
|
- **`[[grupo]]`:** named networks with their own cron cadence (e.g.
|
|
`*/5 * * * *` for a critical core vs. `0 3 * * *` for an exhaustive
|
|
nightly sweep) and probe profile. Editable live from the dashboard's
|
|
Groups view (`/api/config/groups`); `scanner` hot-reloads on its own by
|
|
watching the config file's mtime.
|
|
|
|
### 5. Scoped diffs & event history
|
|
|
|
Rather than disconnected point-in-time reports, Harpia evaluates state
|
|
differences against the specific scope the completed sweep actually
|
|
covered:
|
|
|
|
- **State tables:** deduplicated current state for assets, services and
|
|
findings.
|
|
- **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
|
|
a disappearance.
|
|
- **Event log:** append-only log of `host_novo`, `porta_aberta`,
|
|
`servico_alterado`, `vulnerabilidade_nova`, `vulnerabilidade_corrigida`
|
|
and friends, each with deterministic JSON evidence.
|
|
|
|
### 6. Vulnerability correlation
|
|
|
|
`scan::fingerprint` captures a banner per open port (HTTP `Server` header,
|
|
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
|
|
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
|
|
certificates, unencrypted administrative ports) independent of CVE
|
|
matching.
|
|
|
|
### 7. Determinism
|
|
|
|
Every documented source of variation in a result is explicit, not
|
|
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
|
|
are always sorted by IP then port before being returned or written, and
|
|
scheduling jitter is a deterministic function of the slot, not a random
|
|
draw.
|