Implementa xexeu feeds import/sync e sincronização periódica de CVE/KEV embutida no xexeu serve
This commit is contained in:
1 parent
b4d2c29d24
commit
4ce5d7f595
7 files changed
+1817
-48
No files matched your search
@@ -14,7 +14,7 @@ use axum::{Json, Router};
|
||||
use chrono::{DateTime, Utc};
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use xexeu_core::batch::{EngineMode, SweepBatch, SweepManifest, SweepStatus};
|
||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
||||
use xexeu_core::diff::{diff_batch, DiffOptions};
|
||||
@@ -27,6 +27,7 @@ use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
use xexeu_core::targets::{
|
||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||
};
|
||||
use xexeu_core::vuln::{import_kev, import_nvd, sync_feeds, KevCatalog, SyncOptions, VulnDatabase};
|
||||
|
||||
const DEFAULT_CONFIG: &str = "config/xexeu.toml";
|
||||
|
||||
@@ -118,12 +119,20 @@ enum FeedsAction {
|
||||
Sync {
|
||||
#[arg(long, default_value = "config/xexeu.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/xexeu")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
/// Import feed files copied manually for isolated networks.
|
||||
Import {
|
||||
directory: PathBuf,
|
||||
directory: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
nvd: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
kev: Option<PathBuf>,
|
||||
#[arg(long, default_value = "config/xexeu.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/xexeu")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -154,11 +163,23 @@ async fn main() -> ExitCode {
|
||||
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 } => run_doctor(json),
|
||||
Command::Feeds { .. } => not_implemented("feeds"),
|
||||
Command::Export { .. } => not_implemented("export"),
|
||||
}
|
||||
}
|
||||
@@ -605,6 +626,8 @@ struct ServerState {
|
||||
config_path: PathBuf,
|
||||
storage: Arc<Mutex<SqliteStorage>>,
|
||||
sweeps_ingested: Arc<AtomicUsize>,
|
||||
vuln_db: Arc<RwLock<VulnDatabase>>,
|
||||
feeds_last_sync: Arc<RwLock<Option<DateTime<Utc>>>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -626,6 +649,9 @@ struct StatusResponse {
|
||||
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>,
|
||||
}
|
||||
|
||||
@@ -659,11 +685,23 @@ async fn status_handler(State(state): State<ServerState>) -> Json<StatusResponse
|
||||
})
|
||||
.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,
|
||||
})
|
||||
}
|
||||
@@ -814,8 +852,8 @@ async fn dashboard_handler() -> Html<&'static str> {
|
||||
const sRes = await fetch('/api/status');
|
||||
const status = await sRes.json();
|
||||
document.getElementById('status-card').innerHTML = `
|
||||
<div><strong>Versão:</strong> ${status.version} | <strong>Lotes Ingeridos:</strong> ${status.sweeps_ingested}</div>
|
||||
<div style="margin-top: 6px; font-size: 0.85rem; color: #94a3b8;">Configuração: <code>${status.config_path}</code></div>
|
||||
<div><strong>Versão:</strong> ${status.version} | <strong>Lotes Ingeridos:</strong> ${status.sweeps_ingested} | <strong>CVEs:</strong> ${status.feeds_cve_count} (${status.feeds_kev_count} no KEV)</div>
|
||||
<div style="margin-top: 6px; font-size: 0.85rem; color: #94a3b8;">Configuração: <code>${status.config_path}</code> | <strong>Último Sync:</strong> ${status.feeds_last_sync || 'não executado'}</div>
|
||||
`;
|
||||
const hRes = await fetch('/api/hosts');
|
||||
const hosts = await hRes.json();
|
||||
@@ -842,6 +880,23 @@ async fn dashboard_handler() -> Html<&'static str> {
|
||||
Html(HTML)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
async fn run_serve(
|
||||
bind: &str,
|
||||
config_path: &Path,
|
||||
@@ -865,6 +920,33 @@ async fn run_serve(
|
||||
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));
|
||||
|
||||
// Spawn background poller for incoming sweeps.
|
||||
let poller_storage = Arc::clone(&shared_storage);
|
||||
let poller_ingested = Arc::clone(&sweeps_ingested);
|
||||
@@ -873,11 +955,50 @@ async fn run_serve(
|
||||
poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await;
|
||||
});
|
||||
|
||||
// Spawn periodic background sync if auto_sync is enabled in config
|
||||
if config.defaults.feeds.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();
|
||||
let interval_str = config.defaults.feeds.sync_interval.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: Arc::new(config),
|
||||
config_path: config_path.to_path_buf(),
|
||||
storage: shared_storage,
|
||||
sweeps_ingested,
|
||||
vuln_db: shared_vuln_db,
|
||||
feeds_last_sync: shared_last_sync,
|
||||
};
|
||||
|
||||
let app = Router::new()
|
||||
@@ -932,6 +1053,145 @@ fn run_changes(since: &str, data_dir: &Path) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
|
||||
Reference in new issue
Block a user