refactor!: rename project from Xexéu to Harpia
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
Release / Build image (amd64) (push) Successful in 10m49s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 20m40s
CI / Format and clippy (push) Successful in 5m43s
CI / Tests (Linux) (push) Successful in 16m5s
CI / Dependency audit (push) Successful in 11s
CI / Docker image (build and smoke test) (push) Skipped
Release / Build image (arm64) (push) Successful in 7m34s
Release / Publish tags (push) Successful in 15s
Release / Gitea release (push) Skipped
Release / CLI (linux-aarch64) (push) Skipped
Release / CLI (linux-x86_64) (push) Skipped
Renames the whole project, after the harpy eagle: crates (xexeu-core/xexeu-cli -> harpia-core/harpia-cli), binary (xexeu -> harpia), admin token env var (XEXEU_ADMIN_TOKEN -> HARPIA_ADMIN_TOKEN), compose env vars (XEXEU_* -> HARPIA_*), container image (ciberfauna/xexeu -> ciberfauna/harpia) and the Gitea repository (ciberfauna/xexeu -> ciberfauna/harpia). Logo updated to the new brand artwork. All docs (EN/PT-BR), CI workflows, scripts, GUI strings and the openspec change history updated to match. BREAKING CHANGE: binary, crate, env var and image names all changed; existing .env files, scripts and deployments referencing the old xexeu/XEXEU names must be updated. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VAyr8cd6jzwpJM9cS1oGjy
This commit is contained in:
1 parent
1dc754a561
commit
5ed6cb2c95
93 files changed
+849
-826
No files matched your search
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "harpia-cli"
|
||||
description = "Harpia: continuous attack-surface auditing daemon, scanner and CLI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "harpia"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
harpia-core = { path = "../harpia-core" }
|
||||
axum = "0.8"
|
||||
chrono = { version = "0.4", features = ["clock"] }
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
libc = "0.2"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "time", "sync"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Admin token for the API routes that change state (group CRUD).
|
||||
//!
|
||||
//! Reads stay open, as before: the dashboard is meant to sit on loopback or
|
||||
//! behind a reverse proxy. Writes decide what the scanner sweeps, so they need
|
||||
//! the admin token in `Authorization: Bearer <token>` or `X-Harpia-Token`, and a
|
||||
//! browser `Origin`, when sent, must match `Host` (CSRF).
|
||||
//!
|
||||
//! The token comes from `--admin-token`/`HARPIA_ADMIN_TOKEN`; without one, a
|
||||
//! random token is generated at startup and printed once, the same way
|
||||
//! `sabia ui` hands out its session token.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Request, State};
|
||||
use axum::http::{header, HeaderMap, Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
||||
/// Shortest token accepted from configuration; shorter ones are guessable.
|
||||
pub const MIN_TOKEN_LEN: usize = 16;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AdminToken(Arc<str>);
|
||||
|
||||
impl AdminToken {
|
||||
pub fn new(token: &str) -> Self {
|
||||
Self(Arc::from(token))
|
||||
}
|
||||
|
||||
/// 32 random bytes from the kernel, hex-encoded.
|
||||
pub fn generate() -> std::io::Result<Self> {
|
||||
let mut bytes = [0u8; 32];
|
||||
File::open("/dev/urandom")?.read_exact(&mut bytes)?;
|
||||
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
Ok(Self::new(&hex))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Constant-time comparison: the time taken does not reveal how many
|
||||
/// leading characters of a guess were right.
|
||||
pub fn matches(&self, candidate: &str) -> bool {
|
||||
let expected = self.0.as_bytes();
|
||||
let candidate = candidate.as_bytes();
|
||||
let mut diff = expected.len() ^ candidate.len();
|
||||
for (index, byte) in expected.iter().enumerate() {
|
||||
diff |= usize::from(byte ^ candidate.get(index).copied().unwrap_or(0));
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Token sent by the client, from `Authorization: Bearer` or `X-Harpia-Token`.
|
||||
fn presented_token(headers: &HeaderMap) -> Option<&str> {
|
||||
if let Some(value) = headers.get("x-harpia-token").and_then(|v| v.to_str().ok()) {
|
||||
return Some(value.trim());
|
||||
}
|
||||
headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
}
|
||||
|
||||
/// `true` when there is no `Origin` (non-browser client) or its host matches `Host`.
|
||||
fn same_origin(headers: &HeaderMap) -> bool {
|
||||
let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {
|
||||
return true;
|
||||
};
|
||||
let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
let origin_host = origin
|
||||
.split_once("://")
|
||||
.map(|(_, rest)| rest)
|
||||
.unwrap_or(origin)
|
||||
.trim_end_matches('/');
|
||||
origin_host.eq_ignore_ascii_case(host)
|
||||
}
|
||||
|
||||
fn is_write(method: &Method) -> bool {
|
||||
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
|
||||
}
|
||||
|
||||
pub async fn require_admin(
|
||||
State(token): State<AdminToken>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
if is_write(request.method()) {
|
||||
let headers = request.headers();
|
||||
if !same_origin(headers) {
|
||||
return (StatusCode::FORBIDDEN, "origem da requisição não confere").into_response();
|
||||
}
|
||||
match presented_token(headers) {
|
||||
Some(candidate) if token.matches(candidate) => {}
|
||||
_ => {
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Bearer")],
|
||||
"token de administração ausente ou inválido",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
#[test]
|
||||
fn matches_only_the_exact_token() {
|
||||
let token = AdminToken::new("abcdef0123456789");
|
||||
assert!(token.matches("abcdef0123456789"));
|
||||
assert!(!token.matches("abcdef012345678"));
|
||||
assert!(!token.matches("abcdef01234567890"));
|
||||
assert!(!token.matches("Abcdef0123456789"));
|
||||
assert!(!token.matches(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_long_and_distinct() {
|
||||
let a = AdminToken::generate().unwrap();
|
||||
let b = AdminToken::generate().unwrap();
|
||||
assert_eq!(a.as_str().len(), 64);
|
||||
assert_ne!(a.as_str(), b.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bearer_and_custom_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer xyz"),
|
||||
);
|
||||
assert_eq!(presented_token(&headers), Some("xyz"));
|
||||
headers.insert("x-harpia-token", HeaderValue::from_static("abc"));
|
||||
assert_eq!(presented_token(&headers), Some("abc"));
|
||||
headers.clear();
|
||||
headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Basic xyz"));
|
||||
assert_eq!(presented_token(&headers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origin_must_match_host() {
|
||||
let mut headers = HeaderMap::new();
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(header::HOST, HeaderValue::from_static("127.0.0.1:8788"));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("http://127.0.0.1:8788"),
|
||||
);
|
||||
assert!(same_origin(&headers));
|
||||
headers.insert(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_static("https://evil.example"),
|
||||
);
|
||||
assert!(!same_origin(&headers));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! `harpia changes`, `harpia doctor` and `harpia export`.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use crate::server::export::{current_state_to_dtos, generate_hosts_csv};
|
||||
use crate::{fail, parse_since};
|
||||
use harpia_core::storage::{SqliteStorage, Storage};
|
||||
|
||||
pub(crate) fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
|
||||
let db_path = data_dir.join("harpia.db");
|
||||
if !db_path.exists() {
|
||||
return fail(&format!(
|
||||
"banco de dados não encontrado em {}",
|
||||
db_path.display()
|
||||
));
|
||||
}
|
||||
let storage = match SqliteStorage::open(&db_path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return fail(&format!("falha ao abrir banco: {e}")),
|
||||
};
|
||||
let since_dt = parse_since(since);
|
||||
match storage.events(since_dt) {
|
||||
Ok(events) => match serde_json::to_string_pretty(&events) {
|
||||
Ok(json) => {
|
||||
println!("{json}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => fail(&format!("falha ao serializar eventos: {e}")),
|
||||
},
|
||||
Err(e) => fail(&format!("falha ao consultar eventos: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_doctor(as_json: bool, config_path: &Path, data_dir: &Path) -> ExitCode {
|
||||
let report = harpia_core::doctor::run(config_path, data_dir);
|
||||
|
||||
if as_json {
|
||||
match serde_json::to_string_pretty(&report) {
|
||||
Ok(json) => println!("{json}"),
|
||||
Err(error) => return fail(&format!("falha ao serializar o diagnóstico: {error}")),
|
||||
}
|
||||
} else {
|
||||
print!("{}", report.render_table());
|
||||
}
|
||||
|
||||
if report.ok {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run_export(format: &str, data_dir: &Path, out_file: Option<&Path>) -> ExitCode {
|
||||
let db_path = data_dir.join("harpia.db");
|
||||
let storage = match SqliteStorage::open(&db_path) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
return fail(&format!(
|
||||
"falha ao abrir banco em {}: {err}",
|
||||
db_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let state = match storage.load_state(&[]) {
|
||||
Ok(s) => s,
|
||||
Err(err) => return fail(&format!("falha ao carregar estado: {err}")),
|
||||
};
|
||||
|
||||
let content = match format.to_ascii_lowercase().as_str() {
|
||||
"json" => {
|
||||
let dtos = current_state_to_dtos(&state);
|
||||
match serde_json::to_string_pretty(&dtos) {
|
||||
Ok(s) => s,
|
||||
Err(err) => return fail(&format!("falha ao serializar JSON: {err}")),
|
||||
}
|
||||
}
|
||||
"csv" => generate_hosts_csv(&state),
|
||||
other => {
|
||||
return fail(&format!(
|
||||
"formato não suportado: '{other}' (use 'json' ou 'csv')"
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(path) = out_file {
|
||||
if let Some(parent) = path.parent() {
|
||||
if !parent.as_os_str().is_empty() {
|
||||
if let Err(e) = fs::create_dir_all(parent) {
|
||||
return fail(&format!(
|
||||
"falha ao criar diretório para {}: {e}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = fs::write(path, &content) {
|
||||
return fail(&format!(
|
||||
"falha ao salvar export em {}: {e}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
} else {
|
||||
print!("{content}");
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! `harpia config check`: validation report, effective schedules and overlapping groups.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::net::IpAddr;
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use crate::{fail, validated_config};
|
||||
use chrono::Utc;
|
||||
use harpia_core::config::HarpiaConfig;
|
||||
use harpia_core::targets::{effective_cadence, expand_group, IpRange};
|
||||
|
||||
pub(crate) fn run_config_check(path: &Path) -> ExitCode {
|
||||
let (config, report) = match validated_config(path) {
|
||||
Ok(loaded) => loaded,
|
||||
Err(message) => return fail(&message),
|
||||
};
|
||||
|
||||
println!("Configuração válida: {}", path.display());
|
||||
for group in &report.groups {
|
||||
println!(
|
||||
"grupo {}: {} endereço(s), {} nome(s), perfil {}, cron {}",
|
||||
group.group, group.addresses, group.names, group.profile, group.cron
|
||||
);
|
||||
}
|
||||
|
||||
for warning in &report.warnings {
|
||||
println!("aviso: grupo {}: {}", warning.group, warning.message);
|
||||
}
|
||||
|
||||
let now = Utc::now();
|
||||
match overlapping_ranges(&config) {
|
||||
Ok(overlaps) if overlaps.is_empty() => {}
|
||||
Ok(overlaps) => {
|
||||
println!("\nSobreposições:");
|
||||
for range in overlaps {
|
||||
match effective_cadence(&config, range.start(), now) {
|
||||
Ok(Some(cadence)) => println!(
|
||||
" {} ({} endereço(s)): grupos [{}], efetivo {} a cada {}s, próxima {}",
|
||||
range,
|
||||
range.count(),
|
||||
cadence.groups.join(", "),
|
||||
cadence.effective_group,
|
||||
cadence.interval_secs,
|
||||
cadence.next_run.to_rfc3339()
|
||||
),
|
||||
Ok(None) => println!(
|
||||
" {} ({} endereço(s)): nenhum grupo cobre a sobreposição",
|
||||
range,
|
||||
range.count()
|
||||
),
|
||||
Err(error) => {
|
||||
println!(" {}: falha ao calcular a cadência efetiva: {error}", range)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(message) => return fail(&message),
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn overlapping_ranges(config: &HarpiaConfig) -> Result<Vec<IpRange>, String> {
|
||||
let expansions = config
|
||||
.groups
|
||||
.iter()
|
||||
.map(expand_group)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| format!("falha ao expandir os grupos: {error}"))?;
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
let mut overlaps = Vec::new();
|
||||
for (index, left_group) in expansions.iter().enumerate() {
|
||||
for right_group in expansions.iter().skip(index + 1) {
|
||||
for left in left_group.ranges() {
|
||||
for right in right_group.ranges() {
|
||||
let start = left.start().max(right.start());
|
||||
let end = left.end().min(right.end());
|
||||
if start > end {
|
||||
continue;
|
||||
}
|
||||
if let Ok(range) = IpRange::new(start, end) {
|
||||
if seen.insert(range.to_string()) {
|
||||
overlaps.push(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overlaps.sort_by_key(|range| (range.start().is_ipv6(), ip_value(range.start())));
|
||||
Ok(overlaps)
|
||||
}
|
||||
|
||||
fn ip_value(address: IpAddr) -> u128 {
|
||||
match address {
|
||||
IpAddr::V4(ip) => u32::from(ip) as u128,
|
||||
IpAddr::V6(ip) => u128::from(ip),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! `harpia feeds import` and `harpia feeds sync`.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use crate::fail;
|
||||
use harpia_core::vuln::{
|
||||
import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase,
|
||||
};
|
||||
|
||||
fn find_matching_file(dir: &Path, keyword: &str, ext: &str) -> Option<PathBuf> {
|
||||
let entries = fs::read_dir(dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
let lower = name.to_lowercase();
|
||||
if lower.contains(keyword) && lower.ends_with(ext) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn run_feeds_import(
|
||||
directory: Option<PathBuf>,
|
||||
nvd_path: Option<PathBuf>,
|
||||
kev_path: Option<PathBuf>,
|
||||
data_dir: &Path,
|
||||
) -> ExitCode {
|
||||
let nvd_file = nvd_path.or_else(|| {
|
||||
directory.as_ref().map(|d| {
|
||||
let direct = d.join("nvd.json");
|
||||
if direct.exists() {
|
||||
direct
|
||||
} else {
|
||||
find_matching_file(d, "nvd", "json").unwrap_or(direct)
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
let kev_file = kev_path.or_else(|| {
|
||||
directory.as_ref().map(|d| {
|
||||
let direct_json = d.join("kev.json");
|
||||
if direct_json.exists() {
|
||||
direct_json
|
||||
} else {
|
||||
let direct_csv = d.join("kev.csv");
|
||||
if direct_csv.exists() {
|
||||
direct_csv
|
||||
} else {
|
||||
find_matching_file(d, "kev", "json")
|
||||
.or_else(|| find_matching_file(d, "kev", "csv"))
|
||||
.unwrap_or(direct_json)
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
let nvd_file = match nvd_file {
|
||||
Some(f) if f.exists() => f,
|
||||
Some(f) => return fail(&format!("arquivo NVD não encontrado em: {}", f.display())),
|
||||
None => return fail("informe o diretório com os feeds ou use --nvd <arquivo>"),
|
||||
};
|
||||
|
||||
let nvd = match import_nvd(&nvd_file) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return fail(&format!("falha ao importar feed NVD: {e}")),
|
||||
};
|
||||
|
||||
let kev = if let Some(kf) = &kev_file {
|
||||
if kf.exists() {
|
||||
match import_kev(kf) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return fail(&format!("falha ao importar feed CISA KEV: {e}")),
|
||||
}
|
||||
} else {
|
||||
KevCatalog::default()
|
||||
}
|
||||
} else {
|
||||
KevCatalog::default()
|
||||
};
|
||||
|
||||
let db = VulnDatabase { nvd, kev };
|
||||
let db_path = data_dir.join("vuln_db.json");
|
||||
if let Err(e) = db.save_to_file(&db_path) {
|
||||
return fail(&format!(
|
||||
"falha ao salvar base de vulnerabilidades em {}: {e}",
|
||||
db_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
println!(
|
||||
"Base de vulnerabilidades importada com sucesso: {} CVEs ({} no KEV) salvos em {}",
|
||||
db.cve_count(),
|
||||
db.kev_count(),
|
||||
db_path.display()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
pub(crate) async fn run_feeds_sync(data_dir: &Path) -> ExitCode {
|
||||
let db_path = data_dir.join("vuln_db.json");
|
||||
let mut db = if db_path.exists() {
|
||||
match VulnDatabase::load_from_file(&db_path) {
|
||||
Ok(loaded) => loaded,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"aviso: não foi possível carregar base anterior em {}: {e}; iniciando base nova",
|
||||
db_path.display()
|
||||
);
|
||||
VulnDatabase::default()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
VulnDatabase::default()
|
||||
};
|
||||
|
||||
let sync_options = SyncOptions::default();
|
||||
println!("Sincronizando feeds de vulnerabilidade (NVD e CISA KEV)...");
|
||||
|
||||
let downloaded = match sync_feeds(&sync_options).await {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("falha na sincronização dos feeds: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
db.merge(downloaded);
|
||||
|
||||
if let Err(e) = db.save_to_file(&db_path) {
|
||||
return fail(&format!(
|
||||
"falha ao salvar base atualizada em {}: {e}",
|
||||
db_path.display()
|
||||
));
|
||||
}
|
||||
|
||||
println!(
|
||||
"Sincronização de feeds concluída: {} CVEs totais ({} no KEV) gravados em {}",
|
||||
db.cve_count(),
|
||||
db.kev_count(),
|
||||
db_path.display()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
mod auth;
|
||||
mod commands;
|
||||
mod config_cmd;
|
||||
mod feeds_cmd;
|
||||
mod scanner;
|
||||
mod server;
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use clap::{Parser, Subcommand};
|
||||
use commands::{run_changes, run_doctor, run_export};
|
||||
use config_cmd::run_config_check;
|
||||
use feeds_cmd::{run_feeds_import, run_feeds_sync};
|
||||
use harpia_core::config::{HarpiaConfig, ValidationReport};
|
||||
use scanner::{run_scanner, scan_once};
|
||||
use server::run_serve;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "harpia",
|
||||
about = "Harpia — continuous attack-surface and vulnerability auditing",
|
||||
version
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Run the API server, batch ingestion, diffs and the embedded dashboard.
|
||||
Serve {
|
||||
#[arg(long, default_value = "0.0.0.0:8788")]
|
||||
bind: String,
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/sweeps")]
|
||||
sweeps: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
/// Token required by the API routes that change state. Without it, a
|
||||
/// random token is generated at startup and printed once.
|
||||
#[arg(long, env = "HARPIA_ADMIN_TOKEN", hide_env_values = true)]
|
||||
admin_token: Option<String>,
|
||||
},
|
||||
/// Run the continuous scheduler and scan engine, writing sweep batches.
|
||||
Scanner {
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/sweeps")]
|
||||
out: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
/// Run a single sweep for diagnostics.
|
||||
Scan {
|
||||
#[arg(long)]
|
||||
group: Option<String>,
|
||||
#[arg(long)]
|
||||
once: bool,
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/sweeps")]
|
||||
out: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
/// Inspect the configuration.
|
||||
Config {
|
||||
#[command(subcommand)]
|
||||
action: ConfigAction,
|
||||
},
|
||||
/// Synchronize or import vulnerability feeds.
|
||||
Feeds {
|
||||
#[command(subcommand)]
|
||||
action: FeedsAction,
|
||||
},
|
||||
/// Query change events.
|
||||
Changes {
|
||||
#[arg(long, default_value = "24h")]
|
||||
since: String,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
/// Export the current state.
|
||||
Export {
|
||||
#[arg(long, default_value = "json")]
|
||||
format: String,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
#[arg(long)]
|
||||
out: Option<PathBuf>,
|
||||
},
|
||||
/// Check the runtime environment.
|
||||
Doctor {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ConfigAction {
|
||||
/// Validate the configuration and print the effective cadence per group.
|
||||
Check {
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum FeedsAction {
|
||||
/// Download NVD and CISA KEV feeds incrementally.
|
||||
Sync {
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
/// Import feed files copied manually for isolated networks.
|
||||
Import {
|
||||
directory: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
nvd: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
kev: Option<PathBuf>,
|
||||
#[arg(long, default_value = "config/harpia.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/harpia")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Command::Scan {
|
||||
group,
|
||||
once,
|
||||
config,
|
||||
out,
|
||||
data_dir,
|
||||
} => match scan_once(group, once, &config, &out, &data_dir).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Scanner {
|
||||
config,
|
||||
out,
|
||||
data_dir,
|
||||
} => match run_scanner(&config, &out, &data_dir).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Serve {
|
||||
bind,
|
||||
config,
|
||||
sweeps,
|
||||
data_dir,
|
||||
admin_token,
|
||||
} => match run_serve(&bind, &config, &sweeps, &data_dir, admin_token.as_deref()).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Changes { since, data_dir } => run_changes(&since, &data_dir),
|
||||
Command::Feeds { action } => match action {
|
||||
FeedsAction::Import {
|
||||
directory,
|
||||
nvd,
|
||||
kev,
|
||||
config: _,
|
||||
data_dir,
|
||||
} => run_feeds_import(directory, nvd, kev, &data_dir),
|
||||
FeedsAction::Sync {
|
||||
config: _,
|
||||
data_dir,
|
||||
} => run_feeds_sync(&data_dir).await,
|
||||
},
|
||||
Command::Config { action } => match action {
|
||||
ConfigAction::Check { config } => run_config_check(&config),
|
||||
},
|
||||
Command::Doctor {
|
||||
json,
|
||||
config,
|
||||
data_dir,
|
||||
} => run_doctor(json, &config, &data_dir),
|
||||
Command::Export {
|
||||
format,
|
||||
data_dir,
|
||||
out,
|
||||
} => run_export(&format, &data_dir, out.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn fail(message: &str) -> ExitCode {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
|
||||
fn validated_config(path: &Path) -> Result<(HarpiaConfig, ValidationReport), String> {
|
||||
let raw = fs::read_to_string(path)
|
||||
.map_err(|error| format!("não foi possível ler {}: {error}", path.display()))?;
|
||||
HarpiaConfig::load_validated(&raw)
|
||||
.map_err(|error| format!("configuração inválida em {}: {error}", path.display()))
|
||||
}
|
||||
|
||||
fn parse_since(raw: &str) -> Option<DateTime<Utc>> {
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if raw.len() > 1 {
|
||||
let (num_str, unit) = raw.split_at(raw.len() - 1);
|
||||
if let Ok(number) = num_str.parse::<i64>() {
|
||||
let duration = match unit {
|
||||
"s" => Some(chrono::Duration::seconds(number)),
|
||||
"m" => Some(chrono::Duration::minutes(number)),
|
||||
"h" => Some(chrono::Duration::hours(number)),
|
||||
"d" => Some(chrono::Duration::days(number)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(dur) = duration {
|
||||
return Some(Utc::now() - dur);
|
||||
}
|
||||
}
|
||||
}
|
||||
DateTime::parse_from_rfc3339(raw)
|
||||
.ok()
|
||||
.map(|date_time| date_time.with_timezone(&Utc))
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! `harpia scanner` and `harpia scan`: per-group sweeps written as batches.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::server::shutdown_signal;
|
||||
use crate::validated_config;
|
||||
use chrono::Utc;
|
||||
use harpia_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
|
||||
use harpia_core::config::HarpiaConfig;
|
||||
use harpia_core::scan::{
|
||||
discover_hosts_tcp, fingerprint_service, scan_hosts_syn, scan_hosts_tcp_connect,
|
||||
DiscoveryConfig, HostPortScanResult, HostState, PortScanConfig, PortState, PortTarget,
|
||||
SynScanConfig, DEFAULT_DISCOVERY_PORTS,
|
||||
};
|
||||
use harpia_core::schedule::{should_run_now, RunDecision, RunHistory};
|
||||
use harpia_core::targets::{expand_group, filter_in_scope, resolve_name, scope_ranges};
|
||||
use harpia_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
|
||||
use harpia_core::vuln::matcher::match_banner;
|
||||
use harpia_core::vuln::VulnDatabase;
|
||||
|
||||
struct ScanSummary {
|
||||
batch: SweepBatch,
|
||||
directory: PathBuf,
|
||||
targets_count: usize,
|
||||
alive_count: usize,
|
||||
}
|
||||
|
||||
async fn execute_scan_for_group(
|
||||
config: &HarpiaConfig,
|
||||
group_name: &str,
|
||||
out: &Path,
|
||||
data_dir: &Path,
|
||||
) -> Result<ScanSummary, String> {
|
||||
let group = config
|
||||
.group(group_name)
|
||||
.ok_or_else(|| format!("grupo '{group_name}' não existe na configuração"))?;
|
||||
let expansion =
|
||||
expand_group(group).map_err(|error| format!("grupo '{group_name}': {error}"))?;
|
||||
let scope =
|
||||
scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?;
|
||||
|
||||
let mut addresses: BTreeSet<IpAddr> = expansion.ips().collect();
|
||||
for hostname in expansion.names() {
|
||||
match resolve_name(hostname) {
|
||||
Ok(resolved) => {
|
||||
let (inside, outside) = filter_in_scope(&scope, &resolved);
|
||||
for address in outside {
|
||||
eprintln!(
|
||||
"aviso: {hostname} resolve para {address}, fora do escopo autorizado; ignorado"
|
||||
);
|
||||
}
|
||||
if inside.is_empty() {
|
||||
eprintln!(
|
||||
"aviso: {hostname} não resolve para nenhum endereço dentro do escopo autorizado"
|
||||
);
|
||||
}
|
||||
addresses.extend(inside);
|
||||
}
|
||||
Err(error) => eprintln!("aviso: não foi possível resolver {hostname}: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
if addresses.is_empty() {
|
||||
return Err("nenhum alvo dentro do escopo autorizado".to_string());
|
||||
}
|
||||
|
||||
let profile_name = group.effective_profile(config);
|
||||
let profile = config
|
||||
.profiles
|
||||
.get(profile_name)
|
||||
.ok_or_else(|| format!("perfil '{profile_name}' não definido"))?;
|
||||
|
||||
if profile.engine != "nativo" && profile.engine != "nativo-sem-raw" {
|
||||
return Err(format!(
|
||||
"motor '{}' do perfil '{profile_name}' não implementado; use nativo",
|
||||
profile.engine
|
||||
));
|
||||
}
|
||||
let ports = PortTarget::parse(&profile.tcp)
|
||||
.map_err(|error| format!("perfil '{profile_name}': {error}"))?
|
||||
.to_ports();
|
||||
if ports.is_empty() {
|
||||
return Err(format!("perfil '{profile_name}' não seleciona portas TCP"));
|
||||
}
|
||||
|
||||
let targets: Vec<IpAddr> = addresses.iter().copied().collect();
|
||||
let concurrency = config.defaults.simultaneous_hosts.unwrap_or(16).max(1);
|
||||
let started_at = Utc::now();
|
||||
|
||||
let hosts = discover_hosts_tcp(
|
||||
&targets,
|
||||
&DiscoveryConfig {
|
||||
ports: DEFAULT_DISCOVERY_PORTS.to_vec(),
|
||||
timeout: Duration::from_millis(600),
|
||||
max_concurrency: concurrency,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let alive: Vec<IpAddr> = hosts
|
||||
.iter()
|
||||
.filter(|host| host.state == HostState::Alive)
|
||||
.map(|host| host.ip)
|
||||
.collect();
|
||||
|
||||
// `nativo` tries the raw-socket SYN engine first and only falls back to
|
||||
// the unprivileged `nativo-sem-raw` TCP-connect engine when CAP_NET_RAW
|
||||
// isn't actually usable (missing capability, or the raw socket fails to
|
||||
// create for some other reason) — the engine mode actually used, not the
|
||||
// one requested, is what gets recorded in the sweep manifest below, so an
|
||||
// operator reading `/api/status` or the manifest never has to guess which
|
||||
// mode really ran.
|
||||
let wants_raw = profile.engine == "nativo";
|
||||
let (port_results, engine_used): (Vec<HostPortScanResult>, EngineMode) = if alive.is_empty() {
|
||||
(Vec::new(), EngineMode::NativeWithoutRaw)
|
||||
} else if wants_raw && harpia_core::caps::has_net_raw() {
|
||||
let syn_hosts = alive.clone();
|
||||
let syn_ports = ports.clone();
|
||||
let syn_config = SynScanConfig::default();
|
||||
let syn_result = tokio::task::spawn_blocking(move || {
|
||||
scan_hosts_syn(&syn_hosts, &syn_ports, &syn_config)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("tarefa de varredura SYN falhou: {error}"))?;
|
||||
match syn_result {
|
||||
Ok(results) => (results, EngineMode::Native),
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"aviso: varredura SYN falhou ({error}), recorrendo ao modo nativo-sem-raw"
|
||||
);
|
||||
(
|
||||
scan_hosts_tcp_connect(
|
||||
&alive,
|
||||
&ports,
|
||||
&PortScanConfig {
|
||||
timeout: Duration::from_millis(1200),
|
||||
max_concurrency: concurrency.saturating_mul(4).max(16),
|
||||
},
|
||||
)
|
||||
.await,
|
||||
EngineMode::NativeWithoutRaw,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if wants_raw {
|
||||
eprintln!(
|
||||
"aviso: perfil '{profile_name}' pede o motor nativo, mas CAP_NET_RAW não está disponível; usando nativo-sem-raw"
|
||||
);
|
||||
}
|
||||
(
|
||||
scan_hosts_tcp_connect(
|
||||
&alive,
|
||||
&ports,
|
||||
&PortScanConfig {
|
||||
timeout: Duration::from_millis(1200),
|
||||
max_concurrency: concurrency.saturating_mul(4).max(16),
|
||||
},
|
||||
)
|
||||
.await,
|
||||
EngineMode::NativeWithoutRaw,
|
||||
)
|
||||
};
|
||||
|
||||
let vuln_db = VulnDatabase::load_from_file(&data_dir.join("vuln_db.json")).unwrap_or_default();
|
||||
let mut services = Vec::new();
|
||||
|
||||
for result in &port_results {
|
||||
for port in &result.ports {
|
||||
if port.state != PortState::Open {
|
||||
continue;
|
||||
}
|
||||
|
||||
let fp = fingerprint_service(result.ip, port.port, Duration::from_millis(1500)).await;
|
||||
let mut findings = Vec::new();
|
||||
|
||||
let (product, version, cpe) = if let Some(info) = &fp.banner_info {
|
||||
let mut matched = match_banner(info, &vuln_db);
|
||||
findings.append(&mut matched);
|
||||
(
|
||||
Some(info.product_name.clone()),
|
||||
info.version.clone(),
|
||||
Some(info.cpe.to_cpe23()),
|
||||
)
|
||||
} else {
|
||||
(None, None, None)
|
||||
};
|
||||
|
||||
if let Some(der) = &fp.tls_cert_der {
|
||||
if let Ok(Some(f)) = check_tls_certificate_der(der, None) {
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
|
||||
if harpia_core::vuln::checks::COMMON_ADMIN_PORTS.contains(&port.port) {
|
||||
if let Some(raw) = &fp.raw_banner {
|
||||
if let Some(f) = evaluate_http_admin_response(port.port, raw) {
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
services.push(ServiceObservation {
|
||||
ip: result.ip,
|
||||
port: port.port,
|
||||
product,
|
||||
version,
|
||||
cpe,
|
||||
findings,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut manifest = SweepManifest::new(
|
||||
group.name.clone(),
|
||||
expansion.ranges().iter().map(ToString::to_string).collect(),
|
||||
profile_name,
|
||||
engine_used,
|
||||
started_at,
|
||||
);
|
||||
manifest.finish(SweepStatus::Complete, Utc::now());
|
||||
|
||||
let batch = SweepBatch::new(manifest, hosts, port_results).with_services(services);
|
||||
let directory = batch
|
||||
.write(out)
|
||||
.map_err(|error| format!("falha ao gravar o lote: {error}"))?;
|
||||
|
||||
Ok(ScanSummary {
|
||||
targets_count: targets.len(),
|
||||
alive_count: alive.len(),
|
||||
batch,
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
out: &Path,
|
||||
data_dir: &Path,
|
||||
) -> Result<(), String> {
|
||||
if !once {
|
||||
return Err("varredura contínua pertence ao comando scanner; use --once".to_string());
|
||||
}
|
||||
let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?;
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
let summary = execute_scan_for_group(&config, &name, out, data_dir).await?;
|
||||
|
||||
let profile_name = summary.batch.manifest.profile.as_str();
|
||||
println!(
|
||||
"lote {} (grupo {}, perfil {}) gravado em {}",
|
||||
summary.batch.manifest.sweep_id,
|
||||
name,
|
||||
profile_name,
|
||||
summary.directory.display()
|
||||
);
|
||||
println!(
|
||||
"alvos: {}; vivos: {}",
|
||||
summary.targets_count, summary.alive_count
|
||||
);
|
||||
for result in &summary.batch.ports {
|
||||
let open: Vec<String> = result
|
||||
.ports
|
||||
.iter()
|
||||
.filter(|port| port.state == PortState::Open)
|
||||
.map(|port| port.port.to_string())
|
||||
.collect();
|
||||
if !open.is_empty() {
|
||||
println!(" {}: {}", result.ip, open.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn run_scanner(
|
||||
config_path: &Path,
|
||||
out_dir: &Path,
|
||||
data_dir: &Path,
|
||||
) -> Result<(), String> {
|
||||
let (mut config, _report) = validated_config(config_path)?;
|
||||
fs::create_dir_all(out_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", out_dir.display()))?;
|
||||
|
||||
let mut histories: BTreeMap<String, RunHistory> = BTreeMap::new();
|
||||
for group in &config.groups {
|
||||
histories.insert(group.name.clone(), RunHistory::default());
|
||||
}
|
||||
|
||||
println!(
|
||||
"scanner contínuo iniciado com {} grupo(s) configurado(s)",
|
||||
config.groups.len()
|
||||
);
|
||||
|
||||
let tick_interval = std::env::var("HARPIA_SCANNER_TICK_SECS")
|
||||
.ok()
|
||||
.and_then(|val| val.parse().ok())
|
||||
.map(Duration::from_secs)
|
||||
.unwrap_or(Duration::from_secs(10));
|
||||
|
||||
let mut last_mtime = fs::metadata(config_path).and_then(|m| m.modified()).ok();
|
||||
|
||||
loop {
|
||||
// Hot-reload configuration if file modified time changed
|
||||
if let Ok(mtime) = fs::metadata(config_path).and_then(|m| m.modified()) {
|
||||
if Some(mtime) != last_mtime {
|
||||
last_mtime = Some(mtime);
|
||||
match validated_config(config_path) {
|
||||
Ok((new_config, _)) => {
|
||||
println!(
|
||||
"scanner: configuração recarregada com sucesso ({} grupos)",
|
||||
new_config.groups.len()
|
||||
);
|
||||
let current_group_names: BTreeSet<String> =
|
||||
new_config.groups.iter().map(|g| g.name.clone()).collect();
|
||||
histories.retain(|name, _| current_group_names.contains(name));
|
||||
for group in &new_config.groups {
|
||||
histories.entry(group.name.clone()).or_default();
|
||||
}
|
||||
config = new_config;
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: configuração alterada em disco mas inválida ({err}); mantendo configuração anterior em memória"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let now = Utc::now();
|
||||
for group in &config.groups {
|
||||
let history = histories.entry(group.name.clone()).or_default();
|
||||
|
||||
match should_run_now(group, &config, now, history) {
|
||||
Ok(RunDecision::Run) => {
|
||||
history.running = true;
|
||||
history.last_started = Some(now);
|
||||
|
||||
match execute_scan_for_group(&config, &group.name, out_dir, data_dir).await {
|
||||
Ok(summary) => {
|
||||
history.running = false;
|
||||
history.last_finished = Some(Utc::now());
|
||||
let open_count = summary
|
||||
.batch
|
||||
.ports
|
||||
.iter()
|
||||
.flat_map(|r| &r.ports)
|
||||
.filter(|p| p.state == PortState::Open)
|
||||
.count();
|
||||
println!(
|
||||
"[{}] grupo {}: {} alvo(s), {} vivo(s), {} porta(s) aberta(s) (lote {})",
|
||||
Utc::now().to_rfc3339(),
|
||||
group.name,
|
||||
summary.targets_count,
|
||||
summary.alive_count,
|
||||
open_count,
|
||||
summary.batch.manifest.sweep_id
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
history.running = false;
|
||||
eprintln!("erro na varredura do grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RunDecision::Deferred { .. }) => {
|
||||
eprintln!(
|
||||
"aviso: execução do grupo {} adiada (anterior ainda em andamento)",
|
||||
group.name
|
||||
);
|
||||
}
|
||||
Ok(RunDecision::Wait { .. }) => {}
|
||||
Err(error) => {
|
||||
eprintln!("erro no agendador para o grupo {}: {error}", group.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
println!("scanner encerrado graciosamente");
|
||||
break;
|
||||
}
|
||||
_ = tokio::time::sleep(tick_interval) => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! JSON API and the executive report.
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::export::{current_state_to_dtos, HostDto};
|
||||
use super::ServerState;
|
||||
use crate::parse_since;
|
||||
use axum::extract::{Path as AxumPath, Query, State};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::Json;
|
||||
use chrono::Utc;
|
||||
use harpia_core::config::{GroupConfig, HarpiaConfig};
|
||||
use harpia_core::report::ExecutiveReport;
|
||||
use harpia_core::schedule::next_runs;
|
||||
use harpia_core::storage::Storage;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct HealthResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
}
|
||||
|
||||
pub(crate) async fn health_handler() -> Json<HealthResponse> {
|
||||
Json(HealthResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct StatusResponse {
|
||||
status: &'static str,
|
||||
version: &'static str,
|
||||
config_path: String,
|
||||
sweeps_ingested: usize,
|
||||
feeds_cve_count: usize,
|
||||
feeds_kev_count: usize,
|
||||
feeds_last_sync: Option<String>,
|
||||
groups: Vec<GroupScheduleDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GroupScheduleDto {
|
||||
group: String,
|
||||
profile: String,
|
||||
cron: String,
|
||||
next_run: String,
|
||||
}
|
||||
|
||||
pub(crate) async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
||||
let now = Utc::now();
|
||||
let config = state.config.read().await;
|
||||
let schedules = next_runs(&config, now).unwrap_or_default();
|
||||
let groups = config
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
let next_run = schedules
|
||||
.iter()
|
||||
.find(|s| s.group == group.name)
|
||||
.map(|s| s.next_run.to_rfc3339())
|
||||
.unwrap_or_default();
|
||||
GroupScheduleDto {
|
||||
group: group.name.clone(),
|
||||
profile: group.effective_profile(&config).to_string(),
|
||||
cron: group.effective_cron(&config).to_string(),
|
||||
next_run,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let (cve_count, kev_count) = {
|
||||
let db = state.vuln_db.read().await;
|
||||
(db.cve_count(), db.kev_count())
|
||||
};
|
||||
let last_sync = {
|
||||
let sync = state.feeds_last_sync.read().await;
|
||||
sync.map(|dt| dt.to_rfc3339())
|
||||
};
|
||||
|
||||
Json(StatusResponse {
|
||||
status: "ok",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
config_path: state.config_path.display().to_string(),
|
||||
sweeps_ingested: state.sweeps_ingested.load(Ordering::SeqCst),
|
||||
feeds_cve_count: cve_count,
|
||||
feeds_kev_count: kev_count,
|
||||
feeds_last_sync: last_sync,
|
||||
groups,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn get_config_handler(State(state): State<ServerState>) -> Json<HarpiaConfig> {
|
||||
// Webhook URLs are credentials and reads are not authenticated.
|
||||
let config = state.config.read().await;
|
||||
Json(config.redacted())
|
||||
}
|
||||
|
||||
pub(crate) async fn create_group_handler(
|
||||
State(state): State<ServerState>,
|
||||
Json(new_group): Json<GroupConfig>,
|
||||
) -> Result<(StatusCode, Json<GroupConfig>), (StatusCode, String)> {
|
||||
let group_name = new_group.name.trim().to_string();
|
||||
if group_name.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"nome do grupo não pode ser vazio".to_string(),
|
||||
));
|
||||
}
|
||||
// `sweep` batches are written to `sweeps/<group>/<sweep_id>/`, so an unsafe
|
||||
// name here (`/`, `..`) would only fail much later, when a sweep for this
|
||||
// group actually runs. Reject it now, with a clear error, instead.
|
||||
if harpia_core::batch::safe_component(&group_name).is_err() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!(
|
||||
"nome do grupo `{group_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let mut config_guard = state.config.write().await;
|
||||
let mut draft = config_guard.clone();
|
||||
|
||||
if draft.groups.iter().any(|g| g.name == group_name) {
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
format!("grupo `{group_name}` já existe"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.groups.push(new_group.clone());
|
||||
|
||||
if let Err(err) = draft.validate() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("configuração inválida: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao salvar configuração: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
*config_guard = draft;
|
||||
Ok((StatusCode::CREATED, Json(new_group)))
|
||||
}
|
||||
|
||||
pub(crate) async fn update_group_handler(
|
||||
State(state): State<ServerState>,
|
||||
AxumPath(group_name): AxumPath<String>,
|
||||
Json(updated_group): Json<GroupConfig>,
|
||||
) -> Result<Json<GroupConfig>, (StatusCode, String)> {
|
||||
let mut config_guard = state.config.write().await;
|
||||
let mut draft = config_guard.clone();
|
||||
|
||||
let pos = draft
|
||||
.groups
|
||||
.iter()
|
||||
.position(|g| g.name == group_name)
|
||||
.ok_or_else(|| {
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("grupo `{group_name}` não encontrado"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let new_name = updated_group.name.trim();
|
||||
if new_name.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"nome do grupo não pode ser vazio".to_string(),
|
||||
));
|
||||
}
|
||||
if harpia_core::batch::safe_component(new_name).is_err() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!(
|
||||
"nome do grupo `{new_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
if new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) {
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
format!("grupo `{new_name}` já existe"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.groups[pos] = updated_group.clone();
|
||||
|
||||
if let Err(err) = draft.validate() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("configuração inválida: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao salvar configuração: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
*config_guard = draft;
|
||||
Ok(Json(updated_group))
|
||||
}
|
||||
|
||||
pub(crate) async fn delete_group_handler(
|
||||
State(state): State<ServerState>,
|
||||
AxumPath(group_name): AxumPath<String>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
let mut config_guard = state.config.write().await;
|
||||
let mut draft = config_guard.clone();
|
||||
|
||||
if !draft.groups.iter().any(|g| g.name == group_name) {
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("grupo `{group_name}` não encontrado"),
|
||||
));
|
||||
}
|
||||
|
||||
if draft.groups.len() <= 1 {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"não é permitido remover o último grupo configurado".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
draft.groups.retain(|g| g.name != group_name);
|
||||
|
||||
if let Err(err) = draft.validate() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("configuração inválida: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao salvar configuração: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
*config_guard = draft;
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
|
||||
pub(crate) async fn hosts_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<Json<Vec<HostDto>>, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let dtos = current_state_to_dtos(¤t_state);
|
||||
Ok(Json(dtos))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct ChangesQuery {
|
||||
pub(crate) since: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) async fn changes_handler(
|
||||
State(state): State<ServerState>,
|
||||
Query(query): Query<ChangesQuery>,
|
||||
) -> Result<Json<Vec<harpia_core::diff::Event>>, (StatusCode, String)> {
|
||||
let since = query.since.as_deref().and_then(parse_since);
|
||||
let storage = state.storage.lock().await;
|
||||
let events = storage.events(since).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar eventos: {error}"),
|
||||
)
|
||||
})?;
|
||||
Ok(Json(events))
|
||||
}
|
||||
|
||||
pub(crate) async fn report_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let config = state.config.read().await.clone();
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado para relatório: {error}"),
|
||||
)
|
||||
})?;
|
||||
let vuln_db = state.vuln_db.read().await.clone();
|
||||
let last_sync = *state.feeds_last_sync.read().await;
|
||||
|
||||
let report = ExecutiveReport::build(&config, ¤t_state, &vuln_db, last_sync, Utc::now());
|
||||
let html = report.render_html();
|
||||
Ok(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html))
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Dashboard files embedded in the binary.
|
||||
|
||||
use axum::http::header;
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
const INDEX_HTML: &str = include_str!("../../../../apps/gui/ui/index.html");
|
||||
|
||||
const APP_CSS: &str = include_str!("../../../../apps/gui/ui/app.css");
|
||||
|
||||
const APP_JS: &str = include_str!("../../../../apps/gui/ui/app.js");
|
||||
|
||||
const I18N_JS: &str = include_str!("../../../../apps/gui/ui/i18n.js");
|
||||
|
||||
const I18N_EN_JS: &str = include_str!("../../../../apps/gui/ui/i18n-en.js");
|
||||
|
||||
const PAGED_JS: &str = include_str!("../../../../apps/gui/ui/paged.polyfill.min.js");
|
||||
|
||||
const LOGO_PNG: &[u8] = include_bytes!("../../../../logo.png");
|
||||
|
||||
pub(crate) async fn index_handler() -> impl IntoResponse {
|
||||
(
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
INDEX_HTML,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn css_handler() -> impl IntoResponse {
|
||||
([(header::CONTENT_TYPE, "text/css; charset=utf-8")], APP_CSS)
|
||||
}
|
||||
|
||||
pub(crate) async fn js_handler() -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"application/javascript; charset=utf-8",
|
||||
)],
|
||||
APP_JS,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn i18n_js_handler() -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"application/javascript; charset=utf-8",
|
||||
)],
|
||||
I18N_JS,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn i18n_en_js_handler() -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"application/javascript; charset=utf-8",
|
||||
)],
|
||||
I18N_EN_JS,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn paged_js_handler() -> impl IntoResponse {
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"application/javascript; charset=utf-8",
|
||||
)],
|
||||
PAGED_JS,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn logo_handler() -> impl IntoResponse {
|
||||
([(header::CONTENT_TYPE, "image/png")], LOGO_PNG)
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! CSV exports, shared with `harpia export`.
|
||||
|
||||
use super::api::ChangesQuery;
|
||||
use super::ServerState;
|
||||
use crate::parse_since;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use chrono::Utc;
|
||||
use harpia_core::diff::{CurrentState, EventKind};
|
||||
use harpia_core::storage::Storage;
|
||||
use harpia_core::vuln::matcher::{Confidence, Finding};
|
||||
use serde::Serialize;
|
||||
|
||||
/// Escapes a CSV field per RFC 4180, and neutralizes CSV/formula injection
|
||||
/// (OWASP's "CSV Injection"): a cell starting with `=`, `+`, `-`, `@` or a tab
|
||||
/// is interpreted as a formula by Excel/LibreOffice/Sheets when the export is
|
||||
/// opened, which could execute attacker-influenced content (a CVE
|
||||
/// description pulled from the NVD feed, or an operator-controlled config
|
||||
/// value). Prefixing it with a single quote forces every spreadsheet
|
||||
/// application to treat it as plain text, same as GitHub's and Google's own
|
||||
/// CSV export sanitization.
|
||||
fn csv_escape(s: &str) -> String {
|
||||
let needs_formula_guard = s
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|c| matches!(c, '=' | '+' | '-' | '@' | '\t'));
|
||||
let s_owned;
|
||||
let s = if needs_formula_guard {
|
||||
s_owned = format!("'{s}");
|
||||
&s_owned
|
||||
} else {
|
||||
s
|
||||
};
|
||||
|
||||
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
|
||||
let escaped = s.replace('"', "\"\"");
|
||||
format!("\"{escaped}\"")
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct HostDto {
|
||||
asset_key: String,
|
||||
network: String,
|
||||
ip: String,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
ports: Vec<PortDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PortDto {
|
||||
protocol: String,
|
||||
port: u16,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
product: Option<String>,
|
||||
version: Option<String>,
|
||||
cpe: Option<String>,
|
||||
findings: Vec<Finding>,
|
||||
}
|
||||
|
||||
pub(crate) fn current_state_to_dtos(current_state: &CurrentState) -> Vec<HostDto> {
|
||||
current_state
|
||||
.assets
|
||||
.iter()
|
||||
.map(|asset| HostDto {
|
||||
asset_key: asset.asset_key.clone(),
|
||||
network: asset.network.clone(),
|
||||
ip: asset.ip.to_string(),
|
||||
status: asset.status.as_str(),
|
||||
absences: asset.absences,
|
||||
first_seen: asset.first_seen.to_rfc3339(),
|
||||
last_seen: asset.last_seen.to_rfc3339(),
|
||||
ports: asset
|
||||
.ports
|
||||
.iter()
|
||||
.map(|port| PortDto {
|
||||
protocol: port.protocol.clone(),
|
||||
port: port.port,
|
||||
status: port.status.as_str(),
|
||||
absences: port.absences,
|
||||
first_seen: port.first_seen.to_rfc3339(),
|
||||
last_seen: port.last_seen.to_rfc3339(),
|
||||
product: port.product.clone(),
|
||||
version: port.version.clone(),
|
||||
cpe: port.cpe.clone(),
|
||||
findings: port.findings.clone(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn generate_hosts_csv(current_state: &CurrentState) -> String {
|
||||
let mut csv = String::new();
|
||||
csv.push_str("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados\r\n");
|
||||
|
||||
for asset in ¤t_state.assets {
|
||||
if asset.ports.is_empty() {
|
||||
let row = [
|
||||
csv_escape(&asset.ip.to_string()),
|
||||
csv_escape(&asset.network),
|
||||
csv_escape(asset.status.as_str()),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
"0".to_string(),
|
||||
];
|
||||
csv.push_str(&row.join(","));
|
||||
csv.push_str("\r\n");
|
||||
} else {
|
||||
for port in &asset.ports {
|
||||
let max_cvss = port
|
||||
.findings
|
||||
.iter()
|
||||
.filter_map(|f| f.cvss)
|
||||
.fold(None, |acc, v| Some(acc.map_or(v, |m: f32| m.max(v))));
|
||||
let max_cvss_str = max_cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
|
||||
let findings_count = port.findings.len().to_string();
|
||||
|
||||
let row = [
|
||||
csv_escape(&asset.ip.to_string()),
|
||||
csv_escape(&asset.network),
|
||||
csv_escape(asset.status.as_str()),
|
||||
csv_escape(&port.protocol),
|
||||
csv_escape(&port.port.to_string()),
|
||||
csv_escape(port.status.as_str()),
|
||||
csv_escape(port.product.as_deref().unwrap_or("")),
|
||||
csv_escape(port.version.as_deref().unwrap_or("")),
|
||||
csv_escape(port.cpe.as_deref().unwrap_or("")),
|
||||
csv_escape(&max_cvss_str),
|
||||
csv_escape(&findings_count),
|
||||
];
|
||||
csv.push_str(&row.join(","));
|
||||
csv.push_str("\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
csv
|
||||
}
|
||||
|
||||
pub(crate) async fn export_hosts_csv_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let csv = generate_hosts_csv(¤t_state);
|
||||
|
||||
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||
let disposition = format!("attachment; filename=\"harpia-hosts-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
|
||||
pub(crate) async fn export_findings_csv_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut csv = String::new();
|
||||
csv.push_str("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição\r\n");
|
||||
|
||||
for asset in ¤t_state.assets {
|
||||
for port in &asset.ports {
|
||||
for finding in &port.findings {
|
||||
let cvss_str = finding.cvss.map(|c| format!("{c:.1}")).unwrap_or_default();
|
||||
let kev_str = if finding.kev { "Sim" } else { "Não" };
|
||||
let confianca_str = match finding.confianca {
|
||||
Confidence::Alto => "Alta",
|
||||
Confidence::Medio => "Média",
|
||||
Confidence::Baixo => "Baixa",
|
||||
};
|
||||
|
||||
let row = [
|
||||
csv_escape(&asset.ip.to_string()),
|
||||
csv_escape(&port.port.to_string()),
|
||||
csv_escape(&finding.id),
|
||||
csv_escape(&cvss_str),
|
||||
csv_escape(kev_str),
|
||||
csv_escape(confianca_str),
|
||||
csv_escape(&finding.title),
|
||||
csv_escape(&finding.description),
|
||||
];
|
||||
csv.push_str(&row.join(","));
|
||||
csv.push_str("\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||
let disposition = format!("attachment; filename=\"harpia-findings-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
|
||||
pub(crate) async fn export_changes_csv_handler(
|
||||
State(state): State<ServerState>,
|
||||
Query(query): Query<ChangesQuery>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let since = query.since.as_deref().and_then(parse_since);
|
||||
let storage = state.storage.lock().await;
|
||||
let events = storage.events(since).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar eventos: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut csv = String::new();
|
||||
csv.push_str("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe\r\n");
|
||||
|
||||
for event in &events {
|
||||
let tipo_str = match event.kind {
|
||||
EventKind::HostNew => "Novo Host",
|
||||
EventKind::HostReturned => "Host Retornado",
|
||||
EventKind::HostDisappeared => "Host Sumido",
|
||||
EventKind::PortNew => "Nova Porta Aberta",
|
||||
EventKind::PortClosed => "Porta Fechada",
|
||||
EventKind::ServiceChanged => "Serviço Alterado",
|
||||
};
|
||||
|
||||
let detail = if let Some(svc) = &event.service {
|
||||
if let (Some(prev), Some(curr)) = (&event.previous, &event.current) {
|
||||
format!("{}/{}: {} -> {}", svc.protocol, svc.port, prev, curr)
|
||||
} else {
|
||||
format!("{}/{}", svc.protocol, svc.port)
|
||||
}
|
||||
} else if !event.evidence.is_null() && event.evidence != serde_json::json!({}) {
|
||||
event.evidence.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let row = [
|
||||
csv_escape(&event.occurred_at.to_rfc3339()),
|
||||
csv_escape(tipo_str),
|
||||
csv_escape(&event.asset_key),
|
||||
csv_escape(&event.group),
|
||||
csv_escape(&detail),
|
||||
];
|
||||
csv.push_str(&row.join(","));
|
||||
csv.push_str("\r\n");
|
||||
}
|
||||
|
||||
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||
let disposition = format!("attachment; filename=\"harpia-changes-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! `/metrics` in the Prometheus text format, and the webhook deliveries that
|
||||
//! feed some of its counters.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use chrono::{DateTime, Utc};
|
||||
use harpia_core::alert;
|
||||
use harpia_core::batch::SweepManifest;
|
||||
use harpia_core::config::HarpiaConfig;
|
||||
use harpia_core::diff::{AssetStatus, Event, PortStatus};
|
||||
use harpia_core::storage::Storage;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use super::ServerState;
|
||||
|
||||
/// Last ingested sweep of a group.
|
||||
struct SweepStat {
|
||||
finished_at: DateTime<Utc>,
|
||||
duration_secs: f64,
|
||||
complete: bool,
|
||||
events: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Metrics {
|
||||
webhook_ok: AtomicU64,
|
||||
webhook_failed: AtomicU64,
|
||||
sweeps: Mutex<BTreeMap<String, SweepStat>>,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
pub(crate) async fn record_sweep(&self, manifest: &SweepManifest, events: usize) {
|
||||
let finished_at = manifest.finished_at.unwrap_or(manifest.started_at);
|
||||
let duration_secs = (finished_at - manifest.started_at)
|
||||
.num_milliseconds()
|
||||
.max(0) as f64
|
||||
/ 1000.0;
|
||||
self.sweeps.lock().await.insert(
|
||||
manifest.group.clone(),
|
||||
SweepStat {
|
||||
finished_at,
|
||||
duration_secs,
|
||||
complete: manifest.status == harpia_core::batch::SweepStatus::Complete,
|
||||
events,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts the sweep's events to every webhook that wants them, in the
|
||||
/// background: a slow or broken receiver never holds up ingestion.
|
||||
pub(crate) async fn notify(
|
||||
config: &RwLock<HarpiaConfig>,
|
||||
metrics: &Arc<Metrics>,
|
||||
client: &reqwest::Client,
|
||||
manifest: &SweepManifest,
|
||||
events: &[Event],
|
||||
) {
|
||||
let webhooks = config.read().await.webhooks.clone();
|
||||
for webhook in webhooks {
|
||||
let selected = alert::select_events(&webhook, &manifest.group, events);
|
||||
if selected.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let body = alert::render(
|
||||
webhook.format,
|
||||
&manifest.group,
|
||||
manifest.sweep_id,
|
||||
&selected,
|
||||
);
|
||||
let key = webhook
|
||||
.secret_env
|
||||
.as_deref()
|
||||
.and_then(|name| std::env::var(name).ok())
|
||||
.filter(|key| !key.is_empty());
|
||||
if webhook.secret_env.is_some() && key.is_none() {
|
||||
eprintln!(
|
||||
"aviso: webhook {} pede assinatura, mas a variável {} está vazia; enviando sem assinar",
|
||||
webhook.redacted_url(),
|
||||
webhook.secret_env.as_deref().unwrap_or_default()
|
||||
);
|
||||
}
|
||||
let (metrics, client, count) = (Arc::clone(metrics), client.clone(), selected.len());
|
||||
tokio::spawn(async move {
|
||||
let key = key.as_deref().map(str::as_bytes);
|
||||
match alert::deliver(&client, &webhook.url, &body, key, Duration::from_secs(2)).await {
|
||||
Ok(()) => {
|
||||
metrics.webhook_ok.fetch_add(1, Ordering::Relaxed);
|
||||
println!(
|
||||
"webhook {}: {count} evento(s) enviados",
|
||||
webhook.redacted_url()
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
metrics.webhook_failed.fetch_add(1, Ordering::Relaxed);
|
||||
eprintln!(
|
||||
"aviso: webhook {} falhou após {} tentativas: {error}",
|
||||
webhook.redacted_url(),
|
||||
alert::MAX_ATTEMPTS
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Label value with `\`, `"` and newlines escaped.
|
||||
fn label(value: &str) -> String {
|
||||
value
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
.replace('\n', "\\n")
|
||||
}
|
||||
|
||||
fn metric(out: &mut String, name: &str, kind: &str, help: &str, samples: &[(String, f64)]) {
|
||||
let _ = writeln!(out, "# HELP {name} {help}");
|
||||
let _ = writeln!(out, "# TYPE {name} {kind}");
|
||||
for (labels, value) in samples {
|
||||
let _ = writeln!(out, "{name}{labels} {value}");
|
||||
}
|
||||
}
|
||||
|
||||
fn severity(cvss: Option<f32>) -> &'static str {
|
||||
match cvss {
|
||||
Some(score) if score >= 9.0 => "critica",
|
||||
Some(score) if score >= 7.0 => "alta",
|
||||
Some(score) if score >= 4.0 => "media",
|
||||
Some(score) if score > 0.0 => "baixa",
|
||||
_ => "sem_cvss",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn metrics_handler(State(state): State<ServerState>) -> impl IntoResponse {
|
||||
let current = match state.storage.lock().await.load_state(&[]) {
|
||||
Ok(current) => current,
|
||||
Err(error) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
[(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
|
||||
format!("falha ao carregar estado: {error}"),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let (mut active, mut gone, mut open_ports, mut kev) = (0u64, 0u64, 0u64, 0u64);
|
||||
let mut findings: BTreeMap<&str, u64> = ["critica", "alta", "media", "baixa", "sem_cvss"]
|
||||
.into_iter()
|
||||
.map(|level| (level, 0))
|
||||
.collect();
|
||||
for asset in ¤t.assets {
|
||||
match asset.status {
|
||||
AssetStatus::Active => active += 1,
|
||||
AssetStatus::Gone => gone += 1,
|
||||
}
|
||||
for port in asset
|
||||
.ports
|
||||
.iter()
|
||||
.filter(|port| port.status == PortStatus::Open)
|
||||
{
|
||||
open_ports += 1;
|
||||
for finding in &port.findings {
|
||||
*findings.entry(severity(finding.cvss)).or_default() += 1;
|
||||
kev += u64::from(finding.kev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = String::new();
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_build_info",
|
||||
"gauge",
|
||||
"Running Harpia version.",
|
||||
&[(
|
||||
format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")),
|
||||
1.0,
|
||||
)],
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_sweeps_ingested_total",
|
||||
"counter",
|
||||
"Sweep batches ingested since start.",
|
||||
&[(
|
||||
String::new(),
|
||||
state.sweeps_ingested.load(Ordering::SeqCst) as f64,
|
||||
)],
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_assets",
|
||||
"gauge",
|
||||
"Known hosts by status.",
|
||||
&[
|
||||
("{status=\"ativo\"}".into(), active as f64),
|
||||
("{status=\"sumido\"}".into(), gone as f64),
|
||||
],
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_open_ports",
|
||||
"gauge",
|
||||
"Open ports on known hosts.",
|
||||
&[(String::new(), open_ports as f64)],
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_findings",
|
||||
"gauge",
|
||||
"Findings on open ports by CVSS severity.",
|
||||
&findings
|
||||
.iter()
|
||||
.map(|(level, count)| (format!("{{severidade=\"{level}\"}}"), *count as f64))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_kev_findings",
|
||||
"gauge",
|
||||
"Findings listed in CISA KEV.",
|
||||
&[(String::new(), kev as f64)],
|
||||
);
|
||||
|
||||
let (cves, kev_entries) = {
|
||||
let db = state.vuln_db.read().await;
|
||||
(db.cve_count(), db.kev_count())
|
||||
};
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_vuln_db_cves",
|
||||
"gauge",
|
||||
"CVEs in the local database.",
|
||||
&[(String::new(), cves as f64)],
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_vuln_db_kev",
|
||||
"gauge",
|
||||
"KEV entries in the local database.",
|
||||
&[(String::new(), kev_entries as f64)],
|
||||
);
|
||||
if let Some(last_sync) = *state.feeds_last_sync.read().await {
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_feeds_last_sync_timestamp_seconds",
|
||||
"gauge",
|
||||
"Unix time of the last successful feed sync.",
|
||||
&[(String::new(), last_sync.timestamp() as f64)],
|
||||
);
|
||||
}
|
||||
|
||||
let sweeps = state.metrics.sweeps.lock().await;
|
||||
let per_group = |value: &dyn Fn(&SweepStat) -> f64| -> Vec<(String, f64)> {
|
||||
sweeps
|
||||
.iter()
|
||||
.map(|(group, stat)| (format!("{{grupo=\"{}\"}}", label(group)), value(stat)))
|
||||
.collect()
|
||||
};
|
||||
if !sweeps.is_empty() {
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_last_sweep_timestamp_seconds",
|
||||
"gauge",
|
||||
"Unix time the group's last ingested sweep finished.",
|
||||
&per_group(&|stat| stat.finished_at.timestamp() as f64),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_last_sweep_duration_seconds",
|
||||
"gauge",
|
||||
"Duration of the group's last ingested sweep.",
|
||||
&per_group(&|stat| stat.duration_secs),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_last_sweep_complete",
|
||||
"gauge",
|
||||
"1 if the group's last sweep covered every target.",
|
||||
&per_group(&|stat| f64::from(u8::from(stat.complete))),
|
||||
);
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_last_sweep_events",
|
||||
"gauge",
|
||||
"Surface changes found by the group's last sweep.",
|
||||
&per_group(&|stat| stat.events as f64),
|
||||
);
|
||||
}
|
||||
drop(sweeps);
|
||||
|
||||
metric(
|
||||
&mut out,
|
||||
"harpia_webhook_deliveries_total",
|
||||
"counter",
|
||||
"Webhook deliveries by result.",
|
||||
&[
|
||||
(
|
||||
"{resultado=\"ok\"}".into(),
|
||||
state.metrics.webhook_ok.load(Ordering::Relaxed) as f64,
|
||||
),
|
||||
(
|
||||
"{resultado=\"falha\"}".into(),
|
||||
state.metrics.webhook_failed.load(Ordering::Relaxed) as f64,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"text/plain; version=0.0.4; charset=utf-8",
|
||||
)],
|
||||
out,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! `harpia serve`: background batch ingestion, feed sync and the HTTP server.
|
||||
|
||||
mod api;
|
||||
mod assets;
|
||||
pub(crate) mod export;
|
||||
mod metrics;
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::{auth, validated_config};
|
||||
use api::{
|
||||
changes_handler, create_group_handler, delete_group_handler, get_config_handler,
|
||||
health_handler, hosts_handler, report_handler, status_handler, update_group_handler,
|
||||
};
|
||||
use assets::{
|
||||
css_handler, i18n_en_js_handler, i18n_js_handler, index_handler, js_handler, logo_handler,
|
||||
paged_js_handler,
|
||||
};
|
||||
use axum::Router;
|
||||
use chrono::{DateTime, Utc};
|
||||
use export::{export_changes_csv_handler, export_findings_csv_handler, export_hosts_csv_handler};
|
||||
use harpia_core::batch::SweepBatch;
|
||||
use harpia_core::config::HarpiaConfig;
|
||||
use harpia_core::diff::{diff_batch, DiffOptions};
|
||||
use harpia_core::storage::{SqliteStorage, Storage};
|
||||
use harpia_core::vuln::{sync_feeds, SyncOptions, VulnDatabase};
|
||||
use metrics::{metrics_handler, notify, Metrics};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
fn find_sweep_manifests(sweeps_dir: &Path) -> Vec<PathBuf> {
|
||||
let mut manifests = Vec::new();
|
||||
let group_entries = match fs::read_dir(sweeps_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => return manifests,
|
||||
};
|
||||
for group_entry in group_entries.flatten() {
|
||||
if !group_entry.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let sweep_entries = match fs::read_dir(group_entry.path()) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for sweep_entry in sweep_entries.flatten() {
|
||||
let sweep_path = sweep_entry.path();
|
||||
if sweep_path.is_dir() && sweep_path.join("manifest.json").exists() {
|
||||
manifests.push(sweep_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Lexicographical sorting by ULID directory name orders sweeps chronologically.
|
||||
manifests.sort();
|
||||
manifests
|
||||
}
|
||||
|
||||
async fn poll_sweeps(
|
||||
sweeps_dir: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
config: Arc<RwLock<HarpiaConfig>>,
|
||||
metrics: Arc<Metrics>,
|
||||
) {
|
||||
let client = reqwest::Client::new();
|
||||
loop {
|
||||
let manifests = find_sweep_manifests(&sweeps_dir);
|
||||
for sweep_path in manifests {
|
||||
match SweepBatch::read(&sweep_path) {
|
||||
Ok(batch) => {
|
||||
let mut storage_guard = storage.lock().await;
|
||||
match storage_guard.load_state(&[]) {
|
||||
Ok(current_state) => {
|
||||
match diff_batch(¤t_state, &batch, &DiffOptions::default()) {
|
||||
Ok(diff) => match storage_guard.ingest(&batch, &diff) {
|
||||
Ok(true) => {
|
||||
sweeps_ingested.fetch_add(1, Ordering::SeqCst);
|
||||
println!(
|
||||
"lote {} (grupo {}) ingerido com sucesso ({} eventos)",
|
||||
batch.manifest.sweep_id,
|
||||
batch.manifest.group,
|
||||
diff.events.len()
|
||||
);
|
||||
metrics
|
||||
.record_sweep(&batch.manifest, diff.events.len())
|
||||
.await;
|
||||
notify(
|
||||
&config,
|
||||
&metrics,
|
||||
&client,
|
||||
&batch.manifest,
|
||||
&diff.events,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(false) => {
|
||||
// Sweep already recorded.
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ingerir lote {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao calcular diff de {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("aviso: falha ao carregar estado do banco: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao ler lote em {}: {err}",
|
||||
sweep_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ServerState {
|
||||
config: Arc<RwLock<HarpiaConfig>>,
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
vuln_db: Arc<RwLock<VulnDatabase>>,
|
||||
feeds_last_sync: Arc<RwLock<Option<DateTime<Utc>>>>,
|
||||
metrics: Arc<Metrics>,
|
||||
}
|
||||
|
||||
fn parse_duration_str(raw: &str) -> Option<Duration> {
|
||||
let raw = raw.trim();
|
||||
if raw.len() > 1 {
|
||||
let (num_str, unit) = raw.split_at(raw.len() - 1);
|
||||
if let Ok(n) = num_str.parse::<u64>() {
|
||||
match unit {
|
||||
"s" => return Some(Duration::from_secs(n)),
|
||||
"m" => return Some(Duration::from_secs(n * 60)),
|
||||
"h" => return Some(Duration::from_secs(n * 3600)),
|
||||
"d" => return Some(Duration::from_secs(n * 86400)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) async fn run_serve(
|
||||
bind: &str,
|
||||
config_path: &Path,
|
||||
sweeps_dir: &Path,
|
||||
data_dir: &Path,
|
||||
admin_token: Option<&str>,
|
||||
) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
// An empty HARPIA_ADMIN_TOKEN (compose's default) means "generate one".
|
||||
let admin_token = admin_token.map(str::trim).filter(|token| !token.is_empty());
|
||||
let (admin_token, token_generated) = match admin_token {
|
||||
Some(token) if token.len() >= auth::MIN_TOKEN_LEN => (auth::AdminToken::new(token), false),
|
||||
Some(_) => {
|
||||
return Err(format!(
|
||||
"HARPIA_ADMIN_TOKEN precisa ter pelo menos {} caracteres",
|
||||
auth::MIN_TOKEN_LEN
|
||||
))
|
||||
}
|
||||
None => (
|
||||
auth::AdminToken::generate()
|
||||
.map_err(|error| format!("falha ao gerar token de administração: {error}"))?,
|
||||
true,
|
||||
),
|
||||
};
|
||||
fs::create_dir_all(sweeps_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
|
||||
fs::create_dir_all(data_dir)
|
||||
.map_err(|error| format!("falha ao criar {}: {error}", data_dir.display()))?;
|
||||
|
||||
let db_path = data_dir.join("harpia.db");
|
||||
let storage = SqliteStorage::open(&db_path).map_err(|error| {
|
||||
format!(
|
||||
"falha ao abrir banco de dados em {}: {error}",
|
||||
db_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let shared_storage = Arc::new(Mutex::new(storage));
|
||||
let sweeps_ingested = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
// Load initial vulnerability database if present on disk
|
||||
let vuln_db_path = data_dir.join("vuln_db.json");
|
||||
let (initial_db, last_sync) = if vuln_db_path.exists() {
|
||||
match VulnDatabase::load_from_file(&vuln_db_path) {
|
||||
Ok(db) => {
|
||||
println!(
|
||||
"Base de vulnerabilidades carregada: {} CVEs ({} no KEV)",
|
||||
db.cve_count(),
|
||||
db.kev_count()
|
||||
);
|
||||
(db, None)
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"aviso: falha ao carregar {}: {err}; iniciando base vazia",
|
||||
vuln_db_path.display()
|
||||
);
|
||||
(VulnDatabase::default(), None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(VulnDatabase::default(), None)
|
||||
};
|
||||
|
||||
let shared_vuln_db = Arc::new(RwLock::new(initial_db));
|
||||
let shared_last_sync = Arc::new(RwLock::new(last_sync));
|
||||
|
||||
let auto_sync = config.defaults.feeds.auto_sync;
|
||||
let interval_str = config.defaults.feeds.sync_interval.clone();
|
||||
let shared_config = Arc::new(RwLock::new(config));
|
||||
let shared_metrics = Arc::new(Metrics::default());
|
||||
|
||||
// Spawn background poller for incoming sweeps.
|
||||
let poller_storage = Arc::clone(&shared_storage);
|
||||
let poller_ingested = Arc::clone(&sweeps_ingested);
|
||||
let poller_sweeps = sweeps_dir.to_path_buf();
|
||||
let poller_config = Arc::clone(&shared_config);
|
||||
let poller_metrics = Arc::clone(&shared_metrics);
|
||||
tokio::spawn(async move {
|
||||
poll_sweeps(
|
||||
poller_sweeps,
|
||||
poller_storage,
|
||||
poller_ingested,
|
||||
poller_config,
|
||||
poller_metrics,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
// Spawn periodic background sync if auto_sync is enabled in config
|
||||
if auto_sync {
|
||||
let timer_db = Arc::clone(&shared_vuln_db);
|
||||
let timer_last_sync = Arc::clone(&shared_last_sync);
|
||||
let timer_db_path = vuln_db_path.clone();
|
||||
tokio::spawn(async move {
|
||||
let interval = parse_duration_str(&interval_str).unwrap_or(Duration::from_secs(86400));
|
||||
println!("Sincronizador automático de feeds ativo (intervalo: {interval_str})");
|
||||
loop {
|
||||
tokio::time::sleep(interval).await;
|
||||
println!("Iniciando sincronização periódica de feeds de vulnerabilidade...");
|
||||
let sync_opts = SyncOptions::default();
|
||||
match sync_feeds(&sync_opts).await {
|
||||
Ok(downloaded) => {
|
||||
let mut db_guard = timer_db.write().await;
|
||||
db_guard.merge(downloaded);
|
||||
if let Err(e) = db_guard.save_to_file(&timer_db_path) {
|
||||
eprintln!(
|
||||
"aviso: falha ao salvar base de vulnerabilidades atualizada: {e}"
|
||||
);
|
||||
}
|
||||
let mut sync_guard = timer_last_sync.write().await;
|
||||
*sync_guard = Some(Utc::now());
|
||||
println!(
|
||||
"Feeds sincronizados periodicamente com sucesso ({} CVEs)",
|
||||
db_guard.cve_count()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("aviso: falha na sincronização periódica de feeds: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let state = ServerState {
|
||||
config: shared_config,
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
vuln_db: shared_vuln_db,
|
||||
feeds_last_sync: shared_last_sync,
|
||||
metrics: shared_metrics,
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
.route("/metrics", axum::routing::get(metrics_handler))
|
||||
.route("/api/health", axum::routing::get(health_handler))
|
||||
.route("/api/status", axum::routing::get(status_handler))
|
||||
.route("/api/hosts", axum::routing::get(hosts_handler))
|
||||
.route("/api/changes", axum::routing::get(changes_handler))
|
||||
.route("/api/config", axum::routing::get(get_config_handler))
|
||||
.route(
|
||||
"/api/config/groups",
|
||||
axum::routing::post(create_group_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/config/groups/{nome}",
|
||||
axum::routing::put(update_group_handler).delete(delete_group_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/hosts.csv",
|
||||
axum::routing::get(export_hosts_csv_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/findings.csv",
|
||||
axum::routing::get(export_findings_csv_handler),
|
||||
)
|
||||
.route(
|
||||
"/api/export/changes.csv",
|
||||
axum::routing::get(export_changes_csv_handler),
|
||||
)
|
||||
.route("/relatorio", axum::routing::get(report_handler))
|
||||
.route("/report", axum::routing::get(report_handler))
|
||||
.route("/", axum::routing::get(index_handler))
|
||||
.route("/dashboard", axum::routing::get(index_handler))
|
||||
.route("/app.css", axum::routing::get(css_handler))
|
||||
.route("/app.js", axum::routing::get(js_handler))
|
||||
.route("/i18n.js", axum::routing::get(i18n_js_handler))
|
||||
.route("/i18n-en.js", axum::routing::get(i18n_en_js_handler))
|
||||
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
|
||||
.route("/logo.png", axum::routing::get(logo_handler))
|
||||
.with_state(state)
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
admin_token.clone(),
|
||||
auth::require_admin,
|
||||
));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(bind)
|
||||
.await
|
||||
.map_err(|error| format!("falha ao vincular endereço {bind}: {error}"))?;
|
||||
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
|
||||
|
||||
println!("Harpia listening on http://{local_addr}");
|
||||
if token_generated {
|
||||
println!(
|
||||
"Token de administração gerado nesta execução (defina HARPIA_ADMIN_TOKEN para fixá-lo): \
|
||||
http://{local_addr}/?token={}",
|
||||
admin_token.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await
|
||||
.map_err(|error| format!("erro no servidor HTTP: {error}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("falha ao registrar listener de Ctrl+C");
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
Ok(mut signal) => signal.recv().await,
|
||||
Err(_) => std::future::pending::<Option<()>>().await,
|
||||
};
|
||||
};
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
const WEBHOOK_KEY: &str = "e2e-webhook-signing-key";
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
let code = response
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|code| code.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
/// Accepts one POST, answers 200 and hands over its headers (lowercased) and body.
|
||||
fn webhook_receiver() -> (u16, mpsc::Receiver<(String, Vec<u8>)>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind webhook receiver");
|
||||
let port = listener.local_addr().expect("receiver address").port();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { break };
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut headers = String::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
headers.push_str(&line.to_ascii_lowercase());
|
||||
}
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.and_then(|value| value.trim().parse().ok())
|
||||
.unwrap_or(0);
|
||||
let mut body = vec![0; length];
|
||||
reader.read_exact(&mut body).expect("read webhook body");
|
||||
let mut stream = reader.into_inner();
|
||||
let _ = stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
let _ = sender.send((headers, body));
|
||||
}
|
||||
});
|
||||
(port, receiver)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ingested_sweep_triggers_signed_webhook_and_updates_metrics() {
|
||||
// Something to find: one open port on loopback.
|
||||
let target = TcpListener::bind("127.0.0.1:0").expect("bind target");
|
||||
let target_port = target.local_addr().expect("target address").port();
|
||||
std::thread::spawn(move || for _ in target.incoming() {});
|
||||
|
||||
let (hook_port, deliveries) = webhook_receiver();
|
||||
// Nothing listens here: deliveries fail and must be counted, not crash anything.
|
||||
let dead_port = TcpListener::bind("127.0.0.1:0")
|
||||
.expect("reserve a port")
|
||||
.local_addr()
|
||||
.expect("reserved address")
|
||||
.port();
|
||||
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{target_port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
|
||||
[[webhook]]
|
||||
url = "http://127.0.0.1:{hook_port}/hook/secret-path"
|
||||
eventos = ["porta_nova"]
|
||||
segredo_env = "HARPIA_E2E_WEBHOOK_KEY"
|
||||
|
||||
[[webhook]]
|
||||
url = "http://127.0.0.1:{dead_port}/down"
|
||||
formato = "slack"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.env("HARPIA_E2E_WEBHOOK_KEY", WEBHOOK_KEY)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
let mut reader = BufReader::new(child.stdout.take().expect("take stdout"));
|
||||
let _guard = ChildGuard(child);
|
||||
let mut addr = None;
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(rest) = line.split("listening on http://").nth(1) {
|
||||
addr = Some(rest.trim().to_string());
|
||||
break;
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
let addr = addr.expect("server must print its address");
|
||||
std::thread::spawn(move || for _ in reader.lines() {});
|
||||
|
||||
// The API never shows the webhook URL's path: chat webhook URLs are credentials.
|
||||
let (status, body) = http_get(&addr, "/api/config");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains(&format!("http://127.0.0.1:{hook_port}/…")),
|
||||
"{body}"
|
||||
);
|
||||
assert!(!body.contains("secret-path"), "{body}");
|
||||
|
||||
let scan = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
assert!(
|
||||
scan.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&scan.stderr)
|
||||
);
|
||||
|
||||
let (headers, body) = deliveries
|
||||
.recv_timeout(Duration::from_secs(15))
|
||||
.expect("the webhook receives the sweep's changes");
|
||||
let payload: serde_json::Value = serde_json::from_slice(&body).expect("JSON body");
|
||||
assert_eq!(payload["grupo"], "local");
|
||||
let events = payload["eventos"].as_array().expect("events array");
|
||||
assert!(!events.is_empty());
|
||||
assert!(
|
||||
events.iter().all(|event| event["tipo"] == "porta_nova"),
|
||||
"only subscribed kinds are sent: {payload}"
|
||||
);
|
||||
let expected = harpia_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body);
|
||||
assert!(
|
||||
headers.contains(&format!("x-harpia-signature: {expected}")),
|
||||
"signature header in: {headers}"
|
||||
);
|
||||
|
||||
// The dead receiver is retried (2 s, then 4 s) before it counts as a failure.
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
let metrics = loop {
|
||||
let (status, body) = http_get(&addr, "/metrics");
|
||||
assert_eq!(status, 200);
|
||||
if body.contains("harpia_webhook_deliveries_total{resultado=\"falha\"} 1")
|
||||
|| Instant::now() > deadline
|
||||
{
|
||||
break body;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
};
|
||||
for expected in [
|
||||
"harpia_sweeps_ingested_total 1",
|
||||
"harpia_assets{status=\"ativo\"} 1",
|
||||
"harpia_open_ports 1",
|
||||
"harpia_last_sweep_complete{grupo=\"local\"} 1",
|
||||
"harpia_webhook_deliveries_total{resultado=\"ok\"} 1",
|
||||
"harpia_webhook_deliveries_total{resultado=\"falha\"} 1",
|
||||
"# TYPE harpia_findings gauge",
|
||||
] {
|
||||
assert!(
|
||||
metrics.contains(expected),
|
||||
"missing `{expected}` in:\n{metrics}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
const ADMIN_TOKEN: &str = "e2e-admin-token-0123456789";
|
||||
|
||||
fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
|
||||
let auth = format!("Authorization: Bearer {ADMIN_TOKEN}\r\n");
|
||||
http_request_with(addr, method, path, body, &auth)
|
||||
}
|
||||
|
||||
/// `extra_headers` is a raw block of `Name: value\r\n` lines.
|
||||
fn http_request_with(
|
||||
addr: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&str>,
|
||||
extra_headers: &str,
|
||||
) -> (u16, String, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.expect("set read timeout");
|
||||
|
||||
let payload = body.unwrap_or("");
|
||||
let request = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{extra_headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
|
||||
payload.len()
|
||||
);
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
|
||||
let parts: Vec<&str> = response.split("\r\n\r\n").collect();
|
||||
let header_part = parts.first().copied().unwrap_or("");
|
||||
let body_part = parts.get(1).copied().unwrap_or("").to_string();
|
||||
|
||||
let status_line = header_part.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
|
||||
(code, header_part.to_string(), body_part)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_crud_and_export_e2e() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||
responsavel = "SecOps Test"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "inicial"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
// 1. Spawn `harpia serve --bind 127.0.0.1:0`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.env("HARPIA_ADMIN_TOKEN", ADMIN_TOKEN)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut server_addr = None;
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).is_ok() {
|
||||
if let Some(pos) = line.find("http://") {
|
||||
let addr = line[pos + 7..].trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
|
||||
let _server_guard = ChildGuard(child);
|
||||
let addr = server_addr.expect("server must output listening address");
|
||||
|
||||
// 2. Test GET /api/config
|
||||
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(body.contains("\"escopo\""));
|
||||
assert!(body.contains("\"inicial\""));
|
||||
|
||||
// Writes need the admin token; a browser Origin must match Host.
|
||||
let group = r#"{"nome": "sem-token", "alvos": ["127.0.0.1"]}"#;
|
||||
let (code, headers, _) =
|
||||
http_request_with(&addr, "POST", "/api/config/groups", Some(group), "");
|
||||
assert_eq!(code, 401);
|
||||
assert!(headers.contains("www-authenticate: Bearer"));
|
||||
let wrong = "Authorization: Bearer e2e-admin-token-0123456788\r\n";
|
||||
let (code, _, _) = http_request_with(&addr, "POST", "/api/config/groups", Some(group), wrong);
|
||||
assert_eq!(code, 401);
|
||||
let (code, _, _) = http_request_with(&addr, "DELETE", "/api/config/groups/inicial", None, "");
|
||||
assert_eq!(code, 401);
|
||||
let cross_site =
|
||||
format!("Authorization: Bearer {ADMIN_TOKEN}\r\nOrigin: https://evil.example\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(group),
|
||||
&cross_site,
|
||||
);
|
||||
assert_eq!(code, 403);
|
||||
let same_site = format!("X-Harpia-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
|
||||
let (code, _, _) = http_request_with(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(r#"{"nome": "fora", "alvos": ["192.168.1.1"]}"#),
|
||||
&same_site,
|
||||
);
|
||||
assert_eq!(
|
||||
code, 400,
|
||||
"same-origin request with the custom header reaches the handler"
|
||||
);
|
||||
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(
|
||||
!body.contains("sem-token"),
|
||||
"rejected writes must not change the config"
|
||||
);
|
||||
|
||||
// 3. Test POST /api/config/groups - out of scope rejection
|
||||
let (code, _, body) = http_request(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(r#"{"nome": "fora-escopo", "alvos": ["192.168.1.1"]}"#),
|
||||
);
|
||||
assert_eq!(code, 400);
|
||||
assert!(body.contains("fora do escopo autorizado"));
|
||||
|
||||
// 4. Test POST /api/config/groups - invalid cron rejection
|
||||
let (code, _, body) = http_request(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(r#"{"nome": "cron-ruim", "alvos": ["10.0.0.1"], "cron": "isto-nao-e-cron"}"#),
|
||||
);
|
||||
assert_eq!(code, 400);
|
||||
assert!(body.contains("cron inválido"));
|
||||
|
||||
// 5. Test POST /api/config/groups - valid creation
|
||||
let (code, _, body) = http_request(
|
||||
&addr,
|
||||
"POST",
|
||||
"/api/config/groups",
|
||||
Some(
|
||||
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.10"], "cron": "0 3 * * *", "criticidade": "alta"}"#,
|
||||
),
|
||||
);
|
||||
assert_eq!(code, 201);
|
||||
assert!(body.contains("\"novo-grupo\""));
|
||||
|
||||
// Verify config file was updated on disk
|
||||
let file_content = fs::read_to_string(&config_path).expect("read config file");
|
||||
assert!(file_content.contains("novo-grupo"));
|
||||
|
||||
// 6. Test PUT /api/config/groups/novo-grupo - update group
|
||||
let (code, _, body) = http_request(
|
||||
&addr,
|
||||
"PUT",
|
||||
"/api/config/groups/novo-grupo",
|
||||
Some(
|
||||
r#"{"nome": "novo-grupo", "alvos": ["10.0.0.20"], "cron": "0 4 * * *", "criticidade": "critica"}"#,
|
||||
),
|
||||
);
|
||||
assert_eq!(code, 200);
|
||||
assert!(body.contains("10.0.0.20"));
|
||||
assert!(body.contains("critica"));
|
||||
|
||||
// 7. Test DELETE /api/config/groups/novo-grupo - delete group
|
||||
let (code, _, _) = http_request(&addr, "DELETE", "/api/config/groups/novo-grupo", None);
|
||||
assert_eq!(code, 200);
|
||||
|
||||
// Verify file on disk has only 1 group
|
||||
let file_content = fs::read_to_string(&config_path).expect("read config file");
|
||||
assert!(!file_content.contains("novo-grupo"));
|
||||
|
||||
// 8. Test DELETE /api/config/groups/inicial - cannot delete last group
|
||||
let (code, _, body) = http_request(&addr, "DELETE", "/api/config/groups/inicial", None);
|
||||
assert_eq!(code, 400);
|
||||
assert!(body.contains("último grupo"));
|
||||
|
||||
// 9. Test CSV Exports
|
||||
// Hosts CSV
|
||||
let (code, headers, body) = http_request(&addr, "GET", "/api/export/hosts.csv", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-hosts-"));
|
||||
assert!(body.starts_with("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados"));
|
||||
|
||||
// Findings CSV
|
||||
let (code, headers, body) = http_request(&addr, "GET", "/api/export/findings.csv", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-findings-"));
|
||||
assert!(body.starts_with("Endereço IP,Porta,CVE / ID,CVSS,No KEV,Confiança,Título,Descrição"));
|
||||
|
||||
// Changes CSV
|
||||
let (code, headers, body) =
|
||||
http_request(&addr, "GET", "/api/export/changes.csv?since=24h", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/csv; charset=utf-8"));
|
||||
assert!(headers.contains("content-disposition: attachment; filename=\"harpia-changes-"));
|
||||
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
|
||||
|
||||
// Executive Report HTML
|
||||
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("Indicadores-Chave de Exposição (KPIs)"));
|
||||
assert!(body.contains("Glossário e Metodologia de Avaliação"));
|
||||
|
||||
let (code, headers, _) = http_request(&addr, "GET", "/report", None);
|
||||
assert_eq!(code, 200);
|
||||
assert!(headers.contains("content-type: text/html; charset=utf-8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_hot_reload_on_config_file_change() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "primeiro"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("write initial configuration");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.env("HARPIA_SCANNER_TICK_SECS", "1")
|
||||
.args([
|
||||
"scanner",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia scanner");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let _scanner_guard = ChildGuard(child);
|
||||
|
||||
// Read initial startup line
|
||||
let mut initial_line = String::new();
|
||||
reader
|
||||
.read_line(&mut initial_line)
|
||||
.expect("read initial line");
|
||||
assert!(initial_line.contains("1 grupo(s) configurado(s)"));
|
||||
|
||||
// Sleep briefly so filesystem mtime changes
|
||||
std::thread::sleep(Duration::from_millis(1100));
|
||||
|
||||
// Append second group to config file
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32", "10.0.0.0/24"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "primeiro"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
|
||||
[[grupo]]
|
||||
nome = "segundo"
|
||||
alvos = ["10.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("update configuration");
|
||||
|
||||
// Wait for reload log message
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut reloaded = false;
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).is_ok()
|
||||
&& line.contains("configuração recarregada com sucesso (2 grupos)")
|
||||
{
|
||||
reloaded = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
reloaded,
|
||||
"scanner should detect modified config file and reload"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
use chrono::Utc;
|
||||
use harpia_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState};
|
||||
use harpia_core::storage::{SqliteStorage, Storage};
|
||||
use harpia_core::vuln::matcher::{Confidence, Finding, FindingType};
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn doctor_command_json_and_table_and_invalid_config() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let valid_config = workspace.path().join("harpia.toml");
|
||||
let invalid_config = workspace.path().join("invalid.toml");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&valid_config,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["10.0.0.0/8"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
|
||||
[[grupo]]
|
||||
nome = "servidores"
|
||||
alvos = ["10.0.0.1"]
|
||||
"#,
|
||||
)
|
||||
.expect("write valid config");
|
||||
|
||||
fs::write(&invalid_config, "invalid toml content !!").expect("write invalid config");
|
||||
|
||||
// 1. Valid doctor in table mode
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"expected success: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("Harpia v"));
|
||||
assert!(stdout.contains("versao"));
|
||||
assert!(stdout.contains("config"));
|
||||
assert!(stdout.contains("sqlite"));
|
||||
assert!(stdout.contains("Resultado: OK"));
|
||||
|
||||
// 2. Valid doctor in JSON mode
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--json",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor --json");
|
||||
|
||||
assert!(output_json.status.success());
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse json output");
|
||||
assert_eq!(parsed["ok"], true);
|
||||
assert!(parsed["checks"].is_array());
|
||||
let checks = parsed["checks"].as_array().unwrap();
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "config" && c["status"] == "ok"));
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "sqlite" && c["status"] == "ok"));
|
||||
|
||||
// 3. Invalid doctor mode exits with error code 1
|
||||
let output_invalid = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
invalid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia doctor with invalid config");
|
||||
|
||||
assert!(!output_invalid.status.success());
|
||||
let stdout_invalid = String::from_utf8_lossy(&output_invalid.stdout);
|
||||
assert!(stdout_invalid.contains("Resultado: FALHA"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_command_json_and_csv_with_fixture() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
let db_path = data_dir.join("harpia.db");
|
||||
let mut storage = SqliteStorage::open(&db_path).expect("open sqlite storage");
|
||||
|
||||
let now = Utc::now();
|
||||
let diff = DiffResult {
|
||||
state: vec![AssetState {
|
||||
asset_key: "dmz/10.0.0.42".to_string(),
|
||||
network: "dmz".to_string(),
|
||||
ip: "10.0.0.42".parse().unwrap(),
|
||||
status: AssetStatus::Active,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
ports: vec![ServiceState {
|
||||
protocol: "tcp".to_string(),
|
||||
port: 80,
|
||||
status: PortStatus::Open,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
product: Some("nginx".to_string()),
|
||||
version: Some("1.18.0".to_string()),
|
||||
cpe: Some("cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*".to_string()),
|
||||
findings: vec![Finding {
|
||||
tipo: FindingType::Cve,
|
||||
id: "CVE-2021-23017".to_string(),
|
||||
cvss: Some(7.5),
|
||||
kev: false,
|
||||
confianca: Confidence::Alto,
|
||||
title: "1-byte memory overwrite in resolver".to_string(),
|
||||
description: "A 1-byte memory overwrite vulnerability exists in resolver."
|
||||
.to_string(),
|
||||
evidencia: serde_json::json!({ "banner": "nginx 1.18.0" }),
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
events: vec![],
|
||||
};
|
||||
|
||||
storage
|
||||
.apply_diff(&diff)
|
||||
.expect("apply fixture state to database");
|
||||
|
||||
// 1. Export JSON to stdout
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"json",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia export --format json");
|
||||
|
||||
assert!(
|
||||
output_json.status.success(),
|
||||
"export json failed: {}",
|
||||
String::from_utf8_lossy(&output_json.stderr)
|
||||
);
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse export json");
|
||||
assert!(parsed.is_array());
|
||||
let hosts = parsed.as_array().unwrap();
|
||||
assert_eq!(hosts.len(), 1);
|
||||
assert_eq!(hosts[0]["ip"], "10.0.0.42");
|
||||
assert_eq!(hosts[0]["network"], "dmz");
|
||||
assert_eq!(hosts[0]["ports"][0]["port"], 80);
|
||||
assert_eq!(hosts[0]["ports"][0]["product"], "nginx");
|
||||
assert_eq!(hosts[0]["ports"][0]["findings"][0]["id"], "CVE-2021-23017");
|
||||
|
||||
// 2. Export CSV to file with --out
|
||||
let out_csv_file = workspace.path().join("export.csv");
|
||||
let output_csv = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"csv",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
"--out",
|
||||
out_csv_file.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia export --format csv --out ...");
|
||||
|
||||
assert!(output_csv.status.success());
|
||||
let csv_content = fs::read_to_string(&out_csv_file).expect("read exported csv");
|
||||
assert!(csv_content.contains("Endereço IP,Grupo,Status do Host,Protocolo,Porta"));
|
||||
assert!(csv_content.contains("10.0.0.42,dmz,ativo,tcp,80,aberta,nginx,1.18.0,cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*,7.5,1"));
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
let status_line = response.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
fn start_mock_feed_server() -> (String, std::thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
|
||||
let addr = listener.local_addr().expect("mock address").to_string();
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let mut stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(_) => break,
|
||||
};
|
||||
let mut buf = [0u8; 2048];
|
||||
let n = stream.read(&mut buf).unwrap_or(0);
|
||||
let req = String::from_utf8_lossy(&buf[..n]);
|
||||
|
||||
if req.contains("/cves") {
|
||||
let body = r#"{
|
||||
"format": "NVD_CVE",
|
||||
"version": "2.0",
|
||||
"vulnerabilities": [
|
||||
{
|
||||
"cve": {
|
||||
"id": "CVE-2021-41773",
|
||||
"descriptions": [
|
||||
{"lang": "en", "value": "Apache HTTP Server path traversal"}
|
||||
],
|
||||
"metrics": {
|
||||
"cvssMetricV31": [
|
||||
{"cvssData": {"baseScore": 7.5}}
|
||||
]
|
||||
},
|
||||
"configurations": [
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"cpeMatch": [
|
||||
{
|
||||
"criteria": "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*",
|
||||
"vulnerable": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let resp = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
} else if req.contains("/kev") {
|
||||
let body = r#"{
|
||||
"title": "CISA KEV",
|
||||
"vulnerabilities": [
|
||||
{"cveID": "CVE-2021-41773"}
|
||||
]
|
||||
}"#;
|
||||
let resp = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
} else {
|
||||
let resp =
|
||||
"HTTP/1.1 404 NOT FOUND\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
(addr, handle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feeds_import_command_and_serve_loads_database() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let feeds_dir = workspace.path().join("feeds_in");
|
||||
let data_dir = workspace.path().join("data");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
fs::create_dir_all(&feeds_dir).expect("create feeds dir");
|
||||
|
||||
let nvd_content = r#"{
|
||||
"format": "NVD_CVE",
|
||||
"version": "2.0",
|
||||
"vulnerabilities": [
|
||||
{
|
||||
"cve": {
|
||||
"id": "CVE-2024-6387",
|
||||
"descriptions": [{"lang": "en", "value": "regreSSHion"}],
|
||||
"configurations": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"cve": {
|
||||
"id": "CVE-2021-41773",
|
||||
"descriptions": [{"lang": "en", "value": "Apache traversal"}],
|
||||
"configurations": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
fs::write(feeds_dir.join("nvd.json"), nvd_content).expect("write nvd.json");
|
||||
|
||||
let kev_content = r#"{"vulnerabilities": [{"cveID": "CVE-2021-41773"}]}"#;
|
||||
fs::write(feeds_dir.join("kev.json"), kev_content).expect("write kev.json");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
// 1. Run `harpia feeds import <feeds_dir> --data-dir <data_dir>`
|
||||
let import_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"feeds",
|
||||
"import",
|
||||
feeds_dir.to_str().expect("feeds dir"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run feeds import");
|
||||
|
||||
assert!(
|
||||
import_output.status.success(),
|
||||
"import failed: {}",
|
||||
String::from_utf8_lossy(&import_output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&import_output.stdout);
|
||||
assert!(stdout.contains("2 CVEs (1 no KEV)"), "stdout: {stdout}");
|
||||
|
||||
let db_path = data_dir.join("vuln_db.json");
|
||||
assert!(db_path.exists(), "vuln_db.json must exist");
|
||||
|
||||
// 2. Start `harpia serve` and ensure /api/status displays the imported database
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout_pipe = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout_pipe);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
let mut line = String::new();
|
||||
while Instant::now() < deadline {
|
||||
line.clear();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(n) if n > 0 => {
|
||||
if line.contains("listening on http://") {
|
||||
let addr = line
|
||||
.split("http://")
|
||||
.nth(1)
|
||||
.expect("server address part")
|
||||
.trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server must print address");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""feeds_cve_count":2"#), "body: {body}");
|
||||
assert!(body.contains(r#""feeds_kev_count":1"#), "body: {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feeds_sync_mock_http_and_periodic_serve_timer() {
|
||||
let (mock_addr, _mock_handle) = start_mock_feed_server();
|
||||
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let data_dir = workspace.path().join("data");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[padrao.feeds]
|
||||
sincronizar_automaticamente = true
|
||||
intervalo_sincronizacao = "1s"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
// 1. Run `harpia feeds sync` using mock endpoints
|
||||
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"feeds",
|
||||
"sync",
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
|
||||
.env("HARPIA_KEV_URL", format!("http://{mock_addr}/kev"))
|
||||
.output()
|
||||
.expect("run feeds sync");
|
||||
|
||||
assert!(
|
||||
sync_output.status.success(),
|
||||
"sync failed: {}",
|
||||
String::from_utf8_lossy(&sync_output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&sync_output.stdout);
|
||||
assert!(
|
||||
stdout.contains("1 CVEs totais (1 no KEV)"),
|
||||
"stdout: {stdout}"
|
||||
);
|
||||
|
||||
// 2. Start `harpia serve` with auto-sync enabled
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", format!("http://{mock_addr}/cves"))
|
||||
.env("HARPIA_KEV_URL", format!("http://{mock_addr}/kev"))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout_pipe = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout_pipe);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
let mut line = String::new();
|
||||
while Instant::now() < deadline {
|
||||
line.clear();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(n) if n > 0 => {
|
||||
if line.contains("listening on http://") {
|
||||
let addr = line
|
||||
.split("http://")
|
||||
.nth(1)
|
||||
.expect("server address part")
|
||||
.trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server must print address");
|
||||
|
||||
// Wait 1.5s for the 1s auto-sync timer to fire
|
||||
std::thread::sleep(Duration::from_millis(1500));
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""feeds_cve_count":1"#), "body: {body}");
|
||||
assert!(
|
||||
body.contains(r#""feeds_last_sync":""#),
|
||||
"body must have last sync timestamp: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feeds_sync_network_failure_does_not_corrupt_existing_database_and_server_stays_healthy() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let data_dir = workspace.path().join("data");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
// Pre-populate with initial database
|
||||
let initial_db_content = r#"{
|
||||
"nvd": {
|
||||
"records": {
|
||||
"CVE-1999-0001": {
|
||||
"id": "CVE-1999-0001",
|
||||
"description": "Historical vulnerability",
|
||||
"cvss_score": 5.0,
|
||||
"cvss_vector": null,
|
||||
"cpe_matches": []
|
||||
}
|
||||
}
|
||||
},
|
||||
"kev": {
|
||||
"cve_ids": []
|
||||
}
|
||||
}"#;
|
||||
fs::write(data_dir.join("vuln_db.json"), initial_db_content).expect("write initial db");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[padrao.feeds]
|
||||
sincronizar_automaticamente = true
|
||||
intervalo_sincronizacao = "1s"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "80"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
// 1. Run `harpia feeds sync` pointing to an unreachable port (e.g. 127.0.0.1:1)
|
||||
let sync_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"feeds",
|
||||
"sync",
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.env("HARPIA_KEV_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.output()
|
||||
.expect("run feeds sync");
|
||||
|
||||
// Must exit with failure
|
||||
assert!(
|
||||
!sync_output.status.success(),
|
||||
"sync to unreachable address must fail with error code"
|
||||
);
|
||||
|
||||
// Existing database must NOT be corrupted
|
||||
let db_content = fs::read_to_string(data_dir.join("vuln_db.json")).expect("read db");
|
||||
assert!(
|
||||
db_content.contains("CVE-1999-0001"),
|
||||
"original db must remain intact"
|
||||
);
|
||||
|
||||
// 2. Start `harpia serve` pointing to unreachable port for auto_sync
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.env("HARPIA_NVD_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.env("HARPIA_KEV_URL", "http://127.0.0.1:1/nonexistent")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout_pipe = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout_pipe);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
let mut line = String::new();
|
||||
while Instant::now() < deadline {
|
||||
line.clear();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(n) if n > 0 => {
|
||||
if line.contains("listening on http://") {
|
||||
let addr = line
|
||||
.split("http://")
|
||||
.nth(1)
|
||||
.expect("server address part")
|
||||
.trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server must print address");
|
||||
|
||||
// Wait 1.5s for the timer to tick and fail network call
|
||||
std::thread::sleep(Duration::from_millis(1500));
|
||||
|
||||
// Server must still be alive and respond HTTP 200 OK
|
||||
let (health_status, health_body) = http_get(&server_addr, "/api/health");
|
||||
assert_eq!(health_status, 200);
|
||||
assert!(health_body.contains(r#""status":"ok""#));
|
||||
|
||||
// Status must still show the intact database
|
||||
let (status_code, status_body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status_code, 200);
|
||||
assert!(status_body.contains(r#""feeds_cve_count":1"#));
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use harpia_core::batch::SweepBatch;
|
||||
use harpia_core::vuln::feeds::{Cpe, CpeMatchCriteria, CveRecord, VulnDatabase};
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
let status_line = response.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_and_vuln_matching_e2e() {
|
||||
// 1. Mock HTTP service returning Apache 2.4.49 Server header
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
|
||||
let target_port = target_listener.local_addr().expect("target address").port();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
for stream in target_listener.incoming() {
|
||||
let mut stream = match stream {
|
||||
Ok(s) => s,
|
||||
Err(_) => break,
|
||||
};
|
||||
let mut buf = [0u8; 1024];
|
||||
let _ = stream.read(&mut buf);
|
||||
let resp = "HTTP/1.1 200 OK\r\nServer: Apache/2.4.49 (Unix)\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK";
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Setup workspace, config, and fixture vuln_db.json
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{target_port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
let mut db = VulnDatabase::default();
|
||||
db.kev.cve_ids.insert("CVE-2021-41773".to_string());
|
||||
db.nvd.records.insert(
|
||||
"CVE-2021-41773".to_string(),
|
||||
CveRecord {
|
||||
id: "CVE-2021-41773".to_string(),
|
||||
description: "Path traversal and file disclosure in Apache HTTP Server 2.4.49"
|
||||
.to_string(),
|
||||
cvss_score: Some(7.5),
|
||||
cvss_vector: None,
|
||||
cpe_matches: vec![CpeMatchCriteria {
|
||||
criteria: "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*".to_string(),
|
||||
cpe: Cpe::parse("cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*").unwrap(),
|
||||
version_start_including: None,
|
||||
version_start_excluding: None,
|
||||
version_end_including: None,
|
||||
version_end_excluding: None,
|
||||
}],
|
||||
},
|
||||
);
|
||||
db.save_to_file(&data_dir.join("vuln_db.json"))
|
||||
.expect("save fixture vuln_db.json");
|
||||
|
||||
// 3. Run scan --once with --data-dir pointing to our fixture database
|
||||
let scan_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
|
||||
assert!(
|
||||
scan_output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&scan_output.stderr)
|
||||
);
|
||||
|
||||
// 4. Validate generated Parquet batch
|
||||
let group_dir = sweeps_dir.join("local");
|
||||
let sweep_dir = fs::read_dir(&group_dir)
|
||||
.expect("group directory")
|
||||
.next()
|
||||
.expect("one sweep")
|
||||
.expect("sweep entry")
|
||||
.path();
|
||||
|
||||
let batch = SweepBatch::read(&sweep_dir).expect("read batch");
|
||||
assert_eq!(batch.services.len(), 1, "expected 1 service observation");
|
||||
let service = &batch.services[0];
|
||||
assert_eq!(service.port, target_port);
|
||||
assert_eq!(service.product.as_deref(), Some("Apache HTTP Server"));
|
||||
assert_eq!(service.version.as_deref(), Some("2.4.49"));
|
||||
assert!(
|
||||
service
|
||||
.cpe
|
||||
.as_ref()
|
||||
.map(|s| s.contains("http_server"))
|
||||
.unwrap_or(false),
|
||||
"cpe should contain http_server: {:?}",
|
||||
service.cpe
|
||||
);
|
||||
assert_eq!(service.findings.len(), 1, "expected 1 finding on service");
|
||||
let finding = &service.findings[0];
|
||||
assert_eq!(finding.id, "CVE-2021-41773");
|
||||
assert!(finding.kev);
|
||||
assert_eq!(finding.cvss, Some(7.5));
|
||||
|
||||
// 5. Run serve and verify /api/hosts
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(pos) = line.find("http://") {
|
||||
let rest = &line[pos + "http://".len()..];
|
||||
let addr = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server failed to output listening address");
|
||||
|
||||
// Poll /api/hosts until the sweep is ingested and host has findings
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut finding_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("CVE-2021-41773") && body.contains("Apache HTTP Server") {
|
||||
finding_found = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
|
||||
assert!(
|
||||
finding_found,
|
||||
"expected /api/hosts to return Apache HTTP Server and CVE-2021-41773"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use std::process::Command;
|
||||
|
||||
use harpia_core::batch::{SweepBatch, SweepStatus};
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn scan_once_writes_a_complete_batch_with_the_open_port() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
|
||||
let port = listener.local_addr().expect("listener address").port();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
if stream.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config = workspace.path().join("harpia.toml");
|
||||
fs::write(
|
||||
&config,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
let sweeps = workspace.path().join("sweeps");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("vivos: 1"), "unexpected stdout: {stdout}");
|
||||
|
||||
let group_dir = sweeps.join("local");
|
||||
let sweep_dir = fs::read_dir(&group_dir)
|
||||
.expect("group directory")
|
||||
.next()
|
||||
.expect("one sweep")
|
||||
.expect("sweep entry")
|
||||
.path();
|
||||
|
||||
let batch = SweepBatch::read(&sweep_dir).expect("read batch");
|
||||
assert_eq!(batch.manifest.status, SweepStatus::Complete);
|
||||
assert_eq!(batch.manifest.group, "local");
|
||||
assert_eq!(batch.alive_hosts().count(), 1);
|
||||
|
||||
let open: Vec<u16> = batch.open_ports("127.0.0.1".parse().expect("ip")).collect();
|
||||
assert_eq!(open, vec![port]);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).expect("read response");
|
||||
let status_line = response.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_ingests_sweeps_and_responds_to_api_and_dashboard() {
|
||||
// 1. Start a target listener on loopback.
|
||||
let target_listener = TcpListener::bind("127.0.0.1:0").expect("bind target listener");
|
||||
let target_port = target_listener.local_addr().expect("target address").port();
|
||||
std::thread::spawn(move || {
|
||||
for stream in target_listener.incoming() {
|
||||
if stream.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Setup workspace with config, sweeps dir, and data dir.
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("harpia.toml");
|
||||
let sweeps_dir = workspace.path().join("sweeps");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
format!(
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["127.0.0.1/32"]
|
||||
responsavel = "teste"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
hosts_simultaneos = 2
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "{target_port}"
|
||||
|
||||
[[grupo]]
|
||||
nome = "local"
|
||||
alvos = ["127.0.0.1/32"]
|
||||
"#
|
||||
),
|
||||
)
|
||||
.expect("write configuration");
|
||||
|
||||
// 3. Spawn `harpia serve --bind 127.0.0.1:0 ...`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data dir"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
let mut line = String::new();
|
||||
while Instant::now() < deadline {
|
||||
line.clear();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(n) if n > 0 => {
|
||||
if line.contains("listening on http://") {
|
||||
let addr = line
|
||||
.split("http://")
|
||||
.nth(1)
|
||||
.expect("server address part")
|
||||
.trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server must print listening address");
|
||||
|
||||
// 4. Test /api/health
|
||||
let (status, body) = http_get(&server_addr, "/api/health");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""status":"ok""#), "health body: {body}");
|
||||
|
||||
// 5. Test /api/status before sweep ingestion
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains(r#""status":"ok""#), "status body: {body}");
|
||||
|
||||
// 6. Run scan --once to produce a sweep batch into sweeps_dir
|
||||
let scan_output = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"scan",
|
||||
"--group",
|
||||
"local",
|
||||
"--once",
|
||||
"--config",
|
||||
config_path.to_str().expect("config path"),
|
||||
"--out",
|
||||
sweeps_dir.to_str().expect("sweeps path"),
|
||||
])
|
||||
.output()
|
||||
.expect("run harpia scan");
|
||||
assert!(
|
||||
scan_output.status.success(),
|
||||
"scan failed: {}",
|
||||
String::from_utf8_lossy(&scan_output.stderr)
|
||||
);
|
||||
|
||||
// 7. Poll /api/hosts until the background poller ingests the sweep and exposes the host
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut host_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("127.0.0.1") && body.contains(&target_port.to_string()) {
|
||||
assert!(
|
||||
body.contains(r#""status":"ativo""#),
|
||||
"asset status in: {body}"
|
||||
);
|
||||
host_found = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
assert!(
|
||||
host_found,
|
||||
"expected host and port to be ingested and visible in /api/hosts"
|
||||
);
|
||||
|
||||
// 8. Verify /api/status now reflects the ingested sweep
|
||||
let (status, body) = http_get(&server_addr, "/api/status");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains(r#""sweeps_ingested":1"#),
|
||||
"status sweeps_ingested: {body}"
|
||||
);
|
||||
|
||||
// 9. Verify /api/changes?since=24h returns diff events
|
||||
let (status, body) = http_get(&server_addr, "/api/changes?since=24h");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("host_novo") || body.contains("porta_nova"),
|
||||
"changes events: {body}"
|
||||
);
|
||||
|
||||
// 10. Verify / and /dashboard return HTML, and static assets are served
|
||||
let (status, body) = http_get(&server_addr, "/");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"), "dashboard html: {body}");
|
||||
assert!(body.contains("app.css"), "dashboard html links css: {body}");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/dashboard");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"), "dashboard html: {body}");
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.css");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("--sev-critical"),
|
||||
"app.css contains severity tokens"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("renderSeverityChart"),
|
||||
"app.js contains chart logic"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/i18n.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("export function tr"),
|
||||
"i18n.js contains tr function"
|
||||
);
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/i18n-en.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(
|
||||
body.contains("export const EN"),
|
||||
"i18n-en.js contains dictionary"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct ChildGuard(std::process::Child);
|
||||
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_get(addr: &str, path: &str) -> (u16, String) {
|
||||
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).expect("write request");
|
||||
let mut bytes = Vec::new();
|
||||
stream.read_to_end(&mut bytes).expect("read response");
|
||||
let response = String::from_utf8_lossy(&bytes).to_string();
|
||||
let status_line = response.lines().next().unwrap_or("");
|
||||
let code: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("0")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||
(code, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_validates_against_real_dvwa_scan_data() {
|
||||
let validate_dir = Path::new("/tmp/harpia-validate");
|
||||
if !validate_dir.exists() {
|
||||
eprintln!("skip: /tmp/harpia-validate does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
let config_path = validate_dir.join("harpia.toml");
|
||||
let sweeps_dir = validate_dir.join("sweeps");
|
||||
let data_dir = validate_dir.join("data");
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_harpia"))
|
||||
.args([
|
||||
"serve",
|
||||
"--bind",
|
||||
"127.0.0.1:0",
|
||||
"--config",
|
||||
config_path.to_str().expect("config"),
|
||||
"--sweeps",
|
||||
sweeps_dir.to_str().expect("sweeps"),
|
||||
"--data-dir",
|
||||
data_dir.to_str().expect("data"),
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.expect("spawn harpia serve");
|
||||
|
||||
let stdout = child.stdout.take().expect("take stdout");
|
||||
let mut reader = BufReader::new(stdout);
|
||||
let mut server_addr = None;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
if let Some(pos) = line.find("http://") {
|
||||
let rest = &line[pos + "http://".len()..];
|
||||
let addr = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
server_addr = Some(addr.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _guard = ChildGuard(child);
|
||||
let server_addr = server_addr.expect("server listening addr");
|
||||
|
||||
// Poll /api/hosts
|
||||
let poll_deadline = Instant::now() + Duration::from_secs(6);
|
||||
let mut dvwa_found = false;
|
||||
while Instant::now() < poll_deadline {
|
||||
let (status, body) = http_get(&server_addr, "/api/hosts");
|
||||
if status == 200 && body.contains("172.30.0.10") && body.contains("CVE-2017-3167") {
|
||||
dvwa_found = true;
|
||||
assert!(body.contains("Apache HTTP Server"));
|
||||
assert!(body.contains("2.4.25"));
|
||||
assert!(body.contains(r#""cvss":9.8"#));
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
|
||||
assert!(
|
||||
dvwa_found,
|
||||
"expected DVWA host 172.30.0.10 with CVE-2017-3167 in /api/hosts"
|
||||
);
|
||||
|
||||
// Check dashboard and static assets
|
||||
let (status, body) = http_get(&server_addr, "/");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("Harpia"));
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.css");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("--sev-critical"));
|
||||
|
||||
let (status, body) = http_get(&server_addr, "/app.js");
|
||||
assert_eq!(status, 200);
|
||||
assert!(body.contains("renderSeverityChart"));
|
||||
|
||||
let (status, _) = http_get(&server_addr, "/logo.png");
|
||||
assert_eq!(status, 200);
|
||||
}
|
||||
Reference in new issue
Block a user