server/ (state, ingestion, API, CSV exports, embedded assets), scanner, feeds_cmd, config_cmd and commands. Code moved as is; no behavior change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
298 lines
10 KiB
Rust
298 lines
10 KiB
Rust
//! CSV exports, shared with `xexeu export`.
|
|
|
|
use super::api::ChangesQuery;
|
|
use super::ServerState;
|
|
use crate::parse_since;
|
|
use axum::extract::{Query, State};
|
|
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
|
use axum::response::IntoResponse;
|
|
use chrono::Utc;
|
|
use serde::Serialize;
|
|
use xexeu_core::diff::{CurrentState, EventKind};
|
|
use xexeu_core::storage::Storage;
|
|
use xexeu_core::vuln::matcher::{Confidence, Finding};
|
|
|
|
/// 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}\"")
|
|
} else {
|
|
s.to_string()
|
|
}
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub(crate) 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>,
|
|
}
|
|
|
|
pub(crate) 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()
|
|
}
|
|
|
|
pub(crate) 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");
|
|
|
|
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");
|
|
}
|
|
}
|
|
}
|
|
csv
|
|
}
|
|
|
|
pub(crate) 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\"");
|
|
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))
|
|
}
|
|
|
|
pub(crate) async fn export_findings_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 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))
|
|
}
|
|
|
|
pub(crate) async fn export_changes_csv_handler(
|
|
State(state): State<ServerState>,
|
|
Query(query): Query<ChangesQuery>,
|
|
) -> Result<impl IntoResponse, (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}"),
|
|
)
|
|
})?;
|
|
|
|
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))
|
|
}
|