use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fs; use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; 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}; 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::{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, }; use xexeu_core::schedule::{next_runs, should_run_now, RunDecision, RunHistory}; 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::checks::{check_tls_certificate_der, evaluate_http_admin_response}; 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"; #[derive(Parser)] #[command( name = "xexeu", about = "Xexéu — 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/xexeu.toml")] config: PathBuf, #[arg(long, default_value = "data/sweeps")] sweeps: PathBuf, #[arg(long, default_value = "data/xexeu")] data_dir: PathBuf, }, /// Run the continuous scheduler and scan engine, writing sweep batches. Scanner { #[arg(long, default_value = "config/xexeu.toml")] config: PathBuf, #[arg(long, default_value = "data/sweeps")] out: PathBuf, #[arg(long, default_value = "data/xexeu")] data_dir: PathBuf, }, /// Run a single sweep for diagnostics. Scan { #[arg(long)] group: Option, #[arg(long)] once: bool, #[arg(long, default_value = "config/xexeu.toml")] config: PathBuf, #[arg(long, default_value = "data/sweeps")] out: PathBuf, #[arg(long, default_value = "data/xexeu")] 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/xexeu")] data_dir: PathBuf, }, /// Export the current state. Export { #[arg(long, default_value = "json")] format: String, #[arg(long, default_value = "data/xexeu")] data_dir: PathBuf, }, /// Check the runtime environment. Doctor { #[arg(long)] json: bool, }, } #[derive(Subcommand)] enum ConfigAction { /// Validate the configuration and print the effective cadence per group. Check { #[arg(long, default_value = "config/xexeu.toml")] config: PathBuf, }, } #[derive(Subcommand)] enum FeedsAction { /// Download NVD and CISA KEV feeds incrementally. 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: Option, #[arg(long)] nvd: Option, #[arg(long)] kev: Option, #[arg(long, default_value = "config/xexeu.toml")] config: PathBuf, #[arg(long, default_value = "data/xexeu")] 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, } => match run_serve(&bind, &config, &sweeps, &data_dir).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 } => run_doctor(json), Command::Export { .. } => not_implemented("export"), } } fn fail(message: &str) -> ExitCode { eprintln!("{message}"); ExitCode::FAILURE } fn not_implemented(command: &str) -> ExitCode { eprintln!("{command}: não implementado ainda"); ExitCode::FAILURE } fn validated_config(path: &Path) -> Result<(XexeuConfig, ValidationReport), String> { let raw = fs::read_to_string(path) .map_err(|error| format!("não foi possível ler {}: {error}", path.display()))?; XexeuConfig::load_validated(&raw) .map_err(|error| format!("configuração inválida em {}: {error}", path.display())) } 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: &XexeuConfig) -> Result, String> { let expansions = config .groups .iter() .map(expand_group) .collect::, _>>() .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), } } struct ScanSummary { batch: SweepBatch, directory: PathBuf, targets_count: usize, alive_count: usize, } async fn execute_scan_for_group( config: &XexeuConfig, group_name: &str, out: &Path, data_dir: &Path, ) -> Result { 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 = 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 = 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 = hosts .iter() .filter(|host| host.state == HostState::Alive) .map(|host| host.ip) .collect(); let port_results = if alive.is_empty() { Vec::new() } else { scan_hosts_tcp_connect( &alive, &ports, &PortScanConfig { timeout: Duration::from_millis(1200), max_concurrency: concurrency.saturating_mul(4).max(16), }, ) .await }; 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 xexeu_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, EngineMode::NativeWithoutRaw, 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, }) } async fn scan_once( group: Option, 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 = 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(()) } 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 = 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("XEXEU_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 = 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(()) } fn find_sweep_manifests(sweeps_dir: &Path) -> Vec { 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>, sweeps_ingested: Arc, ) { 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() ); } 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)] struct ServerState { config: Arc>, config_path: PathBuf, storage: Arc>, sweeps_ingested: Arc, vuln_db: Arc>, feeds_last_sync: Arc>>>, } #[derive(Serialize)] struct HealthResponse { status: &'static str, version: &'static str, } async fn health_handler() -> Json { Json(HealthResponse { status: "ok", version: env!("CARGO_PKG_VERSION"), }) } #[derive(Serialize)] 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, groups: Vec, } #[derive(Serialize)] struct GroupScheduleDto { group: String, profile: String, cron: String, next_run: String, } async fn status_handler(State(state): State) -> Json { 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, }) } async fn get_config_handler(State(state): State) -> Json { let config = state.config.read().await; Json(config.clone()) } async fn create_group_handler( State(state): State, Json(new_group): Json, ) -> Result<(StatusCode, Json), (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, AxumPath(group_name): AxumPath, Json(updated_group): Json, ) -> Result, (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, AxumPath(group_name): AxumPath, ) -> Result { 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, ) -> Result { 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, ) -> Result { 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, Query(query): Query, ) -> Result { 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, network: String, ip: String, status: &'static str, absences: u32, first_seen: String, last_seen: String, ports: Vec, } #[derive(Serialize)] struct PortDto { protocol: String, port: u16, status: &'static str, absences: u32, first_seen: String, last_seen: String, product: Option, version: Option, cpe: Option, findings: Vec, } async fn hosts_handler( State(state): State, ) -> Result>, (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 .assets .into_iter() .map(|asset| HostDto { asset_key: asset.asset_key, network: asset.network, 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 .into_iter() .map(|port| PortDto { protocol: port.protocol, 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, version: port.version, cpe: port.cpe, findings: port.findings, }) .collect(), }) .collect(); Ok(Json(dtos)) } #[derive(Deserialize)] struct ChangesQuery { since: Option, } fn parse_since(raw: &str) -> Option> { 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::() { 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)) } async fn changes_handler( State(state): State, Query(query): Query, ) -> Result>, (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)) } 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 LOGO_PNG: &[u8] = include_bytes!("../../../logo.png"); async fn index_handler() -> impl IntoResponse { ( [(header::CONTENT_TYPE, "text/html; charset=utf-8")], INDEX_HTML, ) } async fn css_handler() -> impl IntoResponse { ([(header::CONTENT_TYPE, "text/css; charset=utf-8")], APP_CSS) } async fn js_handler() -> impl IntoResponse { ( [( header::CONTENT_TYPE, "application/javascript; charset=utf-8", )], APP_JS, ) } async fn i18n_js_handler() -> impl IntoResponse { ( [( header::CONTENT_TYPE, "application/javascript; charset=utf-8", )], I18N_JS, ) } async fn i18n_en_js_handler() -> impl IntoResponse { ( [( header::CONTENT_TYPE, "application/javascript; charset=utf-8", )], I18N_EN_JS, ) } async fn logo_handler() -> impl IntoResponse { ([(header::CONTENT_TYPE, "image/png")], LOGO_PNG) } fn parse_duration_str(raw: &str) -> Option { 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::() { 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, sweeps_dir: &Path, data_dir: &Path, ) -> Result<(), String> { let (config, _report) = validated_config(config_path)?; 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("xexeu.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)); // 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(); tokio::spawn(async move { 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(RwLock::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() .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("/", 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("/logo.png", axum::routing::get(logo_handler)) .with_state(state); 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!("Xexéu listening on http://{local_addr}"); axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal()) .await .map_err(|error| format!("erro no servidor HTTP: {error}"))?; Ok(()) } fn run_changes(since: &str, data_dir: &Path) -> ExitCode { let db_path = data_dir.join("xexeu.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}")), } } fn find_matching_file(dir: &Path, keyword: &str, ext: &str) -> Option { 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, nvd_path: Option, kev_path: Option, 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 "), }; 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() .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::>().await, }; }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, } } #[derive(Serialize)] struct DoctorReport { version: &'static str, config: DoctorConfig, root: bool, net_raw: Option, } #[derive(Serialize)] struct DoctorConfig { path: String, exists: bool, valid: bool, error: Option, } fn run_doctor(as_json: bool) -> ExitCode { let path = Path::new(DEFAULT_CONFIG); let exists = path.exists(); let (valid, error) = if exists { match fs::read_to_string(path) { Ok(raw) => match XexeuConfig::load_validated(&raw) { Ok(_) => (true, None), Err(error) => (false, Some(error.to_string())), }, Err(error) => (false, Some(format!("não foi possível ler: {error}"))), } } else { ( false, Some("arquivo de configuração não encontrado".to_string()), ) }; let report = DoctorReport { version: env!("CARGO_PKG_VERSION"), config: DoctorConfig { path: path.display().to_string(), exists, valid, error, }, // SAFETY: geteuid takes no arguments, cannot fail and only reads the process identity. root: unsafe { libc::geteuid() == 0 }, net_raw: net_raw_capability(), }; 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}")), } return ExitCode::SUCCESS; } println!("xexeu {}", report.version); match ( &report.config.error, report.config.exists, report.config.valid, ) { (_, true, true) => println!("config {}: presente e válida", report.config.path), (Some(error), true, false) => println!("config {}: inválida: {error}", report.config.path), (Some(error), false, _) => println!("config {}: {error}", report.config.path), _ => println!("config {}: inválida", report.config.path), } println!("root: {}", yes_no(report.root)); match report.net_raw { Some(value) => println!("NET_RAW: {}", yes_no(value)), None => println!("NET_RAW: desconhecido"), } ExitCode::SUCCESS } fn yes_no(value: bool) -> &'static str { if value { "sim" } else { "não" } } fn net_raw_capability() -> Option { let status = fs::read_to_string("/proc/self/status").ok()?; let line = status.lines().find(|line| line.starts_with("CapEff:"))?; let mask = u64::from_str_radix(line.split_whitespace().nth(1)?, 16).ok()?; Some(mask & (1 << 13) != 0) }