feat(ci,doctor,export): add Gitea CI/CD, verification scripts, doctor and export commands
This commit is contained in:
1 parent
d1475e7141
commit
db2cdc03ef
15 files changed
+1406
-168
No files matched your search
+252
-166
@@ -17,11 +17,12 @@ 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::diff::{diff_batch, CurrentState, DiffOptions, EventKind};
|
||||
use xexeu_core::report::ExecutiveReport;
|
||||
use xexeu_core::scan::{
|
||||
discover_hosts_tcp, fingerprint_service, scan_hosts_tcp_connect, DiscoveryConfig, HostState,
|
||||
PortScanConfig, PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||
discover_hosts_tcp, fingerprint_service, scan_hosts_syn, scan_hosts_tcp_connect,
|
||||
DiscoveryConfig, HostPortScanResult, HostState, PortScanConfig, PortState, PortTarget,
|
||||
SynScanConfig, DEFAULT_DISCOVERY_PORTS,
|
||||
};
|
||||
use xexeu_core::schedule::{next_runs, should_run_now, RunDecision, RunHistory};
|
||||
use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
@@ -32,8 +33,6 @@ use xexeu_core::vuln::checks::{check_tls_certificate_der, evaluate_http_admin_re
|
||||
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",
|
||||
@@ -103,11 +102,17 @@ enum Command {
|
||||
format: String,
|
||||
#[arg(long, default_value = "data/xexeu")]
|
||||
data_dir: PathBuf,
|
||||
#[arg(long)]
|
||||
out: Option<PathBuf>,
|
||||
},
|
||||
/// Check the runtime environment.
|
||||
Doctor {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
#[arg(long, default_value = "config/xexeu.toml")]
|
||||
config: PathBuf,
|
||||
#[arg(long, default_value = "data/xexeu")]
|
||||
data_dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -191,8 +196,16 @@ async fn main() -> ExitCode {
|
||||
Command::Config { action } => match action {
|
||||
ConfigAction::Check { config } => run_config_check(&config),
|
||||
},
|
||||
Command::Doctor { json } => run_doctor(json),
|
||||
Command::Export { .. } => not_implemented("export"),
|
||||
Command::Doctor {
|
||||
json,
|
||||
config,
|
||||
data_dir,
|
||||
} => run_doctor(json, &config, &data_dir),
|
||||
Command::Export {
|
||||
format,
|
||||
data_dir,
|
||||
out,
|
||||
} => run_export(&format, &data_dir, out.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,11 +214,6 @@ fn fail(message: &str) -> ExitCode {
|
||||
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()))?;
|
||||
@@ -389,18 +397,63 @@ async fn execute_scan_for_group(
|
||||
.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),
|
||||
},
|
||||
)
|
||||
// `nativo` tries the raw-socket SYN engine first and only falls back to
|
||||
// the unprivileged `nativo-sem-raw` TCP-connect engine when CAP_NET_RAW
|
||||
// isn't actually usable (missing capability, or the raw socket fails to
|
||||
// create for some other reason) — the engine mode actually used, not the
|
||||
// one requested, is what gets recorded in the sweep manifest below, so an
|
||||
// operator reading `/api/status` or the manifest never has to guess which
|
||||
// mode really ran.
|
||||
let wants_raw = profile.engine == "nativo";
|
||||
let (port_results, engine_used): (Vec<HostPortScanResult>, EngineMode) = if alive.is_empty() {
|
||||
(Vec::new(), EngineMode::NativeWithoutRaw)
|
||||
} else if wants_raw && xexeu_core::caps::has_net_raw() {
|
||||
let syn_hosts = alive.clone();
|
||||
let syn_ports = ports.clone();
|
||||
let syn_config = SynScanConfig::default();
|
||||
let syn_result = tokio::task::spawn_blocking(move || {
|
||||
scan_hosts_syn(&syn_hosts, &syn_ports, &syn_config)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("tarefa de varredura SYN falhou: {error}"))?;
|
||||
match syn_result {
|
||||
Ok(results) => (results, EngineMode::Native),
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"aviso: varredura SYN falhou ({error}), recorrendo ao modo nativo-sem-raw"
|
||||
);
|
||||
(
|
||||
scan_hosts_tcp_connect(
|
||||
&alive,
|
||||
&ports,
|
||||
&PortScanConfig {
|
||||
timeout: Duration::from_millis(1200),
|
||||
max_concurrency: concurrency.saturating_mul(4).max(16),
|
||||
},
|
||||
)
|
||||
.await,
|
||||
EngineMode::NativeWithoutRaw,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if wants_raw {
|
||||
eprintln!(
|
||||
"aviso: perfil '{profile_name}' pede o motor nativo, mas CAP_NET_RAW não está disponível; usando nativo-sem-raw"
|
||||
);
|
||||
}
|
||||
(
|
||||
scan_hosts_tcp_connect(
|
||||
&alive,
|
||||
&ports,
|
||||
&PortScanConfig {
|
||||
timeout: Duration::from_millis(1200),
|
||||
max_concurrency: concurrency.saturating_mul(4).max(16),
|
||||
},
|
||||
)
|
||||
.await,
|
||||
EngineMode::NativeWithoutRaw,
|
||||
)
|
||||
};
|
||||
|
||||
let vuln_db = VulnDatabase::load_from_file(&data_dir.join("vuln_db.json")).unwrap_or_default();
|
||||
@@ -456,7 +509,7 @@ async fn execute_scan_for_group(
|
||||
group.name.clone(),
|
||||
expansion.ranges().iter().map(ToString::to_string).collect(),
|
||||
profile_name,
|
||||
EngineMode::NativeWithoutRaw,
|
||||
engine_used,
|
||||
started_at,
|
||||
);
|
||||
manifest.finish(SweepStatus::Complete, Utc::now());
|
||||
@@ -814,6 +867,17 @@ async fn create_group_handler(
|
||||
"nome do grupo não pode ser vazio".to_string(),
|
||||
));
|
||||
}
|
||||
// `sweep` batches are written to `sweeps/<group>/<sweep_id>/`, so an unsafe
|
||||
// name here (`/`, `..`) would only fail much later, when a sweep for this
|
||||
// group actually runs. Reject it now, with a clear error, instead.
|
||||
if xexeu_core::batch::safe_component(&group_name).is_err() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!(
|
||||
"nome do grupo `{group_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let mut config_guard = state.config.write().await;
|
||||
let mut draft = config_guard.clone();
|
||||
@@ -871,6 +935,14 @@ async fn update_group_handler(
|
||||
"nome do grupo não pode ser vazio".to_string(),
|
||||
));
|
||||
}
|
||||
if xexeu_core::batch::safe_component(new_name).is_err() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!(
|
||||
"nome do grupo `{new_name}` inválido: use apenas letras, números, `-`, `_` ou `.`"
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
if new_name != group_name && draft.groups.iter().any(|g| g.name == new_name) {
|
||||
return Err((
|
||||
@@ -940,7 +1012,27 @@ async fn delete_group_handler(
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
|
||||
/// Escapes a CSV field per RFC 4180, and neutralizes CSV/formula injection
|
||||
/// (OWASP's "CSV Injection"): a cell starting with `=`, `+`, `-`, `@` or a tab
|
||||
/// is interpreted as a formula by Excel/LibreOffice/Sheets when the export is
|
||||
/// opened, which could execute attacker-influenced content (a CVE
|
||||
/// description pulled from the NVD feed, or an operator-controlled config
|
||||
/// value). Prefixing it with a single quote forces every spreadsheet
|
||||
/// application to treat it as plain text, same as GitHub's and Google's own
|
||||
/// CSV export sanitization.
|
||||
fn csv_escape(s: &str) -> String {
|
||||
let needs_formula_guard = s
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|c| matches!(c, '=' | '+' | '-' | '@' | '\t'));
|
||||
let s_owned;
|
||||
let s = if needs_formula_guard {
|
||||
s_owned = format!("'{s}");
|
||||
&s_owned
|
||||
} else {
|
||||
s
|
||||
};
|
||||
|
||||
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
|
||||
let escaped = s.replace('"', "\"\"");
|
||||
format!("\"{escaped}\"")
|
||||
@@ -949,17 +1041,65 @@ fn csv_escape(s: &str) -> 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}"),
|
||||
)
|
||||
})?;
|
||||
#[derive(Serialize)]
|
||||
struct HostDto {
|
||||
asset_key: String,
|
||||
network: String,
|
||||
ip: String,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
ports: Vec<PortDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PortDto {
|
||||
protocol: String,
|
||||
port: u16,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
product: Option<String>,
|
||||
version: Option<String>,
|
||||
cpe: Option<String>,
|
||||
findings: Vec<Finding>,
|
||||
}
|
||||
|
||||
fn current_state_to_dtos(current_state: &CurrentState) -> Vec<HostDto> {
|
||||
current_state
|
||||
.assets
|
||||
.iter()
|
||||
.map(|asset| HostDto {
|
||||
asset_key: asset.asset_key.clone(),
|
||||
network: asset.network.clone(),
|
||||
ip: asset.ip.to_string(),
|
||||
status: asset.status.as_str(),
|
||||
absences: asset.absences,
|
||||
first_seen: asset.first_seen.to_rfc3339(),
|
||||
last_seen: asset.last_seen.to_rfc3339(),
|
||||
ports: asset
|
||||
.ports
|
||||
.iter()
|
||||
.map(|port| PortDto {
|
||||
protocol: port.protocol.clone(),
|
||||
port: port.port,
|
||||
status: port.status.as_str(),
|
||||
absences: port.absences,
|
||||
first_seen: port.first_seen.to_rfc3339(),
|
||||
last_seen: port.last_seen.to_rfc3339(),
|
||||
product: port.product.clone(),
|
||||
version: port.version.clone(),
|
||||
cpe: port.cpe.clone(),
|
||||
findings: port.findings.clone(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generate_hosts_csv(current_state: &CurrentState) -> String {
|
||||
let mut csv = String::new();
|
||||
csv.push_str("Endereço IP,Grupo,Status do Host,Protocolo,Porta,Status da Porta,Produto,Versão,CPE,Maior CVSS,Quantidade de Achados\r\n");
|
||||
|
||||
@@ -1008,6 +1148,21 @@ async fn export_hosts_csv_handler(
|
||||
}
|
||||
}
|
||||
}
|
||||
csv
|
||||
}
|
||||
|
||||
async fn export_hosts_csv_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let storage = state.storage.lock().await;
|
||||
let current_state = storage.load_state(&[]).map_err(|error| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("erro ao consultar estado: {error}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let csv = generate_hosts_csv(¤t_state);
|
||||
|
||||
let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
|
||||
let disposition = format!("attachment; filename=\"xexeu-hosts-{timestamp}.csv\"");
|
||||
@@ -1141,32 +1296,6 @@ async fn export_changes_csv_handler(
|
||||
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<PortDto>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PortDto {
|
||||
protocol: String,
|
||||
port: u16,
|
||||
status: &'static str,
|
||||
absences: u32,
|
||||
first_seen: String,
|
||||
last_seen: String,
|
||||
product: Option<String>,
|
||||
version: Option<String>,
|
||||
cpe: Option<String>,
|
||||
findings: Vec<Finding>,
|
||||
}
|
||||
|
||||
async fn hosts_handler(
|
||||
State(state): State<ServerState>,
|
||||
) -> Result<Json<Vec<HostDto>>, (StatusCode, String)> {
|
||||
@@ -1178,36 +1307,7 @@ async fn hosts_handler(
|
||||
)
|
||||
})?;
|
||||
|
||||
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();
|
||||
|
||||
let dtos = current_state_to_dtos(¤t_state);
|
||||
Ok(Json(dtos))
|
||||
}
|
||||
|
||||
@@ -1703,92 +1803,78 @@ async fn shutdown_signal() {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DoctorReport {
|
||||
version: &'static str,
|
||||
config: DoctorConfig,
|
||||
root: bool,
|
||||
net_raw: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DoctorConfig {
|
||||
path: String,
|
||||
exists: bool,
|
||||
valid: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
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(),
|
||||
};
|
||||
fn run_doctor(as_json: bool, config_path: &Path, data_dir: &Path) -> ExitCode {
|
||||
let report = xexeu_core::doctor::run(config_path, data_dir);
|
||||
|
||||
if as_json {
|
||||
match serde_json::to_string_pretty(&report) {
|
||||
Ok(json) => println!("{json}"),
|
||||
Err(error) => return fail(&format!("falha ao serializar o diagnóstico: {error}")),
|
||||
}
|
||||
return ExitCode::SUCCESS;
|
||||
} else {
|
||||
print!("{}", report.render_table());
|
||||
}
|
||||
|
||||
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),
|
||||
if report.ok {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
println!("root: {}", yes_no(report.root));
|
||||
match report.net_raw {
|
||||
Some(value) => println!("NET_RAW: {}", yes_no(value)),
|
||||
None => println!("NET_RAW: desconhecido"),
|
||||
}
|
||||
|
||||
fn run_export(format: &str, data_dir: &Path, out_file: Option<&Path>) -> ExitCode {
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
let storage = match SqliteStorage::open(&db_path) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
return fail(&format!(
|
||||
"falha ao abrir banco em {}: {err}",
|
||||
db_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let state = match storage.load_state(&[]) {
|
||||
Ok(s) => s,
|
||||
Err(err) => return fail(&format!("falha ao carregar estado: {err}")),
|
||||
};
|
||||
|
||||
let content = match format.to_ascii_lowercase().as_str() {
|
||||
"json" => {
|
||||
let dtos = current_state_to_dtos(&state);
|
||||
match serde_json::to_string_pretty(&dtos) {
|
||||
Ok(s) => s,
|
||||
Err(err) => return fail(&format!("falha ao serializar JSON: {err}")),
|
||||
}
|
||||
}
|
||||
"csv" => generate_hosts_csv(&state),
|
||||
other => {
|
||||
return fail(&format!(
|
||||
"formato não suportado: '{other}' (use 'json' ou 'csv')"
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(path) = out_file {
|
||||
if let Some(parent) = path.parent() {
|
||||
if !parent.as_os_str().is_empty() {
|
||||
if let Err(e) = fs::create_dir_all(parent) {
|
||||
return fail(&format!(
|
||||
"falha ao criar diretório para {}: {e}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = fs::write(path, &content) {
|
||||
return fail(&format!(
|
||||
"falha ao salvar export em {}: {e}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
} else {
|
||||
print!("{content}");
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn yes_no(value: bool) -> &'static str {
|
||||
if value {
|
||||
"sim"
|
||||
} else {
|
||||
"não"
|
||||
}
|
||||
}
|
||||
|
||||
fn net_raw_capability() -> Option<bool> {
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
use chrono::Utc;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
use xexeu_core::diff::{AssetState, AssetStatus, DiffResult, PortStatus, ServiceState};
|
||||
use xexeu_core::storage::{SqliteStorage, Storage};
|
||||
use xexeu_core::vuln::matcher::{Confidence, Finding, FindingType};
|
||||
|
||||
#[test]
|
||||
fn doctor_command_json_and_table_and_invalid_config() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let valid_config = workspace.path().join("xexeu.toml");
|
||||
let invalid_config = workspace.path().join("invalid.toml");
|
||||
let data_dir = workspace.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&valid_config,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["10.0.0.0/8"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
|
||||
[[grupo]]
|
||||
nome = "servidores"
|
||||
alvos = ["10.0.0.1"]
|
||||
"#,
|
||||
)
|
||||
.expect("write valid config");
|
||||
|
||||
fs::write(&invalid_config, "invalid toml content !!").expect("write invalid config");
|
||||
|
||||
// 1. Valid doctor in table mode
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu doctor");
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"expected success: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("Xexéu v"));
|
||||
assert!(stdout.contains("versao"));
|
||||
assert!(stdout.contains("config"));
|
||||
assert!(stdout.contains("sqlite"));
|
||||
assert!(stdout.contains("Resultado: OK"));
|
||||
|
||||
// 2. Valid doctor in JSON mode
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--json",
|
||||
"--config",
|
||||
valid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu doctor --json");
|
||||
|
||||
assert!(output_json.status.success());
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse json output");
|
||||
assert_eq!(parsed["ok"], true);
|
||||
assert!(parsed["checks"].is_array());
|
||||
let checks = parsed["checks"].as_array().unwrap();
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "config" && c["status"] == "ok"));
|
||||
assert!(checks
|
||||
.iter()
|
||||
.any(|c| c["name"] == "sqlite" && c["status"] == "ok"));
|
||||
|
||||
// 3. Invalid doctor mode exits with error code 1
|
||||
let output_invalid = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"doctor",
|
||||
"--config",
|
||||
invalid_config.to_str().unwrap(),
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu doctor with invalid config");
|
||||
|
||||
assert!(!output_invalid.status.success());
|
||||
let stdout_invalid = String::from_utf8_lossy(&output_invalid.stdout);
|
||||
assert!(stdout_invalid.contains("Resultado: FALHA"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_command_json_and_csv_with_fixture() {
|
||||
let workspace = TempDir::new().expect("temporary directory");
|
||||
let data_dir = workspace.path().join("data");
|
||||
fs::create_dir_all(&data_dir).expect("create data dir");
|
||||
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
let mut storage = SqliteStorage::open(&db_path).expect("open sqlite storage");
|
||||
|
||||
let now = Utc::now();
|
||||
let diff = DiffResult {
|
||||
state: vec![AssetState {
|
||||
asset_key: "dmz/10.0.0.42".to_string(),
|
||||
network: "dmz".to_string(),
|
||||
ip: "10.0.0.42".parse().unwrap(),
|
||||
status: AssetStatus::Active,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
ports: vec![ServiceState {
|
||||
protocol: "tcp".to_string(),
|
||||
port: 80,
|
||||
status: PortStatus::Open,
|
||||
absences: 0,
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
product: Some("nginx".to_string()),
|
||||
version: Some("1.18.0".to_string()),
|
||||
cpe: Some("cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*".to_string()),
|
||||
findings: vec![Finding {
|
||||
tipo: FindingType::Cve,
|
||||
id: "CVE-2021-23017".to_string(),
|
||||
cvss: Some(7.5),
|
||||
kev: false,
|
||||
confianca: Confidence::Alto,
|
||||
title: "1-byte memory overwrite in resolver".to_string(),
|
||||
description: "A 1-byte memory overwrite vulnerability exists in resolver."
|
||||
.to_string(),
|
||||
evidencia: serde_json::json!({ "banner": "nginx 1.18.0" }),
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
events: vec![],
|
||||
};
|
||||
|
||||
storage
|
||||
.apply_diff(&diff)
|
||||
.expect("apply fixture state to database");
|
||||
|
||||
// 1. Export JSON to stdout
|
||||
let output_json = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"json",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu export --format json");
|
||||
|
||||
assert!(
|
||||
output_json.status.success(),
|
||||
"export json failed: {}",
|
||||
String::from_utf8_lossy(&output_json.stderr)
|
||||
);
|
||||
let parsed: serde_json::Value =
|
||||
serde_json::from_slice(&output_json.stdout).expect("parse export json");
|
||||
assert!(parsed.is_array());
|
||||
let hosts = parsed.as_array().unwrap();
|
||||
assert_eq!(hosts.len(), 1);
|
||||
assert_eq!(hosts[0]["ip"], "10.0.0.42");
|
||||
assert_eq!(hosts[0]["network"], "dmz");
|
||||
assert_eq!(hosts[0]["ports"][0]["port"], 80);
|
||||
assert_eq!(hosts[0]["ports"][0]["product"], "nginx");
|
||||
assert_eq!(hosts[0]["ports"][0]["findings"][0]["id"], "CVE-2021-23017");
|
||||
|
||||
// 2. Export CSV to file with --out
|
||||
let out_csv_file = workspace.path().join("export.csv");
|
||||
let output_csv = Command::new(env!("CARGO_BIN_EXE_xexeu"))
|
||||
.args([
|
||||
"export",
|
||||
"--format",
|
||||
"csv",
|
||||
"--data-dir",
|
||||
data_dir.to_str().unwrap(),
|
||||
"--out",
|
||||
out_csv_file.to_str().unwrap(),
|
||||
])
|
||||
.output()
|
||||
.expect("run xexeu export --format csv --out ...");
|
||||
|
||||
assert!(output_csv.status.success());
|
||||
let csv_content = fs::read_to_string(&out_csv_file).expect("read exported csv");
|
||||
assert!(csv_content.contains("Endereço IP,Grupo,Status do Host,Protocolo,Porta"));
|
||||
assert!(csv_content.contains("10.0.0.42,dmz,ativo,tcp,80,aberta,nginx,1.18.0,cpe:2.3:a:f5:nginx:1.18.0:*:*:*:*:*:*:*,7.5,1"));
|
||||
}
|
||||
Reference in new issue
Block a user