Implementa xexeu feeds import/sync e sincronização periódica de CVE/KEV embutida no xexeu serve

This commit is contained in:
Lucas Guerra committed 2026-11-02 00:13:35 -03:00
1 parent b4d2c29d24
commit 4ce5d7f595
7 files changed
+1817 -48

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd
croner = "4"
ipnet = "2"
parquet = { version = "60", default-features = false, features = ["arrow", "snap"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
rusqlite = { version = "0.41", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+32
View File
@@ -63,6 +63,37 @@ pub struct DefaultsConfig {
/// Consecutive unanswered scans before a host is considered gone.
#[serde(rename = "ausencias_para_sumir", default)]
pub absences_before_disappear: Option<u32>,
/// Vulnerability feeds synchronization settings.
#[serde(rename = "feeds", default)]
pub feeds: FeedsConfig,
}
/// Vulnerability feeds synchronization settings under `[padrao.feeds]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct FeedsConfig {
/// Whether to automatically sync vulnerability feeds periodically in the server.
#[serde(rename = "sincronizar_automaticamente", default = "default_false")]
pub auto_sync: bool,
/// Interval between automatic synchronizations (e.g. "24h", "12h").
#[serde(rename = "intervalo_sincronizacao", default = "default_sync_interval")]
pub sync_interval: String,
}
fn default_false() -> bool {
false
}
fn default_sync_interval() -> String {
"24h".to_string()
}
impl Default for FeedsConfig {
fn default() -> Self {
Self {
auto_sync: false,
sync_interval: default_sync_interval(),
}
}
}
impl Default for DefaultsConfig {
@@ -74,6 +105,7 @@ impl Default for DefaultsConfig {
max_pps: None,
simultaneous_hosts: None,
absences_before_disappear: None,
feeds: FeedsConfig::default(),
}
}
}
+346 -32
View File
@@ -3,11 +3,13 @@
//! This module provides deterministic parsers for local NVD and CISA KEV feeds,
//! indexing them into memory for fast lookup during service banner correlation.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
use std::time::Duration;
use thiserror::Error;
/// Error encountered during feed import.
@@ -27,6 +29,8 @@ pub enum FeedError {
},
#[error("Invalid feed format in '{path}': {detail}")]
Format { path: String, detail: String },
#[error("Network error fetching feed from '{url}': {detail}")]
Network { url: String, detail: String },
}
/// Structured Common Platform Enumeration (CPE) representation.
@@ -111,19 +115,19 @@ pub struct CveRecord {
}
/// In-memory catalog of NVD vulnerabilities.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NvdCatalog {
pub records: HashMap<String, CveRecord>,
}
/// In-memory catalog of CISA Known Exploited Vulnerabilities (KEV).
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KevCatalog {
pub cve_ids: HashSet<String>,
}
/// Combined local vulnerability database.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VulnDatabase {
pub nvd: NvdCatalog,
pub kev: KevCatalog,
@@ -145,6 +149,61 @@ impl VulnDatabase {
pub fn is_in_kev(&self, cve_id: &str) -> bool {
self.kev.cve_ids.contains(cve_id)
}
/// Merges another vulnerability database into this one without duplicating entries.
pub fn merge(&mut self, other: VulnDatabase) {
for (id, record) in other.nvd.records {
self.nvd.records.insert(id, record);
}
for id in other.kev.cve_ids {
self.kev.cve_ids.insert(id);
}
}
/// Returns the number of CVE records in the NVD catalog.
pub fn cve_count(&self) -> usize {
self.nvd.records.len()
}
/// Returns the number of CVE IDs in the CISA KEV catalog.
pub fn kev_count(&self) -> usize {
self.kev.cve_ids.len()
}
/// Saves the combined database to a JSON file on disk.
pub fn save_to_file(&self, path: &Path) -> Result<(), FeedError> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|e| FeedError::Io {
path: parent.display().to_string(),
source: e,
})?;
}
}
let file = File::create(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let writer = std::io::BufWriter::new(file);
serde_json::to_writer(writer, self).map_err(|e| FeedError::Json {
path: path.display().to_string(),
source: e,
})?;
Ok(())
}
/// Loads the combined database from a JSON file on disk.
pub fn load_from_file(path: &Path) -> Result<Self, FeedError> {
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let reader = BufReader::new(file);
serde_json::from_reader(reader).map_err(|e| FeedError::Json {
path: path.display().to_string(),
source: e,
})
}
}
// ---------------------------------------------------------------------------
@@ -240,16 +299,10 @@ fn default_true() -> bool {
true
}
/// Imports an NVD CVE JSON 2.0 file from disk.
pub fn import_nvd(path: &Path) -> Result<NvdCatalog, FeedError> {
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let reader = BufReader::new(file);
/// Parses an NVD CVE JSON 2.0 payload from any reader.
pub fn parse_nvd_json<R: Read>(reader: R) -> Result<NvdCatalog, FeedError> {
let dto: NvdFeedDto = serde_json::from_reader(reader).map_err(|e| FeedError::Json {
path: path.display().to_string(),
path: "payload".to_string(),
source: e,
})?;
@@ -323,6 +376,22 @@ pub fn import_nvd(path: &Path) -> Result<NvdCatalog, FeedError> {
Ok(NvdCatalog { records })
}
/// Imports an NVD CVE JSON 2.0 file from disk.
pub fn import_nvd(path: &Path) -> Result<NvdCatalog, FeedError> {
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let reader = BufReader::new(file);
parse_nvd_json(reader).map_err(|e| match e {
FeedError::Json { source, .. } => FeedError::Json {
path: path.display().to_string(),
source,
},
other => other,
})
}
// ---------------------------------------------------------------------------
// CISA KEV Ingestion (JSON and CSV)
// ---------------------------------------------------------------------------
@@ -339,20 +408,13 @@ struct KevItemDto {
cve_id: String,
}
/// Imports CISA Known Exploited Vulnerabilities from a JSON or CSV file.
pub fn import_kev(path: &Path) -> Result<KevCatalog, FeedError> {
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let mut reader = BufReader::new(file);
// Peek the first non-whitespace character to distinguish JSON from CSV
/// Parses CISA KEV data from a reader (handles both JSON and CSV formats).
pub fn parse_kev_reader<R: BufRead>(mut reader: R) -> Result<KevCatalog, FeedError> {
let mut first_line = String::new();
reader
.read_line(&mut first_line)
.map_err(|e| FeedError::Io {
path: path.display().to_string(),
path: "reader".to_string(),
source: e,
})?;
@@ -360,16 +422,11 @@ pub fn import_kev(path: &Path) -> Result<KevCatalog, FeedError> {
let mut cve_ids = HashSet::new();
if trimmed.starts_with('{') {
// Re-read entire JSON
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
let chained = std::io::Cursor::new(first_line).chain(reader);
let dto: KevJsonDto = serde_json::from_reader(chained).map_err(|e| FeedError::Json {
path: "reader".to_string(),
source: e,
})?;
let dto: KevJsonDto =
serde_json::from_reader(BufReader::new(file)).map_err(|e| FeedError::Json {
path: path.display().to_string(),
source: e,
})?;
for item in dto.vulnerabilities {
cve_ids.insert(item.cve_id);
}
@@ -382,7 +439,7 @@ pub fn import_kev(path: &Path) -> Result<KevCatalog, FeedError> {
}
for line_res in reader.lines() {
let line = line_res.map_err(|e| FeedError::Io {
path: path.display().to_string(),
path: "reader".to_string(),
source: e,
})?;
if let Some(id) = extract_cve_from_line(&line) {
@@ -394,6 +451,26 @@ pub fn import_kev(path: &Path) -> Result<KevCatalog, FeedError> {
Ok(KevCatalog { cve_ids })
}
/// Imports CISA Known Exploited Vulnerabilities from a JSON or CSV file.
pub fn import_kev(path: &Path) -> Result<KevCatalog, FeedError> {
let file = File::open(path).map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let reader = BufReader::new(file);
parse_kev_reader(reader).map_err(|e| match e {
FeedError::Io { source, .. } => FeedError::Io {
path: path.display().to_string(),
source,
},
FeedError::Json { source, .. } => FeedError::Json {
path: path.display().to_string(),
source,
},
other => other,
})
}
fn extract_cve_from_line(line: &str) -> Option<String> {
let col = line.split(',').next()?.trim().trim_matches('"');
if col.starts_with("CVE-") {
@@ -403,6 +480,130 @@ fn extract_cve_from_line(line: &str) -> Option<String> {
}
}
// ---------------------------------------------------------------------------
// HTTP Synchronization (NVD CVE 2.0 API & CISA KEV)
// ---------------------------------------------------------------------------
/// Default official endpoint for NVD CVE API 2.0.
pub const NVD_CVE_API_URL: &str = "https://services.nvd.nist.gov/rest/json/cves/2.0";
/// Default official endpoint for CISA KEV JSON catalog.
pub const CISA_KEV_API_URL: &str =
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json";
/// Options for synchronizing vulnerability feeds.
#[derive(Debug, Clone)]
pub struct SyncOptions {
/// NVD CVE 2.0 API URL (overrideable for testing or custom proxies).
pub nvd_url: String,
/// CISA KEV JSON URL (overrideable for testing).
pub kev_url: String,
/// Timeout for HTTP calls.
pub timeout: Duration,
/// Optional incremental start date for NVD changes (`lastModStartDate`).
pub last_mod_start: Option<DateTime<Utc>>,
}
impl Default for SyncOptions {
fn default() -> Self {
let nvd_url =
std::env::var("XEXEU_NVD_URL").unwrap_or_else(|_| NVD_CVE_API_URL.to_string());
let kev_url =
std::env::var("XEXEU_KEV_URL").unwrap_or_else(|_| CISA_KEV_API_URL.to_string());
Self {
nvd_url,
kev_url,
timeout: Duration::from_secs(30),
last_mod_start: None,
}
}
}
/// Downloads and parses NVD CVE records from an API endpoint.
pub async fn sync_nvd(client: &reqwest::Client, url: &str) -> Result<NvdCatalog, FeedError> {
let resp = client
.get(url)
.header("User-Agent", "Xexeu-Vuln-Sync/0.1.0")
.send()
.await
.map_err(|e| FeedError::Network {
url: url.to_string(),
detail: e.to_string(),
})?;
if !resp.status().is_success() {
return Err(FeedError::Network {
url: url.to_string(),
detail: format!("status HTTP {}", resp.status()),
});
}
let bytes = resp.bytes().await.map_err(|e| FeedError::Network {
url: url.to_string(),
detail: format!("falha ao ler corpo da resposta: {e}"),
})?;
parse_nvd_json(bytes.as_ref())
}
/// Downloads and parses CISA KEV catalog from an HTTP endpoint.
pub async fn sync_kev(client: &reqwest::Client, url: &str) -> Result<KevCatalog, FeedError> {
let resp = client
.get(url)
.header("User-Agent", "Xexeu-Vuln-Sync/0.1.0")
.send()
.await
.map_err(|e| FeedError::Network {
url: url.to_string(),
detail: e.to_string(),
})?;
if !resp.status().is_success() {
return Err(FeedError::Network {
url: url.to_string(),
detail: format!("status HTTP {}", resp.status()),
});
}
let bytes = resp.bytes().await.map_err(|e| FeedError::Network {
url: url.to_string(),
detail: format!("falha ao ler corpo da resposta: {e}"),
})?;
parse_kev_reader(BufReader::new(bytes.as_ref()))
}
/// Synchronizes both NVD and CISA KEV feeds over HTTP according to `options`.
pub async fn sync_feeds(options: &SyncOptions) -> Result<VulnDatabase, FeedError> {
let client = reqwest::Client::builder()
.timeout(options.timeout)
.build()
.map_err(|e| FeedError::Network {
url: "client_builder".to_string(),
detail: e.to_string(),
})?;
let effective_nvd_url = if let Some(start) = options.last_mod_start {
let start_str = start.format("%Y-%m-%dT%H:%M:%S.000").to_string();
let end_str = Utc::now().format("%Y-%m-%dT%H:%M:%S.000").to_string();
let sep = if options.nvd_url.contains('?') {
'&'
} else {
'?'
};
format!(
"{}{}lastModStartDate={}&lastModEndDate={}",
options.nvd_url, sep, start_str, end_str
)
} else {
options.nvd_url.clone()
};
let nvd = sync_nvd(&client, &effective_nvd_url).await?;
let kev = sync_kev(&client, &options.kev_url).await?;
Ok(VulnDatabase { nvd, kev })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -546,4 +747,117 @@ mod tests {
let kev_csv_parsed = import_kev(f_csv.path()).unwrap();
assert!(kev_csv_parsed.cve_ids.contains("CVE-2024-6387"));
}
#[test]
fn test_vuln_database_merge_and_disk_roundtrip() {
let mut db1 = VulnDatabase::default();
let mut db2 = VulnDatabase::default();
let rec1 = CveRecord {
id: "CVE-2021-41773".to_string(),
description: "Apache flaw".to_string(),
cvss_score: Some(7.5),
cvss_vector: None,
cpe_matches: vec![],
};
let rec2 = CveRecord {
id: "CVE-2024-6387".to_string(),
description: "OpenSSH flaw".to_string(),
cvss_score: Some(8.1),
cvss_vector: None,
cpe_matches: vec![],
};
db1.nvd.records.insert(rec1.id.clone(), rec1);
db1.kev.cve_ids.insert("CVE-2021-41773".to_string());
db2.nvd.records.insert(rec2.id.clone(), rec2);
db2.kev.cve_ids.insert("CVE-2024-6387".to_string());
db1.merge(db2);
assert_eq!(db1.cve_count(), 2);
assert_eq!(db1.kev_count(), 2);
assert!(db1.is_in_kev("CVE-2021-41773"));
assert!(db1.is_in_kev("CVE-2024-6387"));
let temp_dir = tempfile::tempdir().unwrap();
let db_path = temp_dir.path().join("vuln_db.json");
db1.save_to_file(&db_path).unwrap();
let loaded = VulnDatabase::load_from_file(&db_path).unwrap();
assert_eq!(loaded.cve_count(), 2);
assert_eq!(loaded.kev_count(), 2);
assert!(loaded.is_in_kev("CVE-2021-41773"));
}
#[tokio::test]
async fn test_sync_feeds_mock_http_success_and_failure() {
use std::io::Read;
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = match stream {
Ok(s) => s,
Err(_) => break,
};
let mut buf = [0u8; 1024];
let n = stream.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]);
if req.contains("/cves") {
let body = r#"{"format":"NVD_CVE","version":"2.0","vulnerabilities":[{"cve":{"id":"CVE-2021-41773","descriptions":[{"lang":"en","value":"Apache"}]}}]}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(resp.as_bytes());
} else if req.contains("/kev") {
let body = r#"{"vulnerabilities":[{"cveID":"CVE-2021-41773"}]}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(resp.as_bytes());
} else {
let resp =
"HTTP/1.1 404 NOT FOUND\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
let _ = stream.write_all(resp.as_bytes());
}
}
});
let options = SyncOptions {
nvd_url: format!("http://127.0.0.1:{port}/cves"),
kev_url: format!("http://127.0.0.1:{port}/kev"),
timeout: Duration::from_secs(2),
last_mod_start: None,
};
let db = sync_feeds(&options).await.expect("sync should succeed");
assert_eq!(db.cve_count(), 1);
assert!(db.nvd.records.contains_key("CVE-2021-41773"));
assert!(db.is_in_kev("CVE-2021-41773"));
// Test network failure with bad URL
let bad_options = SyncOptions {
nvd_url: "http://127.0.0.1:1/nonexistent".to_string(),
kev_url: format!("http://127.0.0.1:{port}/kev"),
timeout: Duration::from_millis(500),
last_mod_start: None,
};
let err = sync_feeds(&bad_options).await;
assert!(err.is_err());
match err {
Err(FeedError::Network { url, .. }) => {
assert!(url.contains("127.0.0.1:1"));
}
other => panic!("expected Network error, got {:?}", other),
}
}
}
+3 -2
View File
@@ -9,8 +9,9 @@ pub use checks::{
probe_unencrypted_admin_service, CheckError, COMMON_ADMIN_PORTS,
};
pub use feeds::{
import_kev, import_nvd, Cpe, CpeMatchCriteria, CveRecord, FeedError, KevCatalog, NvdCatalog,
VulnDatabase,
import_kev, import_nvd, parse_kev_reader, parse_nvd_json, sync_feeds, sync_kev, sync_nvd, Cpe,
CpeMatchCriteria, CveRecord, FeedError, KevCatalog, NvdCatalog, SyncOptions, VulnDatabase,
CISA_KEV_API_URL, NVD_CVE_API_URL,
};
pub use matcher::{
match_banner, parse_banner_to_cpe, BannerInfo, Confidence, Finding, FindingType,