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))
|
||||
|
||||
Reference in new issue
Block a user