From ad1394af4f1dd85511bfe8cd07f2deccc3b37e2f Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 6 Oct 2026 20:50:24 +0200 Subject: [PATCH] fix(cve): KEV from CISA's GitHub mirror, exploitation cached per source (#493) On stage and prod www.cisa.gov answers 403 to the datacenter, so the KEV catalog was never read. Since a CVE's row was cached only when KEV, EPSS and Vulnrichment all answered, cve_exploitation stayed empty and every scan asked EPSS and Vulnrichment again. - KEV is read from CISA's mirror cisagov/kev-data on raw.githubusercontent.com (same feed, CC0), with www.cisa.gov as the fallback. - KEV is applied from the cached catalog on every run and no longer stored per CVE. A cve_exploitation row keeps EPSS and SSVC, each with an *_answered flag, merged with $set so a later answer keeps the other's. A source that failed is asked again alone; a row expires a day after its first write. Rows from before have no flag and are asked again. - Tests: KEV fallback after a 403, a blocked KEV that keeps EPSS and SSVC, a retry that asks only EPSS, the merge, old rows, and the Mongo write path (skipped without Mongo). - Docs: tools reference (source and egress rows), test plan check 19. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .../src/pipeline/cve_enrichment.rs | 559 +++++++++++++----- docs/reference/tools.md | 6 +- .../release/staging-test-plan-after-v0.4.5.md | 9 +- 3 files changed, 431 insertions(+), 143 deletions(-) diff --git a/compliance-agent/src/pipeline/cve_enrichment.rs b/compliance-agent/src/pipeline/cve_enrichment.rs index 90a03d4..bae1d6c 100644 --- a/compliance-agent/src/pipeline/cve_enrichment.rs +++ b/compliance-agent/src/pipeline/cve_enrichment.rs @@ -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; +/// 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, + /// 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, +} + +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, String>>; - /// Keep `answers` for a day. - fn put<'a>( - &'a self, - answers: &'a [(String, Exploitation)], - ) -> BoxFuture<'a, Result<(), String>>; + ) -> BoxFuture<'a, Result, 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, String>>; /// Keep the KEV catalog for a day. @@ -106,7 +149,7 @@ pub(crate) struct CveEnricher { http: PublicHttp, cache: Option>, enabled: bool, - kev_url: String, + kev_urls: Vec, 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, counts: &mut EnrichCounts, ) -> HashMap { let ids: Vec = 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 = ids - .into_iter() - .filter(|id| !found.contains_key(id)) + counts.cached = answers.values().filter(|a| a.complete()).count(); + let mut pending: Vec = 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 { - 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, + failed: &mut Vec<&'static str>, + ) -> Vec<(String, CveAnswers)> { + let unanswered = |answered: fn(&CveAnswers) -> bool| -> Vec { + 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 { 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 { + 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 (`__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, kev: mongodb::Collection, 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, String> { + async fn read(&self, cves: &[String]) -> Result, 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, String>> { + ) -> BoxFuture<'a, Result, 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, + epss: Arc, + vulnrichment: Arc, + } + + 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) { - 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>, + rows: Mutex>, kev: Mutex>, } @@ -754,7 +877,7 @@ mod tests { fn get_many<'a>( &'a self, cves: &'a [String], - ) -> BoxFuture<'a, Result, String>> { + ) -> BoxFuture<'a, Result, 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, 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::(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)); } } diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 5840581..2dec937 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -196,7 +196,7 @@ Every CVE alert is enriched with what is known about its exploitation, after the | Source | What it says | Licence | How it is read | |---|---|---|---| -| [CISA Known Exploited Vulnerabilities (KEV)](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) | the CVE is exploited in the wild; the date CISA added it; known use in ransomware campaigns | CC0 1.0 | the whole catalog (one JSON file, about 2 MB), at most once a day | +| [CISA Known Exploited Vulnerabilities (KEV)](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) | the CVE is exploited in the wild; the date CISA added it; known use in ransomware campaigns | CC0 1.0 | the whole catalog (one JSON file, about 2 MB), at most once a day: from CISA's mirror on GitHub ([cisagov/kev-data](https://github.com/cisagov/kev-data)), else from `www.cisa.gov`, which refuses many datacenter addresses | | [FIRST EPSS](https://www.first.org/epss) | the probability that the CVE is exploited in the next 30 days, and its percentile | free to use; FIRST asks for attribution | FIRST's API, up to 50 CVE ids per request | | [CISA Vulnrichment](https://github.com/cisagov/vulnrichment) | the SSVC decision point *Exploitation* (`none`, `poc`, `active`) | CC0 1.0 | the CVE's record in the GitHub repository (`/xxx/CVE-….json`); a CVE CISA has not rated is a 404 | @@ -386,8 +386,8 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie |---|---|---|---|---|---| | `api.osv.dev` (`/v1/querybatch`, `/v1/vulns/{id}`) | purls of SBOM components, advisory ids | `pipeline/cve.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB, 8 advisory reads at once | none (CVE stage) | | `services.nvd.nist.gov` (`/rest/json/cves/2.0`) | CVE ids (CVSS score), CPE product prefixes (CODESYS, embedded libraries) | `pipeline/cve.rs`, `pipeline/nvd_cpe.rs` | guarded | 30 s per request, 5 s connect, body ≤ 16 MiB, 3 retries after 6/12/24 s, answers cached 6 h | `NVD_API_KEY` (optional, raises NVD's rate limit) | -| `www.cisa.gov` (`/sites/default/files/feeds/known_exploited_vulnerabilities.json`) | nothing (a GET of the public catalog) | `pipeline/cve_enrichment.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB; at most once a day (cached for all tenants) | `CVE_EXPLOIT_LOOKUP=false` | -| `api.first.org` (`/data/v1/epss`) | CVE ids of the alerts | `pipeline/cve_enrichment.rs` | guarded | as above, 50 CVE ids per request, 500 uncached CVEs and 2 min per scan; answers cached a day | `CVE_EXPLOIT_LOOKUP=false` | +| `raw.githubusercontent.com` (`/cisagov/kev-data/develop/known_exploited_vulnerabilities.json`), else `www.cisa.gov` (`/sites/default/files/feeds/known_exploited_vulnerabilities.json`) | nothing (a GET of the public KEV catalog) | `pipeline/cve_enrichment.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB; at most once a day (cached for all tenants) | `CVE_EXPLOIT_LOOKUP=false` | +| `api.first.org` (`/data/v1/epss`) | CVE ids of the alerts | `pipeline/cve_enrichment.rs` | guarded | as above, 50 CVE ids per request, 500 uncached CVEs and 2 min per scan; answers cached a day per source (EPSS and Vulnrichment apart, so one that fails is asked again alone) | `CVE_EXPLOIT_LOOKUP=false` | | `raw.githubusercontent.com` (`/cisagov/vulnrichment/develop/…`) | CVE ids of the alerts (in the path) | `pipeline/cve_enrichment.rs` | guarded | as above, 8 at once | `CVE_EXPLOIT_LOOKUP=false` | | `api.nuget.org` (registration, catalog) | NuGet package ids and versions, not for ids a `nuget.config` routes to another feed | `pipeline/sbom/nuget_license.rs` | guarded | 10 s per request, 5 s connect, body ≤ 2 MiB, 8 at once, 60 s and 300 uncached packages per scan | `NUGET_LICENSE_LOOKUP=false` | | `registry.npmjs.org` | npm package names and versions, not for a registry or scope `.npmrc`/`.yarnrc.yml` routes elsewhere | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org (bounds per scan; answers cached for all tenants) | `REGISTRY_LICENSE_LOOKUP=false` | diff --git a/docs/release/staging-test-plan-after-v0.4.5.md b/docs/release/staging-test-plan-after-v0.4.5.md index 919b592..c61e1ab 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -64,7 +64,7 @@ and the same agent image (`8ea3731`) locally with the fixtures of this plan. | 16 | PASS | Locally, `Serilog 2.10.0` from `App/App.csproj (transitive, nuget.org)`, Apache-2.0; one `sbom_dependencies` entry naming only the private-feed project; log line present. | | 17 | PASS | Locally, the npm and Maven components get licences; with an `.npmrc` scope and a private Maven repository `@corp/util` and every Maven component stay without one, log `Maven licenses not looked up`. The fixture path is now `fixtures/nightly/eco/js-npm-lock-v3`. | | 18 | PASS | Stage Mongo: findings with `legacy_fingerprints` kept their rows. | -| 19 | PASS / NEEDS USER | Locally, CVE-2021-44228 has KEV (ransomware), EPSS 0.99999, SSVC active. Stage fills `cve_exploitation` with the daily CVE monitor (00:00). Look at: the badges. | +| 19 | FAIL, fixed / NEEDS USER | Locally, CVE-2021-44228 has KEV (ransomware), EPSS 0.99999, SSVC active. On stage `www.cisa.gov` answers 403 to the datacenter, so KEV failed and, since a CVE was only cached when all three sources answered, `cve_exploitation` stayed empty. Fixed: KEV from CISA's GitHub mirror, each source cached on its own. Look at: the badges. | | 20 | NEEDS USER | Edit and re-export a PLC project, then rescan. | | 21 | PASS / NEEDS USER | Locally, the hardening, HEX, signature and reference texts are as written, and the ASLR/RELRO findings have cra-ai-1 and the HEX finding cra-ai-6. Six files group into one inventory finding (#477), so the check now uploads five. Look at: a native unsigned DLL. | | 22 | PASS | Locally: 422 without a justification or action; OpenVEX, CycloneDX VEX and the SBOM validate against the schemas; after the update to log4j 2.17.1 the fixed CVEs are set `fixed` by the scan, and a person's `not_affected` is kept. | @@ -405,8 +405,11 @@ target with history (findings, at least one marked by a person, issues). - **Log:** `CVE exploitation (KEV, EPSS, SSVC)` with `counts` (`cves`, `cached`, `kev`, `epss`, `failed: []`); the second scan reports every CVE as `cached` and makes no request to the three sources. Mongo: - `__admin.cve_exploitation` has one row per CVE, - `__admin.cisa_kev` one row. + `__admin.cve_exploitation` has one row per CVE (`epss_answered`, + `ssvc_answered`), `__admin.cisa_kev` one row. No `KEV catalog not + read` line: KEV comes from CISA's mirror on GitHub (`cisagov/kev-data`), + since `www.cisa.gov` answers 403 to stage and prod. A source that fails + keeps the others' answers; the next scan asks only that source. - **Switch:** `CVE_EXPLOIT_LOOKUP=false` stops the lookups; `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`, `off`) sets the EPSS step-up. - **[visible]** KEV and EPSS badges on the SBOM page; CVE issues for KEV