|
|
|
@@ -9,7 +9,8 @@
|
|
|
|
|
//! CVE issues (#452) all see the same answer.
|
|
|
|
|
//!
|
|
|
|
|
//! - **KEV** (CC0): the whole catalog, one JSON file of about 2 MB, read at
|
|
|
|
|
//! most once a day.
|
|
|
|
|
//! most once a day: from CISA's mirror on GitHub (`cisagov/kev-data`),
|
|
|
|
|
//! else from `www.cisa.gov`, which refuses many datacenter addresses (403).
|
|
|
|
|
//! - **EPSS** (free to use, attribution requested by FIRST): FIRST's API,
|
|
|
|
|
//! up to [`EPSS_BATCH`] CVE ids per request.
|
|
|
|
|
//! - **Vulnrichment** (CC0): CISA's per-CVE record in its GitHub repository
|
|
|
|
@@ -18,8 +19,9 @@
|
|
|
|
|
//! Only CVE ids leave the agent, through the net guard like every other
|
|
|
|
|
//! public lookup ([`PublicHttp`]). Answers are cached for a day for all
|
|
|
|
|
//! tenants (see [`MongoExploitCache`]): they are public data keyed by CVE id,
|
|
|
|
|
//! with nothing of the tenant that asked. A source that fails leaves its part
|
|
|
|
|
//! unknown and is not cached, and never fails the scan.
|
|
|
|
|
//! with nothing of the tenant that asked. Each source is cached on its own: a
|
|
|
|
|
//! source that fails leaves its part unknown, keeps what the others answered,
|
|
|
|
|
//! is asked again on the next run, and never fails the scan.
|
|
|
|
|
//! `CVE_EXPLOIT_LOOKUP=false` turns the lookups off.
|
|
|
|
|
|
|
|
|
|
use std::collections::{BTreeSet, HashMap};
|
|
|
|
@@ -34,9 +36,12 @@ use futures_util::StreamExt;
|
|
|
|
|
|
|
|
|
|
use crate::pipeline::public_http::{read_body, read_json, PublicHttp};
|
|
|
|
|
|
|
|
|
|
/// CISA's KEV catalog.
|
|
|
|
|
const KEV_URL: &str =
|
|
|
|
|
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json";
|
|
|
|
|
/// CISA's KEV catalog, in the order they are tried: CISA's official mirror
|
|
|
|
|
/// on GitHub (reachable from datacenters), then CISA's own site.
|
|
|
|
|
const KEV_URLS: [&str; 2] = [
|
|
|
|
|
"https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json",
|
|
|
|
|
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json",
|
|
|
|
|
];
|
|
|
|
|
/// FIRST's EPSS API.
|
|
|
|
|
const EPSS_API: &str = "https://api.first.org/data/v1/epss";
|
|
|
|
|
/// CISA's Vulnrichment records, by year and thousand.
|
|
|
|
@@ -67,6 +72,46 @@ fn lookup_enabled(value: Option<&str>) -> bool {
|
|
|
|
|
/// The KEV catalog: entry by CVE id.
|
|
|
|
|
pub(crate) type KevCatalog = HashMap<String, KevEntry>;
|
|
|
|
|
|
|
|
|
|
/// What the per-CVE sources answered about one CVE. KEV is not kept per
|
|
|
|
|
/// CVE: its whole catalog is cached on its own.
|
|
|
|
|
/// Read from the cache's rows; written field by field (see
|
|
|
|
|
/// [`MongoExploitCache`]).
|
|
|
|
|
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
|
|
|
|
pub(crate) struct CveAnswers {
|
|
|
|
|
/// Whether FIRST answered (with or without a score).
|
|
|
|
|
#[serde(default)]
|
|
|
|
|
pub epss_answered: bool,
|
|
|
|
|
/// FIRST's score, if it has one.
|
|
|
|
|
#[serde(default)]
|
|
|
|
|
pub epss: Option<EpssScore>,
|
|
|
|
|
/// Whether CISA's Vulnrichment answered (a 404 is an answer).
|
|
|
|
|
#[serde(default)]
|
|
|
|
|
pub ssvc_answered: bool,
|
|
|
|
|
/// The SSVC exploitation, if CISA rated the CVE.
|
|
|
|
|
#[serde(default)]
|
|
|
|
|
pub ssvc_exploitation: Option<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl CveAnswers {
|
|
|
|
|
/// Whether every per-CVE source answered, so nobody needs asking.
|
|
|
|
|
fn complete(&self) -> bool {
|
|
|
|
|
self.epss_answered && self.ssvc_answered
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Take over what `newer` answered; a source it has no answer from keeps
|
|
|
|
|
/// the answer already here.
|
|
|
|
|
fn merge(&mut self, newer: &CveAnswers) {
|
|
|
|
|
if newer.epss_answered {
|
|
|
|
|
self.epss_answered = true;
|
|
|
|
|
self.epss = newer.epss.clone();
|
|
|
|
|
}
|
|
|
|
|
if newer.ssvc_answered {
|
|
|
|
|
self.ssvc_answered = true;
|
|
|
|
|
self.ssvc_exploitation = newer.ssvc_exploitation.clone();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Where looked-up answers are kept between runs. A trait so tests run
|
|
|
|
|
/// without Mongo.
|
|
|
|
|
pub(crate) trait ExploitCache: Send + Sync {
|
|
|
|
@@ -74,12 +119,10 @@ pub(crate) trait ExploitCache: Send + Sync {
|
|
|
|
|
fn get_many<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
cves: &'a [String],
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, Exploitation>, String>>;
|
|
|
|
|
/// Keep `answers` for a day.
|
|
|
|
|
fn put<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
answers: &'a [(String, Exploitation)],
|
|
|
|
|
) -> BoxFuture<'a, Result<(), String>>;
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, CveAnswers>, String>>;
|
|
|
|
|
/// Merge `answers` into the stored ones (see [`CveAnswers::merge`]); a row
|
|
|
|
|
/// is kept for a day after it was first written.
|
|
|
|
|
fn put<'a>(&'a self, answers: &'a [(String, CveAnswers)]) -> BoxFuture<'a, Result<(), String>>;
|
|
|
|
|
/// Today's KEV catalog, if one was read.
|
|
|
|
|
fn kev(&self) -> BoxFuture<'_, Result<Option<KevCatalog>, String>>;
|
|
|
|
|
/// Keep the KEV catalog for a day.
|
|
|
|
@@ -106,7 +149,7 @@ pub(crate) struct CveEnricher {
|
|
|
|
|
http: PublicHttp,
|
|
|
|
|
cache: Option<Arc<dyn ExploitCache>>,
|
|
|
|
|
enabled: bool,
|
|
|
|
|
kev_url: String,
|
|
|
|
|
kev_urls: Vec<String>,
|
|
|
|
|
epss_api: String,
|
|
|
|
|
vulnrichment_base: String,
|
|
|
|
|
}
|
|
|
|
@@ -125,7 +168,7 @@ impl CveEnricher {
|
|
|
|
|
http: PublicHttp::new(guard)?,
|
|
|
|
|
cache,
|
|
|
|
|
enabled: lookup_enabled(std::env::var("CVE_EXPLOIT_LOOKUP").ok().as_deref()),
|
|
|
|
|
kev_url: KEV_URL.to_string(),
|
|
|
|
|
kev_urls: KEV_URLS.iter().map(|u| u.to_string()).collect(),
|
|
|
|
|
epss_api: EPSS_API.to_string(),
|
|
|
|
|
vulnrichment_base: VULNRICHMENT_BASE.to_string(),
|
|
|
|
|
})
|
|
|
|
@@ -134,7 +177,7 @@ impl CveEnricher {
|
|
|
|
|
/// Ask the stand-ins at `base` instead of the public sources.
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
fn with_base(mut self, base: &str) -> Self {
|
|
|
|
|
self.kev_url = format!("{base}/kev.json");
|
|
|
|
|
self.kev_urls = vec![format!("{base}/kev.json")];
|
|
|
|
|
self.epss_api = format!("{base}/epss");
|
|
|
|
|
self.vulnrichment_base = format!("{base}/vulnrichment");
|
|
|
|
|
self.enabled = true;
|
|
|
|
@@ -185,97 +228,119 @@ impl CveEnricher {
|
|
|
|
|
counts
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The exploitation of every CVE in `cves`, from the cache or the
|
|
|
|
|
/// sources; a CVE nothing is known about is missing or empty.
|
|
|
|
|
/// The exploitation of every CVE in `cves`: KEV from today's catalog,
|
|
|
|
|
/// EPSS and SSVC from the cache or the sources. A CVE nothing is known
|
|
|
|
|
/// about is empty.
|
|
|
|
|
async fn lookup(
|
|
|
|
|
&self,
|
|
|
|
|
cves: BTreeSet<String>,
|
|
|
|
|
counts: &mut EnrichCounts,
|
|
|
|
|
) -> HashMap<String, Exploitation> {
|
|
|
|
|
let ids: Vec<String> = cves.into_iter().collect();
|
|
|
|
|
let mut found = match &self.cache {
|
|
|
|
|
let kev = self.kev_catalog().await;
|
|
|
|
|
if kev.is_none() {
|
|
|
|
|
counts.failed.push("KEV");
|
|
|
|
|
}
|
|
|
|
|
let mut answers = match &self.cache {
|
|
|
|
|
Some(cache) => cache.get_many(&ids).await.unwrap_or_else(|e| {
|
|
|
|
|
tracing::warn!("CVE exploitation cache unreadable: {e}");
|
|
|
|
|
HashMap::new()
|
|
|
|
|
}),
|
|
|
|
|
None => HashMap::new(),
|
|
|
|
|
};
|
|
|
|
|
counts.cached = found.len();
|
|
|
|
|
let mut missing: Vec<String> = ids
|
|
|
|
|
.into_iter()
|
|
|
|
|
.filter(|id| !found.contains_key(id))
|
|
|
|
|
counts.cached = answers.values().filter(|a| a.complete()).count();
|
|
|
|
|
let mut pending: Vec<String> = ids
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|id| !answers.get(*id).is_some_and(CveAnswers::complete))
|
|
|
|
|
.cloned()
|
|
|
|
|
.collect();
|
|
|
|
|
if missing.is_empty() {
|
|
|
|
|
return found;
|
|
|
|
|
}
|
|
|
|
|
if missing.len() > MAX_UNCACHED {
|
|
|
|
|
if pending.len() > MAX_UNCACHED {
|
|
|
|
|
tracing::info!(
|
|
|
|
|
"CVE exploitation: looking up {MAX_UNCACHED} of {} uncached CVEs; the rest on a later run",
|
|
|
|
|
missing.len()
|
|
|
|
|
pending.len()
|
|
|
|
|
);
|
|
|
|
|
missing.truncate(MAX_UNCACHED);
|
|
|
|
|
pending.truncate(MAX_UNCACHED);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let fetched =
|
|
|
|
|
match tokio::time::timeout(LOOKUP_BUDGET, self.fetch(&missing, &mut counts.failed))
|
|
|
|
|
.await
|
|
|
|
|
{
|
|
|
|
|
Ok(fetched) => fetched,
|
|
|
|
|
if !pending.is_empty() {
|
|
|
|
|
let fetched = tokio::time::timeout(
|
|
|
|
|
LOOKUP_BUDGET,
|
|
|
|
|
self.fetch(&pending, &answers, &mut counts.failed),
|
|
|
|
|
)
|
|
|
|
|
.await;
|
|
|
|
|
match fetched {
|
|
|
|
|
Ok(fresh) => {
|
|
|
|
|
if let (Some(cache), false) = (&self.cache, fresh.is_empty()) {
|
|
|
|
|
if let Err(e) = cache.put(&fresh).await {
|
|
|
|
|
tracing::warn!("CVE exploitation cache not written: {e}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for (id, fresh) in &fresh {
|
|
|
|
|
answers.entry(id.clone()).or_default().merge(fresh);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(_) => {
|
|
|
|
|
tracing::warn!(
|
|
|
|
|
"CVE exploitation lookups took longer than {LOOKUP_BUDGET:?}; left unknown"
|
|
|
|
|
);
|
|
|
|
|
counts.failed.push("timeout");
|
|
|
|
|
return found;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
let complete: Vec<(String, Exploitation)> = fetched
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|(_, (_, complete))| *complete)
|
|
|
|
|
.map(|(id, (e, _))| (id.clone(), e.clone()))
|
|
|
|
|
.collect();
|
|
|
|
|
if let (Some(cache), false) = (&self.cache, complete.is_empty()) {
|
|
|
|
|
if let Err(e) = cache.put(&complete).await {
|
|
|
|
|
tracing::warn!("CVE exploitation cache not written: {e}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
found.extend(fetched.into_iter().map(|(id, (e, _))| (id, e)));
|
|
|
|
|
found
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Ask the three sources about `cves`. Each answer says whether every
|
|
|
|
|
/// source answered (only then is it cached).
|
|
|
|
|
async fn fetch(
|
|
|
|
|
&self,
|
|
|
|
|
cves: &[String],
|
|
|
|
|
failed: &mut Vec<&'static str>,
|
|
|
|
|
) -> HashMap<String, (Exploitation, bool)> {
|
|
|
|
|
let kev = self.kev_catalog().await;
|
|
|
|
|
if kev.is_none() {
|
|
|
|
|
failed.push("KEV");
|
|
|
|
|
}
|
|
|
|
|
let (epss, epss_answered) = self.epss(cves).await;
|
|
|
|
|
if epss_answered.len() < cves.len() {
|
|
|
|
|
failed.push("EPSS");
|
|
|
|
|
}
|
|
|
|
|
let ssvc = self.ssvc(cves).await;
|
|
|
|
|
if ssvc.len() < cves.len() {
|
|
|
|
|
failed.push("Vulnrichment");
|
|
|
|
|
}
|
|
|
|
|
cves.iter()
|
|
|
|
|
ids.into_iter()
|
|
|
|
|
.map(|id| {
|
|
|
|
|
let cached = answers.remove(&id).unwrap_or_default();
|
|
|
|
|
let exploitation = Exploitation {
|
|
|
|
|
kev: kev.as_ref().and_then(|k| k.get(id).cloned()),
|
|
|
|
|
epss: epss.get(id).cloned(),
|
|
|
|
|
ssvc_exploitation: ssvc.get(id).cloned().flatten(),
|
|
|
|
|
kev: kev.as_ref().and_then(|k| k.get(&id).cloned()),
|
|
|
|
|
epss: cached.epss,
|
|
|
|
|
ssvc_exploitation: cached.ssvc_exploitation,
|
|
|
|
|
};
|
|
|
|
|
let complete = kev.is_some() && epss_answered.contains(id) && ssvc.contains_key(id);
|
|
|
|
|
(id.clone(), (exploitation, complete))
|
|
|
|
|
(id, exploitation)
|
|
|
|
|
})
|
|
|
|
|
.collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Today's KEV catalog: from the cache, or read and cached.
|
|
|
|
|
/// Ask EPSS and Vulnrichment about the CVEs in `pending` that `known`
|
|
|
|
|
/// has no answer of theirs for. Returns what was answered, per CVE.
|
|
|
|
|
async fn fetch(
|
|
|
|
|
&self,
|
|
|
|
|
pending: &[String],
|
|
|
|
|
known: &HashMap<String, CveAnswers>,
|
|
|
|
|
failed: &mut Vec<&'static str>,
|
|
|
|
|
) -> Vec<(String, CveAnswers)> {
|
|
|
|
|
let unanswered = |answered: fn(&CveAnswers) -> bool| -> Vec<String> {
|
|
|
|
|
pending
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|id| !known.get(*id).is_some_and(answered))
|
|
|
|
|
.cloned()
|
|
|
|
|
.collect()
|
|
|
|
|
};
|
|
|
|
|
let need_epss = unanswered(|a| a.epss_answered);
|
|
|
|
|
let need_ssvc = unanswered(|a| a.ssvc_answered);
|
|
|
|
|
let (mut epss, epss_answered) = self.epss(&need_epss).await;
|
|
|
|
|
if epss_answered.len() < need_epss.len() {
|
|
|
|
|
failed.push("EPSS");
|
|
|
|
|
}
|
|
|
|
|
let mut ssvc = self.ssvc(&need_ssvc).await;
|
|
|
|
|
if ssvc.len() < need_ssvc.len() {
|
|
|
|
|
failed.push("Vulnrichment");
|
|
|
|
|
}
|
|
|
|
|
pending
|
|
|
|
|
.iter()
|
|
|
|
|
.filter_map(|id| {
|
|
|
|
|
let ssvc_answer = ssvc.remove(id);
|
|
|
|
|
let answers = CveAnswers {
|
|
|
|
|
epss_answered: epss_answered.contains(id),
|
|
|
|
|
epss: epss.remove(id),
|
|
|
|
|
ssvc_answered: ssvc_answer.is_some(),
|
|
|
|
|
ssvc_exploitation: ssvc_answer.flatten(),
|
|
|
|
|
};
|
|
|
|
|
(answers.epss_answered || answers.ssvc_answered).then(|| (id.clone(), answers))
|
|
|
|
|
})
|
|
|
|
|
.collect()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Today's KEV catalog: from the cache, or read from the first source
|
|
|
|
|
/// that answers and cached.
|
|
|
|
|
async fn kev_catalog(&self) -> Option<KevCatalog> {
|
|
|
|
|
if let Some(cache) = &self.cache {
|
|
|
|
|
match cache.kev().await {
|
|
|
|
@@ -284,33 +349,34 @@ impl CveEnricher {
|
|
|
|
|
Err(e) => tracing::warn!("KEV cache unreadable: {e}"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let catalog = async {
|
|
|
|
|
let resp = self
|
|
|
|
|
.http
|
|
|
|
|
.get(&self.kev_url)?
|
|
|
|
|
.send()
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.error_for_status()
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let body: serde_json::Value = read_json(resp).await?;
|
|
|
|
|
parse_kev(&body)
|
|
|
|
|
}
|
|
|
|
|
.await;
|
|
|
|
|
match catalog {
|
|
|
|
|
Ok(catalog) => {
|
|
|
|
|
if let Some(cache) = &self.cache {
|
|
|
|
|
if let Err(e) = cache.put_kev(&catalog).await {
|
|
|
|
|
tracing::warn!("KEV cache not written: {e}");
|
|
|
|
|
for url in &self.kev_urls {
|
|
|
|
|
match self.read_kev(url).await {
|
|
|
|
|
Ok(catalog) => {
|
|
|
|
|
if let Some(cache) = &self.cache {
|
|
|
|
|
if let Err(e) = cache.put_kev(&catalog).await {
|
|
|
|
|
tracing::warn!("KEV cache not written: {e}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return Some(catalog);
|
|
|
|
|
}
|
|
|
|
|
Some(catalog)
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
tracing::warn!("KEV catalog not read: {e}");
|
|
|
|
|
None
|
|
|
|
|
Err(e) => tracing::warn!("KEV catalog not read from {url}: {e}"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The KEV catalog at `url`.
|
|
|
|
|
async fn read_kev(&self, url: &str) -> Result<KevCatalog, String> {
|
|
|
|
|
let resp = self
|
|
|
|
|
.http
|
|
|
|
|
.get(url)?
|
|
|
|
|
.send()
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.error_for_status()
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let body: serde_json::Value = read_json(resp).await?;
|
|
|
|
|
parse_kev(&body)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The EPSS scores of `cves`, and the CVEs FIRST answered for (with or
|
|
|
|
@@ -521,23 +587,24 @@ const CACHE_TTL: Duration = Duration::from_secs(24 * 3600);
|
|
|
|
|
|
|
|
|
|
/// The cache in the cluster-wide admin database (`<prefix>__admin`), shared
|
|
|
|
|
/// by every tenant: public data keyed by CVE id, with nothing of the tenant
|
|
|
|
|
/// that asked. Two collections: `cve_exploitation` (one row per CVE) and
|
|
|
|
|
/// `cisa_kev` (the catalog, one row). Mongo's TTL monitor removes a row a day
|
|
|
|
|
/// after it was written.
|
|
|
|
|
/// that asked. Two collections: `cve_exploitation` (one row per CVE, EPSS
|
|
|
|
|
/// and SSVC) and `cisa_kev` (the catalog, one row). Mongo's TTL monitor
|
|
|
|
|
/// removes a row a day after it was first written.
|
|
|
|
|
pub(crate) struct MongoExploitCache {
|
|
|
|
|
rows: mongodb::Collection<CachedExploitation>,
|
|
|
|
|
kev: mongodb::Collection<CachedKev>,
|
|
|
|
|
indexed: tokio::sync::OnceCell<()>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// One cached answer.
|
|
|
|
|
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
|
|
|
|
/// One cached row. A row written before the sources were cached on their
|
|
|
|
|
/// own has no `*_answered` field and is asked again.
|
|
|
|
|
#[derive(Debug, serde::Deserialize)]
|
|
|
|
|
struct CachedExploitation {
|
|
|
|
|
/// The CVE id.
|
|
|
|
|
#[serde(rename = "_id")]
|
|
|
|
|
cve: String,
|
|
|
|
|
exploitation: Exploitation,
|
|
|
|
|
expires_at: mongodb::bson::DateTime,
|
|
|
|
|
#[serde(flatten)]
|
|
|
|
|
answers: CveAnswers,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The cached KEV catalog.
|
|
|
|
@@ -597,7 +664,7 @@ impl MongoExploitCache {
|
|
|
|
|
mongodb::bson::DateTime::from_system_time(std::time::SystemTime::now() + CACHE_TTL)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn read(&self, cves: &[String]) -> Result<HashMap<String, Exploitation>, String> {
|
|
|
|
|
async fn read(&self, cves: &[String]) -> Result<HashMap<String, CveAnswers>, String> {
|
|
|
|
|
let mut cursor = self
|
|
|
|
|
.rows
|
|
|
|
|
.find(mongodb::bson::doc! {
|
|
|
|
@@ -610,22 +677,53 @@ impl MongoExploitCache {
|
|
|
|
|
let mut out = HashMap::new();
|
|
|
|
|
while let Some(row) = cursor.next().await {
|
|
|
|
|
let row = row.map_err(|e| e.to_string())?;
|
|
|
|
|
out.insert(row.cve, row.exploitation);
|
|
|
|
|
out.insert(row.cve, row.answers);
|
|
|
|
|
}
|
|
|
|
|
Ok(out)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn write(&self, answers: &[(String, Exploitation)]) -> Result<(), String> {
|
|
|
|
|
async fn write(&self, answers: &[(String, CveAnswers)]) -> Result<(), String> {
|
|
|
|
|
self.ensure_index().await?;
|
|
|
|
|
let expires_at = Self::expiry();
|
|
|
|
|
for (cve, exploitation) in answers {
|
|
|
|
|
let row = CachedExploitation {
|
|
|
|
|
cve: cve.clone(),
|
|
|
|
|
exploitation: exploitation.clone(),
|
|
|
|
|
expires_at,
|
|
|
|
|
for (cve, answers) in answers {
|
|
|
|
|
// Only the sources that answered: another source's stored answer
|
|
|
|
|
// stays, and the row keeps the expiry of its first write.
|
|
|
|
|
let mut set = mongodb::bson::Document::new();
|
|
|
|
|
let mut unset = mongodb::bson::Document::new();
|
|
|
|
|
if answers.epss_answered {
|
|
|
|
|
set.insert("epss_answered", true);
|
|
|
|
|
match &answers.epss {
|
|
|
|
|
Some(score) => {
|
|
|
|
|
set.insert(
|
|
|
|
|
"epss",
|
|
|
|
|
mongodb::bson::to_bson(score).map_err(|e| e.to_string())?,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
unset.insert("epss", "");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if answers.ssvc_answered {
|
|
|
|
|
set.insert("ssvc_answered", true);
|
|
|
|
|
match &answers.ssvc_exploitation {
|
|
|
|
|
Some(value) => {
|
|
|
|
|
set.insert("ssvc_exploitation", value);
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
unset.insert("ssvc_exploitation", "");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let mut update = mongodb::bson::doc! {
|
|
|
|
|
"$set": set,
|
|
|
|
|
"$setOnInsert": { "expires_at": expires_at },
|
|
|
|
|
};
|
|
|
|
|
if !unset.is_empty() {
|
|
|
|
|
update.insert("$unset", unset);
|
|
|
|
|
}
|
|
|
|
|
self.rows
|
|
|
|
|
.replace_one(mongodb::bson::doc! { "_id": &row.cve }, &row)
|
|
|
|
|
.update_one(mongodb::bson::doc! { "_id": cve }, update)
|
|
|
|
|
.upsert(true)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
@@ -665,14 +763,11 @@ impl ExploitCache for MongoExploitCache {
|
|
|
|
|
fn get_many<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
cves: &'a [String],
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, Exploitation>, String>> {
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, CveAnswers>, String>> {
|
|
|
|
|
Box::pin(self.read(cves))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn put<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
answers: &'a [(String, Exploitation)],
|
|
|
|
|
) -> BoxFuture<'a, Result<(), String>> {
|
|
|
|
|
fn put<'a>(&'a self, answers: &'a [(String, CveAnswers)]) -> BoxFuture<'a, Result<(), String>> {
|
|
|
|
|
Box::pin(self.write(answers))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@@ -699,12 +794,36 @@ mod tests {
|
|
|
|
|
const VULNRICHMENT_FIXTURE: &str =
|
|
|
|
|
include_str!("../../tests/fixtures/exploitation/CVE-2021-44228.json");
|
|
|
|
|
|
|
|
|
|
/// The requests each stand-in answered.
|
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
|
struct Hits {
|
|
|
|
|
kev: Arc<AtomicUsize>,
|
|
|
|
|
epss: Arc<AtomicUsize>,
|
|
|
|
|
vulnrichment: Arc<AtomicUsize>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Hits {
|
|
|
|
|
/// (KEV, EPSS, Vulnrichment) requests so far.
|
|
|
|
|
fn get(&self) -> (usize, usize, usize) {
|
|
|
|
|
(
|
|
|
|
|
self.kev.load(Ordering::SeqCst),
|
|
|
|
|
self.epss.load(Ordering::SeqCst),
|
|
|
|
|
self.vulnrichment.load(Ordering::SeqCst),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Stand-ins for KEV, EPSS and Vulnrichment on loopback, answering from
|
|
|
|
|
/// the fixtures; they count the requests. With `epss_down`, EPSS answers
|
|
|
|
|
/// 503.
|
|
|
|
|
async fn fake_sources(epss_down: bool) -> (String, Arc<AtomicUsize>) {
|
|
|
|
|
let hits = Arc::new(AtomicUsize::new(0));
|
|
|
|
|
let (h1, h2, h3) = (hits.clone(), hits.clone(), hits.clone());
|
|
|
|
|
/// 503. `/kev-blocked.json` answers 403, as www.cisa.gov does to many
|
|
|
|
|
/// datacenters.
|
|
|
|
|
async fn fake_sources(epss_down: bool) -> (String, Hits) {
|
|
|
|
|
let hits = Hits::default();
|
|
|
|
|
let (h1, h2, h3) = (
|
|
|
|
|
hits.kev.clone(),
|
|
|
|
|
hits.epss.clone(),
|
|
|
|
|
hits.vulnrichment.clone(),
|
|
|
|
|
);
|
|
|
|
|
let app = axum::Router::new()
|
|
|
|
|
.route(
|
|
|
|
|
"/kev.json",
|
|
|
|
@@ -713,6 +832,10 @@ mod tests {
|
|
|
|
|
async { KEV_FIXTURE }
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.route(
|
|
|
|
|
"/kev-blocked.json",
|
|
|
|
|
axum::routing::get(|| async { axum::http::StatusCode::FORBIDDEN }),
|
|
|
|
|
)
|
|
|
|
|
.route(
|
|
|
|
|
"/epss",
|
|
|
|
|
axum::routing::get(move || {
|
|
|
|
@@ -746,7 +869,7 @@ mod tests {
|
|
|
|
|
/// A cache in memory.
|
|
|
|
|
#[derive(Default)]
|
|
|
|
|
struct MemoryCache {
|
|
|
|
|
rows: Mutex<HashMap<String, Exploitation>>,
|
|
|
|
|
rows: Mutex<HashMap<String, CveAnswers>>,
|
|
|
|
|
kev: Mutex<Option<KevCatalog>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@@ -754,7 +877,7 @@ mod tests {
|
|
|
|
|
fn get_many<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
cves: &'a [String],
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, Exploitation>, String>> {
|
|
|
|
|
) -> BoxFuture<'a, Result<HashMap<String, CveAnswers>, String>> {
|
|
|
|
|
let rows = self.rows.lock().unwrap();
|
|
|
|
|
let out = cves
|
|
|
|
|
.iter()
|
|
|
|
@@ -764,9 +887,12 @@ mod tests {
|
|
|
|
|
}
|
|
|
|
|
fn put<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
answers: &'a [(String, Exploitation)],
|
|
|
|
|
answers: &'a [(String, CveAnswers)],
|
|
|
|
|
) -> BoxFuture<'a, Result<(), String>> {
|
|
|
|
|
self.rows.lock().unwrap().extend(answers.iter().cloned());
|
|
|
|
|
let mut rows = self.rows.lock().unwrap();
|
|
|
|
|
for (id, answers) in answers {
|
|
|
|
|
rows.entry(id.clone()).or_default().merge(answers);
|
|
|
|
|
}
|
|
|
|
|
Box::pin(async { Ok(()) })
|
|
|
|
|
}
|
|
|
|
|
fn kev(&self) -> BoxFuture<'_, Result<Option<KevCatalog>, String>> {
|
|
|
|
@@ -917,25 +1043,25 @@ mod tests {
|
|
|
|
|
entries[0].known_vulnerabilities[0].exploitation.as_ref(),
|
|
|
|
|
Some(log4j)
|
|
|
|
|
);
|
|
|
|
|
// KEV, one EPSS batch, two Vulnrichment records (one a 404).
|
|
|
|
|
let first = hits.load(Ordering::SeqCst);
|
|
|
|
|
assert_eq!(first, 3, "the 404 is not counted by the route");
|
|
|
|
|
// KEV, one EPSS batch, two Vulnrichment records (the 404 is not
|
|
|
|
|
// counted by the route).
|
|
|
|
|
assert_eq!(hits.get(), (1, 1, 1));
|
|
|
|
|
|
|
|
|
|
// Another scan the same day asks nobody.
|
|
|
|
|
let mut again = vec![alert("CVE-2021-44228", &[])];
|
|
|
|
|
let counts = enricher.enrich(&mut again, &mut []).await;
|
|
|
|
|
assert_eq!(counts.cached, 1);
|
|
|
|
|
assert_eq!(hits.load(Ordering::SeqCst), first);
|
|
|
|
|
assert_eq!(hits.get(), (1, 1, 1));
|
|
|
|
|
assert!(again[0].exploitation.as_ref().unwrap().kev.is_some());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn a_failed_source_is_left_unknown_and_not_cached() {
|
|
|
|
|
let (base, _) = fake_sources(true).await;
|
|
|
|
|
async fn a_failed_source_is_asked_again_and_the_others_are_kept() {
|
|
|
|
|
let (down, down_hits) = fake_sources(true).await;
|
|
|
|
|
let cache = Arc::new(MemoryCache::default());
|
|
|
|
|
let enricher = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone()))
|
|
|
|
|
.unwrap()
|
|
|
|
|
.with_base(&base);
|
|
|
|
|
.with_base(&down);
|
|
|
|
|
let mut alerts = vec![alert("CVE-2021-44228", &[])];
|
|
|
|
|
|
|
|
|
|
let counts = enricher.enrich(&mut alerts, &mut []).await;
|
|
|
|
@@ -943,9 +1069,168 @@ mod tests {
|
|
|
|
|
assert_eq!(counts.failed, ["EPSS"]);
|
|
|
|
|
let e = alerts[0].exploitation.as_ref().unwrap();
|
|
|
|
|
assert!(e.kev.is_some() && e.epss.is_none());
|
|
|
|
|
// Not cached, so the next run asks EPSS again; the KEV catalog is.
|
|
|
|
|
assert!(cache.rows.lock().unwrap().is_empty());
|
|
|
|
|
assert_eq!(e.ssvc_exploitation.as_deref(), Some("active"));
|
|
|
|
|
// SSVC and the KEV catalog are cached; EPSS is not.
|
|
|
|
|
let row = cache.rows.lock().unwrap()["CVE-2021-44228"].clone();
|
|
|
|
|
assert!(row.ssvc_answered && !row.epss_answered);
|
|
|
|
|
assert!(cache.kev.lock().unwrap().is_some());
|
|
|
|
|
assert_eq!(down_hits.get(), (1, 1, 1));
|
|
|
|
|
|
|
|
|
|
// The next run asks only EPSS.
|
|
|
|
|
let (up, up_hits) = fake_sources(false).await;
|
|
|
|
|
let enricher = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone()))
|
|
|
|
|
.unwrap()
|
|
|
|
|
.with_base(&up);
|
|
|
|
|
let mut again = vec![alert("CVE-2021-44228", &[])];
|
|
|
|
|
let counts = enricher.enrich(&mut again, &mut []).await;
|
|
|
|
|
assert!(counts.failed.is_empty(), "{:?}", counts.failed);
|
|
|
|
|
assert_eq!(up_hits.get(), (0, 1, 0));
|
|
|
|
|
let e = again[0].exploitation.as_ref().unwrap();
|
|
|
|
|
assert!(e.kev.is_some() && e.epss.is_some());
|
|
|
|
|
assert_eq!(e.ssvc_exploitation.as_deref(), Some("active"));
|
|
|
|
|
assert!(cache.rows.lock().unwrap()["CVE-2021-44228"].complete());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn a_blocked_kev_source_falls_back_and_never_drops_the_others() {
|
|
|
|
|
let (base, hits) = fake_sources(false).await;
|
|
|
|
|
let cache = Arc::new(MemoryCache::default());
|
|
|
|
|
|
|
|
|
|
// Every KEV source blocked: EPSS and SSVC are still cached.
|
|
|
|
|
let mut blocked = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone()))
|
|
|
|
|
.unwrap()
|
|
|
|
|
.with_base(&base);
|
|
|
|
|
blocked.kev_urls = vec![format!("{base}/kev-blocked.json")];
|
|
|
|
|
let mut alerts = vec![alert("CVE-2021-44228", &[])];
|
|
|
|
|
let counts = blocked.enrich(&mut alerts, &mut []).await;
|
|
|
|
|
assert_eq!(counts.failed, ["KEV"]);
|
|
|
|
|
let e = alerts[0].exploitation.as_ref().unwrap();
|
|
|
|
|
assert!(e.kev.is_none() && e.epss.is_some());
|
|
|
|
|
assert!(cache.rows.lock().unwrap()["CVE-2021-44228"].complete());
|
|
|
|
|
|
|
|
|
|
// The first source blocked, the second answers; nothing else is
|
|
|
|
|
// asked again.
|
|
|
|
|
let mut fallback = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone()))
|
|
|
|
|
.unwrap()
|
|
|
|
|
.with_base(&base);
|
|
|
|
|
fallback.kev_urls = vec![
|
|
|
|
|
format!("{base}/kev-blocked.json"),
|
|
|
|
|
format!("{base}/kev.json"),
|
|
|
|
|
];
|
|
|
|
|
let mut again = vec![alert("CVE-2021-44228", &[])];
|
|
|
|
|
let counts = fallback.enrich(&mut again, &mut []).await;
|
|
|
|
|
assert!(counts.failed.is_empty(), "{:?}", counts.failed);
|
|
|
|
|
assert_eq!((counts.cached, counts.kev), (1, 1));
|
|
|
|
|
assert_eq!(hits.get(), (1, 1, 1));
|
|
|
|
|
assert!(again[0].exploitation.as_ref().unwrap().kev.is_some());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_merge_keeps_what_the_newer_answer_lacks() {
|
|
|
|
|
let mut stored = CveAnswers {
|
|
|
|
|
ssvc_answered: true,
|
|
|
|
|
ssvc_exploitation: Some("poc".into()),
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
};
|
|
|
|
|
stored.merge(&CveAnswers {
|
|
|
|
|
epss_answered: true,
|
|
|
|
|
epss: None,
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
});
|
|
|
|
|
assert!(stored.complete());
|
|
|
|
|
assert_eq!(stored.ssvc_exploitation.as_deref(), Some("poc"));
|
|
|
|
|
stored.merge(&CveAnswers {
|
|
|
|
|
ssvc_answered: true,
|
|
|
|
|
ssvc_exploitation: None,
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
});
|
|
|
|
|
assert_eq!(stored.ssvc_exploitation, None);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn the_mongo_cache_merges_sources_and_keeps_the_first_expiry() {
|
|
|
|
|
let uri = std::env::var("TEST_MONGODB_URI")
|
|
|
|
|
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
|
|
|
|
let Ok(client) = mongodb::Client::with_uri_str(&uri).await else {
|
|
|
|
|
eprintln!("SKIP cve_enrichment: bad MongoDB URI {uri}");
|
|
|
|
|
return;
|
|
|
|
|
};
|
|
|
|
|
let name = format!("cvexp_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
|
|
|
|
let db = client.database(&name);
|
|
|
|
|
let ping = db.run_command(mongodb::bson::doc! { "ping": 1 });
|
|
|
|
|
if !matches!(
|
|
|
|
|
tokio::time::timeout(Duration::from_secs(3), ping).await,
|
|
|
|
|
Ok(Ok(_))
|
|
|
|
|
) {
|
|
|
|
|
eprintln!("SKIP cve_enrichment: no MongoDB reachable at {uri}");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
let cache = MongoExploitCache::new(&db);
|
|
|
|
|
let id = "CVE-2021-44228".to_string();
|
|
|
|
|
let expiry = || async {
|
|
|
|
|
db.collection::<mongodb::bson::Document>(MongoExploitCache::COLLECTION)
|
|
|
|
|
.find_one(mongodb::bson::doc! { "_id": "CVE-2021-44228" })
|
|
|
|
|
.await
|
|
|
|
|
.unwrap()
|
|
|
|
|
.unwrap()
|
|
|
|
|
.get_datetime("expires_at")
|
|
|
|
|
.copied()
|
|
|
|
|
.unwrap()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// SSVC first, EPSS failed.
|
|
|
|
|
let ssvc = CveAnswers {
|
|
|
|
|
ssvc_answered: true,
|
|
|
|
|
ssvc_exploitation: Some("active".into()),
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
};
|
|
|
|
|
cache.write(&[(id.clone(), ssvc)]).await.unwrap();
|
|
|
|
|
let first_expiry = expiry().await;
|
|
|
|
|
let row = cache.read(std::slice::from_ref(&id)).await.unwrap()[&id].clone();
|
|
|
|
|
assert!(row.ssvc_answered && !row.epss_answered);
|
|
|
|
|
|
|
|
|
|
// EPSS on a later run: SSVC stays, the expiry too.
|
|
|
|
|
let score = EpssScore {
|
|
|
|
|
score: 0.94,
|
|
|
|
|
percentile: 0.99,
|
|
|
|
|
date: "2026-10-06".into(),
|
|
|
|
|
};
|
|
|
|
|
let epss = CveAnswers {
|
|
|
|
|
epss_answered: true,
|
|
|
|
|
epss: Some(score.clone()),
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
};
|
|
|
|
|
cache.write(&[(id.clone(), epss)]).await.unwrap();
|
|
|
|
|
let row = cache.read(std::slice::from_ref(&id)).await.unwrap()[&id].clone();
|
|
|
|
|
assert!(row.complete());
|
|
|
|
|
assert_eq!(row.epss, Some(score));
|
|
|
|
|
assert_eq!(row.ssvc_exploitation.as_deref(), Some("active"));
|
|
|
|
|
assert_eq!(expiry().await, first_expiry);
|
|
|
|
|
|
|
|
|
|
// An answer without a score removes the stored score.
|
|
|
|
|
let no_score = CveAnswers {
|
|
|
|
|
epss_answered: true,
|
|
|
|
|
..CveAnswers::default()
|
|
|
|
|
};
|
|
|
|
|
cache.write(&[(id.clone(), no_score)]).await.unwrap();
|
|
|
|
|
let row = cache.read(std::slice::from_ref(&id)).await.unwrap()[&id].clone();
|
|
|
|
|
assert_eq!(row.epss, None);
|
|
|
|
|
assert_eq!(row.ssvc_exploitation.as_deref(), Some("active"));
|
|
|
|
|
|
|
|
|
|
db.drop().await.unwrap();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn a_row_from_before_is_asked_again() {
|
|
|
|
|
// Written when a row held one combined answer.
|
|
|
|
|
let old = mongodb::bson::doc! {
|
|
|
|
|
"_id": "CVE-2021-44228",
|
|
|
|
|
"exploitation": { "ssvc_exploitation": "active" },
|
|
|
|
|
"expires_at": mongodb::bson::DateTime::now(),
|
|
|
|
|
};
|
|
|
|
|
let row: CachedExploitation = mongodb::bson::from_document(old).unwrap();
|
|
|
|
|
assert_eq!(row.cve, "CVE-2021-44228");
|
|
|
|
|
assert!(!row.answers.epss_answered && !row.answers.ssvc_answered);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
@@ -958,7 +1243,7 @@ mod tests {
|
|
|
|
|
|
|
|
|
|
let counts = enricher.enrich(&mut alerts, &mut []).await;
|
|
|
|
|
|
|
|
|
|
assert_eq!(hits.load(Ordering::SeqCst), 0, "a request reached it");
|
|
|
|
|
assert_eq!(hits.get(), (0, 0, 0), "a request reached it");
|
|
|
|
|
assert!(alerts[0].exploitation.is_none());
|
|
|
|
|
assert_eq!(counts.failed, ["KEV", "EPSS", "Vulnrichment"]);
|
|
|
|
|
}
|
|
|
|
@@ -972,6 +1257,6 @@ mod tests {
|
|
|
|
|
let mut alerts = vec![alert("GHSA-xxxx-yyyy-zzzz", &[])];
|
|
|
|
|
let counts = enricher.enrich(&mut alerts, &mut []).await;
|
|
|
|
|
assert_eq!(counts.cves, 0);
|
|
|
|
|
assert_eq!(hits.load(Ordering::SeqCst), 0);
|
|
|
|
|
assert_eq!(hits.get(), (0, 0, 0));
|
|
|
|
|
}
|
|
|
|
|
}
|