Files
harpia/crates/xexeu-core/src/vuln/feeds.rs
T

550 lines
18 KiB
Rust

//! Vulnerability feed ingestion for NVD CVE JSON 2.0 and CISA KEV catalogs (offline mode).
//!
//! This module provides deterministic parsers for local NVD and CISA KEV feeds,
//! indexing them into memory for fast lookup during service banner correlation.
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use thiserror::Error;
/// Error encountered during feed import.
#[derive(Debug, Error)]
pub enum FeedError {
#[error("I/O error reading feed file '{path}': {source}")]
Io {
path: String,
#[source]
source: std::io::Error,
},
#[error("JSON parsing error in '{path}': {source}")]
Json {
path: String,
#[source]
source: serde_json::Error,
},
#[error("Invalid feed format in '{path}': {detail}")]
Format { path: String, detail: String },
}
/// Structured Common Platform Enumeration (CPE) representation.
///
/// Supports CPE 2.3 format (`cpe:2.3:part:vendor:product:version:...`)
/// as well as CPE 2.2 URI format (`cpe:/part:vendor:product:version`).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Cpe {
/// Part: "a" (application), "o" (operating system), "h" (hardware).
pub part: String,
/// Vendor name (e.g. "openbsd", "apache", "f5").
pub vendor: String,
/// Product name (e.g. "openssh", "http_server", "nginx").
pub product: String,
/// Version string, or "*" / "-" if unconstrained.
pub version: String,
/// Update/patch string, or "*".
pub update: String,
}
impl Cpe {
/// Parses a CPE 2.3 or 2.2 string.
pub fn parse(s: &str) -> Result<Self, String> {
let trimmed = s.trim();
if trimmed.starts_with("cpe:2.3:") {
let parts: Vec<&str> = trimmed.split(':').collect();
if parts.len() < 6 {
return Err(format!("CPE 2.3 string has too few components: '{s}'"));
}
Ok(Self {
part: parts[2].to_lowercase(),
vendor: parts[3].to_lowercase(),
product: parts[4].to_lowercase(),
version: parts[5].to_string(),
update: parts.get(6).unwrap_or(&"*").to_string(),
})
} else if let Some(body) = trimmed.strip_prefix("cpe:/") {
let parts: Vec<&str> = body.split(':').collect();
if parts.len() < 3 {
return Err(format!("CPE 2.2 URI has too few components: '{s}'"));
}
Ok(Self {
part: parts[0].to_lowercase(),
vendor: parts[1].to_lowercase(),
product: parts[2].to_lowercase(),
version: parts.get(3).unwrap_or(&"*").to_string(),
update: parts.get(4).unwrap_or(&"*").to_string(),
})
} else {
Err(format!("unrecognized CPE format: '{s}'"))
}
}
/// Formats as standard CPE 2.3 string.
pub fn to_cpe23(&self) -> String {
format!(
"cpe:2.3:{}:{}:{}:{}:{}:*:*:*:*:*:*",
self.part, self.vendor, self.product, self.version, self.update
)
}
}
/// CPE match criteria inside an NVD configuration node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CpeMatchCriteria {
pub criteria: String,
pub cpe: Cpe,
pub version_start_including: Option<String>,
pub version_start_excluding: Option<String>,
pub version_end_including: Option<String>,
pub version_end_excluding: Option<String>,
}
/// Normalized CVE record from the NVD feed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CveRecord {
pub id: String,
pub description: String,
pub cvss_score: Option<f32>,
pub cvss_vector: Option<String>,
pub cpe_matches: Vec<CpeMatchCriteria>,
}
/// In-memory catalog of NVD vulnerabilities.
#[derive(Debug, Clone, Default)]
pub struct NvdCatalog {
pub records: HashMap<String, CveRecord>,
}
/// In-memory catalog of CISA Known Exploited Vulnerabilities (KEV).
#[derive(Debug, Clone, Default)]
pub struct KevCatalog {
pub cve_ids: HashSet<String>,
}
/// Combined local vulnerability database.
#[derive(Debug, Clone, Default)]
pub struct VulnDatabase {
pub nvd: NvdCatalog,
pub kev: KevCatalog,
}
impl VulnDatabase {
/// Loads both NVD and CISA KEV feeds from local files (offline mode).
pub fn load_offline(nvd_path: &Path, kev_path: Option<&Path>) -> Result<Self, FeedError> {
let nvd = import_nvd(nvd_path)?;
let kev = if let Some(kp) = kev_path {
import_kev(kp)?
} else {
KevCatalog::default()
};
Ok(Self { nvd, kev })
}
/// Checks if a CVE ID is listed in the CISA KEV catalog.
pub fn is_in_kev(&self, cve_id: &str) -> bool {
self.kev.cve_ids.contains(cve_id)
}
}
// ---------------------------------------------------------------------------
// NVD JSON 2.0 Deserialization DTOs
// ---------------------------------------------------------------------------
#[derive(Deserialize)]
struct NvdFeedDto {
#[serde(default)]
vulnerabilities: Vec<NvdVulnItemDto>,
}
#[derive(Deserialize)]
struct NvdVulnItemDto {
cve: NvdCveDto,
}
#[derive(Deserialize)]
struct NvdCveDto {
id: String,
#[serde(default)]
descriptions: Vec<NvdDescriptionDto>,
#[serde(default)]
metrics: Option<NvdMetricsDto>,
#[serde(default)]
configurations: Vec<NvdConfigurationDto>,
}
#[derive(Deserialize)]
struct NvdDescriptionDto {
lang: String,
value: String,
}
#[derive(Deserialize)]
struct NvdMetricsDto {
#[serde(rename = "cvssMetricV31")]
cvss_v31: Option<Vec<NvdCvssMetricItemDto>>,
#[serde(rename = "cvssMetricV30")]
cvss_v30: Option<Vec<NvdCvssMetricItemDto>>,
#[serde(rename = "cvssMetricV2")]
cvss_v2: Option<Vec<NvdCvssMetricV2ItemDto>>,
}
#[derive(Deserialize)]
struct NvdCvssMetricItemDto {
#[serde(rename = "cvssData")]
cvss_data: NvdCvssDataDto,
}
#[derive(Deserialize)]
struct NvdCvssDataDto {
#[serde(rename = "baseScore")]
base_score: f32,
#[serde(rename = "vectorString")]
vector_string: Option<String>,
}
#[derive(Deserialize)]
struct NvdCvssMetricV2ItemDto {
#[serde(rename = "cvssData")]
cvss_data: NvdCvssDataDto,
}
#[derive(Deserialize)]
struct NvdConfigurationDto {
#[serde(default)]
nodes: Vec<NvdNodeDto>,
}
#[derive(Deserialize)]
struct NvdNodeDto {
#[serde(rename = "cpeMatch", default)]
cpe_match: Vec<NvdCpeMatchDto>,
}
#[derive(Deserialize)]
struct NvdCpeMatchDto {
criteria: String,
#[serde(default = "default_true")]
vulnerable: bool,
#[serde(rename = "versionStartIncluding")]
version_start_including: Option<String>,
#[serde(rename = "versionStartExcluding")]
version_start_excluding: Option<String>,
#[serde(rename = "versionEndIncluding")]
version_end_including: Option<String>,
#[serde(rename = "versionEndExcluding")]
version_end_excluding: Option<String>,
}
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);
let dto: NvdFeedDto = serde_json::from_reader(reader).map_err(|e| FeedError::Json {
path: path.display().to_string(),
source: e,
})?;
let mut records = HashMap::with_capacity(dto.vulnerabilities.len());
for item in dto.vulnerabilities {
let cve_id = item.cve.id;
let description = item
.cve
.descriptions
.iter()
.find(|d| d.lang == "en")
.map(|d| d.value.clone())
.unwrap_or_else(|| {
item.cve
.descriptions
.first()
.map(|d| d.value.clone())
.unwrap_or_default()
});
let mut cvss_score = None;
let mut cvss_vector = None;
if let Some(metrics) = item.cve.metrics {
if let Some(v31) = metrics.cvss_v31.and_then(|v| v.into_iter().next()) {
cvss_score = Some(v31.cvss_data.base_score);
cvss_vector = v31.cvss_data.vector_string;
} else if let Some(v30) = metrics.cvss_v30.and_then(|v| v.into_iter().next()) {
cvss_score = Some(v30.cvss_data.base_score);
cvss_vector = v30.cvss_data.vector_string;
} else if let Some(v2) = metrics.cvss_v2.and_then(|v| v.into_iter().next()) {
cvss_score = Some(v2.cvss_data.base_score);
cvss_vector = v2.cvss_data.vector_string;
}
}
let mut cpe_matches = Vec::new();
for config in item.cve.configurations {
for node in config.nodes {
for m in node.cpe_match {
if !m.vulnerable {
continue;
}
if let Ok(cpe) = Cpe::parse(&m.criteria) {
cpe_matches.push(CpeMatchCriteria {
criteria: m.criteria,
cpe,
version_start_including: m.version_start_including,
version_start_excluding: m.version_start_excluding,
version_end_including: m.version_end_including,
version_end_excluding: m.version_end_excluding,
});
}
}
}
}
records.insert(
cve_id.clone(),
CveRecord {
id: cve_id,
description,
cvss_score,
cvss_vector,
cpe_matches,
},
);
}
Ok(NvdCatalog { records })
}
// ---------------------------------------------------------------------------
// CISA KEV Ingestion (JSON and CSV)
// ---------------------------------------------------------------------------
#[derive(Deserialize)]
struct KevJsonDto {
#[serde(default)]
vulnerabilities: Vec<KevItemDto>,
}
#[derive(Deserialize)]
struct KevItemDto {
#[serde(rename = "cveID")]
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
let mut first_line = String::new();
reader
.read_line(&mut first_line)
.map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
let trimmed = first_line.trim_start();
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(),
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);
}
} else {
// CSV parsing: column 0 is typically cveID
if !trimmed.starts_with("cveID") && trimmed.contains("CVE-") {
if let Some(id) = extract_cve_from_line(trimmed) {
cve_ids.insert(id);
}
}
for line_res in reader.lines() {
let line = line_res.map_err(|e| FeedError::Io {
path: path.display().to_string(),
source: e,
})?;
if let Some(id) = extract_cve_from_line(&line) {
cve_ids.insert(id);
}
}
}
Ok(KevCatalog { cve_ids })
}
fn extract_cve_from_line(line: &str) -> Option<String> {
let col = line.split(',').next()?.trim().trim_matches('"');
if col.starts_with("CVE-") {
Some(col.to_string())
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn test_cpe_parsing() {
let cpe23 = Cpe::parse("cpe:2.3:a:openbsd:openssh:9.3p1:*:*:*:*:*:*:*").unwrap();
assert_eq!(cpe23.part, "a");
assert_eq!(cpe23.vendor, "openbsd");
assert_eq!(cpe23.product, "openssh");
assert_eq!(cpe23.version, "9.3p1");
let cpe22 = Cpe::parse("cpe:/a:apache:http_server:2.4.49").unwrap();
assert_eq!(cpe22.part, "a");
assert_eq!(cpe22.vendor, "apache");
assert_eq!(cpe22.product, "http_server");
assert_eq!(cpe22.version, "2.4.49");
}
#[test]
fn test_import_nvd_fixture() {
let nvd_json = r#"{
"format": "NVD_CVE",
"version": "2.0",
"vulnerabilities": [
{
"cve": {
"id": "CVE-2024-6387",
"descriptions": [
{"lang": "en", "value": "A signal handler race condition was found in OpenSSH..."}
],
"metrics": {
"cvssMetricV31": [
{
"cvssData": {
"version": "3.1",
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H",
"baseScore": 8.1
}
}
]
},
"configurations": [
{
"nodes": [
{
"cpeMatch": [
{
"criteria": "cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*",
"versionStartIncluding": "8.5p1",
"versionEndExcluding": "9.8p1",
"vulnerable": true
}
]
}
]
}
]
}
},
{
"cve": {
"id": "CVE-2021-41773",
"descriptions": [
{"lang": "en", "value": "A flaw was found in a change made to path normalization in Apache HTTP Server 2.4.49."}
],
"metrics": {
"cvssMetricV31": [
{
"cvssData": {
"baseScore": 7.5
}
}
]
},
"configurations": [
{
"nodes": [
{
"cpeMatch": [
{
"criteria": "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*",
"vulnerable": true
}
]
}
]
}
]
}
}
]
}"#;
let mut file = NamedTempFile::new().unwrap();
file.write_all(nvd_json.as_bytes()).unwrap();
let catalog = import_nvd(file.path()).unwrap();
assert_eq!(catalog.records.len(), 2);
let openssh = catalog.records.get("CVE-2024-6387").unwrap();
assert_eq!(openssh.cvss_score, Some(8.1));
assert_eq!(openssh.cpe_matches.len(), 1);
assert_eq!(
openssh.cpe_matches[0].version_start_including.as_deref(),
Some("8.5p1")
);
assert_eq!(
openssh.cpe_matches[0].version_end_excluding.as_deref(),
Some("9.8p1")
);
let apache = catalog.records.get("CVE-2021-41773").unwrap();
assert_eq!(apache.cvss_score, Some(7.5));
assert_eq!(apache.cpe_matches[0].cpe.version, "2.4.49");
}
#[test]
fn test_import_kev_json_and_csv() {
// Test JSON format
let kev_json = r#"{
"title": "CISA KEV",
"vulnerabilities": [
{"cveID": "CVE-2021-41773"}
]
}"#;
let mut f_json = NamedTempFile::new().unwrap();
f_json.write_all(kev_json.as_bytes()).unwrap();
let kev = import_kev(f_json.path()).unwrap();
assert!(kev.cve_ids.contains("CVE-2021-41773"));
assert!(!kev.cve_ids.contains("CVE-2024-6387"));
// Test CSV format
let kev_csv = "cveID,vendorProject,product\nCVE-2024-6387,OpenBSD,OpenSSH\n";
let mut f_csv = NamedTempFile::new().unwrap();
f_csv.write_all(kev_csv.as_bytes()).unwrap();
let kev_csv_parsed = import_kev(f_csv.path()).unwrap();
assert!(kev_csv_parsed.cve_ids.contains("CVE-2024-6387"));
}
}