Implementa batch/storage/diff, correlação de vulnerabilidades (CPE/CVE/KEV) e liga config check / scan --once na CLI

This commit is contained in:
Lucas Guerra committed 2026-11-01 23:41:55 -03:00
1 parent 942655a5e0
commit a814e100fb
12 files changed
+5093 -43

No files matched your search

+10 -2
View File
@@ -9,10 +9,18 @@ authors.workspace = true
rust-version.workspace = true
[dependencies]
chrono = { version = "0.4", default-features = false, features = ["clock"] }
arrow-array = "60"
arrow-schema = "60"
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
croner = "4"
ipnet = "2"
parquet = { version = "60", default-features = false, features = ["arrow", "snap"] }
rusqlite = { version = "0.41", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
tempfile = "3"
thiserror = "1"
ulid = { version = "3", features = ["serde"] }
toml = "1"
tokio = { version = "1", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
+730 -2
View File
@@ -1,2 +1,730 @@
//! Sweep batch format: atomically written by the scanner and idempotently read by the server.
// TODO: implement batch writing, manifest handling and idempotent ingestion.
//! Sweep batch format: atomically written by the scanner and read back by the server.
//!
//! A sweep lives in `<root>/<group>/<sweep_id>/` and contains:
//!
//! - `observations.parquet`: one row per probed host and one row per probed port;
//! - `manifest.json`: written **last**, through an atomic rename, so a partially written
//! batch is never mistaken for a complete one.
//!
//! The manifest carries a SHA-256 of the Parquet file, which is verified on read.
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_array::{Array, ArrayRef, RecordBatch, StringArray, UInt16Array};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use chrono::{DateTime, Utc};
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::ArrowWriter;
use parquet::basic::Compression;
use parquet::file::properties::WriterProperties;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use thiserror::Error;
use ulid::Ulid;
use crate::scan::{HostDiscoveryResult, HostPortScanResult, HostState, PortScanResult, PortState};
/// Name of the observations file inside a sweep directory.
pub const OBSERVATIONS_FILE: &str = "observations.parquet";
/// Name of the manifest file inside a sweep directory.
pub const MANIFEST_FILE: &str = "manifest.json";
const COL_IP: usize = 0;
const COL_HOST_STATE: usize = 1;
const COL_RESPONDED_PORT: usize = 2;
const COL_PORT: usize = 3;
const COL_PORT_STATE: usize = 4;
const COL_PRODUCT: usize = 5;
const COL_VERSION: usize = 6;
const COL_CPE: usize = 7;
const COL_SWEEP_ID: usize = 8;
/// Engine that produced a sweep.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EngineMode {
/// Raw-socket engine requiring `NET_RAW`.
#[serde(rename = "nativo")]
Native,
/// Unprivileged TCP-connect engine.
#[serde(rename = "nativo-sem-raw")]
NativeWithoutRaw,
/// Optional nmap adapter.
#[serde(rename = "nmap")]
Nmap,
}
impl EngineMode {
/// Value stored in the manifest and in human-readable output.
pub fn as_str(&self) -> &'static str {
match self {
Self::Native => "nativo",
Self::NativeWithoutRaw => "nativo-sem-raw",
Self::Nmap => "nmap",
}
}
}
/// How much of the group was actually covered by a sweep.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SweepStatus {
/// Every target was probed.
#[serde(rename = "completa")]
Complete,
/// Only part of the targets was probed; never used to infer disappearances.
#[serde(rename = "parcial")]
Partial,
/// The sweep was interrupted.
#[serde(rename = "abortada")]
Aborted,
}
impl SweepStatus {
/// Value stored in the manifest.
pub fn as_str(&self) -> &'static str {
match self {
Self::Complete => "completa",
Self::Partial => "parcial",
Self::Aborted => "abortada",
}
}
}
/// Metadata for one sweep, persisted as `manifest.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SweepManifest {
/// Unique sweep identifier.
#[serde(rename = "sweep_id")]
pub sweep_id: Ulid,
/// Group that produced the sweep.
#[serde(rename = "grupo")]
pub group: String,
/// Expanded scope, as `start-end` ranges or CIDRs.
#[serde(rename = "escopo")]
pub scope: Vec<String>,
/// Port profile used.
#[serde(rename = "perfil")]
pub profile: String,
/// Engine mode used.
#[serde(rename = "modo_motor")]
pub engine_mode: EngineMode,
/// When the sweep started.
#[serde(rename = "inicio")]
pub started_at: DateTime<Utc>,
/// When the sweep finished; `None` while it is still running.
#[serde(rename = "fim")]
pub finished_at: Option<DateTime<Utc>>,
/// Coverage status.
#[serde(rename = "status")]
pub status: SweepStatus,
/// Xexéu version that wrote the batch.
#[serde(rename = "versao")]
pub version: String,
/// SHA-256 of `observations.parquet`, filled by [`SweepBatch::write`].
#[serde(rename = "hash")]
pub content_hash: Option<String>,
}
impl SweepManifest {
/// Creates a manifest for a sweep that is still in progress.
pub fn new(
group: impl Into<String>,
scope: Vec<String>,
profile: impl Into<String>,
engine_mode: EngineMode,
started_at: DateTime<Utc>,
) -> Self {
Self {
sweep_id: Ulid::generate(),
group: group.into(),
scope,
profile: profile.into(),
engine_mode,
started_at,
finished_at: None,
status: SweepStatus::Partial,
version: env!("CARGO_PKG_VERSION").to_string(),
content_hash: None,
}
}
/// Marks the sweep as finished.
pub fn finish(&mut self, status: SweepStatus, finished_at: DateTime<Utc>) {
self.status = status;
self.finished_at = Some(finished_at);
}
/// Whether the sweep covered every target.
pub fn is_complete(&self) -> bool {
self.status == SweepStatus::Complete
}
}
/// Service attributes observed on an open port.
///
/// The fingerprinting engine is still a stub, so the scanner leaves this empty today; the
/// fields are already persisted and diffed so the integration needs no format change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceObservation {
/// Host that owns the port.
pub ip: std::net::IpAddr,
/// Open TCP port.
pub port: u16,
/// Product name, when known.
pub product: Option<String>,
/// Product version, when known.
pub version: Option<String>,
/// CPE identifier, when known.
pub cpe: Option<String>,
}
/// Everything produced by one sweep.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SweepBatch {
/// Sweep metadata.
pub manifest: SweepManifest,
/// Host discovery results, including unresponsive hosts.
pub hosts: Vec<HostDiscoveryResult>,
/// Port results for the hosts that answered discovery.
pub ports: Vec<HostPortScanResult>,
/// Optional service attributes for open ports.
pub services: Vec<ServiceObservation>,
}
impl SweepBatch {
/// Builds a batch without service attributes.
pub fn new(
manifest: SweepManifest,
hosts: Vec<HostDiscoveryResult>,
ports: Vec<HostPortScanResult>,
) -> Self {
Self {
manifest,
hosts,
ports,
services: Vec::new(),
}
}
/// Attaches service attributes.
pub fn with_services(mut self, services: Vec<ServiceObservation>) -> Self {
self.services = services;
self
}
/// Hosts that answered discovery.
pub fn alive_hosts(&self) -> impl Iterator<Item = &HostDiscoveryResult> {
self.hosts
.iter()
.filter(|host| host.state == HostState::Alive)
}
/// Open ports advertised by a host.
pub fn open_ports(&self, ip: std::net::IpAddr) -> impl Iterator<Item = u16> + '_ {
self.ports
.iter()
.filter(move |result| result.ip == ip)
.flat_map(|result| result.ports.iter())
.filter(|port| port.state == PortState::Open)
.map(|port| port.port)
}
/// Writes the batch atomically under `<root>/<group>/<sweep_id>/` and returns that directory.
///
/// The Parquet file is moved into place first and the manifest last, so a reader never sees
/// a manifest without its observations.
pub fn write(&self, root: &Path) -> Result<PathBuf, BatchError> {
if self.manifest.finished_at.is_none() {
return Err(BatchError::NotFinished);
}
let group = safe_component(&self.manifest.group)?;
let directory = root.join(group).join(self.manifest.sweep_id.to_string());
fs::create_dir_all(&directory)?;
let batch = self.to_record_batch()?;
let parquet_path = directory.join(OBSERVATIONS_FILE);
let temporary = NamedTempFile::new_in(&directory)?;
let properties = WriterProperties::builder()
.set_compression(Compression::SNAPPY)
.build();
let mut writer = ArrowWriter::try_new(temporary.as_file(), schema(), Some(properties))?;
writer.write(&batch)?;
writer.close()?;
let content_hash = hash_file(temporary.path())?;
temporary
.persist(&parquet_path)
.map_err(|error| error.error)?;
let mut manifest = self.manifest.clone();
manifest.content_hash = Some(content_hash);
let json = serde_json::to_vec_pretty(&manifest)?;
let mut temporary = NamedTempFile::new_in(&directory)?;
temporary.write_all(&json)?;
temporary.as_file().sync_all()?;
temporary
.persist(directory.join(MANIFEST_FILE))
.map_err(|error| error.error)?;
Ok(directory)
}
/// Reads a batch previously written by [`SweepBatch::write`].
pub fn read(directory: &Path) -> Result<Self, BatchError> {
let manifest_path = directory.join(MANIFEST_FILE);
let manifest: SweepManifest = serde_json::from_slice(&fs::read(&manifest_path)?)?;
let parquet_path = directory.join(OBSERVATIONS_FILE);
let actual = hash_file(&parquet_path)?;
match manifest.content_hash.as_deref() {
Some(expected) if expected == actual => {}
Some(expected) => {
return Err(BatchError::HashMismatch {
expected: expected.to_string(),
actual,
});
}
None => {
return Err(BatchError::Corrupt(
"manifesto sem hash de conteúdo".to_string(),
));
}
}
let reader =
ParquetRecordBatchReaderBuilder::try_new(File::open(&parquet_path)?)?.build()?;
let mut hosts = Vec::new();
let mut port_results: BTreeMap<std::net::IpAddr, Vec<PortScanResult>> = BTreeMap::new();
let mut services = Vec::new();
for batch in reader {
let batch = batch?;
let sweep_ids = string_column(&batch, COL_SWEEP_ID)?;
for row in 0..batch.num_rows() {
let sweep_id = sweep_ids.value(row);
if sweep_id != manifest.sweep_id.to_string() {
return Err(BatchError::Corrupt(format!(
"sweep_id `{sweep_id}` não confere com o manifesto"
)));
}
let ip: std::net::IpAddr = string_column(&batch, COL_IP)?
.value(row)
.parse()
.map_err(|error| BatchError::Corrupt(format!("IP inválido: {error}")))?;
let host_state = optional_string(&batch, COL_HOST_STATE, row);
let port = optional_u16(&batch, COL_PORT, row);
match (host_state, port) {
(Some(state), None) => {
let responded_port = optional_u16(&batch, COL_RESPONDED_PORT, row);
hosts.push(HostDiscoveryResult {
ip,
state: parse_host_state(&state)?,
responded_port,
});
}
(None, Some(port)) => {
let state = optional_string(&batch, COL_PORT_STATE, row)
.ok_or_else(|| BatchError::Corrupt("porta sem estado".to_string()))?;
port_results.entry(ip).or_default().push(PortScanResult {
port,
state: parse_port_state(&state)?,
});
let product = optional_string(&batch, COL_PRODUCT, row);
let version = optional_string(&batch, COL_VERSION, row);
let cpe = optional_string(&batch, COL_CPE, row);
if product.is_some() || version.is_some() || cpe.is_some() {
services.push(ServiceObservation {
ip,
port,
product,
version,
cpe,
});
}
}
_ => {
return Err(BatchError::Corrupt(format!(
"linha {row} sem host nem porta"
)));
}
}
}
}
let mut ports: Vec<HostPortScanResult> = port_results
.into_iter()
.map(|(ip, mut ports)| {
ports.sort_by_key(|port| port.port);
HostPortScanResult { ip, ports }
})
.collect();
ports.sort_by_key(|result| result.ip);
hosts.sort_by_key(|host| host.ip);
services.sort_by_key(|left| (left.ip, left.port));
Ok(Self {
manifest,
hosts,
ports,
services,
})
}
fn to_record_batch(&self) -> Result<RecordBatch, BatchError> {
let services: BTreeMap<(std::net::IpAddr, u16), &ServiceObservation> = self
.services
.iter()
.map(|service| ((service.ip, service.port), service))
.collect();
let mut hosts: Vec<&HostDiscoveryResult> = self.hosts.iter().collect();
hosts.sort_by_key(|host| host.ip);
let mut host_ports: Vec<&HostPortScanResult> = self.ports.iter().collect();
host_ports.sort_by_key(|result| result.ip);
let mut ips = Vec::new();
let mut host_states = Vec::new();
let mut responded_ports = Vec::new();
let mut ports = Vec::new();
let mut port_states = Vec::new();
let mut products = Vec::new();
let mut versions = Vec::new();
let mut cpes = Vec::new();
let mut sweep_ids = Vec::new();
let sweep_id = self.manifest.sweep_id.to_string();
for host in hosts {
ips.push(host.ip.to_string());
host_states.push(Some(host_state_str(host.state).to_string()));
responded_ports.push(host.responded_port);
ports.push(None);
port_states.push(None);
products.push(None);
versions.push(None);
cpes.push(None);
sweep_ids.push(sweep_id.clone());
}
for result in host_ports {
let mut declared: BTreeMap<u16, PortState> = BTreeMap::new();
for port in &result.ports {
declared.insert(port.port, port.state);
}
for (port, state) in declared {
ips.push(result.ip.to_string());
host_states.push(None);
responded_ports.push(None);
ports.push(Some(port));
port_states.push(Some(port_state_str(state).to_string()));
let service = services.get(&(result.ip, port));
products.push(service.and_then(|service| service.product.clone()));
versions.push(service.and_then(|service| service.version.clone()));
cpes.push(service.and_then(|service| service.cpe.clone()));
sweep_ids.push(sweep_id.clone());
}
}
let columns: Vec<ArrayRef> = vec![
Arc::new(StringArray::from(ips)),
Arc::new(StringArray::from(host_states)),
Arc::new(UInt16Array::from(responded_ports)),
Arc::new(UInt16Array::from(ports)),
Arc::new(StringArray::from(port_states)),
Arc::new(StringArray::from(products)),
Arc::new(StringArray::from(versions)),
Arc::new(StringArray::from(cpes)),
Arc::new(StringArray::from(sweep_ids)),
];
Ok(RecordBatch::try_new(schema(), columns)?)
}
}
/// Errors raised while writing or reading a sweep batch.
#[derive(Debug, Error)]
pub enum BatchError {
/// Filesystem failure.
#[error("erro de E/S: {0}")]
Io(#[from] io::Error),
/// Parquet failure.
#[error("erro de Parquet: {0}")]
Parquet(#[from] parquet::errors::ParquetError),
/// Arrow failure.
#[error("erro de Arrow: {0}")]
Arrow(#[from] arrow_schema::ArrowError),
/// JSON failure.
#[error("manifesto inválido: {0}")]
Json(#[from] serde_json::Error),
/// The batch was written before being marked as finished.
#[error("lote não finalizado: marque o status e o fim antes de gravar")]
NotFinished,
/// The group name cannot be used as a directory name.
#[error("grupo inválido para caminho: `{0}`")]
InvalidGroup(String),
/// The manifest hash does not match the observations file.
#[error("hash do lote não confere: esperado {expected}, encontrado {actual}")]
HashMismatch {
/// Hash recorded in the manifest.
expected: String,
/// Hash computed from the file.
actual: String,
},
/// The observations file is structurally invalid.
#[error("observações corrompidas: {0}")]
Corrupt(String),
}
fn schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("ip", DataType::Utf8, false),
Field::new("host_state", DataType::Utf8, true),
Field::new("responded_port", DataType::UInt16, true),
Field::new("port", DataType::UInt16, true),
Field::new("port_state", DataType::Utf8, true),
Field::new("product", DataType::Utf8, true),
Field::new("version", DataType::Utf8, true),
Field::new("cpe", DataType::Utf8, true),
Field::new("sweep_id", DataType::Utf8, false),
]))
}
fn host_state_str(state: HostState) -> &'static str {
match state {
HostState::Alive => "alive",
HostState::Unresponsive => "unresponsive",
}
}
fn parse_host_state(value: &str) -> Result<HostState, BatchError> {
match value {
"alive" => Ok(HostState::Alive),
"unresponsive" => Ok(HostState::Unresponsive),
other => Err(BatchError::Corrupt(format!("estado de host `{other}`"))),
}
}
fn port_state_str(state: PortState) -> &'static str {
match state {
PortState::Open => "open",
PortState::Closed => "closed",
PortState::Filtered => "filtered",
}
}
fn parse_port_state(value: &str) -> Result<PortState, BatchError> {
match value {
"open" => Ok(PortState::Open),
"closed" => Ok(PortState::Closed),
"filtered" => Ok(PortState::Filtered),
other => Err(BatchError::Corrupt(format!("estado de porta `{other}`"))),
}
}
fn string_column(batch: &RecordBatch, index: usize) -> Result<&StringArray, BatchError> {
batch
.column(index)
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| BatchError::Corrupt(format!("coluna {index} não é texto")))
}
fn optional_string(batch: &RecordBatch, index: usize, row: usize) -> Option<String> {
let array = batch.column(index).as_any().downcast_ref::<StringArray>()?;
if array.is_null(row) {
None
} else {
Some(array.value(row).to_string())
}
}
fn optional_u16(batch: &RecordBatch, index: usize, row: usize) -> Option<u16> {
let array = batch.column(index).as_any().downcast_ref::<UInt16Array>()?;
if array.is_null(row) {
None
} else {
Some(array.value(row))
}
}
fn safe_component(group: &str) -> Result<&str, BatchError> {
let valid = !group.is_empty()
&& group != "."
&& group != ".."
&& group.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
});
if valid {
Ok(group)
} else {
Err(BatchError::InvalidGroup(group.to_string()))
}
}
fn hash_file(path: &Path) -> Result<String, io::Error> {
let mut hasher = Sha256::new();
let mut file = File::open(path)?;
let mut buffer = [0_u8; 16 * 1024];
loop {
let read = io::Read::read(&mut file, &mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
use tempfile::tempdir;
fn now() -> DateTime<Utc> {
DateTime::from_timestamp(1_700_000_000, 0).expect("valid instant")
}
fn manifest() -> SweepManifest {
let mut manifest = SweepManifest::new(
"dmz",
vec!["203.0.113.0-203.0.113.255".to_string()],
"padrao",
EngineMode::NativeWithoutRaw,
now(),
);
manifest.finish(SweepStatus::Complete, now());
manifest
}
fn batch() -> SweepBatch {
let alive = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5));
let gone = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6));
SweepBatch::new(
manifest(),
vec![
HostDiscoveryResult {
ip: alive,
state: HostState::Alive,
responded_port: Some(22),
},
HostDiscoveryResult {
ip: gone,
state: HostState::Unresponsive,
responded_port: None,
},
],
vec![HostPortScanResult {
ip: alive,
ports: vec![
PortScanResult {
port: 22,
state: PortState::Open,
},
PortScanResult {
port: 443,
state: PortState::Closed,
},
],
}],
)
.with_services(vec![ServiceObservation {
ip: alive,
port: 22,
product: Some("OpenSSH".to_string()),
version: Some("9.3p1".to_string()),
cpe: Some("cpe:2.3:a:openbsd:openssh:9.3p1".to_string()),
}])
}
#[test]
fn round_trips_through_parquet_and_manifest() {
let root = tempdir().expect("temporary directory");
let original = batch();
let directory = original.write(root.path()).expect("batch is written");
assert!(directory.join(OBSERVATIONS_FILE).exists());
assert!(directory.join(MANIFEST_FILE).exists());
let restored = SweepBatch::read(&directory).expect("batch is read");
let mut expected = original.clone();
expected.manifest.content_hash = restored.manifest.content_hash.clone();
assert_eq!(restored, expected);
assert!(restored.manifest.content_hash.is_some());
assert_eq!(restored.manifest.status, SweepStatus::Complete);
}
#[test]
fn write_leaves_no_temporary_files_behind() {
let root = tempdir().expect("temporary directory");
let directory = batch().write(root.path()).expect("batch is written");
let entries: Vec<_> = fs::read_dir(&directory)
.expect("directory is readable")
.map(|entry| entry.expect("entry is readable").file_name())
.collect();
assert_eq!(entries.len(), 2, "unexpected files: {entries:?}");
}
#[test]
fn unfinished_batch_is_rejected() {
let root = tempdir().expect("temporary directory");
let mut unfinished = batch();
unfinished.manifest.finished_at = None;
assert!(matches!(
unfinished.write(root.path()),
Err(BatchError::NotFinished)
));
}
#[test]
fn tampered_observations_are_rejected() {
let root = tempdir().expect("temporary directory");
let directory = batch().write(root.path()).expect("batch is written");
let mut file = fs::OpenOptions::new()
.append(true)
.open(directory.join(OBSERVATIONS_FILE))
.expect("file is writable");
file.write_all(b"tampered").expect("file is appended");
assert!(matches!(
SweepBatch::read(&directory),
Err(BatchError::HashMismatch { .. })
));
}
#[test]
fn group_name_that_escapes_the_directory_is_rejected() {
let root = tempdir().expect("temporary directory");
let mut unsafe_batch = batch();
unsafe_batch.manifest.group = "../fora".to_string();
assert!(matches!(
unsafe_batch.write(root.path()),
Err(BatchError::InvalidGroup(_))
));
}
}
File diff suppressed because it is too large. Load diff
+588 -2
View File
@@ -1,2 +1,588 @@
//! DuckDB + Parquet storage for sweeps, observations, the deduplicated current state and events.
// TODO: implement the storage layer with the server as the single writer.
//! Local-first persistence for sweeps, the deduplicated current state and the event log.
//!
//! # Why SQLite in this slice
//!
//! `design.md` targets DuckDB. Binding `libduckdb` requires a system or prebuilt library, which
//! would make `cargo build` depend on infrastructure that is not available on every developer
//! machine yet. The [`Storage`] trait isolates the SQL surface, so the server can switch to a
//! DuckDB implementation later without touching the diff engine. The first concrete
//! implementation, [`SqliteStorage`], uses `rusqlite` with the bundled SQLite, which embeds
//! cleanly and lets the pipeline run end to end today.
//!
//! Tables:
//!
//! - `sweeps`: idempotency key for ingestion;
//! - `assets`: deduplicated state keyed by `asset_key = (rede_logica, ip)`;
//! - `services`: ports per asset, keyed by `(asset_key, proto, porta)`;
//! - `events`: append-only log with the full event JSON as evidence.
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::net::IpAddr;
use std::path::Path;
use chrono::{DateTime, SecondsFormat, Utc};
use rusqlite::{params, Connection};
use thiserror::Error;
use crate::batch::{SweepBatch, SweepManifest};
use crate::diff::{
AssetState, AssetStatus, CurrentState, DiffResult, Event, PortStatus, ServiceState,
};
use crate::targets::IpRange;
/// Persistence contract for the current state and the event log.
pub trait Storage {
/// Records a sweep, returning `false` when it had already been ingested.
fn record_sweep(&mut self, manifest: &SweepManifest) -> Result<bool, StorageError>;
/// Loads the deduplicated state, optionally restricted to a scope.
///
/// An empty scope means "no filter".
fn load_state(&self, scope: &[IpRange]) -> Result<CurrentState, StorageError>;
/// Applies a diff result: upserts the next state and appends its events.
fn apply_diff(&mut self, diff: &DiffResult) -> Result<(), StorageError>;
/// Idempotently ingests a batch and its diff in one transaction.
///
/// Returns `false` when the sweep had already been ingested.
fn ingest(&mut self, batch: &SweepBatch, diff: &DiffResult) -> Result<bool, StorageError>;
/// Returns events ordered by occurrence, optionally filtered by a lower bound.
fn events(&self, since: Option<DateTime<Utc>>) -> Result<Vec<Event>, StorageError>;
}
/// Errors raised by the storage layer.
#[derive(Debug, Error)]
pub enum StorageError {
/// SQLite failure.
#[error("erro de banco: {0}")]
Sqlite(#[from] rusqlite::Error),
/// Filesystem failure.
#[error("erro de E/S: {0}")]
Io(#[from] io::Error),
/// Stored JSON is invalid.
#[error("evento armazenado inválido: {0}")]
Json(#[from] serde_json::Error),
/// Stored value does not match the expected shape.
#[error("estado corrompido: {0}")]
Corrupt(String),
}
/// SQLite implementation of [`Storage`].
#[derive(Debug)]
pub struct SqliteStorage {
connection: Connection,
}
impl SqliteStorage {
/// Opens (and creates, if needed) the database at `path`.
pub fn open(path: &Path) -> Result<Self, StorageError> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
let connection = Connection::open(path)?;
Self::initialize(connection)
}
/// Opens a private in-memory database, useful for tests and ephemeral runs.
pub fn open_in_memory() -> Result<Self, StorageError> {
Self::initialize(Connection::open_in_memory()?)
}
fn initialize(connection: Connection) -> Result<Self, StorageError> {
connection.pragma_update(None, "journal_mode", "WAL")?;
connection.pragma_update(None, "foreign_keys", "ON")?;
connection.execute_batch(
"
CREATE TABLE IF NOT EXISTS sweeps (
sweep_id TEXT PRIMARY KEY,
group_name TEXT NOT NULL,
profile TEXT NOT NULL,
engine TEXT NOT NULL,
status TEXT NOT NULL,
started_at TEXT NOT NULL,
finished_at TEXT,
content_hash TEXT
);
CREATE TABLE IF NOT EXISTS assets (
asset_key TEXT PRIMARY KEY,
network TEXT NOT NULL,
ip TEXT NOT NULL,
status TEXT NOT NULL,
absences INTEGER NOT NULL DEFAULT 0,
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_assets_ip ON assets(ip);
CREATE TABLE IF NOT EXISTS services (
asset_key TEXT NOT NULL,
proto TEXT NOT NULL,
port INTEGER NOT NULL,
status TEXT NOT NULL,
absences INTEGER NOT NULL DEFAULT 0,
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
product TEXT,
version TEXT,
cpe TEXT,
PRIMARY KEY (asset_key, proto, port),
FOREIGN KEY (asset_key) REFERENCES assets(asset_key) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS events (
event_id TEXT PRIMARY KEY,
sweep_id TEXT NOT NULL,
group_name TEXT NOT NULL,
kind TEXT NOT NULL,
asset_key TEXT NOT NULL,
payload TEXT NOT NULL,
occurred_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_events_time ON events(occurred_at);
",
)?;
Ok(Self { connection })
}
/// Number of stored events, useful for diagnostics.
pub fn event_count(&self) -> Result<usize, StorageError> {
let count: i64 = self
.connection
.query_row("SELECT COUNT(*) FROM events", [], |row| row.get(0))?;
Ok(count as usize)
}
}
impl Storage for SqliteStorage {
fn record_sweep(&mut self, manifest: &SweepManifest) -> Result<bool, StorageError> {
insert_sweep(&self.connection, manifest)
}
fn load_state(&self, scope: &[IpRange]) -> Result<CurrentState, StorageError> {
let mut statement = self.connection.prepare(
"SELECT asset_key, network, ip, status, absences, first_seen, last_seen
FROM assets ORDER BY asset_key",
)?;
let mut assets = BTreeMap::new();
let rows = statement.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, String>(6)?,
))
})?;
for row in rows {
let (asset_key, network, ip, status, absences, first_seen, last_seen) = row?;
let ip = parse_ip(&ip)?;
if !scope.is_empty() && !scope.iter().any(|range| range.contains(ip)) {
continue;
}
assets.insert(
asset_key.clone(),
AssetState {
asset_key,
network,
ip,
status: parse_asset_status(&status)?,
absences: absences as u32,
first_seen: parse_time(&first_seen)?,
last_seen: parse_time(&last_seen)?,
ports: Vec::new(),
},
);
}
let mut statement = self.connection.prepare(
"SELECT asset_key, proto, port, status, absences, first_seen, last_seen,
product, version, cpe
FROM services ORDER BY asset_key, port",
)?;
let rows = statement.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, String>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, String>(6)?,
row.get::<_, Option<String>>(7)?,
row.get::<_, Option<String>>(8)?,
row.get::<_, Option<String>>(9)?,
))
})?;
for row in rows {
let (
asset_key,
protocol,
port,
status,
absences,
first_seen,
last_seen,
product,
version,
cpe,
) = row?;
if let Some(asset) = assets.get_mut(&asset_key) {
asset.ports.push(ServiceState {
protocol,
port: port as u16,
status: parse_port_status(&status)?,
absences: absences as u32,
first_seen: parse_time(&first_seen)?,
last_seen: parse_time(&last_seen)?,
product,
version,
cpe,
});
}
}
Ok(CurrentState::new(assets.into_values().collect()))
}
fn apply_diff(&mut self, diff: &DiffResult) -> Result<(), StorageError> {
let transaction = self.connection.transaction()?;
apply_state(&transaction, diff)?;
insert_events(&transaction, diff)?;
transaction.commit()?;
Ok(())
}
fn ingest(&mut self, batch: &SweepBatch, diff: &DiffResult) -> Result<bool, StorageError> {
let transaction = self.connection.transaction()?;
if !insert_sweep(&transaction, &batch.manifest)? {
return Ok(false);
}
apply_state(&transaction, diff)?;
insert_events(&transaction, diff)?;
transaction.commit()?;
Ok(true)
}
fn events(&self, since: Option<DateTime<Utc>>) -> Result<Vec<Event>, StorageError> {
let mut events = Vec::new();
match since {
Some(since) => {
let mut statement = self.connection.prepare(
"SELECT payload FROM events WHERE occurred_at >= ?1
ORDER BY occurred_at, event_id",
)?;
let rows =
statement.query_map([format_time(since)], |row| row.get::<_, String>(0))?;
for payload in rows {
events.push(serde_json::from_str(&payload?)?);
}
}
None => {
let mut statement = self
.connection
.prepare("SELECT payload FROM events ORDER BY occurred_at, event_id")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
for payload in rows {
events.push(serde_json::from_str(&payload?)?);
}
}
}
Ok(events)
}
}
fn insert_sweep(connection: &Connection, manifest: &SweepManifest) -> Result<bool, StorageError> {
let inserted = connection.execute(
"INSERT OR IGNORE INTO sweeps
(sweep_id, group_name, profile, engine, status, started_at, finished_at, content_hash)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![
manifest.sweep_id.to_string(),
manifest.group,
manifest.profile,
manifest.engine_mode.as_str(),
manifest.status.as_str(),
format_time(manifest.started_at),
manifest.finished_at.map(format_time),
manifest.content_hash,
],
)?;
Ok(inserted == 1)
}
fn apply_state(connection: &Connection, diff: &DiffResult) -> Result<(), StorageError> {
for asset in &diff.state {
connection.execute(
"INSERT INTO assets
(asset_key, network, ip, status, absences, first_seen, last_seen)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT(asset_key) DO UPDATE SET
network = excluded.network,
ip = excluded.ip,
status = excluded.status,
absences = excluded.absences,
last_seen = excluded.last_seen",
params![
asset.asset_key,
asset.network,
asset.ip.to_string(),
asset.status.as_str(),
i64::from(asset.absences),
format_time(asset.first_seen),
format_time(asset.last_seen),
],
)?;
for service in &asset.ports {
connection.execute(
"INSERT INTO services
(asset_key, proto, port, status, absences, first_seen, last_seen,
product, version, cpe)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(asset_key, proto, port) DO UPDATE SET
status = excluded.status,
absences = excluded.absences,
last_seen = excluded.last_seen,
product = excluded.product,
version = excluded.version,
cpe = excluded.cpe",
params![
asset.asset_key,
service.protocol,
i64::from(service.port),
service.status.as_str(),
i64::from(service.absences),
format_time(service.first_seen),
format_time(service.last_seen),
service.product,
service.version,
service.cpe,
],
)?;
}
}
Ok(())
}
fn insert_events(connection: &Connection, diff: &DiffResult) -> Result<(), StorageError> {
for event in &diff.events {
connection.execute(
"INSERT OR IGNORE INTO events
(event_id, sweep_id, group_name, kind, asset_key, payload, occurred_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
event.event_id.to_string(),
event.sweep_id.to_string(),
event.group,
event.kind.as_str(),
event.asset_key,
serde_json::to_string(event)?,
format_time(event.occurred_at),
],
)?;
}
Ok(())
}
fn format_time(value: DateTime<Utc>) -> String {
value.to_rfc3339_opts(SecondsFormat::Secs, true)
}
fn parse_time(raw: &str) -> Result<DateTime<Utc>, StorageError> {
DateTime::parse_from_rfc3339(raw)
.map(|value| value.with_timezone(&Utc))
.map_err(|error| StorageError::Corrupt(format!("data inválida `{raw}`: {error}")))
}
fn parse_ip(raw: &str) -> Result<IpAddr, StorageError> {
raw.parse()
.map_err(|error| StorageError::Corrupt(format!("IP inválido `{raw}`: {error}")))
}
fn parse_asset_status(raw: &str) -> Result<AssetStatus, StorageError> {
match raw {
"ativo" => Ok(AssetStatus::Active),
"sumido" => Ok(AssetStatus::Gone),
other => Err(StorageError::Corrupt(format!("status de ativo `{other}`"))),
}
}
fn parse_port_status(raw: &str) -> Result<PortStatus, StorageError> {
match raw {
"aberta" => Ok(PortStatus::Open),
"fechada" => Ok(PortStatus::Closed),
other => Err(StorageError::Corrupt(format!("status de porta `{other}`"))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::batch::{EngineMode, SweepBatch, SweepStatus};
use crate::diff::{diff_batch, DiffOptions};
use crate::scan::{
HostDiscoveryResult, HostPortScanResult, HostState, PortScanResult, PortState,
};
use std::net::Ipv4Addr;
fn at(seconds: i64) -> DateTime<Utc> {
DateTime::from_timestamp(1_700_000_000 + seconds, 0).expect("valid instant")
}
fn batch(
status: SweepStatus,
host_state: HostState,
ports: Vec<(u16, PortState)>,
) -> SweepBatch {
let ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5));
let mut manifest = SweepManifest::new(
"dmz",
vec!["203.0.113.0/24".to_string()],
"padrao",
EngineMode::NativeWithoutRaw,
at(0),
);
manifest.finish(status, at(60));
SweepBatch::new(
manifest,
vec![HostDiscoveryResult {
ip,
state: host_state,
responded_port: (host_state == HostState::Alive).then_some(22),
}],
vec![HostPortScanResult {
ip,
ports: ports
.into_iter()
.map(|(port, state)| PortScanResult { port, state })
.collect(),
}],
)
}
#[test]
fn ingests_state_and_events_end_to_end() {
let mut storage = SqliteStorage::open_in_memory().expect("database opens");
let batch = batch(
SweepStatus::Complete,
HostState::Alive,
vec![(22, PortState::Open)],
);
let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default())
.expect("diff succeeds");
assert!(storage.ingest(&batch, &diff).expect("ingest succeeds"));
let state = storage.load_state(&[]).expect("state loads");
assert_eq!(state.assets.len(), 1);
assert_eq!(state.assets[0].asset_key, "dmz/203.0.113.5");
assert_eq!(state.assets[0].ports.len(), 1);
assert_eq!(state.assets[0].ports[0].status, PortStatus::Open);
let events = storage.events(None).expect("events load");
assert_eq!(events.len(), 2);
assert!(events
.iter()
.any(|event| event.kind.as_str() == "host_novo"));
}
#[test]
fn ingestion_is_idempotent_per_sweep() {
let mut storage = SqliteStorage::open_in_memory().expect("database opens");
let batch = batch(
SweepStatus::Complete,
HostState::Alive,
vec![(22, PortState::Open)],
);
let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default())
.expect("diff succeeds");
assert!(storage.ingest(&batch, &diff).expect("first ingest"));
assert!(!storage.ingest(&batch, &diff).expect("second ingest"));
assert_eq!(storage.event_count().expect("count"), 2);
}
#[test]
fn absence_counter_survives_a_reload() {
let mut storage = SqliteStorage::open_in_memory().expect("database opens");
let first = batch(
SweepStatus::Complete,
HostState::Alive,
vec![(22, PortState::Open)],
);
let first_diff = diff_batch(&CurrentState::default(), &first, &DiffOptions::default())
.expect("first diff");
storage.ingest(&first, &first_diff).expect("first ingest");
let state = storage.load_state(&[]).expect("state loads");
let second = batch(SweepStatus::Complete, HostState::Unresponsive, vec![]);
let second_diff =
diff_batch(&state, &second, &DiffOptions::default()).expect("second diff");
storage
.ingest(&second, &second_diff)
.expect("second ingest");
let state = storage.load_state(&[]).expect("state reloads");
assert_eq!(state.assets[0].absences, 1);
assert_eq!(state.assets[0].status, AssetStatus::Active);
// The unresponsive sweep produced no disappearance event.
assert_eq!(storage.event_count().expect("count"), 2);
}
#[test]
fn load_state_respects_the_scope_filter() {
let mut storage = SqliteStorage::open_in_memory().expect("database opens");
let batch = batch(
SweepStatus::Complete,
HostState::Alive,
vec![(22, PortState::Open)],
);
let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default())
.expect("diff succeeds");
storage.ingest(&batch, &diff).expect("ingest succeeds");
let outside = [
IpRange::new("10.0.0.1".parse().unwrap(), "10.0.0.9".parse().unwrap()).expect("range"),
];
assert!(storage
.load_state(&outside)
.expect("state loads")
.assets
.is_empty());
let inside = [IpRange::new(
"203.0.113.0".parse().unwrap(),
"203.0.113.255".parse().unwrap(),
)
.expect("range")];
assert_eq!(
storage
.load_state(&inside)
.expect("state loads")
.assets
.len(),
1
);
}
}
+455 -2
View File
@@ -1,2 +1,455 @@
//! Safe configuration checks: weak TLS, expiring certificates, weak SSH algorithms, exposed admin services and cleartext protocols.
// TODO: implement non-intrusive configuration checks.
//! Safe, non-intrusive configuration security checks.
//!
//! Checks in this module observe standard service responses without sending
//! intrusive, destabilizing, or exploit payloads.
//!
//! Implemented checks:
//! 1. **TLS Certificate Expiration:** Detects certificates that are already expired
//! or expiring in less than 30 days.
//! 2. **Unencrypted Administrative Service:** Detects sensitive administrative interfaces
//! (e.g. ports 8080, 9090, 8000, 8888, 9000) answering cleartext HTTP without TLS redirection.
use super::matcher::{Confidence, Finding, FindingType};
use chrono::{DateTime, Utc};
use std::net::SocketAddr;
use std::time::Duration;
use thiserror::Error;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
/// Error encountered during configuration checks.
#[derive(Debug, Error)]
pub enum CheckError {
#[error("I/O error during check: {0}")]
Io(#[from] std::io::Error),
#[error("X.509 DER certificate parsing error: {0}")]
DerParsing(String),
}
// ---------------------------------------------------------------------------
// Check 1: TLS Certificate Expiration
// ---------------------------------------------------------------------------
/// Parses an X.509 DER-encoded certificate and evaluates whether it is expired
/// or expiring in less than 30 days.
///
/// Accepts an optional `now_utc` for deterministic testing.
pub fn check_tls_certificate_der(
der: &[u8],
now_utc: Option<DateTime<Utc>>,
) -> Result<Option<Finding>, CheckError> {
let now = now_utc.unwrap_or_else(Utc::now);
let not_after = parse_x509_der_not_after(der)
.map_err(|e| CheckError::DerParsing(format!("failed to parse validity: {e}")))?;
let remaining_seconds = not_after.signed_duration_since(now).num_seconds();
let remaining_days = remaining_seconds as f64 / 86400.0;
if remaining_seconds <= 0 {
// Expired certificate
let days_expired = (-remaining_days).ceil() as i64;
Ok(Some(Finding {
tipo: FindingType::Check,
id: "tls-cert-expired".into(),
cvss: Some(7.5),
kev: false,
confianca: Confidence::Alto,
title: "Certificado TLS Expirado".into(),
description: format!(
"O certificado TLS expirou há {} dias ({}) e causará falhas de validação de clientes.",
days_expired,
not_after.to_rfc3339()
),
evidencia: serde_json::json!({
"not_after": not_after.to_rfc3339(),
"current_time": now.to_rfc3339(),
"expired": true,
"days_expired": days_expired,
}),
}))
} else if remaining_days < 30.0 {
// Expiring in less than 30 days
let days_left = remaining_days.floor() as i64;
Ok(Some(Finding {
tipo: FindingType::Check,
id: "tls-cert-expiring".into(),
cvss: Some(5.3),
kev: false,
confianca: Confidence::Alto,
title: "Certificado TLS Expirando em Menos de 30 Dias".into(),
description: format!(
"O certificado TLS expira em {} dias ({}) e deve ser renovado prontamente.",
days_left,
not_after.to_rfc3339()
),
evidencia: serde_json::json!({
"not_after": not_after.to_rfc3339(),
"current_time": now.to_rfc3339(),
"expired": false,
"days_remaining": days_left,
}),
}))
} else {
// Certificate is valid with ample time
Ok(None)
}
}
/// Minimal, zero-dependency X.509 DER parser to extract the `notAfter` validity timestamp.
///
/// Navigates:
/// Certificate (SEQUENCE) -> TBSCertificate (SEQUENCE) -> Validity (SEQUENCE) -> notAfter
pub fn parse_x509_der_not_after(der: &[u8]) -> Result<DateTime<Utc>, String> {
if der.is_empty() || der[0] != 0x30 {
return Err("expected Certificate SEQUENCE".into());
}
let (_, mut off) = read_der_len(der, 1)?;
// TBSCertificate (SEQUENCE)
if off >= der.len() || der[off] != 0x30 {
return Err("expected TBSCertificate SEQUENCE".into());
}
let (tbs_len, next_off) = read_der_len(der, off + 1)?;
off = next_off;
let tbs_end = off + tbs_len;
if tbs_end > der.len() {
return Err("TBSCertificate length exceeds buffer".into());
}
// Element 1: version [0] EXPLICIT (optional in X.509)
if off < tbs_end && der[off] == 0xA0 {
let (v_len, next_off) = read_der_len(der, off + 1)?;
off = next_off + v_len;
}
// Element 2: serialNumber (INTEGER)
if off >= tbs_end || der[off] != 0x02 {
return Err("expected serialNumber INTEGER".into());
}
let (s_len, next_off) = read_der_len(der, off + 1)?;
off = next_off + s_len;
// Element 3: signature (AlgorithmIdentifier SEQUENCE)
if off >= tbs_end || der[off] != 0x30 {
return Err("expected signature AlgorithmIdentifier SEQUENCE".into());
}
let (sig_len, next_off) = read_der_len(der, off + 1)?;
off = next_off + sig_len;
// Element 4: issuer (Name SEQUENCE)
if off >= tbs_end || der[off] != 0x30 {
return Err("expected issuer SEQUENCE".into());
}
let (iss_len, next_off) = read_der_len(der, off + 1)?;
off = next_off + iss_len;
// Element 5: Validity (SEQUENCE)
if off >= tbs_end || der[off] != 0x30 {
return Err("expected validity SEQUENCE".into());
}
let (_val_len, next_off) = read_der_len(der, off + 1)?;
off = next_off;
// Inside Validity: notBefore (UTCTime: 0x17 or GeneralizedTime: 0x18)
if off >= tbs_end || (der[off] != 0x17 && der[off] != 0x18) {
return Err("expected notBefore UTCTime/GeneralizedTime".into());
}
let (nb_len, next_off) = read_der_len(der, off + 1)?;
off = next_off + nb_len;
// notAfter (UTCTime: 0x17 or GeneralizedTime: 0x18)
if off >= tbs_end || (der[off] != 0x17 && der[off] != 0x18) {
return Err("expected notAfter UTCTime/GeneralizedTime".into());
}
let is_utc_time = der[off] == 0x17;
let (na_len, next_off) = read_der_len(der, off + 1)?;
off = next_off;
if off + na_len > der.len() {
return Err("notAfter length exceeds buffer".into());
}
let time_str = std::str::from_utf8(&der[off..off + na_len])
.map_err(|e| format!("notAfter is not UTF-8: {e}"))?;
parse_asn1_time_string(time_str, is_utc_time)
}
fn read_der_len(data: &[u8], offset: usize) -> Result<(usize, usize), String> {
if offset >= data.len() {
return Err("unexpected EOF reading DER length".into());
}
let b = data[offset];
if b < 0x80 {
Ok((b as usize, offset + 1))
} else {
let count = (b & 0x7F) as usize;
if count == 0 || count > 4 {
return Err("unsupported DER multi-byte length".into());
}
if offset + 1 + count > data.len() {
return Err("unexpected EOF in multi-byte length".into());
}
let mut len: usize = 0;
for i in 0..count {
len = (len << 8) | (data[offset + 1 + i] as usize);
}
Ok((len, offset + 1 + count))
}
}
fn parse_asn1_time_string(s: &str, is_utc: bool) -> Result<DateTime<Utc>, String> {
let clean = s.trim_end_matches('Z');
if is_utc {
// YYMMDDHHMMSS
if clean.len() < 12 {
return Err(format!("UTCTime too short: '{s}'"));
}
let yy: i32 = clean[0..2]
.parse()
.map_err(|e| format!("invalid year: {e}"))?;
let year = if yy >= 50 { 1900 + yy } else { 2000 + yy };
let month: u32 = clean[2..4]
.parse()
.map_err(|e| format!("invalid month: {e}"))?;
let day: u32 = clean[4..6]
.parse()
.map_err(|e| format!("invalid day: {e}"))?;
let hour: u32 = clean[6..8]
.parse()
.map_err(|e| format!("invalid hour: {e}"))?;
let min: u32 = clean[8..10]
.parse()
.map_err(|e| format!("invalid minute: {e}"))?;
let sec: u32 = clean[10..12]
.parse()
.map_err(|e| format!("invalid second: {e}"))?;
let naive = chrono::NaiveDate::from_ymd_opt(year, month, day)
.and_then(|d| d.and_hms_opt(hour, min, sec))
.ok_or_else(|| format!("invalid date/time values in '{s}'"))?;
Ok(DateTime::from_naive_utc_and_offset(naive, Utc))
} else {
// YYYYMMDDHHMMSS
if clean.len() < 14 {
return Err(format!("GeneralizedTime too short: '{s}'"));
}
let year: i32 = clean[0..4]
.parse()
.map_err(|e| format!("invalid year: {e}"))?;
let month: u32 = clean[4..6]
.parse()
.map_err(|e| format!("invalid month: {e}"))?;
let day: u32 = clean[6..8]
.parse()
.map_err(|e| format!("invalid day: {e}"))?;
let hour: u32 = clean[8..10]
.parse()
.map_err(|e| format!("invalid hour: {e}"))?;
let min: u32 = clean[10..12]
.parse()
.map_err(|e| format!("invalid minute: {e}"))?;
let sec: u32 = clean[12..14]
.parse()
.map_err(|e| format!("invalid second: {e}"))?;
let naive = chrono::NaiveDate::from_ymd_opt(year, month, day)
.and_then(|d| d.and_hms_opt(hour, min, sec))
.ok_or_else(|| format!("invalid date/time values in '{s}'"))?;
Ok(DateTime::from_naive_utc_and_offset(naive, Utc))
}
}
// ---------------------------------------------------------------------------
// Check 2: Unencrypted Administrative Service Exposal
// ---------------------------------------------------------------------------
/// Well-known administrative and management TCP ports.
pub const COMMON_ADMIN_PORTS: &[u16] = &[8080, 8000, 8888, 9090, 9000, 8443, 10000];
/// Evaluates a raw HTTP response from a probed management port.
///
/// If the service answers with plain HTTP and does NOT issue a redirect to HTTPS,
/// it is considered an unencrypted administrative interface exposure.
pub fn evaluate_http_admin_response(port: u16, response_headers: &str) -> Option<Finding> {
let first_line = response_headers.lines().next().unwrap_or("");
if !first_line.starts_with("HTTP/1.0") && !first_line.starts_with("HTTP/1.1") {
return None;
}
let status_code: u16 = first_line
.split_whitespace()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
// If it is a redirect (301, 302, 307, 308) to HTTPS, it is properly secured
let is_https_redirect =
(status_code == 301 || status_code == 302 || status_code == 307 || status_code == 308)
&& response_headers
.lines()
.any(|l| l.to_lowercase().starts_with("location:") && l.contains("https://"));
if is_https_redirect {
return None;
}
// HTTP 200, 401 (Auth required), 403 (Forbidden), 404 served in cleartext
Some(Finding {
tipo: FindingType::Check,
id: "admin-http-unencrypted".into(),
cvss: Some(6.5),
kev: false,
confianca: Confidence::Alto,
title: "Serviço Administrativo Exposto Sem TLS".into(),
description: format!(
"Porta de administração ({}) respondeu em HTTP claro (status {}) sem redirecionamento obrigatório para HTTPS, permitindo interceptação e roubo de credenciais.",
port, status_code
),
evidencia: serde_json::json!({
"port": port,
"status_code": status_code,
"first_line": first_line,
"is_redirect_to_https": false,
}),
})
}
/// Actively probes a TCP endpoint with an HTTP request to detect cleartext exposure.
pub async fn probe_unencrypted_admin_service(
addr: SocketAddr,
timeout_duration: Duration,
) -> Result<Option<Finding>, CheckError> {
let connect_future = TcpStream::connect(addr);
let mut stream = match tokio::time::timeout(timeout_duration, connect_future).await {
Ok(Ok(s)) => s,
_ => return Ok(None),
};
let req = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: xexeu-audit/0.1\r\nConnection: close\r\n\r\n",
addr
);
if (tokio::time::timeout(timeout_duration, stream.write_all(req.as_bytes())).await).is_err() {
return Ok(None);
}
let mut buf = vec![0u8; 2048];
let n = match tokio::time::timeout(timeout_duration, stream.read(&mut buf)).await {
Ok(Ok(n)) if n > 0 => n,
_ => return Ok(None),
};
let response_text = String::from_utf8_lossy(&buf[..n]);
Ok(evaluate_http_admin_response(addr.port(), &response_text))
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
use tokio::net::TcpListener;
#[test]
fn test_x509_der_not_after_parsing_and_expiring_check() {
// Construct a synthetic minimal DER certificate structure with notAfter = 2026-11-20
// UTCTime format: "261120000000Z"
let not_before = b"261101000000Z";
let not_after = b"261120000000Z";
// Build Validity SEQUENCE
let mut validity = vec![0x30];
validity.push((2 + not_before.len() + 2 + not_after.len()) as u8);
validity.push(0x17);
validity.push(not_before.len() as u8);
validity.extend_from_slice(not_before);
validity.push(0x17);
validity.push(not_after.len() as u8);
validity.extend_from_slice(not_after);
// Build minimal TBSCertificate:
// serialNumber (0x02, 0x01, 0x01), signature (0x30, 0x00), issuer (0x30, 0x00), validity
let mut tbs = vec![0x02, 0x01, 0x01, 0x30, 0x00, 0x30, 0x00];
tbs.extend_from_slice(&validity);
let mut tbs_seq = vec![0x30, tbs.len() as u8];
tbs_seq.extend_from_slice(&tbs);
// Wrap into Certificate SEQUENCE
let mut cert = vec![0x30, tbs_seq.len() as u8];
cert.extend_from_slice(&tbs_seq);
let parsed = parse_x509_der_not_after(&cert).expect("DER parse success");
assert_eq!(
parsed,
DateTime::parse_from_rfc3339("2026-11-20T00:00:00Z").unwrap()
);
// Case A: Evaluated on 2026-11-01 -> 19 days remaining (< 30 days -> expiring)
let eval_time = DateTime::parse_from_rfc3339("2026-11-01T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let finding = check_tls_certificate_der(&cert, Some(eval_time))
.unwrap()
.expect("finding emitted");
assert_eq!(finding.id, "tls-cert-expiring");
assert_eq!(finding.confianca, Confidence::Alto);
// Case B: Evaluated on 2026-12-01 -> expired
let eval_expired = DateTime::parse_from_rfc3339("2026-12-01T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let finding_exp = check_tls_certificate_der(&cert, Some(eval_expired))
.unwrap()
.expect("finding emitted");
assert_eq!(finding_exp.id, "tls-cert-expired");
// Case C: Evaluated on 2026-10-01 -> 50 days remaining (>= 30 days -> no finding)
let eval_safe = DateTime::parse_from_rfc3339("2026-10-01T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let finding_safe = check_tls_certificate_der(&cert, Some(eval_safe)).unwrap();
assert!(finding_safe.is_none());
}
#[test]
fn test_evaluate_http_admin_response() {
// Plain HTTP 200 on port 8080 without TLS
let resp_plain =
"HTTP/1.1 200 OK\r\nServer: Tomcat\r\nContent-Length: 10\r\n\r\nHello Admin";
let finding = evaluate_http_admin_response(8080, resp_plain).expect("finding expected");
assert_eq!(finding.id, "admin-http-unencrypted");
assert_eq!(finding.cvss, Some(6.5));
// HTTP 301 Redirect to HTTPS
let resp_redirect =
"HTTP/1.1 301 Moved Permanently\r\nLocation: https://example.org:8443/\r\n\r\n";
let no_finding = evaluate_http_admin_response(8080, resp_redirect);
assert!(no_finding.is_none());
}
#[tokio::test]
async fn test_probe_unencrypted_admin_service_live_listener() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
if let Ok((mut socket, _)) = listener.accept().await {
let mut buf = [0u8; 512];
let _ = socket.read(&mut buf).await;
let reply = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK";
let _ = socket.write_all(reply.as_bytes()).await;
}
});
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
let finding = probe_unencrypted_admin_service(addr, Duration::from_millis(500))
.await
.unwrap()
.expect("should detect exposed HTTP admin");
assert_eq!(finding.id, "admin-http-unencrypted");
}
}
+549 -2
View File
@@ -1,2 +1,549 @@
//! Imports and incrementally syncs NVD CVE JSON 2.0 and the CISA KEV catalog into the local base.
// TODO: implement feed sync and offline import.
//! 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"));
}
}
+555 -2
View File
@@ -1,2 +1,555 @@
//! Correlates a candidate CPE with NVD configurations, honoring version ranges and assigning a confidence level.
// TODO: implement CPE-to-CVE matching with version-range comparison.
//! Banner normalization, candidate CPE derivation, and deterministic CVE correlation.
//!
//! # Heuristic Banner Parsing Limitations
//!
//! Service banner fingerprinting has inherent real-world limitations:
//! 1. **Distribution Backports:** Linux distributions (Debian, Ubuntu, RHEL) frequently
//! backport security patches to older upstream versions (e.g. `OpenSSH_8.9p1 Ubuntu-3ubuntu0.10`).
//! In such cases, a pure version check will flag a CVE that may already be patched downstream.
//! When distribution indicators are present, the match confidence is reduced to
//! [`Confidence::Medio`] (`provavel`) and a backport note is added to the evidence JSON.
//! 2. **Custom / Stripped Banners:** Some administrators obfuscate or truncate banners
//! (e.g. `Server: Apache` without version). In this case, no CVE findings are emitted
//! or only informative low-confidence events are produced.
//! 3. **Non-Standard Formats:** Non-standard daemon banners without delimiters may not
//! yield clean CPE candidate records.
use super::feeds::{Cpe, CpeMatchCriteria, VulnDatabase};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// Finding classification type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FindingType {
Cve,
Check,
}
/// Assessment confidence level for a vulnerability finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Confidence {
/// Exact product and version extracted from banner matched the vulnerable range,
/// with no unresolved distribution backport suffixes (`confirmada-por-versao`).
#[serde(rename = "confirmada-por-versao", alias = "alto", alias = "Alto")]
Alto,
/// Product matched and version fell within criteria, but distribution backport
/// indicators (e.g. `Ubuntu-`, `Debian-`) suggest the flaw might be patched (`provavel`).
#[serde(rename = "provavel", alias = "medio", alias = "Medio")]
Medio,
/// Product identified with ambiguous version or generic heuristic (`indeterminada`).
#[serde(rename = "indeterminada", alias = "baixo", alias = "Baixo")]
Baixo,
}
/// Vulnerability or configuration security finding.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Finding {
/// Finding category: CVE or configuration check.
pub tipo: FindingType,
/// Unique identifier: e.g. "CVE-2024-6387" or "tls-cert-expiring".
pub id: String,
/// CVSS base score (0.0 to 10.0), if available.
pub cvss: Option<f32>,
/// Whether the vulnerability is cataloged in CISA KEV (actively exploited).
pub kev: bool,
/// Confidence level in the finding's accuracy.
pub confianca: Confidence,
/// Short summary title.
pub title: String,
/// Explanatory description.
pub description: String,
/// Verifiable deterministic JSON evidence.
pub evidencia: serde_json::Value,
}
/// Candidate information parsed from a raw service banner.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BannerInfo {
/// Normalized candidate CPE.
pub cpe: Cpe,
/// Detected product display name.
pub product_name: String,
/// Extracted version string (if any).
pub version: Option<String>,
/// Whether distribution-specific backport indicators were observed.
pub is_backport: bool,
/// The original raw banner.
pub raw_banner: String,
}
/// Heuristically derives a candidate [`BannerInfo`] and [`Cpe`] from a banner string.
pub fn parse_banner_to_cpe(banner: &str) -> Option<BannerInfo> {
let trimmed = banner.trim();
if trimmed.is_empty() {
return None;
}
let is_backport = trimmed.contains("Ubuntu")
|| trimmed.contains("Debian")
|| trimmed.contains("CentOS")
|| trimmed.contains("Red Hat")
|| trimmed.contains("RHEL")
|| trimmed.contains("el7")
|| trimmed.contains("el8")
|| trimmed.contains("el9");
// Case 1: SSH banner (e.g. "SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10" or "OpenSSH_9.3p1")
if let Some(pos) = trimmed.find("OpenSSH") {
let after = &trimmed[pos + "OpenSSH".len()..];
let after = after.trim_start_matches(['_', '/', ' ']);
let version_token = after.split_whitespace().next().unwrap_or("");
let version = clean_version_token(version_token);
let cpe = Cpe {
part: "a".into(),
vendor: "openbsd".into(),
product: "openssh".into(),
version: if version.is_empty() {
"*".into()
} else {
version.clone()
},
update: "*".into(),
};
return Some(BannerInfo {
cpe,
product_name: "OpenSSH".into(),
version: if version.is_empty() {
None
} else {
Some(version)
},
is_backport,
raw_banner: trimmed.into(),
});
}
// Case 2: Apache HTTP Server (e.g. "Server: Apache/2.4.49 (Unix)" or "Apache/2.4.49")
if let Some(pos) = trimmed.find("Apache") {
let after = &trimmed[pos + "Apache".len()..];
let after = after.trim_start_matches(['/', ' ']);
let version_token = after.split_whitespace().next().unwrap_or("");
let version = clean_version_token(version_token);
let cpe = Cpe {
part: "a".into(),
vendor: "apache".into(),
product: "http_server".into(),
version: if version.is_empty() {
"*".into()
} else {
version.clone()
},
update: "*".into(),
};
return Some(BannerInfo {
cpe,
product_name: "Apache HTTP Server".into(),
version: if version.is_empty() {
None
} else {
Some(version)
},
is_backport,
raw_banner: trimmed.into(),
});
}
// Case 3: Nginx (e.g. "Server: nginx/1.18.0" or "nginx/1.24.0")
if let Some(pos) = trimmed.to_lowercase().find("nginx") {
let after = &trimmed[pos + "nginx".len()..];
let after = after.trim_start_matches(['/', ' ']);
let version_token = after.split_whitespace().next().unwrap_or("");
let version = clean_version_token(version_token);
let cpe = Cpe {
part: "a".into(),
vendor: "f5".into(),
product: "nginx".into(),
version: if version.is_empty() {
"*".into()
} else {
version.clone()
},
update: "*".into(),
};
return Some(BannerInfo {
cpe,
product_name: "nginx".into(),
version: if version.is_empty() {
None
} else {
Some(version)
},
is_backport,
raw_banner: trimmed.into(),
});
}
// Case 4: Generic HTTP "Server: Product/Version" or "Product/Version"
let probe = if let Some(stripped) = trimmed.strip_prefix("Server:") {
stripped.trim()
} else {
trimmed
};
if let Some((prod, rest)) = probe.split_once('/') {
let prod = prod.trim();
let version_token = rest.split_whitespace().next().unwrap_or("");
let version = clean_version_token(version_token);
if !prod.is_empty() && !version.is_empty() {
let prod_lower = prod.to_lowercase();
let cpe = Cpe {
part: "a".into(),
vendor: prod_lower.clone(),
product: prod_lower,
version: version.clone(),
update: "*".into(),
};
return Some(BannerInfo {
cpe,
product_name: prod.into(),
version: Some(version),
is_backport,
raw_banner: trimmed.into(),
});
}
}
None
}
fn clean_version_token(s: &str) -> String {
let s = s.trim_matches(|c: char| !c.is_alphanumeric() && c != '.');
s.to_string()
}
// ---------------------------------------------------------------------------
// Deterministic Version Parsing & Comparison
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
enum VersionChunk {
Num(u64),
Str(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedVersion {
chunks: Vec<VersionChunk>,
}
impl ParsedVersion {
fn parse(v: &str) -> Self {
let mut chunks = Vec::new();
let mut current_num: Option<u64> = None;
let mut current_str = String::new();
for ch in v.chars() {
if ch.is_ascii_digit() {
if !current_str.is_empty() {
chunks.push(VersionChunk::Str(std::mem::take(&mut current_str)));
}
let digit = ch.to_digit(10).unwrap() as u64;
current_num = Some(
current_num
.unwrap_or(0)
.saturating_mul(10)
.saturating_add(digit),
);
} else if ch.is_alphabetic() {
if let Some(n) = current_num.take() {
chunks.push(VersionChunk::Num(n));
}
current_str.push(ch.to_ascii_lowercase());
} else {
// delimiter (e.g. '.', '-', '_')
if let Some(n) = current_num.take() {
chunks.push(VersionChunk::Num(n));
}
if !current_str.is_empty() {
chunks.push(VersionChunk::Str(std::mem::take(&mut current_str)));
}
}
}
if let Some(n) = current_num {
chunks.push(VersionChunk::Num(n));
}
if !current_str.is_empty() {
chunks.push(VersionChunk::Str(current_str));
}
Self { chunks }
}
}
impl PartialOrd for ParsedVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ParsedVersion {
fn cmp(&self, other: &Self) -> Ordering {
let min_len = self.chunks.len().min(other.chunks.len());
for i in 0..min_len {
match (&self.chunks[i], &other.chunks[i]) {
(VersionChunk::Num(a), VersionChunk::Num(b)) => {
let ord = a.cmp(b);
if ord != Ordering::Equal {
return ord;
}
}
(VersionChunk::Str(a), VersionChunk::Str(b)) => {
let ord = a.cmp(b);
if ord != Ordering::Equal {
return ord;
}
}
(VersionChunk::Num(_), VersionChunk::Str(_)) => return Ordering::Greater,
(VersionChunk::Str(_), VersionChunk::Num(_)) => return Ordering::Less,
}
}
self.chunks.len().cmp(&other.chunks.len())
}
}
fn version_matches_criteria(candidate_v: &str, criteria: &CpeMatchCriteria) -> bool {
let cand = ParsedVersion::parse(candidate_v);
// Exact version in criteria (if specified and not wildcard)
if criteria.cpe.version != "*" && criteria.cpe.version != "-" {
let crit_ver = ParsedVersion::parse(&criteria.cpe.version);
if cand != crit_ver {
return false;
}
}
if let Some(start_inc) = &criteria.version_start_including {
if cand < ParsedVersion::parse(start_inc) {
return false;
}
}
if let Some(start_exc) = &criteria.version_start_excluding {
if cand <= ParsedVersion::parse(start_exc) {
return false;
}
}
if let Some(end_inc) = &criteria.version_end_including {
if cand > ParsedVersion::parse(end_inc) {
return false;
}
}
if let Some(end_exc) = &criteria.version_end_excluding {
if cand >= ParsedVersion::parse(end_exc) {
return false;
}
}
true
}
/// Matches a candidate [`BannerInfo`] against the local vulnerability database.
///
/// Returns a deterministically sorted list of [`Finding`]s.
pub fn match_banner(banner_info: &BannerInfo, db: &VulnDatabase) -> Vec<Finding> {
let mut findings = Vec::new();
let cand_cpe = &banner_info.cpe;
for (cve_id, record) in &db.nvd.records {
for criteria in &record.cpe_matches {
// Check product match (vendor and product)
let vendor_match = criteria.cpe.vendor == cand_cpe.vendor
|| (criteria.cpe.vendor == "f5" && cand_cpe.vendor == "nginx")
|| (criteria.cpe.vendor == "nginx" && cand_cpe.vendor == "f5");
let product_match = criteria.cpe.product == cand_cpe.product;
if !vendor_match || !product_match {
continue;
}
// Check version range match
if cand_cpe.version == "*" {
// If candidate has no version, do not generate false CVE positives
continue;
}
if version_matches_criteria(&cand_cpe.version, criteria) {
let kev = db.is_in_kev(cve_id);
let confianca = if banner_info.is_backport {
Confidence::Medio
} else {
Confidence::Alto
};
let rule_str = format!(
"criteria={}; start_inc={:?}; end_exc={:?}",
criteria.criteria,
criteria.version_start_including,
criteria.version_end_excluding
);
findings.push(Finding {
tipo: FindingType::Cve,
id: cve_id.clone(),
cvss: record.cvss_score,
kev,
confianca,
title: format!("{}: {}", cve_id, banner_info.product_name),
description: record.description.clone(),
evidencia: serde_json::json!({
"banner": banner_info.raw_banner,
"cpe": cand_cpe.to_cpe23(),
"matched_criteria": criteria.criteria,
"rule": rule_str,
"distribution_backport_suspected": banner_info.is_backport,
}),
});
break; // One match per CVE record is sufficient
}
}
}
// Deterministic sorting:
// 1. KEV first (actively exploited)
// 2. Highest CVSS score first (None sorted last)
// 3. Alphabetical by CVE ID ascending
findings.sort_by(|a, b| {
b.kev
.cmp(&a.kev)
.then_with(|| {
let cvss_a = a.cvss.unwrap_or(0.0);
let cvss_b = b.cvss.unwrap_or(0.0);
cvss_b.partial_cmp(&cvss_a).unwrap_or(Ordering::Equal)
})
.then_with(|| a.id.cmp(&b.id))
});
findings
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vuln::feeds::{CveRecord, KevCatalog, NvdCatalog};
use std::collections::{HashMap, HashSet};
#[test]
fn test_version_ordering() {
assert!(ParsedVersion::parse("8.5p1") < ParsedVersion::parse("9.3p1"));
assert!(ParsedVersion::parse("9.3p1") < ParsedVersion::parse("9.8p1"));
assert!(ParsedVersion::parse("2.4.48") < ParsedVersion::parse("2.4.49"));
assert!(ParsedVersion::parse("2.4.49") < ParsedVersion::parse("2.4.50"));
assert_eq!(
ParsedVersion::parse("2.4.49"),
ParsedVersion::parse("2.4.49")
);
}
#[test]
fn test_parse_banner_openssh_with_backport() {
let banner = "SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10";
let info = parse_banner_to_cpe(banner).unwrap();
assert_eq!(info.product_name, "OpenSSH");
assert_eq!(info.cpe.vendor, "openbsd");
assert_eq!(info.cpe.product, "openssh");
assert_eq!(info.cpe.version, "8.9p1");
assert!(info.is_backport);
}
#[test]
fn test_parse_banner_apache() {
let banner = "Server: Apache/2.4.49 (Unix) OpenSSL/1.1.1k";
let info = parse_banner_to_cpe(banner).unwrap();
assert_eq!(info.product_name, "Apache HTTP Server");
assert_eq!(info.cpe.vendor, "apache");
assert_eq!(info.cpe.product, "http_server");
assert_eq!(info.cpe.version, "2.4.49");
assert!(!info.is_backport);
}
#[test]
fn test_matcher_deterministic_ranking() {
let mut records = HashMap::new();
// CVE-2024-6387: OpenSSH 8.5p1 - 9.8p1 (cvss 8.1, not in KEV)
records.insert(
"CVE-2024-6387".into(),
CveRecord {
id: "CVE-2024-6387".into(),
description: "OpenSSH regreSSHion flaw".into(),
cvss_score: Some(8.1),
cvss_vector: None,
cpe_matches: vec![CpeMatchCriteria {
criteria: "cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*".into(),
cpe: Cpe::parse("cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*").unwrap(),
version_start_including: Some("8.5p1".into()),
version_start_excluding: None,
version_end_including: None,
version_end_excluding: Some("9.8p1".into()),
}],
},
);
// CVE-2021-41773: Apache 2.4.49 (cvss 7.5, IN KEV)
records.insert(
"CVE-2021-41773".into(),
CveRecord {
id: "CVE-2021-41773".into(),
description: "Apache path traversal".into(),
cvss_score: Some(7.5),
cvss_vector: None,
cpe_matches: vec![CpeMatchCriteria {
criteria: "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*".into(),
cpe: Cpe::parse("cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*").unwrap(),
version_start_including: None,
version_start_excluding: None,
version_end_including: None,
version_end_excluding: None,
}],
},
);
let mut kev_ids = HashSet::new();
kev_ids.insert("CVE-2021-41773".into());
let db = VulnDatabase {
nvd: NvdCatalog { records },
kev: KevCatalog { cve_ids: kev_ids },
};
// Match OpenSSH 9.3p1 (clean, no backport)
let info_clean = parse_banner_to_cpe("SSH-2.0-OpenSSH_9.3p1").unwrap();
let findings_clean = match_banner(&info_clean, &db);
assert_eq!(findings_clean.len(), 1);
assert_eq!(findings_clean[0].id, "CVE-2024-6387");
assert_eq!(findings_clean[0].confianca, Confidence::Alto);
assert!(!findings_clean[0].kev);
// Match OpenSSH 8.9p1 Ubuntu (backport detected)
let info_backport =
parse_banner_to_cpe("SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10").unwrap();
let findings_backport = match_banner(&info_backport, &db);
assert_eq!(findings_backport.len(), 1);
assert_eq!(findings_backport[0].confianca, Confidence::Medio);
// Match Apache 2.4.49 (listed in KEV)
let info_apache = parse_banner_to_cpe("Server: Apache/2.4.49 (Unix)").unwrap();
let findings_apache = match_banner(&info_apache, &db);
assert_eq!(findings_apache.len(), 1);
assert_eq!(findings_apache[0].id, "CVE-2021-41773");
assert!(findings_apache[0].kev);
assert_eq!(findings_apache[0].confianca, Confidence::Alto);
}
}
+12
View File
@@ -3,3 +3,15 @@
pub mod checks;
pub mod feeds;
pub mod matcher;
pub use checks::{
check_tls_certificate_der, evaluate_http_admin_response, parse_x509_der_not_after,
probe_unencrypted_admin_service, CheckError, COMMON_ADMIN_PORTS,
};
pub use feeds::{
import_kev, import_nvd, Cpe, CpeMatchCriteria, CveRecord, FeedError, KevCatalog, NvdCatalog,
VulnDatabase,
};
pub use matcher::{
match_banner, parse_banner_to_cpe, BannerInfo, Confidence, Finding, FindingType,
};