Implementa batch/storage/diff, correlação de vulnerabilidades (CPE/CVE/KEV) e liga config check / scan --once na CLI
This commit is contained in:
1 parent
942655a5e0
commit
a814e100fb
12 files changed
+5093
-43
No files matched your search
+366
-27
@@ -1,5 +1,24 @@
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::fs;
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
use serde::Serialize;
|
||||
use xexeu_core::batch::{EngineMode, SweepBatch, SweepManifest, SweepStatus};
|
||||
use xexeu_core::config::{ValidationReport, XexeuConfig};
|
||||
use xexeu_core::scan::{
|
||||
discover_hosts_tcp, scan_hosts_tcp_connect, DiscoveryConfig, HostState, PortScanConfig,
|
||||
PortState, PortTarget, DEFAULT_DISCOVERY_PORTS,
|
||||
};
|
||||
use xexeu_core::targets::{
|
||||
effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange,
|
||||
};
|
||||
|
||||
const DEFAULT_CONFIG: &str = "config/xexeu.toml";
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -98,37 +117,357 @@ enum FeedsAction {
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Command::Serve {
|
||||
bind: _,
|
||||
config: _,
|
||||
sweeps: _,
|
||||
data_dir: _,
|
||||
} => not_implemented("serve"),
|
||||
Command::Scanner { config: _, out: _ } => not_implemented("scanner"),
|
||||
Command::Scan {
|
||||
group: _,
|
||||
once: _,
|
||||
config: _,
|
||||
out: _,
|
||||
} => not_implemented("scan"),
|
||||
Command::Config { action: _ } => not_implemented("config"),
|
||||
Command::Feeds { action: _ } => not_implemented("feeds"),
|
||||
Command::Changes {
|
||||
since: _,
|
||||
data_dir: _,
|
||||
} => not_implemented("changes"),
|
||||
Command::Export {
|
||||
format: _,
|
||||
data_dir: _,
|
||||
} => not_implemented("export"),
|
||||
Command::Doctor { json: _ } => not_implemented("doctor"),
|
||||
group,
|
||||
once,
|
||||
config,
|
||||
out,
|
||||
} => match scan_once(group, once, &config, &out).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => fail(&message),
|
||||
},
|
||||
Command::Config { action } => match action {
|
||||
ConfigAction::Check { config } => run_config_check(&config),
|
||||
},
|
||||
Command::Doctor { json } => run_doctor(json),
|
||||
Command::Serve { .. } => not_implemented("serve"),
|
||||
Command::Scanner { .. } => not_implemented("scanner"),
|
||||
Command::Feeds { .. } => not_implemented("feeds"),
|
||||
Command::Changes { .. } => not_implemented("changes"),
|
||||
Command::Export { .. } => not_implemented("export"),
|
||||
}
|
||||
}
|
||||
|
||||
fn not_implemented(command: &str) -> ! {
|
||||
fn fail(message: &str) -> ExitCode {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
|
||||
fn not_implemented(command: &str) -> ExitCode {
|
||||
eprintln!("{command}: não implementado ainda");
|
||||
std::process::exit(1);
|
||||
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<Vec<IpRange>, String> {
|
||||
let expansions = config
|
||||
.groups
|
||||
.iter()
|
||||
.map(expand_group)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.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),
|
||||
}
|
||||
}
|
||||
|
||||
async fn scan_once(
|
||||
group: Option<String>,
|
||||
once: bool,
|
||||
config_path: &Path,
|
||||
out: &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 group = config
|
||||
.group(&name)
|
||||
.ok_or_else(|| format!("grupo '{name}' não existe na configuração"))?;
|
||||
let expansion = expand_group(group).map_err(|error| format!("grupo '{name}': {error}"))?;
|
||||
let scope =
|
||||
scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?;
|
||||
|
||||
let mut addresses: BTreeSet<IpAddr> = 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<IpAddr> = 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<IpAddr> = 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 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);
|
||||
let directory = batch
|
||||
.write(out)
|
||||
.map_err(|error| format!("falha ao gravar o lote: {error}"))?;
|
||||
|
||||
println!(
|
||||
"lote {} (grupo {}, perfil {}) gravado em {}",
|
||||
batch.manifest.sweep_id,
|
||||
group.name,
|
||||
profile_name,
|
||||
directory.display()
|
||||
);
|
||||
println!("alvos: {}; vivos: {}", targets.len(), alive.len());
|
||||
for result in &batch.ports {
|
||||
let open: Vec<String> = 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(())
|
||||
}
|
||||
|
||||
#[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(),
|
||||
};
|
||||
|
||||
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<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)
|
||||
}
|
||||
Reference in new issue
Block a user