diff --git a/.env.example b/.env.example index ebf912b..22a3552 100644 --- a/.env.example +++ b/.env.example @@ -9,3 +9,6 @@ XEXEU_PUBLISH=127.0.0.1:8788 XEXEU_ADMIN_TOKEN= # Xexéu container image repository. XEXEU_IMAGE=git.lucasrguerra.dev.br/ciberfauna/xexeu +# Key that signs webhook bodies (X-Xexeu-Signature) when a [[webhook]] sets +# segredo_env = "XEXEU_WEBHOOK_KEY". Empty: webhooks go unsigned. +XEXEU_WEBHOOK_KEY= diff --git a/Cargo.lock b/Cargo.lock index 7ffb530..00b7b6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -554,6 +554,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -756,6 +757,15 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -2386,12 +2396,13 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xexeu-cli" -version = "1.1.0" +version = "1.2.0" dependencies = [ "axum", "chrono", "clap", "libc", + "reqwest", "serde", "serde_json", "tempfile", @@ -2401,12 +2412,13 @@ dependencies = [ [[package]] name = "xexeu-core" -version = "1.1.0" +version = "1.2.0" dependencies = [ "arrow-array", "arrow-schema", "chrono", "croner", + "hmac", "ipnet", "parquet", "proptest", diff --git a/crates/xexeu-cli/Cargo.toml b/crates/xexeu-cli/Cargo.toml index 800dcc9..a4ba261 100644 --- a/crates/xexeu-cli/Cargo.toml +++ b/crates/xexeu-cli/Cargo.toml @@ -18,6 +18,7 @@ axum = "0.8" chrono = { version = "0.4", features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } libc = "0.2" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "time", "sync"] } diff --git a/crates/xexeu-cli/src/server/api.rs b/crates/xexeu-cli/src/server/api.rs index bc501c5..6e42ca5 100644 --- a/crates/xexeu-cli/src/server/api.rs +++ b/crates/xexeu-cli/src/server/api.rs @@ -93,8 +93,9 @@ pub(crate) async fn status_handler(State(state): State) -> Json) -> Json { + // Webhook URLs are credentials and reads are not authenticated. let config = state.config.read().await; - Json(config.clone()) + Json(config.redacted()) } pub(crate) async fn create_group_handler( diff --git a/crates/xexeu-cli/src/server/metrics.rs b/crates/xexeu-cli/src/server/metrics.rs new file mode 100644 index 0000000..01aaa76 --- /dev/null +++ b/crates/xexeu-cli/src/server/metrics.rs @@ -0,0 +1,323 @@ +//! `/metrics` in the Prometheus text format, and the webhook deliveries that +//! feed some of its counters. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::State; +use axum::http::{header, StatusCode}; +use axum::response::IntoResponse; +use chrono::{DateTime, Utc}; +use tokio::sync::{Mutex, RwLock}; +use xexeu_core::alert; +use xexeu_core::batch::SweepManifest; +use xexeu_core::config::XexeuConfig; +use xexeu_core::diff::{AssetStatus, Event, PortStatus}; +use xexeu_core::storage::Storage; + +use super::ServerState; + +/// Last ingested sweep of a group. +struct SweepStat { + finished_at: DateTime, + duration_secs: f64, + complete: bool, + events: usize, +} + +#[derive(Default)] +pub(crate) struct Metrics { + webhook_ok: AtomicU64, + webhook_failed: AtomicU64, + sweeps: Mutex>, +} + +impl Metrics { + pub(crate) async fn record_sweep(&self, manifest: &SweepManifest, events: usize) { + let finished_at = manifest.finished_at.unwrap_or(manifest.started_at); + let duration_secs = (finished_at - manifest.started_at) + .num_milliseconds() + .max(0) as f64 + / 1000.0; + self.sweeps.lock().await.insert( + manifest.group.clone(), + SweepStat { + finished_at, + duration_secs, + complete: manifest.status == xexeu_core::batch::SweepStatus::Complete, + events, + }, + ); + } +} + +/// Posts the sweep's events to every webhook that wants them, in the +/// background: a slow or broken receiver never holds up ingestion. +pub(crate) async fn notify( + config: &RwLock, + metrics: &Arc, + client: &reqwest::Client, + manifest: &SweepManifest, + events: &[Event], +) { + let webhooks = config.read().await.webhooks.clone(); + for webhook in webhooks { + let selected = alert::select_events(&webhook, &manifest.group, events); + if selected.is_empty() { + continue; + } + let body = alert::render( + webhook.format, + &manifest.group, + manifest.sweep_id, + &selected, + ); + let key = webhook + .secret_env + .as_deref() + .and_then(|name| std::env::var(name).ok()) + .filter(|key| !key.is_empty()); + if webhook.secret_env.is_some() && key.is_none() { + eprintln!( + "aviso: webhook {} pede assinatura, mas a variável {} está vazia; enviando sem assinar", + webhook.redacted_url(), + webhook.secret_env.as_deref().unwrap_or_default() + ); + } + let (metrics, client, count) = (Arc::clone(metrics), client.clone(), selected.len()); + tokio::spawn(async move { + let key = key.as_deref().map(str::as_bytes); + match alert::deliver(&client, &webhook.url, &body, key, Duration::from_secs(2)).await { + Ok(()) => { + metrics.webhook_ok.fetch_add(1, Ordering::Relaxed); + println!( + "webhook {}: {count} evento(s) enviados", + webhook.redacted_url() + ); + } + Err(error) => { + metrics.webhook_failed.fetch_add(1, Ordering::Relaxed); + eprintln!( + "aviso: webhook {} falhou após {} tentativas: {error}", + webhook.redacted_url(), + alert::MAX_ATTEMPTS + ); + } + } + }); + } +} + +/// Label value with `\`, `"` and newlines escaped. +fn label(value: &str) -> String { + value + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") +} + +fn metric(out: &mut String, name: &str, kind: &str, help: &str, samples: &[(String, f64)]) { + let _ = writeln!(out, "# HELP {name} {help}"); + let _ = writeln!(out, "# TYPE {name} {kind}"); + for (labels, value) in samples { + let _ = writeln!(out, "{name}{labels} {value}"); + } +} + +fn severity(cvss: Option) -> &'static str { + match cvss { + Some(score) if score >= 9.0 => "critica", + Some(score) if score >= 7.0 => "alta", + Some(score) if score >= 4.0 => "media", + Some(score) if score > 0.0 => "baixa", + _ => "sem_cvss", + } +} + +pub(crate) async fn metrics_handler(State(state): State) -> impl IntoResponse { + let current = match state.storage.lock().await.load_state(&[]) { + Ok(current) => current, + Err(error) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], + format!("falha ao carregar estado: {error}"), + ) + } + }; + + let (mut active, mut gone, mut open_ports, mut kev) = (0u64, 0u64, 0u64, 0u64); + let mut findings: BTreeMap<&str, u64> = ["critica", "alta", "media", "baixa", "sem_cvss"] + .into_iter() + .map(|level| (level, 0)) + .collect(); + for asset in ¤t.assets { + match asset.status { + AssetStatus::Active => active += 1, + AssetStatus::Gone => gone += 1, + } + for port in asset + .ports + .iter() + .filter(|port| port.status == PortStatus::Open) + { + open_ports += 1; + for finding in &port.findings { + *findings.entry(severity(finding.cvss)).or_default() += 1; + kev += u64::from(finding.kev); + } + } + } + + let mut out = String::new(); + metric( + &mut out, + "xexeu_build_info", + "gauge", + "Running Xexéu version.", + &[( + format!("{{version=\"{}\"}}", env!("CARGO_PKG_VERSION")), + 1.0, + )], + ); + metric( + &mut out, + "xexeu_sweeps_ingested_total", + "counter", + "Sweep batches ingested since start.", + &[( + String::new(), + state.sweeps_ingested.load(Ordering::SeqCst) as f64, + )], + ); + metric( + &mut out, + "xexeu_assets", + "gauge", + "Known hosts by status.", + &[ + ("{status=\"ativo\"}".into(), active as f64), + ("{status=\"sumido\"}".into(), gone as f64), + ], + ); + metric( + &mut out, + "xexeu_open_ports", + "gauge", + "Open ports on known hosts.", + &[(String::new(), open_ports as f64)], + ); + metric( + &mut out, + "xexeu_findings", + "gauge", + "Findings on open ports by CVSS severity.", + &findings + .iter() + .map(|(level, count)| (format!("{{severidade=\"{level}\"}}"), *count as f64)) + .collect::>(), + ); + metric( + &mut out, + "xexeu_kev_findings", + "gauge", + "Findings listed in CISA KEV.", + &[(String::new(), kev as f64)], + ); + + let (cves, kev_entries) = { + let db = state.vuln_db.read().await; + (db.cve_count(), db.kev_count()) + }; + metric( + &mut out, + "xexeu_vuln_db_cves", + "gauge", + "CVEs in the local database.", + &[(String::new(), cves as f64)], + ); + metric( + &mut out, + "xexeu_vuln_db_kev", + "gauge", + "KEV entries in the local database.", + &[(String::new(), kev_entries as f64)], + ); + if let Some(last_sync) = *state.feeds_last_sync.read().await { + metric( + &mut out, + "xexeu_feeds_last_sync_timestamp_seconds", + "gauge", + "Unix time of the last successful feed sync.", + &[(String::new(), last_sync.timestamp() as f64)], + ); + } + + let sweeps = state.metrics.sweeps.lock().await; + let per_group = |value: &dyn Fn(&SweepStat) -> f64| -> Vec<(String, f64)> { + sweeps + .iter() + .map(|(group, stat)| (format!("{{grupo=\"{}\"}}", label(group)), value(stat))) + .collect() + }; + if !sweeps.is_empty() { + metric( + &mut out, + "xexeu_last_sweep_timestamp_seconds", + "gauge", + "Unix time the group's last ingested sweep finished.", + &per_group(&|stat| stat.finished_at.timestamp() as f64), + ); + metric( + &mut out, + "xexeu_last_sweep_duration_seconds", + "gauge", + "Duration of the group's last ingested sweep.", + &per_group(&|stat| stat.duration_secs), + ); + metric( + &mut out, + "xexeu_last_sweep_complete", + "gauge", + "1 if the group's last sweep covered every target.", + &per_group(&|stat| f64::from(u8::from(stat.complete))), + ); + metric( + &mut out, + "xexeu_last_sweep_events", + "gauge", + "Surface changes found by the group's last sweep.", + &per_group(&|stat| stat.events as f64), + ); + } + drop(sweeps); + + metric( + &mut out, + "xexeu_webhook_deliveries_total", + "counter", + "Webhook deliveries by result.", + &[ + ( + "{resultado=\"ok\"}".into(), + state.metrics.webhook_ok.load(Ordering::Relaxed) as f64, + ), + ( + "{resultado=\"falha\"}".into(), + state.metrics.webhook_failed.load(Ordering::Relaxed) as f64, + ), + ], + ); + + ( + StatusCode::OK, + [( + header::CONTENT_TYPE, + "text/plain; version=0.0.4; charset=utf-8", + )], + out, + ) +} diff --git a/crates/xexeu-cli/src/server/mod.rs b/crates/xexeu-cli/src/server/mod.rs index 673b83f..d7d010f 100644 --- a/crates/xexeu-cli/src/server/mod.rs +++ b/crates/xexeu-cli/src/server/mod.rs @@ -3,6 +3,7 @@ mod api; mod assets; pub(crate) mod export; +mod metrics; use std::fs; use std::path::{Path, PathBuf}; @@ -22,6 +23,7 @@ use assets::{ use axum::Router; use chrono::{DateTime, Utc}; use export::{export_changes_csv_handler, export_findings_csv_handler, export_hosts_csv_handler}; +use metrics::{metrics_handler, notify, Metrics}; use tokio::sync::{Mutex, RwLock}; use xexeu_core::batch::SweepBatch; use xexeu_core::config::XexeuConfig; @@ -59,7 +61,10 @@ async fn poll_sweeps( sweeps_dir: PathBuf, storage: Arc>, sweeps_ingested: Arc, + config: Arc>, + metrics: Arc, ) { + let client = reqwest::Client::new(); loop { let manifests = find_sweep_manifests(&sweeps_dir); for sweep_path in manifests { @@ -78,6 +83,17 @@ async fn poll_sweeps( batch.manifest.group, diff.events.len() ); + metrics + .record_sweep(&batch.manifest, diff.events.len()) + .await; + notify( + &config, + &metrics, + &client, + &batch.manifest, + &diff.events, + ) + .await; } Ok(false) => { // Sweep already recorded. @@ -122,6 +138,7 @@ pub(crate) struct ServerState { sweeps_ingested: Arc, vuln_db: Arc>, feeds_last_sync: Arc>>>, + metrics: Arc, } fn parse_duration_str(raw: &str) -> Option { @@ -208,20 +225,33 @@ pub(crate) async fn run_serve( let shared_vuln_db = Arc::new(RwLock::new(initial_db)); let shared_last_sync = Arc::new(RwLock::new(last_sync)); + let auto_sync = config.defaults.feeds.auto_sync; + let interval_str = config.defaults.feeds.sync_interval.clone(); + let shared_config = Arc::new(RwLock::new(config)); + let shared_metrics = Arc::new(Metrics::default()); + // 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(); + let poller_config = Arc::clone(&shared_config); + let poller_metrics = Arc::clone(&shared_metrics); tokio::spawn(async move { - poll_sweeps(poller_sweeps, poller_storage, poller_ingested).await; + poll_sweeps( + poller_sweeps, + poller_storage, + poller_ingested, + poller_config, + poller_metrics, + ) + .await; }); // Spawn periodic background sync if auto_sync is enabled in config - if config.defaults.feeds.auto_sync { + if 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})"); @@ -254,15 +284,17 @@ pub(crate) async fn run_serve( } let state = ServerState { - config: Arc::new(RwLock::new(config)), + config: shared_config, config_path: config_path.to_path_buf(), storage: shared_storage, sweeps_ingested, vuln_db: shared_vuln_db, feeds_last_sync: shared_last_sync, + metrics: shared_metrics, }; let app = Router::new() + .route("/metrics", axum::routing::get(metrics_handler)) .route("/api/health", axum::routing::get(health_handler)) .route("/api/status", axum::routing::get(status_handler)) .route("/api/hosts", axum::routing::get(hosts_handler)) diff --git a/crates/xexeu-cli/tests/alerts_metrics_e2e.rs b/crates/xexeu-cli/tests/alerts_metrics_e2e.rs new file mode 100644 index 0000000..3622536 --- /dev/null +++ b/crates/xexeu-cli/tests/alerts_metrics_e2e.rs @@ -0,0 +1,224 @@ +use std::fs; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use tempfile::TempDir; + +struct ChildGuard(std::process::Child); + +impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +const WEBHOOK_KEY: &str = "e2e-webhook-signing-key"; + +fn http_get(addr: &str, path: &str) -> (u16, String) { + let mut stream = TcpStream::connect(addr).expect("connect to server"); + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("set read timeout"); + let request = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).expect("write request"); + let mut response = String::new(); + stream.read_to_string(&mut response).expect("read response"); + let code = response + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse().ok()) + .unwrap_or(0); + let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string(); + (code, body) +} + +/// Accepts one POST, answers 200 and hands over its headers (lowercased) and body. +fn webhook_receiver() -> (u16, mpsc::Receiver<(String, Vec)>) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind webhook receiver"); + let port = listener.local_addr().expect("receiver address").port(); + let (sender, receiver) = mpsc::channel(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { break }; + let mut reader = BufReader::new(stream); + let mut headers = String::new(); + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + headers.push_str(&line.to_ascii_lowercase()); + } + let length = headers + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse().ok()) + .unwrap_or(0); + let mut body = vec![0; length]; + reader.read_exact(&mut body).expect("read webhook body"); + let mut stream = reader.into_inner(); + let _ = stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + let _ = sender.send((headers, body)); + } + }); + (port, receiver) +} + +#[test] +fn ingested_sweep_triggers_signed_webhook_and_updates_metrics() { + // Something to find: one open port on loopback. + let target = TcpListener::bind("127.0.0.1:0").expect("bind target"); + let target_port = target.local_addr().expect("target address").port(); + std::thread::spawn(move || for _ in target.incoming() {}); + + let (hook_port, deliveries) = webhook_receiver(); + // Nothing listens here: deliveries fail and must be counted, not crash anything. + let dead_port = TcpListener::bind("127.0.0.1:0") + .expect("reserve a port") + .local_addr() + .expect("reserved address") + .port(); + + let workspace = TempDir::new().expect("temporary directory"); + let config_path = workspace.path().join("xexeu.toml"); + let sweeps_dir = workspace.path().join("sweeps"); + let data_dir = workspace.path().join("data"); + fs::write( + &config_path, + format!( + r#" +[escopo] +autorizado = ["127.0.0.1/32"] + +[padrao] +cron = "@daily" + +[perfis.padrao] +tcp = "{target_port}" + +[[grupo]] +nome = "local" +alvos = ["127.0.0.1/32"] + +[[webhook]] +url = "http://127.0.0.1:{hook_port}/hook/secret-path" +eventos = ["porta_nova"] +segredo_env = "XEXEU_E2E_WEBHOOK_KEY" + +[[webhook]] +url = "http://127.0.0.1:{dead_port}/down" +formato = "slack" +"# + ), + ) + .expect("write configuration"); + + let mut child = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "serve", + "--bind", + "127.0.0.1:0", + "--config", + config_path.to_str().expect("config path"), + "--sweeps", + sweeps_dir.to_str().expect("sweeps path"), + "--data-dir", + data_dir.to_str().expect("data dir"), + ]) + .env("XEXEU_E2E_WEBHOOK_KEY", WEBHOOK_KEY) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .expect("spawn xexeu serve"); + let mut reader = BufReader::new(child.stdout.take().expect("take stdout")); + let _guard = ChildGuard(child); + let mut addr = None; + let mut line = String::new(); + while reader.read_line(&mut line).unwrap_or(0) > 0 { + if let Some(rest) = line.split("listening on http://").nth(1) { + addr = Some(rest.trim().to_string()); + break; + } + line.clear(); + } + let addr = addr.expect("server must print its address"); + std::thread::spawn(move || for _ in reader.lines() {}); + + // The API never shows the webhook URL's path: chat webhook URLs are credentials. + let (status, body) = http_get(&addr, "/api/config"); + assert_eq!(status, 200); + assert!( + body.contains(&format!("http://127.0.0.1:{hook_port}/…")), + "{body}" + ); + assert!(!body.contains("secret-path"), "{body}"); + + let scan = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "scan", + "--group", + "local", + "--once", + "--config", + config_path.to_str().expect("config path"), + "--out", + sweeps_dir.to_str().expect("sweeps path"), + ]) + .output() + .expect("run xexeu scan"); + assert!( + scan.status.success(), + "{}", + String::from_utf8_lossy(&scan.stderr) + ); + + let (headers, body) = deliveries + .recv_timeout(Duration::from_secs(15)) + .expect("the webhook receives the sweep's changes"); + let payload: serde_json::Value = serde_json::from_slice(&body).expect("JSON body"); + assert_eq!(payload["grupo"], "local"); + let events = payload["eventos"].as_array().expect("events array"); + assert!(!events.is_empty()); + assert!( + events.iter().all(|event| event["tipo"] == "porta_nova"), + "only subscribed kinds are sent: {payload}" + ); + let expected = xexeu_core::alert::sign(WEBHOOK_KEY.as_bytes(), &body); + assert!( + headers.contains(&format!("x-xexeu-signature: {expected}")), + "signature header in: {headers}" + ); + + // The dead receiver is retried (2 s, then 4 s) before it counts as a failure. + let deadline = Instant::now() + Duration::from_secs(20); + let metrics = loop { + let (status, body) = http_get(&addr, "/metrics"); + assert_eq!(status, 200); + if body.contains("xexeu_webhook_deliveries_total{resultado=\"falha\"} 1") + || Instant::now() > deadline + { + break body; + } + std::thread::sleep(Duration::from_millis(500)); + }; + for expected in [ + "xexeu_sweeps_ingested_total 1", + "xexeu_assets{status=\"ativo\"} 1", + "xexeu_open_ports 1", + "xexeu_last_sweep_complete{grupo=\"local\"} 1", + "xexeu_webhook_deliveries_total{resultado=\"ok\"} 1", + "xexeu_webhook_deliveries_total{resultado=\"falha\"} 1", + "# TYPE xexeu_findings gauge", + ] { + assert!( + metrics.contains(expected), + "missing `{expected}` in:\n{metrics}" + ); + } +} diff --git a/crates/xexeu-core/Cargo.toml b/crates/xexeu-core/Cargo.toml index c254c78..b2f490d 100644 --- a/crates/xexeu-core/Cargo.toml +++ b/crates/xexeu-core/Cargo.toml @@ -22,6 +22,7 @@ tokio-rustls = { version = "0.26", default-features = false, features = ["ring"] serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" +hmac = "0.12" socket2 = { version = "0.5", features = ["all"] } tempfile = "3" thiserror = "1" diff --git a/crates/xexeu-core/src/alert.rs b/crates/xexeu-core/src/alert.rs new file mode 100644 index 0000000..90653e4 --- /dev/null +++ b/crates/xexeu-core/src/alert.rs @@ -0,0 +1,265 @@ +//! Webhook alerts for surface changes. +//! +//! After a sweep is ingested, each `[[webhook]]` gets one POST with the events +//! it subscribed to. The body is Xexéu's JSON, or a short text for Slack and +//! Discord. With `segredo_env`, the body is signed with HMAC-SHA256 in +//! `X-Xexeu-Signature: sha256=`, so the receiver can reject forgeries. +//! +//! Delivery never blocks ingestion and never fails it: errors are retried a +//! few times and then reported to the caller to log and count. + +use std::time::Duration; + +use hmac::{Hmac, Mac}; +use serde_json::{json, Value}; +use sha2::Sha256; +use ulid::Ulid; + +use crate::config::{WebhookConfig, WebhookFormat}; +use crate::diff::Event; + +/// Signature header, `sha256=` of the body. +pub const SIGNATURE_HEADER: &str = "X-Xexeu-Signature"; +/// Attempts per delivery, including the first. +pub const MAX_ATTEMPTS: u32 = 3; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +/// Discord rejects longer messages. +const DISCORD_LIMIT: usize = 2000; +/// Lines listed in a chat message before summarizing the rest. +const CHAT_LINES: usize = 20; + +/// Events from a sweep of `group` that `webhook` subscribed to. +pub fn select_events<'a>( + webhook: &WebhookConfig, + group: &str, + events: &'a [Event], +) -> Vec<&'a Event> { + if !webhook.groups.is_empty() && !webhook.groups.iter().any(|name| name == group) { + return Vec::new(); + } + events + .iter() + .filter(|event| { + webhook.events.is_empty() + || webhook + .events + .iter() + .any(|kind| kind == event.kind.as_str()) + }) + .collect() +} + +fn event_line(event: &Event) -> String { + let ip = event + .asset_key + .rsplit('/') + .next() + .unwrap_or(&event.asset_key); + match &event.service { + Some(service) => format!( + "{} {ip} {}/{}", + event.kind.as_str(), + service.protocol, + service.port + ), + None => format!("{} {ip}", event.kind.as_str()), + } +} + +fn chat_text(group: &str, events: &[&Event]) -> String { + let mut text = format!( + "Xexéu: {} mudança(s) na superfície do grupo {group}", + events.len() + ); + for event in events.iter().take(CHAT_LINES) { + text.push_str("\n• "); + text.push_str(&event_line(event)); + } + if events.len() > CHAT_LINES { + text.push_str(&format!("\n… e mais {}", events.len() - CHAT_LINES)); + } + text +} + +/// Request body for `format`. +pub fn render(format: WebhookFormat, group: &str, sweep_id: Ulid, events: &[&Event]) -> Value { + match format { + WebhookFormat::Json => json!({ + "fonte": "xexeu", + "versao": env!("CARGO_PKG_VERSION"), + "grupo": group, + "sweep_id": sweep_id, + "eventos": events, + }), + WebhookFormat::Slack => json!({ "text": chat_text(group, events) }), + WebhookFormat::Discord => { + let mut text = chat_text(group, events); + if text.chars().count() > DISCORD_LIMIT { + text = text.chars().take(DISCORD_LIMIT - 1).collect::() + "…"; + } + json!({ "content": text }) + } + } +} + +/// `sha256=` HMAC of `body` under `key`. +pub fn sign(key: &[u8], body: &[u8]) -> String { + let mut mac = Hmac::::new_from_slice(key).expect("HMAC accepts keys of any length"); + mac.update(body); + let digest = mac.finalize().into_bytes(); + let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect(); + format!("sha256={hex}") +} + +/// Whether a failed attempt is worth repeating. +fn retryable(status: reqwest::StatusCode) -> bool { + status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS +} + +/// POSTs `body` to `url`, retrying network errors, 5xx and 429 with backoff. +/// `backoff` is the wait before the second attempt; it doubles after that. +pub async fn deliver( + client: &reqwest::Client, + url: &str, + body: &Value, + key: Option<&[u8]>, + backoff: Duration, +) -> Result<(), String> { + let payload = serde_json::to_vec(body).map_err(|error| error.to_string())?; + let signature = key.map(|key| sign(key, &payload)); + let mut wait = backoff; + let mut last_error = String::new(); + for attempt in 1..=MAX_ATTEMPTS { + let mut request = client + .post(url) + .timeout(REQUEST_TIMEOUT) + .header(reqwest::header::CONTENT_TYPE, "application/json") + .header( + reqwest::header::USER_AGENT, + concat!("xexeu/", env!("CARGO_PKG_VERSION")), + ) + .body(payload.clone()); + if let Some(signature) = &signature { + request = request.header(SIGNATURE_HEADER, signature); + } + match request.send().await { + Ok(response) if response.status().is_success() => return Ok(()), + Ok(response) => { + last_error = format!("HTTP {}", response.status()); + if !retryable(response.status()) { + break; + } + } + // Never echo the URL: chat webhook URLs are credentials. + Err(error) => last_error = error.without_url().to_string(), + } + if attempt < MAX_ATTEMPTS { + tokio::time::sleep(wait).await; + wait *= 2; + } + } + Err(last_error) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::diff::{EventKind, EventService}; + use chrono::DateTime; + + fn event(kind: EventKind, ip: &str, port: Option) -> Event { + Event { + event_id: Ulid::nil(), + sweep_id: Ulid::nil(), + group: "dmz".into(), + kind, + asset_key: format!("dmz/{ip}"), + service: port.map(|port| EventService { + protocol: "tcp".into(), + port, + product: None, + version: None, + cpe: None, + }), + previous: None, + current: None, + evidence: json!({}), + occurred_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(), + } + } + + fn webhook(events: &[&str], groups: &[&str]) -> WebhookConfig { + WebhookConfig { + url: "https://hooks.example/abc".into(), + format: WebhookFormat::Json, + events: events.iter().map(|s| s.to_string()).collect(), + groups: groups.iter().map(|s| s.to_string()).collect(), + secret_env: None, + } + } + + #[test] + fn filters_by_kind_and_group() { + let events = vec![ + event(EventKind::HostNew, "10.0.0.5", None), + event(EventKind::PortNew, "10.0.0.5", Some(22)), + ]; + assert_eq!(select_events(&webhook(&[], &[]), "dmz", &events).len(), 2); + let only_ports = select_events(&webhook(&["porta_nova"], &[]), "dmz", &events); + assert_eq!(only_ports.len(), 1); + assert_eq!(only_ports[0].kind, EventKind::PortNew); + assert!(select_events(&webhook(&[], &["lan"]), "dmz", &events).is_empty()); + assert_eq!( + select_events(&webhook(&[], &["lan", "dmz"]), "dmz", &events).len(), + 2 + ); + } + + #[test] + fn renders_each_format() { + let events = [event(EventKind::PortNew, "10.0.0.5", Some(22))]; + let refs: Vec<&Event> = events.iter().collect(); + let body = render(WebhookFormat::Json, "dmz", Ulid::nil(), &refs); + assert_eq!(body["grupo"], "dmz"); + assert_eq!(body["eventos"][0]["tipo"], "porta_nova"); + let slack = render(WebhookFormat::Slack, "dmz", Ulid::nil(), &refs); + assert!(slack["text"] + .as_str() + .unwrap() + .contains("porta_nova 10.0.0.5 tcp/22")); + let discord = render(WebhookFormat::Discord, "dmz", Ulid::nil(), &refs); + assert!(discord["content"] + .as_str() + .unwrap() + .starts_with("Xexéu: 1 mudança(s)")); + } + + #[test] + fn long_chat_messages_are_summarized_and_fit_discord() { + let events: Vec = (0..500) + .map(|i| { + event( + EventKind::HostNew, + &format!("10.0.{}.{}", i / 250, i % 250), + None, + ) + }) + .collect(); + let refs: Vec<&Event> = events.iter().collect(); + let text = render(WebhookFormat::Slack, "dmz", Ulid::nil(), &refs)["text"] + .as_str() + .unwrap() + .to_string(); + assert!(text.ends_with("… e mais 480")); + let discord = render(WebhookFormat::Discord, "dmz", Ulid::nil(), &refs); + assert!(discord["content"].as_str().unwrap().chars().count() <= DISCORD_LIMIT); + } + + #[test] + fn signature_matches_rfc_4231_test_case_2() { + assert_eq!( + sign(b"Jefe", b"what do ya want for nothing?"), + "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + } +} diff --git a/crates/xexeu-core/src/config.rs b/crates/xexeu-core/src/config.rs index baa6513..173c164 100644 --- a/crates/xexeu-core/src/config.rs +++ b/crates/xexeu-core/src/config.rs @@ -29,6 +29,114 @@ pub struct XexeuConfig { /// Target groups. #[serde(rename = "grupo", default)] pub groups: Vec, + /// `[[webhook]]`: where surface changes are posted after each ingested sweep. + #[serde(rename = "webhook", default, skip_serializing_if = "Vec::is_empty")] + pub webhooks: Vec, +} + +/// Body shape a webhook receiver expects. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WebhookFormat { + /// Xexéu's own JSON: group, sweep and the full events. + #[default] + Json, + /// Slack incoming webhook (`{"text": ...}`); also Mattermost and Rocket.Chat. + Slack, + /// Discord webhook (`{"content": ...}`). + Discord, +} + +/// `[[webhook]]`: one receiver of surface changes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WebhookConfig { + /// `http(s)://` endpoint. Chat webhook URLs are credentials, so the API + /// only ever shows them redacted. + pub url: String, + #[serde(rename = "formato", default)] + pub format: WebhookFormat, + /// Event kinds to send (`host_novo`, `host_voltou`, `host_sumiu`, + /// `porta_nova`, `porta_fechada`, `servico_alterado`); empty means all. + #[serde(rename = "eventos", default, skip_serializing_if = "Vec::is_empty")] + pub events: Vec, + /// Groups whose sweeps are sent; empty means all. + #[serde(rename = "grupos", default, skip_serializing_if = "Vec::is_empty")] + pub groups: Vec, + /// Name of the environment variable holding the HMAC-SHA256 key; the key + /// itself never goes in the file. + #[serde( + rename = "segredo_env", + default, + skip_serializing_if = "Option::is_none" + )] + pub secret_env: Option, +} + +/// Event kinds a webhook can subscribe to. +pub const WEBHOOK_EVENTS: [&str; 6] = [ + "host_novo", + "host_voltou", + "host_sumiu", + "porta_nova", + "porta_fechada", + "servico_alterado", +]; + +impl WebhookConfig { + /// URL safe to show: scheme and host only. + pub fn redacted_url(&self) -> String { + match self.url.split_once("://") { + Some((scheme, rest)) => { + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + let host = host.rsplit('@').next().unwrap_or(host); + format!("{scheme}://{host}/…") + } + None => "…".to_string(), + } + } + + fn validate(&self, index: usize, groups: &[GroupConfig]) -> Result<(), ConfigError> { + let invalid = |reason: String| ConfigError::InvalidWebhook { index, reason }; + let Some((scheme, rest)) = self.url.split_once("://") else { + return Err(invalid( + "url precisa começar com http:// ou https://".into(), + )); + }; + if !matches!(scheme, "http" | "https") || rest.split('/').next().unwrap_or("").is_empty() { + return Err(invalid( + "url precisa começar com http:// ou https:// e ter host".into(), + )); + } + if let Some(kind) = self + .events + .iter() + .find(|kind| !WEBHOOK_EVENTS.contains(&kind.as_str())) + { + return Err(invalid(format!( + "evento desconhecido `{kind}` (use: {})", + WEBHOOK_EVENTS.join(", ") + ))); + } + if let Some(group) = self + .groups + .iter() + .find(|name| !groups.iter().any(|group| &group.name == *name)) + { + return Err(invalid(format!("grupo desconhecido `{group}`"))); + } + if let Some(name) = &self.secret_env { + let valid = !name.is_empty() + && name + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'); + if !valid { + return Err(invalid(format!( + "segredo_env `{name}` não é um nome de variável de ambiente (A-Z, 0-9, _)" + ))); + } + } + Ok(()) + } } /// `[escopo]`: what the operator is allowed to touch. @@ -277,6 +385,14 @@ pub enum ConfigError { /// Prefix length supplied. prefix: u8, }, + /// A `[[webhook]]` entry is invalid. + #[error("webhook na posição {index} inválido: {reason}")] + InvalidWebhook { + /// Zero-based position in the document. + index: usize, + /// What is wrong with it. + reason: String, + }, /// I/O error reading or writing configuration. #[error("erro de E/S na configuração: {0}")] Io(String), @@ -472,8 +588,21 @@ impl XexeuConfig { }); } + for (index, webhook) in self.webhooks.iter().enumerate() { + webhook.validate(index, &self.groups)?; + } + Ok(report) } + + /// Copy safe to serve over the API: webhook URLs reduced to scheme and host. + pub fn redacted(&self) -> Self { + let mut copy = self.clone(); + for webhook in &mut copy.webhooks { + webhook.url = webhook.redacted_url(); + } + copy + } } fn scope_error(error: TargetError) -> ConfigError { @@ -831,4 +960,74 @@ criticidade = "alta" XexeuConfig::load_validated(&file_content).expect("from disk validates"); assert_eq!(config, from_disk); } + + const WEBHOOK_BASE: &str = r#" +[escopo] +autorizado = ["10.0.0.0/24"] + +[perfis.padrao] + +[[grupo]] +nome = "dmz" +alvos = ["10.0.0.0/28"] +"#; + + fn with_webhook(webhook: &str) -> Result { + XexeuConfig::from_toml_str(&format!("{WEBHOOK_BASE}\n[[webhook]]\n{webhook}"))?.validate() + } + + #[test] + fn webhooks_are_validated() { + assert!(with_webhook(r#"url = "https://hooks.example/T0/B0/x""#).is_ok()); + assert!(with_webhook( + r#"url = "http://10.0.0.9:8080/in" +formato = "discord" +eventos = ["porta_nova", "host_sumiu"] +grupos = ["dmz"] +segredo_env = "XEXEU_WEBHOOK_KEY""# + ) + .is_ok()); + for bad in [ + r#"url = "ftp://hooks.example/x""#, + r#"url = "hooks.example/x""#, + r#"url = "https:///x""#, + r#"url = "https://h.example/x" +eventos = ["porta_aberta"]"#, + r#"url = "https://h.example/x" +grupos = ["lan"]"#, + r#"url = "https://h.example/x" +segredo_env = "minha chave""#, + ] { + assert!( + matches!( + with_webhook(bad), + Err(ConfigError::InvalidWebhook { index: 0, .. }) + ), + "{bad}" + ); + } + assert!(matches!( + with_webhook( + r#"url = "https://h.example/x" +formato = "teams""# + ), + Err(ConfigError::Toml { .. }) + )); + } + + #[test] + fn redacted_config_hides_webhook_paths_and_credentials() { + let config = XexeuConfig::from_toml_str(&format!( + "{WEBHOOK_BASE}\n[[webhook]]\nurl = \"https://user:pw@hooks.slack.example/services/T0/B0/secret?x=1\"\n" + )) + .unwrap(); + let redacted = config.redacted(); + assert_eq!(redacted.webhooks[0].url, "https://hooks.slack.example/…"); + assert!( + config.webhooks[0].url.contains("secret"), + "the original is untouched" + ); + let text = config.to_toml_string().unwrap(); + assert!(text.contains("secret"), "saving keeps the real URL"); + } } diff --git a/crates/xexeu-core/src/lib.rs b/crates/xexeu-core/src/lib.rs index f7f135f..540a5f4 100644 --- a/crates/xexeu-core/src/lib.rs +++ b/crates/xexeu-core/src/lib.rs @@ -1,6 +1,7 @@ //! Xexéu core: configuration, scheduling, scanning, vulnerability correlation, //! storage and diffing for continuous attack-surface auditing. +pub mod alert; pub mod batch; pub mod caps; pub mod config; diff --git a/docker-compose.yml b/docker-compose.yml index da17248..7dc5348 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,6 +32,8 @@ services: environment: # Empty: a token is generated at each start and printed in `docker compose logs xexeu`. XEXEU_ADMIN_TOKEN: ${XEXEU_ADMIN_TOKEN:-} + # Signing key for a [[webhook]] with segredo_env = "XEXEU_WEBHOOK_KEY". + XEXEU_WEBHOOK_KEY: ${XEXEU_WEBHOOK_KEY:-} ports: - "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788" volumes: diff --git a/docs/cli.md b/docs/cli.md index 73b4436..c975359 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -33,6 +33,15 @@ present, must match `Host`. Without `XEXEU_ADMIN_TOKEN`, `serve` prints a fresh `http://…/?token=…` link at each start; opening it logs the dashboard in for that tab. +`GET /metrics` serves Prometheus text: `xexeu_build_info`, +`xexeu_sweeps_ingested_total`, `xexeu_assets{status}`, `xexeu_open_ports`, +`xexeu_findings{severidade}`, `xexeu_kev_findings`, `xexeu_vuln_db_cves`, +`xexeu_feeds_last_sync_timestamp_seconds`, per-group +`xexeu_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` and +`xexeu_webhook_deliveries_total{resultado}`. Like the other reads it needs no +token; an alert on `time() - xexeu_last_sweep_timestamp_seconds` catches a +scanner that stopped. + ## `xexeu scanner` Runs the continuous scheduler and scan engine, writing sweep batches — diff --git a/docs/configuration.md b/docs/configuration.md index 3e3953f..0697a25 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -102,6 +102,36 @@ and a broad daily one covering the same address). The storage layer deduplicates by asset identity, and `config check` lists the overlap with each host's effective (shortest) cadence. +### `[[webhook]]` — change alerts + +After each ingested sweep, `xexeu serve` posts the surface changes it found to +every `[[webhook]]` (one request per sweep, only when there is something to +send): + +```toml +[[webhook]] +url = "https://hooks.slack.com/services/T000/B000/XXXX" +formato = "slack" # json (default) | slack | discord +eventos = ["porta_nova", "host_novo"] # empty or omitted: every kind +grupos = ["dmz"] # empty or omitted: every group +segredo_env = "XEXEU_WEBHOOK_KEY" # optional HMAC-SHA256 signature +``` + +- `formato = "json"` sends `{"fonte", "versao", "grupo", "sweep_id", "eventos"}` + with the same event objects as `/api/changes`. `slack` (also Mattermost and + Rocket.Chat) and `discord` send a short text listing up to 20 changes. +- `eventos`: `host_novo`, `host_voltou`, `host_sumiu`, `porta_nova`, + `porta_fechada`, `servico_alterado`. +- `segredo_env` names an environment variable; its value signs the body as + `X-Xexeu-Signature: sha256=`. The key itself never goes in the file. +- Delivery runs in the background and never holds up ingestion. Network + errors, `5xx` and `429` are retried twice (after 2 s and 4 s); the outcome is + logged and counted in `/metrics`. +- Chat webhook URLs are credentials: `GET /api/config` and the logs show only + `scheme://host/…`. +- `xexeu serve` reads the webhooks at start (and on dashboard edits); restart it + after changing them by hand. + ## Editing a group from the dashboard `xexeu serve`'s **Groups** view can create, edit and delete groups without diff --git a/docs/pt-BR/cli.md b/docs/pt-BR/cli.md index 5e4b00d..086687c 100644 --- a/docs/pt-BR/cli.md +++ b/docs/pt-BR/cli.md @@ -33,6 +33,15 @@ quando presente, precisa bater com o `Host`. Sem `XEXEU_ADMIN_TOKEN`, o `serve` imprime um link `http://…/?token=…` novo a cada partida; abri-lo autentica o dashboard naquela aba. +`GET /metrics` serve texto Prometheus: `xexeu_build_info`, +`xexeu_sweeps_ingested_total`, `xexeu_assets{status}`, `xexeu_open_ports`, +`xexeu_findings{severidade}`, `xexeu_kev_findings`, `xexeu_vuln_db_cves`, +`xexeu_feeds_last_sync_timestamp_seconds`, por grupo +`xexeu_last_sweep_{timestamp_seconds,duration_seconds,complete,events}` e +`xexeu_webhook_deliveries_total{resultado}`. Como as outras leituras, não exige +token; um alerta em `time() - xexeu_last_sweep_timestamp_seconds` pega um +scanner que parou. + ## `xexeu scanner` Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca diff --git a/docs/pt-BR/configuracao.md b/docs/pt-BR/configuracao.md index fa46832..a1c2864 100644 --- a/docs/pt-BR/configuracao.md +++ b/docs/pt-BR/configuracao.md @@ -106,6 +106,37 @@ frequência e um amplo diário cobrindo o mesmo endereço). A camada de armazenamento deduplica por identidade de ativo, e `config check` lista a sobreposição com a cadência efetiva (a mais curta) de cada host. +### `[[webhook]]` — alertas de mudança + +Depois de cada varredura ingerida, o `xexeu serve` envia as mudanças de +superfície encontradas para cada `[[webhook]]` (uma requisição por varredura, +só quando há algo a enviar): + +```toml +[[webhook]] +url = "https://hooks.slack.com/services/T000/B000/XXXX" +formato = "slack" # json (padrão) | slack | discord +eventos = ["porta_nova", "host_novo"] # vazio ou ausente: todos os tipos +grupos = ["dmz"] # vazio ou ausente: todos os grupos +segredo_env = "XEXEU_WEBHOOK_KEY" # assinatura HMAC-SHA256 opcional +``` + +- `formato = "json"` envia `{"fonte", "versao", "grupo", "sweep_id", "eventos"}` + com os mesmos objetos de evento do `/api/changes`. `slack` (também Mattermost + e Rocket.Chat) e `discord` enviam um texto curto listando até 20 mudanças. +- `eventos`: `host_novo`, `host_voltou`, `host_sumiu`, `porta_nova`, + `porta_fechada`, `servico_alterado`. +- `segredo_env` é o nome de uma variável de ambiente; o valor dela assina o + corpo como `X-Xexeu-Signature: sha256=`. A chave nunca vai no + arquivo. +- A entrega roda em segundo plano e nunca segura a ingestão. Erros de rede, + `5xx` e `429` são repetidos duas vezes (após 2 s e 4 s); o resultado vai para + o log e para o `/metrics`. +- URLs de webhook de chat são credenciais: o `GET /api/config` e os logs mostram + só `esquema://host/…`. +- O `xexeu serve` lê os webhooks na partida (e nas edições pelo dashboard); + reinicie-o depois de mudá-los à mão. + ## Editando um grupo pelo dashboard A tela **Grupos** do `xexeu serve` cria, edita e remove grupos sem precisar diff --git a/examples/xexeu.toml b/examples/xexeu.toml index 1ede7cf..3eb849f 100644 --- a/examples/xexeu.toml +++ b/examples/xexeu.toml @@ -56,3 +56,11 @@ alvos = ["10.0.1.1", "10.0.1.2", "10.0.1.10-10.0.1.20", "db01.interno.exemplo.or cron = "0 3 * * *" # varredura completa (1-65535 + vulnerabilidades) às 03:00 perfil = "completo" criticidade = "critica" + +# Alertas: as mudanças de cada varredura vão para um webhook (veja docs/configuration.md). +# [[webhook]] +# url = "https://hooks.slack.com/services/T000/B000/XXXX" +# formato = "slack" +# eventos = ["host_novo", "porta_nova", "servico_alterado"] +# grupos = ["dmz", "nucleo"] +# segredo_env = "XEXEU_WEBHOOK_KEY"