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
@@ -1,2 +1,484 @@
|
||||
//! Environment checks: effective capabilities, nmap availability, feed age and libduckdb linkage.
|
||||
// TODO: implement doctor checks.
|
||||
//! Environment checks: effective capabilities, configuration validity, SQLite access,
|
||||
//! vulnerability database status, and feed synchronization age.
|
||||
|
||||
use crate::config::XexeuConfig;
|
||||
use crate::storage::SqliteStorage;
|
||||
use crate::vuln::VulnDatabase;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// Status for an individual environment check.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum CheckStatus {
|
||||
#[serde(rename = "ok")]
|
||||
Ok,
|
||||
#[serde(rename = "ausente")]
|
||||
Ausente,
|
||||
#[serde(rename = "pendente")]
|
||||
Pendente,
|
||||
#[serde(rename = "falha")]
|
||||
Falha,
|
||||
#[serde(rename = "nao_verificavel")]
|
||||
NaoVerificavel,
|
||||
}
|
||||
|
||||
impl CheckStatus {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Ok => "ok",
|
||||
Self::Ausente => "ausente",
|
||||
Self::Pendente => "pendente",
|
||||
Self::Falha => "falha",
|
||||
Self::NaoVerificavel => "não verificável",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An individual diagnosis check.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DoctorCheck {
|
||||
pub name: String,
|
||||
pub status: CheckStatus,
|
||||
pub critical: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// The complete diagnosis report of the runtime environment.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DoctorReport {
|
||||
pub version: String,
|
||||
pub ok: bool,
|
||||
pub checks: Vec<DoctorCheck>,
|
||||
}
|
||||
|
||||
impl DoctorReport {
|
||||
/// Renders the diagnosis report as a formatted plain-text table.
|
||||
pub fn render_table(&self) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str(&format!(
|
||||
"Xexéu v{} - Diagnóstico do Ambiente\n",
|
||||
self.version
|
||||
));
|
||||
out.push_str(
|
||||
"================================================================================\n",
|
||||
);
|
||||
out.push_str(&format!("{:<15} {:<15} {}\n", "Item", "Status", "Detalhe"));
|
||||
out.push_str(
|
||||
"--------------------------------------------------------------------------------\n",
|
||||
);
|
||||
for check in &self.checks {
|
||||
out.push_str(&format!(
|
||||
"{:<15} {:<15} {}\n",
|
||||
check.name,
|
||||
check.status.as_str(),
|
||||
check.detail
|
||||
));
|
||||
}
|
||||
out.push_str(
|
||||
"--------------------------------------------------------------------------------\n",
|
||||
);
|
||||
if self.ok {
|
||||
out.push_str("Resultado: OK (ambiente apto para execução)\n");
|
||||
} else {
|
||||
out.push_str("Resultado: FALHA (corrija os itens críticos marcados acima)\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the `CapEff:` hex bitmask line from a Linux `/proc/self/status` formatted string.
|
||||
pub fn parse_cap_eff_from_status(status_text: &str) -> Option<u64> {
|
||||
for line in status_text.lines() {
|
||||
if let Some(rest) = line.strip_prefix("CapEff:") {
|
||||
let hex = rest.trim();
|
||||
return u64::from_str_radix(hex, 16).ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parses the effective UID from the `Uid:` line of `/proc/self/status`.
|
||||
pub fn parse_euid_from_status(status_text: &str) -> Option<u32> {
|
||||
for line in status_text.lines() {
|
||||
if let Some(rest) = line.strip_prefix("Uid:") {
|
||||
let mut parts = rest.split_whitespace();
|
||||
let _real = parts.next()?;
|
||||
let effective = parts.next()?;
|
||||
return effective.parse().ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Checks whether `CAP_NET_RAW` (bit 13) is active in the capability bitmask.
|
||||
pub fn has_net_raw_from_mask(mask: u64) -> bool {
|
||||
const CAP_NET_RAW_BIT: u64 = 13;
|
||||
(mask & (1 << CAP_NET_RAW_BIT)) != 0
|
||||
}
|
||||
|
||||
/// Evaluates network raw capability given an optional `/proc/self/status` content and root indicator.
|
||||
pub fn check_net_raw_simulated(status_content: Option<&str>, is_root: bool) -> DoctorCheck {
|
||||
match status_content {
|
||||
Some(content) => match parse_cap_eff_from_status(content) {
|
||||
Some(mask) => {
|
||||
let has_raw = has_net_raw_from_mask(mask);
|
||||
if has_raw {
|
||||
DoctorCheck {
|
||||
name: "net_raw".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: false,
|
||||
detail: format!(
|
||||
"CAP_NET_RAW ativo (varredura SYN raw disponível){}",
|
||||
if is_root { ", rodando como root" } else { "" }
|
||||
),
|
||||
}
|
||||
} else {
|
||||
DoctorCheck {
|
||||
name: "net_raw".to_string(),
|
||||
status: CheckStatus::Ausente,
|
||||
critical: false,
|
||||
detail: format!(
|
||||
"sem CAP_NET_RAW (modo TCP connect / nativo-sem-raw ativo){}",
|
||||
if is_root {
|
||||
", rodando como root sem cap"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
None => DoctorCheck {
|
||||
name: "net_raw".to_string(),
|
||||
status: CheckStatus::NaoVerificavel,
|
||||
critical: false,
|
||||
detail: "não foi possível ler CapEff de /proc/self/status".to_string(),
|
||||
},
|
||||
},
|
||||
None => DoctorCheck {
|
||||
name: "net_raw".to_string(),
|
||||
status: CheckStatus::NaoVerificavel,
|
||||
critical: false,
|
||||
detail: "não verificável fora do Linux (modo TCP connect / nativo-sem-raw)".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the complete environment diagnosis checks.
|
||||
pub fn run(config_path: &Path, data_dir: &Path) -> DoctorReport {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
let mut checks = Vec::new();
|
||||
|
||||
// 1. Binary version
|
||||
checks.push(DoctorCheck {
|
||||
name: "versao".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: false,
|
||||
detail: format!("xexeu v{version}"),
|
||||
});
|
||||
|
||||
// 2. Configuration file check
|
||||
if !config_path.exists() {
|
||||
checks.push(DoctorCheck {
|
||||
name: "config".to_string(),
|
||||
status: CheckStatus::Ausente,
|
||||
critical: true,
|
||||
detail: format!(
|
||||
"arquivo de configuração não encontrado em {}",
|
||||
config_path.display()
|
||||
),
|
||||
});
|
||||
} else {
|
||||
match fs::read_to_string(config_path) {
|
||||
Ok(raw) => match XexeuConfig::load_validated(&raw) {
|
||||
Ok((cfg, _report)) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "config".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: true,
|
||||
detail: format!(
|
||||
"presente e válida ({} grupos) em {}",
|
||||
cfg.groups.len(),
|
||||
config_path.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "config".to_string(),
|
||||
status: CheckStatus::Falha,
|
||||
critical: true,
|
||||
detail: format!("inválida em {}: {e}", config_path.display()),
|
||||
});
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "config".to_string(),
|
||||
status: CheckStatus::Falha,
|
||||
critical: true,
|
||||
detail: format!("erro ao ler {}: {e}", config_path.display()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. CAP_NET_RAW / root capability check
|
||||
let status_str = fs::read_to_string("/proc/self/status").ok();
|
||||
let is_root = status_str
|
||||
.as_deref()
|
||||
.and_then(parse_euid_from_status)
|
||||
.map(|uid| uid == 0)
|
||||
.unwrap_or(false);
|
||||
checks.push(check_net_raw_simulated(status_str.as_deref(), is_root));
|
||||
|
||||
// 4. Local SQLite storage check
|
||||
let db_path = data_dir.join("xexeu.db");
|
||||
if let Some(parent) = db_path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
match SqliteStorage::open(&db_path) {
|
||||
Ok(_) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "sqlite".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: true,
|
||||
detail: format!("banco SQLite acessível em {}", db_path.display()),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "sqlite".to_string(),
|
||||
status: CheckStatus::Falha,
|
||||
critical: true,
|
||||
detail: format!(
|
||||
"falha ao acessar banco SQLite em {}: {e}",
|
||||
db_path.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Vulnerability database check
|
||||
let vuln_db_path = data_dir.join("vuln_db.json");
|
||||
let mut vuln_db_mtime: Option<SystemTime> = None;
|
||||
|
||||
if !vuln_db_path.exists() {
|
||||
checks.push(DoctorCheck {
|
||||
name: "vuln_db".to_string(),
|
||||
status: CheckStatus::Ausente,
|
||||
critical: false,
|
||||
detail: format!(
|
||||
"base ausente em {} (execute 'xexeu feeds sync' ou 'import')",
|
||||
vuln_db_path.display()
|
||||
),
|
||||
});
|
||||
} else {
|
||||
vuln_db_mtime = fs::metadata(&vuln_db_path)
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok());
|
||||
match VulnDatabase::load_from_file(&vuln_db_path) {
|
||||
Ok(db) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "vuln_db".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: false,
|
||||
detail: format!(
|
||||
"presente em {} ({} CVEs, {} no KEV)",
|
||||
vuln_db_path.display(),
|
||||
db.cve_count(),
|
||||
db.kev_count()
|
||||
),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
checks.push(DoctorCheck {
|
||||
name: "vuln_db".to_string(),
|
||||
status: CheckStatus::Falha,
|
||||
critical: false,
|
||||
detail: format!(
|
||||
"arquivo de vulnerabilidades inválido em {}: {e}",
|
||||
vuln_db_path.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Feeds sync age check
|
||||
if let Some(mtime) = vuln_db_mtime {
|
||||
let duration = SystemTime::now().duration_since(mtime).unwrap_or_default();
|
||||
let hours = duration.as_secs() / 3600;
|
||||
let days = hours / 24;
|
||||
let age_desc = if days > 0 {
|
||||
format!("{days} dia(s) atrás")
|
||||
} else if hours > 0 {
|
||||
format!("{hours} hora(s) atrás")
|
||||
} else {
|
||||
let minutes = (duration.as_secs() % 3600) / 60;
|
||||
format!("{minutes} minuto(s) atrás")
|
||||
};
|
||||
|
||||
if days >= 7 {
|
||||
checks.push(DoctorCheck {
|
||||
name: "feeds_sync".to_string(),
|
||||
status: CheckStatus::Pendente,
|
||||
critical: false,
|
||||
detail: format!("última sincronização há {age_desc} (recomendado atualizar)"),
|
||||
});
|
||||
} else {
|
||||
checks.push(DoctorCheck {
|
||||
name: "feeds_sync".to_string(),
|
||||
status: CheckStatus::Ok,
|
||||
critical: false,
|
||||
detail: format!("última sincronização há {age_desc}"),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
checks.push(DoctorCheck {
|
||||
name: "feeds_sync".to_string(),
|
||||
status: CheckStatus::Pendente,
|
||||
critical: false,
|
||||
detail: "sincronização de feeds pendente (nenhuma base encontrada)".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let ok = checks
|
||||
.iter()
|
||||
.all(|c| !c.critical || c.status == CheckStatus::Ok);
|
||||
|
||||
DoctorReport {
|
||||
version,
|
||||
ok,
|
||||
checks,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_cap_eff_parsing_and_net_raw_simulation() {
|
||||
// Bit 13 set: 1 << 13 = 0x2000
|
||||
let status_with_raw = "Name:\txexeu\nUid:\t0\t0\t0\t0\nCapEff:\t0000000000002000\n";
|
||||
assert_eq!(parse_cap_eff_from_status(status_with_raw), Some(0x2000));
|
||||
assert_eq!(parse_euid_from_status(status_with_raw), Some(0));
|
||||
assert!(has_net_raw_from_mask(0x2000));
|
||||
|
||||
let check_ok = check_net_raw_simulated(Some(status_with_raw), true);
|
||||
assert_eq!(check_ok.status, CheckStatus::Ok);
|
||||
assert!(check_ok.detail.contains("CAP_NET_RAW ativo"));
|
||||
assert!(check_ok.detail.contains("rodando como root"));
|
||||
|
||||
// Bit 13 cleared
|
||||
let status_no_raw =
|
||||
"Name:\txexeu\nUid:\t1000\t1000\t1000\t1000\nCapEff:\t0000000000000000\n";
|
||||
assert_eq!(parse_cap_eff_from_status(status_no_raw), Some(0));
|
||||
assert_eq!(parse_euid_from_status(status_no_raw), Some(1000));
|
||||
assert!(!has_net_raw_from_mask(0));
|
||||
|
||||
let check_ausente = check_net_raw_simulated(Some(status_no_raw), false);
|
||||
assert_eq!(check_ausente.status, CheckStatus::Ausente);
|
||||
assert!(check_ausente.detail.contains("TCP connect"));
|
||||
|
||||
// Non-Linux or unparseable
|
||||
let check_none = check_net_raw_simulated(None, false);
|
||||
assert_eq!(check_none.status, CheckStatus::NaoVerificavel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_doctor_with_valid_and_invalid_config() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let data_dir = dir.path().join("data");
|
||||
let valid_config = dir.path().join("valid.toml");
|
||||
let invalid_config = dir.path().join("invalid.toml");
|
||||
let missing_config = dir.path().join("missing.toml");
|
||||
|
||||
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 toml");
|
||||
|
||||
fs::write(&invalid_config, "not valid toml !!!").expect("write invalid toml");
|
||||
|
||||
// Valid config report
|
||||
let report_valid = run(&valid_config, &data_dir);
|
||||
assert!(report_valid.ok);
|
||||
let config_check = report_valid
|
||||
.checks
|
||||
.iter()
|
||||
.find(|c| c.name == "config")
|
||||
.expect("config check present");
|
||||
assert_eq!(config_check.status, CheckStatus::Ok);
|
||||
|
||||
// Invalid config report
|
||||
let report_invalid = run(&invalid_config, &data_dir);
|
||||
assert!(!report_invalid.ok);
|
||||
let config_check = report_invalid
|
||||
.checks
|
||||
.iter()
|
||||
.find(|c| c.name == "config")
|
||||
.expect("config check present");
|
||||
assert_eq!(config_check.status, CheckStatus::Falha);
|
||||
|
||||
// Missing config report
|
||||
let report_missing = run(&missing_config, &data_dir);
|
||||
assert!(!report_missing.ok);
|
||||
let config_check = report_missing
|
||||
.checks
|
||||
.iter()
|
||||
.find(|c| c.name == "config")
|
||||
.expect("config check present");
|
||||
assert_eq!(config_check.status, CheckStatus::Ausente);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_doctor_table_rendering() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let config_path = dir.path().join("xexeu.toml");
|
||||
let data_dir = dir.path().join("data");
|
||||
|
||||
fs::write(
|
||||
&config_path,
|
||||
r#"
|
||||
[escopo]
|
||||
autorizado = ["192.168.1.0/24"]
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
|
||||
[perfis.padrao]
|
||||
|
||||
[[grupo]]
|
||||
nome = "default"
|
||||
alvos = ["192.168.1.1"]
|
||||
"#,
|
||||
)
|
||||
.expect("write toml");
|
||||
|
||||
let report = run(&config_path, &data_dir);
|
||||
let table = report.render_table();
|
||||
assert!(table.contains("Xexéu v"));
|
||||
assert!(table.contains("versao"));
|
||||
assert!(table.contains("config"));
|
||||
assert!(table.contains("sqlite"));
|
||||
assert!(table.contains("Resultado: OK"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user