feat(api,gui): implement target groups CRUD, scanner hot-reload, and CSV export
This commit is contained in:
1 parent
bc72dbffbd
commit
e8e529b09c
7 files changed
+1154
-41
No files matched your search
+406
-13
@@ -7,8 +7,8 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::extract::{Path as AxumPath, Query, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Json, Router};
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -16,8 +16,8 @@ use clap::{Parser, Subcommand};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use xexeu_core::batch::{EngineMode, ServiceObservation, SweepBatch, SweepManifest, SweepStatus};
|
||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
||||
use xexeu_core::config::{GroupConfig, ValidationReport, XexeuConfig};
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions, EventKind};
|
||||
use xexeu_core::scan::{
|
||||
discover_hosts_tcp, fingerprint_service, scan_hosts_tcp_connect, DiscoveryConfig, HostState,
|
||||
PortScanConfig, PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||
@@ -28,7 +28,7 @@ use xexeu_core::targets::{
|
||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||
};
|
||||
use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_response};
|
||||
use xexeu_core::vuln::matcher::{match_banner, Finding};
|
||||
use xexeu_core::vuln::matcher::{match_banner, Confidence, Finding};
|
||||
use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase};
|
||||
|
||||
const DEFAULT_CONFIG: &str = "config/xexeu.toml";
|
||||
@@ -515,7 +515,7 @@ async fn scan_once(
|
||||
}
|
||||
|
||||
async fn run_scanner(config_path: &Path, out_dir: &Path, data_dir: &Path) -> Result<(), String> {
|
||||
let (config, _report) = validated_config(config_path)?;
|
||||
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()))?;
|
||||
|
||||
@@ -535,7 +535,36 @@ async fn run_scanner(config_path: &Path, out_dir: &Path, data_dir: &Path) -> Res
|
||||
.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();
|
||||
@@ -684,7 +713,7 @@ async fn poll_sweeps(
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ServerState {
|
||||
config: Arc<XexeuConfig>,
|
||||
config: Arc<RwLock<XexeuConfig>>,
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
@@ -727,9 +756,9 @@ struct GroupScheduleDto {
|
||||
|
||||
async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse> {
|
||||
let now = Utc::now();
|
||||
let schedules = next_runs(&state.config, now).unwrap_or_default();
|
||||
let groups = state
|
||||
.config
|
||||
let config = state.config.read().await;
|
||||
let schedules = next_runs(&config, now).unwrap_or_default();
|
||||
let groups = config
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
@@ -740,8 +769,8 @@ async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse
|
||||
.unwrap_or_default();
|
||||
GroupScheduleDto {
|
||||
group: group.name.clone(),
|
||||
profile: group.effective_profile(&state.config).to_string(),
|
||||
cron: group.effective_cron(&state.config).to_string(),
|
||||
profile: group.effective_profile(&config).to_string(),
|
||||
cron: group.effective_cron(&config).to_string(),
|
||||
next_run,
|
||||
}
|
||||
})
|
||||
@@ -768,6 +797,349 @@ async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_config_handler(State(state): State<ServerState>) -> Json<XexeuConfig> {
|
||||
let config = state.config.read().await;
|
||||
Json(config.clone())
|
||||
}
|
||||
|
||||
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(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut config_guard = state.config.write().await;
|
||||
let mut draft = config_guard.clone();
|
||||
|
||||
if draft.groups.iter().any(|g| g.name == group_name) {
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
format!("grupo `{group_name}` já existe"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.groups.push(new_group.clone());
|
||||
|
||||
if let Err(err) = draft.validate() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("configuração inválida: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao salvar configuração: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
*config_guard = draft;
|
||||
Ok((StatusCode::CREATED, Json(new_group)))
|
||||
}
|
||||
|
||||
async fn update_group_handler(
|
||||
State(state): State<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 new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) {
|
||||
return Err((
|
||||
StatusCode::CONFLICT,
|
||||
format!("grupo `{new_name}` já existe"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.groups[pos] = updated_group.clone();
|
||||
|
||||
if let Err(err) = draft.validate() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("configuração inválida: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
draft.save_to_file(&state.config_path).map_err(|err| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao salvar configuração: {err}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
*config_guard = draft;
|
||||
Ok(Json(updated_group))
|
||||
}
|
||||
|
||||
async fn delete_group_handler(
|
||||
State(state): State<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)
|
||||
}
|
||||
|
||||
fn csv_escape(s: &str) -> String {
|
||||
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
|
||||
let escaped = s.replace('"', "\"\"");
|
||||
format!("\"{escaped}\"")
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
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 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||
let disposition = format!("attachment; filename=\"xexeu-hosts-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
|
||||
async fn export_findings_csv_handler(
|
||||
State(state): State<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=\"xexeu-findings-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
|
||||
async fn export_changes_csv_handler(
|
||||
State(state): State<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=\"xexeu-changes-{timestamp}.csv\"");
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/csv; charset=utf-8"),
|
||||
);
|
||||
if let Ok(val) = HeaderValue::from_str(&disposition) {
|
||||
headers.insert(header::CONTENT_DISPOSITION, val);
|
||||
}
|
||||
|
||||
Ok((headers, csv))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HostDto {
|
||||
asset_key: String,
|
||||
@@ -1048,7 +1420,7 @@ async fn run_serve(
|
||||
}
|
||||
|
||||
let state = ServerState {
|
||||
config: Arc::new(config),
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
@@ -1061,6 +1433,27 @@ async fn run_serve(
|
||||
.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("/", axum::routing::get(index_handler))
|
||||
.route("/dashboard", axum::routing::get(index_handler))
|
||||
.route("/app.css", axum::routing::get(css_handler))
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
fn http_request(addr: &str, method: &str, path: &str, body: Option<&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\nContent-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("xexeu.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 `xexeu serve --bind 127.0.0.1:0`.
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.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 xexeu 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\""));
|
||||
|
||||
// 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=\"xexeu-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=\"xexeu-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=\"xexeu-changes-"));
|
||||
assert!(body.starts_with("Data/Hora (UTC),Tipo de Evento,Alvo / Host,Grupo,Detalhe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_hot_reload_on_config_file_change() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let config_path = workspace.path().join("xexeu.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_xexeu"))
|
||||
.env("XEXEU_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 xexeu 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"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user