diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 450b199..8ee1e50 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -47,6 +47,9 @@ pub struct ComplianceAgent { /// NuGet licenses looked up on nuget.org, for every tenant (#467): public /// metadata keyed by package and version, in the admin database. pub(crate) nuget_license_cache: Arc, + /// KEV, EPSS and SSVC answers per CVE, for every tenant (#493): public + /// data keyed by CVE id, in the admin database, kept a day. + pub(crate) exploit_cache: Arc, } impl ComplianceAgent { @@ -75,6 +78,9 @@ impl ComplianceAgent { let nuget_license_cache = Arc::new(crate::pipeline::sbom::MongoLicenseCache::new( &db_pool.admin_db(), )); + let exploit_cache = Arc::new(crate::pipeline::cve_enrichment::MongoExploitCache::new( + &db_pool.admin_db(), + )); Self { config, db_pool, @@ -89,6 +95,7 @@ impl ComplianceAgent { secrets, git_source, nuget_license_cache, + exploit_cache, } } @@ -200,7 +207,8 @@ impl ComplianceAgent { let db = self.db_pool.for_tenant_id(tenant_id).await?; let orchestrator = PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone()) - .with_nuget_license_cache(self.nuget_license_cache.clone()); + .with_nuget_license_cache(self.nuget_license_cache.clone()) + .with_exploit_cache(self.exploit_cache.clone()); let started = chrono::Utc::now(); let scanned = orchestrator.run_target(target_id, trigger.clone()).await?; // Support's scans are ours, not the customer's usage; a scheduled scan diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index 93b604b..c96f570 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use std::fmt; -use compliance_core::models::{Finding, FindingStatus, Severity}; +use compliance_core::models::{Exploitation, Finding, FindingStatus, Severity}; use serde::{Deserialize, Deserializer}; use serde_json::Value; @@ -262,11 +262,16 @@ fn triage_selection( (sent, skipped) } +/// What is known about the exploitation of CVEs (KEV, EPSS, SSVC; #493), by +/// CVE id: a finding that names a CVE gets it in its prompt. +pub type ExploitationContext = HashMap; + /// The prompt for the findings at `chunk`, numbered from 1 in chunk order. fn chunk_prompt( findings: &[Finding], chunk: &[usize], graph_context: Option<&GraphContext>, + exploitation: Option<&ExploitationContext>, ) -> String { let mut user_prompt = String::new(); for (n, &i) in chunk.iter().enumerate() { @@ -287,6 +292,18 @@ fn chunk_prompt( file_classification, )); + // Whether the finding's CVE is exploited in the wild. + if let Some(found) = finding + .cve + .as_deref() + .and_then(|cve| exploitation?.get(cve)) + { + user_prompt.push_str(&format!( + "\nExploitation: {}", + crate::pipeline::cve_enrichment::describe(found) + )); + } + // Enrich with surrounding code context if possible if let Some(context) = read_surrounding_context(finding) { user_prompt.push_str(&format!( @@ -346,8 +363,9 @@ async fn triage_chunk( findings: &[Finding], chunk: &[usize], graph_context: Option<&GraphContext>, + exploitation: Option<&ExploitationContext>, ) -> Result, ModelDown> { - let user_prompt = chunk_prompt(findings, chunk, graph_context); + let user_prompt = chunk_prompt(findings, chunk, graph_context, exploitation); let answer = match model.answer(TRIAGE_SYSTEM_PROMPT, &user_prompt).await { Ok(answer) => answer, Err(e) => { @@ -461,6 +479,7 @@ async fn ask_in_chunks( ask: &[usize], size: usize, graph_context: Option<&GraphContext>, + exploitation: Option<&ExploitationContext>, calls: &mut usize, ) -> (Vec<(usize, TriageResult)>, Option) { let chunks: Vec<&[usize]> = ask.chunks(size.max(1)).collect(); @@ -470,7 +489,7 @@ async fn ask_in_chunks( let answers = futures_util::future::join_all( group .iter() - .map(|chunk| triage_chunk(model, findings, chunk, graph_context)), + .map(|chunk| triage_chunk(model, findings, chunk, graph_context, exploitation)), ) .await; // Every call at once failed: the model is down (or hangs until the @@ -506,6 +525,7 @@ async fn ask_all( findings: &[Finding], sent: &[usize], graph_context: Option<&GraphContext>, + exploitation: Option<&ExploitationContext>, calls: &mut usize, ) -> HashMap { let mut verdicts: HashMap = HashMap::new(); @@ -525,8 +545,16 @@ async fn ask_all( size ); } - let (answered, down) = - ask_in_chunks(model, findings, &ask, *size, graph_context, calls).await; + let (answered, down) = ask_in_chunks( + model, + findings, + &ask, + *size, + graph_context, + exploitation, + calls, + ) + .await; for (i, verdict) in answered { verdicts.entry(i).or_insert(verdict); } @@ -559,6 +587,7 @@ pub async fn triage_findings( model: &M, findings: &mut [Finding], graph_context: Option<&GraphContext>, + exploitation: Option<&ExploitationContext>, ) -> TriageSummary { let mut summary = TriageSummary { findings: findings.len(), @@ -583,7 +612,15 @@ pub async fn triage_findings( summary.unique = distinct.len(); let (sent, skipped) = triage_selection(findings, &distinct); - let mut verdicts = ask_all(model, findings, &sent, graph_context, &mut summary.calls).await; + let mut verdicts = ask_all( + model, + findings, + &sent, + graph_context, + exploitation, + &mut summary.calls, + ) + .await; let mut skip_reasons: HashMap = skipped.into_iter().collect(); for &i in &sent { if !verdicts.contains_key(&i) { @@ -1020,6 +1057,33 @@ mod tests { ) } + #[test] + fn a_finding_naming_an_exploited_cve_says_so_in_the_prompt() { + let mut with_cve = finding(); + with_cve.cve = Some("CVE-2021-44228".into()); + let findings = vec![with_cve, finding()]; + let mut known = ExploitationContext::new(); + known.insert( + "CVE-2021-44228".into(), + Exploitation { + kev: Some(compliance_core::models::KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: true, + }), + ..Exploitation::default() + }, + ); + let prompt = chunk_prompt(&findings, &[0, 1], None, Some(&known)); + assert_eq!( + prompt + .matches("Exploitation: in CISA KEV since 2021-12-10") + .count(), + 1, + "{prompt}" + ); + assert!(!chunk_prompt(&findings, &[0], None, None).contains("Exploitation:")); + } + #[test] fn a_dismissed_finding_is_kept_for_review() { let mut f = finding(); @@ -1498,7 +1562,7 @@ mod tests { // The retry names findings 2 and 4 only, as 1 and 2. r#"[{"id":2,"action":"downgrade","confidence":6,"rationale":"internal only"},{"id":1,"action":"confirm","confidence":7,"rationale":"reachable"}]"#, ]); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; let asked = model.asked(); assert_eq!(asked.len(), 2); @@ -1532,7 +1596,7 @@ mod tests { "{\"action\": ", r#"{"id":1,"action":"confirm","confidence":9,"rationale":"secret in config"}"#, ]); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; let asked = model.asked(); assert_eq!(asked.len(), 3); @@ -1556,7 +1620,7 @@ mod tests { async fn a_model_that_is_down_skips_but_keeps_every_finding() { let mut findings: Vec = (1..=3).map(|n| numbered(n, Severity::Critical)).collect(); let model = FakeModel::scripted(&[]); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; assert_eq!(findings.len(), 3); assert!(findings .iter() @@ -1579,7 +1643,7 @@ mod tests { ); // The first four chunks are answered, then the model is gone. let model = FakeModel::scripted(&[&full, &full, &full, &full]); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; assert_eq!(summary.calls, 5); assert_eq!(summary.confirmed, 40); assert_eq!(summary.skipped_no_answer, 5); @@ -1595,7 +1659,7 @@ mod tests { {"id":3,"action":"dismiss","confidence":9,"rationale":"not reachable"}, {"id":4,"action":"confirm","confidence":5,"rationale":"test code"} ]"#]); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; assert_eq!(findings.len(), 4, "nothing is removed"); let statuses: Vec<_> = findings.iter().map(|f| f.status.clone()).collect(); @@ -1631,7 +1695,7 @@ mod tests { numbered(3, Severity::Info), ]; let model = FakeModel::confirming(); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; assert_eq!(model.asked(), [vec!["finding 1".to_string()]]); assert_eq!(findings[0].triage_action.as_deref(), Some("confirm")); @@ -1656,7 +1720,7 @@ mod tests { async fn a_large_scan_is_asked_in_chunks() { let mut findings: Vec = (1..=25).map(|n| numbered(n, Severity::Medium)).collect(); let model = FakeModel::confirming(); - let summary = triage_findings(&model, &mut findings, None).await; + let summary = triage_findings(&model, &mut findings, None, None).await; let sizes: Vec = model.asked().iter().map(Vec::len).collect(); assert_eq!(sizes, [10, 10, 5]); assert_eq!(summary.confirmed, 25); diff --git a/compliance-agent/src/pentest/prompt_builder.rs b/compliance-agent/src/pentest/prompt_builder.rs index d50ab58..9afa3b9 100644 --- a/compliance-agent/src/pentest/prompt_builder.rs +++ b/compliance-agent/src/pentest/prompt_builder.rs @@ -380,6 +380,7 @@ mod tests { source: "nvd".into(), severity: None, url: None, + exploitation: None, }) .collect(); entry diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index 0d1175a..04765c6 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -78,6 +78,7 @@ impl CveScanner { source: "osv".to_string(), severity: vuln.severity, url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)), + exploitation: None, }); let mut alert = CveAlert::new( vuln.id, @@ -388,6 +389,7 @@ fn record_nvd( source: "nvd".to_string(), severity: None, url: Some(format!("https://nvd.nist.gov/vuln/detail/{}", cve.id)), + exploitation: None, }); } let mut alert = CveAlert::new( diff --git a/compliance-agent/src/pipeline/cve_enrichment.rs b/compliance-agent/src/pipeline/cve_enrichment.rs new file mode 100644 index 0000000..90a03d4 --- /dev/null +++ b/compliance-agent/src/pipeline/cve_enrichment.rs @@ -0,0 +1,977 @@ +//! How likely a CVE alert is to be exploited (#493): CISA's Known Exploited +//! Vulnerabilities catalog (KEV), FIRST's Exploit Prediction Scoring System +//! (EPSS) and the SSVC "Exploitation" decision point of CISA's Vulnrichment. +//! +//! The CVE stage finds what affects the components; this step says which of +//! those CVEs are exploited in the wild (KEV, SSVC `active`) or likely to be +//! (EPSS). It runs after the CVE lookup and before the alerts are stored, so +//! the alerts, the SBOM's vulnerability references, the LLM triage and the +//! 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. +//! - **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 +//! (`raw.githubusercontent.com`); a CVE CISA has not enriched is a 404. +//! +//! 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. +//! `CVE_EXPLOIT_LOOKUP=false` turns the lookups off. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::Arc; +use std::time::Duration; + +use compliance_core::models::{CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry}; +use compliance_core::net_guard::NetGuard; +use compliance_core::CoreError; +use futures_util::future::BoxFuture; +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"; +/// FIRST's EPSS API. +const EPSS_API: &str = "https://api.first.org/data/v1/epss"; +/// CISA's Vulnrichment records, by year and thousand. +const VULNRICHMENT_BASE: &str = "https://raw.githubusercontent.com/cisagov/vulnrichment/develop"; + +/// CVE ids in one EPSS request (FIRST's page size is 100). +const EPSS_BATCH: usize = 50; +/// Vulnrichment records read at once. +const CONCURRENT_LOOKUPS: usize = 8; +/// Most CVEs one run looks up that are not cached; the rest stay unknown +/// until the next run. +const MAX_UNCACHED: usize = 500; +/// Time for every lookup of one run together. +const LOOKUP_BUDGET: Duration = Duration::from_secs(120); + +/// The text that credits FIRST wherever an EPSS score is shown. +pub(crate) const EPSS_ATTRIBUTION: &str = + "EPSS: FIRST.org, Exploit Prediction Scoring System, https://www.first.org/epss"; + +/// Whether the `CVE_EXPLOIT_LOOKUP` value turns the lookups on (the default). +fn lookup_enabled(value: Option<&str>) -> bool { + !matches!( + value.map(|v| v.trim().to_ascii_lowercase()).as_deref(), + Some("false" | "0" | "off" | "no") + ) +} + +/// The KEV catalog: entry by CVE id. +pub(crate) type KevCatalog = HashMap; + +/// Where looked-up answers are kept between runs. A trait so tests run +/// without Mongo. +pub(crate) trait ExploitCache: Send + Sync { + /// The cached answers for `cves`; a CVE without a row is missing. + 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>>; + /// Today's KEV catalog, if one was read. + fn kev(&self) -> BoxFuture<'_, Result, String>>; + /// Keep the KEV catalog for a day. + fn put_kev<'a>(&'a self, catalog: &'a KevCatalog) -> BoxFuture<'a, Result<(), String>>; +} + +/// What one run of [`CveEnricher::enrich`] did, for the log. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct EnrichCounts { + /// Distinct CVE ids among the alerts. + pub cves: usize, + /// Of those, answered from the cache. + pub cached: usize, + /// In KEV. + pub kev: usize, + /// With an EPSS score. + pub epss: usize, + /// The sources that failed (`KEV`, `EPSS`, `Vulnrichment`). + pub failed: Vec<&'static str>, +} + +/// Looks up the exploitation of CVEs. +pub(crate) struct CveEnricher { + http: PublicHttp, + cache: Option>, + enabled: bool, + kev_url: String, + epss_api: String, + vulnrichment_base: String, +} + +impl CveEnricher { + /// An enricher whose requests `guard` checks, keeping answers in `cache`. + /// + /// # Errors + /// + /// [`CoreError::Http`] if the HTTP client cannot be built. + pub(crate) fn new( + guard: NetGuard, + cache: Option>, + ) -> Result { + Ok(Self { + http: PublicHttp::new(guard)?, + cache, + enabled: lookup_enabled(std::env::var("CVE_EXPLOIT_LOOKUP").ok().as_deref()), + kev_url: KEV_URL.to_string(), + epss_api: EPSS_API.to_string(), + vulnrichment_base: VULNRICHMENT_BASE.to_string(), + }) + } + + /// 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.epss_api = format!("{base}/epss"); + self.vulnrichment_base = format!("{base}/vulnrichment"); + self.enabled = true; + self + } + + /// Attach the exploitation of each alert's CVE to the alert, and to the + /// SBOM entries' references to the same advisory. + pub(crate) async fn enrich( + &self, + alerts: &mut [CveAlert], + entries: &mut [SbomEntry], + ) -> EnrichCounts { + let cves: BTreeSet = alerts + .iter() + .map(|a| a.cve().to_string()) + .filter(|id| is_cve_id(id)) + .collect(); + let mut counts = EnrichCounts { + cves: cves.len(), + ..EnrichCounts::default() + }; + if cves.is_empty() || !self.enabled { + return counts; + } + let found = self.lookup(cves, &mut counts).await; + counts.kev = found.values().filter(|e| e.kev.is_some()).count(); + counts.epss = found.values().filter(|e| e.epss.is_some()).count(); + + // The advisory id (a GHSA, or the CVE itself) to its CVE. + let mut by_advisory: HashMap = HashMap::new(); + for alert in alerts.iter_mut() { + let cve = alert.cve().to_string(); + if let Some(found) = found.get(&cve).filter(|e| !e.is_empty()) { + alert.exploitation = Some(found.clone()); + } + by_advisory.insert(alert.cve_id.clone(), cve); + } + for vuln in entries + .iter_mut() + .flat_map(|e| e.known_vulnerabilities.iter_mut()) + { + let cve = by_advisory.get(&vuln.id).unwrap_or(&vuln.id); + if let Some(found) = found.get(cve).filter(|e| !e.is_empty()) { + vuln.exploitation = Some(found.clone()); + } + } + counts + } + + /// The exploitation of every CVE in `cves`, from the cache or the + /// sources; a CVE nothing is known about is missing or empty. + async fn lookup( + &self, + cves: BTreeSet, + counts: &mut EnrichCounts, + ) -> HashMap { + let ids: Vec = cves.into_iter().collect(); + let mut found = 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)) + .collect(); + if missing.is_empty() { + return found; + } + if missing.len() > MAX_UNCACHED { + tracing::info!( + "CVE exploitation: looking up {MAX_UNCACHED} of {} uncached CVEs; the rest on a later run", + missing.len() + ); + missing.truncate(MAX_UNCACHED); + } + + let fetched = + match tokio::time::timeout(LOOKUP_BUDGET, self.fetch(&missing, &mut counts.failed)) + .await + { + Ok(fetched) => fetched, + 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() + .map(|id| { + 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(), + }; + let complete = kev.is_some() && epss_answered.contains(id) && ssvc.contains_key(id); + (id.clone(), (exploitation, complete)) + }) + .collect() + } + + /// Today's KEV catalog: from the cache, or read and cached. + async fn kev_catalog(&self) -> Option { + if let Some(cache) = &self.cache { + match cache.kev().await { + Ok(Some(catalog)) => return Some(catalog), + Ok(None) => {} + 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}"); + } + } + Some(catalog) + } + Err(e) => { + tracing::warn!("KEV catalog not read: {e}"); + None + } + } + } + + /// The EPSS scores of `cves`, and the CVEs FIRST answered for (with or + /// without a score). + async fn epss( + &self, + cves: &[String], + ) -> ( + HashMap, + std::collections::HashSet, + ) { + let mut scores = HashMap::new(); + let mut answered = std::collections::HashSet::new(); + for batch in cves.chunks(EPSS_BATCH) { + let result = async { + let resp = self + .http + .get(&self.epss_api)? + .query(&[("cve", batch.join(","))]) + .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_epss(&body) + } + .await; + match result { + Ok(batch_scores) => { + answered.extend(batch.iter().cloned()); + scores.extend(batch_scores); + } + Err(e) => tracing::warn!("EPSS lookup failed for {} CVEs: {e}", batch.len()), + } + } + (scores, answered) + } + + /// The SSVC exploitation of each CVE in `cves` CISA answered for: `None` + /// inside when CISA has no record or no SSVC for it. + async fn ssvc(&self, cves: &[String]) -> HashMap> { + // Owned ids: a stream of borrowed ones makes the scan's future not + // `Send` for every lifetime. + let base = self.vulnrichment_base.clone(); + let http = self.http.clone(); + futures_util::stream::iter(cves.to_vec()) + .map(move |id| { + let (base, http) = (base.clone(), http.clone()); + async move { + let url = format!("{base}/{}", vulnrichment_path(&id)?); + let resp = http.get(&url).ok()?.send().await.ok()?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Some((id, None)); + } + let resp = resp.error_for_status().ok()?; + let body = read_body(resp).await.ok()?; + let record: serde_json::Value = serde_json::from_slice(&body).ok()?; + let exploitation = ssvc_exploitation(&record); + Some((id, exploitation)) + } + }) + .buffer_unordered(CONCURRENT_LOOKUPS) + .filter_map(|answer| async move { answer }) + .collect() + .await + } +} + +/// Whether `id` is a CVE id (`CVE-2021-44228`). +fn is_cve_id(id: &str) -> bool { + let mut parts = id.splitn(3, '-'); + parts.next() == Some("CVE") + && parts + .next() + .is_some_and(|y| y.len() == 4 && y.bytes().all(|b| b.is_ascii_digit())) + && parts + .next() + .is_some_and(|n| n.len() >= 4 && n.bytes().all(|b| b.is_ascii_digit())) +} + +/// Where Vulnrichment keeps the record of `cve`: `/xxx/.json` +/// (`CVE-2021-44228` → `2021/44xxx/CVE-2021-44228.json`). +fn vulnrichment_path(cve: &str) -> Option { + if !is_cve_id(cve) { + return None; + } + let mut parts = cve.splitn(3, '-').skip(1); + let year = parts.next()?; + let number = parts.next()?; + let thousands = &number[..number.len() - 3]; + Some(format!("{year}/{thousands}xxx/{cve}.json")) +} + +/// The KEV catalog from CISA's JSON feed. +fn parse_kev(body: &serde_json::Value) -> Result { + let list = body["vulnerabilities"] + .as_array() + .ok_or("no vulnerabilities in the KEV feed")?; + Ok(list + .iter() + .filter_map(|v| { + let id = v["cveID"].as_str()?; + Some(( + id.to_string(), + KevEntry { + date_added: v["dateAdded"].as_str().unwrap_or_default().to_string(), + known_ransomware: v["knownRansomwareCampaignUse"] + .as_str() + .is_some_and(|s| s.eq_ignore_ascii_case("known")), + }, + )) + }) + .collect()) +} + +/// The scores in an answer of FIRST's EPSS API. +fn parse_epss(body: &serde_json::Value) -> Result, String> { + let list = body["data"] + .as_array() + .ok_or("no data in the EPSS answer")?; + // FIRST sends the numbers as strings. + let number = |v: &serde_json::Value| { + v.as_f64() + .or_else(|| v.as_str().and_then(|s| s.parse().ok())) + }; + Ok(list + .iter() + .filter_map(|row| { + Some(( + row["cve"].as_str()?.to_string(), + EpssScore { + score: number(&row["epss"])?, + percentile: number(&row["percentile"])?, + date: row["date"].as_str().unwrap_or_default().to_string(), + }, + )) + }) + .collect()) +} + +/// The SSVC "Exploitation" decision point of CISA's ADP container in a +/// Vulnrichment (CVE JSON 5) record, lowercase. +fn ssvc_exploitation(record: &serde_json::Value) -> Option { + record["containers"]["adp"] + .as_array()? + .iter() + .filter(|adp| adp["providerMetadata"]["shortName"].as_str() == Some("CISA-ADP")) + .flat_map(|adp| adp["metrics"].as_array().into_iter().flatten()) + .filter(|m| m["other"]["type"].as_str() == Some("ssvc")) + .flat_map(|m| { + m["other"]["content"]["options"] + .as_array() + .into_iter() + .flatten() + }) + .find_map(|option| option["Exploitation"].as_str()) + .map(str::to_ascii_lowercase) +} + +/// The exploitation known for each CVE among `alerts`, by CVE id, for the +/// LLM triage. +pub(crate) fn by_cve(alerts: &[CveAlert]) -> HashMap { + alerts + .iter() + .filter_map(|a| { + a.exploitation + .as_ref() + .map(|e| (a.cve().to_string(), e.clone())) + }) + .collect() +} + +/// One line on what is known about the exploitation, for a prompt or an +/// issue (`in CISA KEV since 2021-12-10 (ransomware); EPSS 0.944 (99.9th percentile); SSVC exploitation: active`). +pub(crate) fn describe(exploitation: &Exploitation) -> String { + let mut parts = Vec::new(); + if let Some(kev) = &exploitation.kev { + let mut s = format!("in CISA KEV since {}", kev.date_added); + if kev.known_ransomware { + s.push_str(" (known ransomware use)"); + } + parts.push(s); + } + if let Some(epss) = &exploitation.epss { + parts.push(format!( + "EPSS {:.3} ({:.1}th percentile)", + epss.score, + epss.percentile * 100.0 + )); + } + if let Some(ssvc) = &exploitation.ssvc_exploitation { + parts.push(format!("SSVC exploitation: {ssvc}")); + } + if parts.is_empty() { + "no known exploitation".to_string() + } else { + parts.join("; ") + } +} + +// --------------------------------------------------------------------------- +// Cache +// --------------------------------------------------------------------------- + +/// How long an answer is kept: KEV and EPSS change daily. +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. +pub(crate) struct MongoExploitCache { + rows: mongodb::Collection, + kev: mongodb::Collection, + indexed: tokio::sync::OnceCell<()>, +} + +/// One cached answer. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +struct CachedExploitation { + /// The CVE id. + #[serde(rename = "_id")] + cve: String, + exploitation: Exploitation, + expires_at: mongodb::bson::DateTime, +} + +/// The cached KEV catalog. +#[derive(Debug, serde::Serialize, serde::Deserialize)] +struct CachedKev { + #[serde(rename = "_id")] + key: String, + entries: KevCatalog, + expires_at: mongodb::bson::DateTime, +} + +impl MongoExploitCache { + /// The per-CVE collection in the admin database. + pub(crate) const COLLECTION: &'static str = "cve_exploitation"; + /// The KEV catalog's collection in the admin database. + pub(crate) const KEV_COLLECTION: &'static str = "cisa_kev"; + /// The id of the catalog's row. + const KEV_ROW: &'static str = "catalog"; + + pub(crate) fn new(admin_db: &mongodb::Database) -> Self { + Self { + rows: admin_db.collection(Self::COLLECTION), + kev: admin_db.collection(Self::KEV_COLLECTION), + indexed: tokio::sync::OnceCell::new(), + } + } + + /// The TTL indexes, once per process. + async fn ensure_index(&self) -> Result<(), String> { + self.indexed + .get_or_try_init(|| async { + let index = || { + mongodb::IndexModel::builder() + .keys(mongodb::bson::doc! { "expires_at": 1 }) + .options( + mongodb::options::IndexOptions::builder() + .expire_after(Duration::ZERO) + .build(), + ) + .build() + }; + self.rows + .create_index(index()) + .await + .map_err(|e| e.to_string())?; + self.kev + .create_index(index()) + .await + .map(drop) + .map_err(|e| e.to_string()) + }) + .await + .map(drop) + } + + fn expiry() -> mongodb::bson::DateTime { + mongodb::bson::DateTime::from_system_time(std::time::SystemTime::now() + CACHE_TTL) + } + + async fn read(&self, cves: &[String]) -> Result, String> { + let mut cursor = self + .rows + .find(mongodb::bson::doc! { + "_id": { "$in": cves }, + // The TTL monitor runs once a minute; an expired row is gone. + "expires_at": { "$gt": mongodb::bson::DateTime::now() }, + }) + .await + .map_err(|e| e.to_string())?; + 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); + } + Ok(out) + } + + async fn write(&self, answers: &[(String, Exploitation)]) -> 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, + }; + self.rows + .replace_one(mongodb::bson::doc! { "_id": &row.cve }, &row) + .upsert(true) + .await + .map_err(|e| e.to_string())?; + } + Ok(()) + } + + async fn read_kev(&self) -> Result, String> { + Ok(self + .kev + .find_one(mongodb::bson::doc! { + "_id": Self::KEV_ROW, + "expires_at": { "$gt": mongodb::bson::DateTime::now() }, + }) + .await + .map_err(|e| e.to_string())? + .map(|row| row.entries)) + } + + async fn write_kev(&self, catalog: &KevCatalog) -> Result<(), String> { + self.ensure_index().await?; + let row = CachedKev { + key: Self::KEV_ROW.to_string(), + entries: catalog.clone(), + expires_at: Self::expiry(), + }; + self.kev + .replace_one(mongodb::bson::doc! { "_id": Self::KEV_ROW }, &row) + .upsert(true) + .await + .map(drop) + .map_err(|e| e.to_string()) + } +} + +impl ExploitCache for MongoExploitCache { + fn get_many<'a>( + &'a self, + cves: &'a [String], + ) -> BoxFuture<'a, Result, String>> { + Box::pin(self.read(cves)) + } + + fn put<'a>( + &'a self, + answers: &'a [(String, Exploitation)], + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(self.write(answers)) + } + + fn kev(&self) -> BoxFuture<'_, Result, String>> { + Box::pin(self.read_kev()) + } + + fn put_kev<'a>(&'a self, catalog: &'a KevCatalog) -> BoxFuture<'a, Result<(), String>> { + Box::pin(self.write_kev(catalog)) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + + use compliance_core::models::{CveSource, VulnRef}; + + const KEV_FIXTURE: &str = include_str!("../../tests/fixtures/exploitation/kev.json"); + const EPSS_FIXTURE: &str = include_str!("../../tests/fixtures/exploitation/epss.json"); + const VULNRICHMENT_FIXTURE: &str = + include_str!("../../tests/fixtures/exploitation/CVE-2021-44228.json"); + + /// 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()); + let app = axum::Router::new() + .route( + "/kev.json", + axum::routing::get(move || { + h1.fetch_add(1, Ordering::SeqCst); + async { KEV_FIXTURE } + }), + ) + .route( + "/epss", + axum::routing::get(move || { + h2.fetch_add(1, Ordering::SeqCst); + async move { + if epss_down { + (axum::http::StatusCode::SERVICE_UNAVAILABLE, "").into_response() + } else { + EPSS_FIXTURE.into_response() + } + } + }), + ) + .route( + "/vulnrichment/2021/44xxx/CVE-2021-44228.json", + axum::routing::get(move || { + h3.fetch_add(1, Ordering::SeqCst); + async { VULNRICHMENT_FIXTURE } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + (url, hits) + } + + use axum::response::IntoResponse; + + /// A cache in memory. + #[derive(Default)] + struct MemoryCache { + rows: Mutex>, + kev: Mutex>, + } + + impl ExploitCache for MemoryCache { + fn get_many<'a>( + &'a self, + cves: &'a [String], + ) -> BoxFuture<'a, Result, String>> { + let rows = self.rows.lock().unwrap(); + let out = cves + .iter() + .filter_map(|c| rows.get(c).map(|e| (c.clone(), e.clone()))) + .collect(); + Box::pin(async move { Ok(out) }) + } + fn put<'a>( + &'a self, + answers: &'a [(String, Exploitation)], + ) -> BoxFuture<'a, Result<(), String>> { + self.rows.lock().unwrap().extend(answers.iter().cloned()); + Box::pin(async { Ok(()) }) + } + fn kev(&self) -> BoxFuture<'_, Result, String>> { + let kev = self.kev.lock().unwrap().clone(); + Box::pin(async move { Ok(kev) }) + } + fn put_kev<'a>(&'a self, catalog: &'a KevCatalog) -> BoxFuture<'a, Result<(), String>> { + *self.kev.lock().unwrap() = Some(catalog.clone()); + Box::pin(async { Ok(()) }) + } + } + + fn alert(id: &str, aliases: &[&str]) -> CveAlert { + let mut a = CveAlert::new( + id.into(), + "t".into(), + "log4j-core".into(), + "2.14.1".into(), + CveSource::Osv, + ); + a.aliases = aliases.iter().map(|s| s.to_string()).collect(); + a + } + + fn entry_with(vuln: &str) -> SbomEntry { + let mut e = SbomEntry::new( + "t".into(), + "log4j-core".into(), + "2.14.1".into(), + "maven".into(), + ); + e.known_vulnerabilities.push(VulnRef { + id: vuln.into(), + source: "osv".into(), + severity: None, + url: None, + exploitation: None, + }); + e + } + + #[test] + fn the_fixtures_parse() { + let kev = parse_kev(&serde_json::from_str(KEV_FIXTURE).unwrap()).unwrap(); + assert_eq!( + kev["CVE-2021-44228"], + KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: true + } + ); + assert!(!kev["CVE-2022-22965"].known_ransomware); + let epss = parse_epss(&serde_json::from_str(EPSS_FIXTURE).unwrap()).unwrap(); + assert_eq!(epss["CVE-2021-44228"].percentile, 1.0); + assert!((epss["CVE-2021-0341"].score - 0.0087).abs() < 1e-9); + assert_eq!(epss["CVE-2021-0341"].date, "2026-10-05"); + let record = serde_json::from_str(VULNRICHMENT_FIXTURE).unwrap(); + assert_eq!(ssvc_exploitation(&record).as_deref(), Some("active")); + assert_eq!( + ssvc_exploitation(&serde_json::json!({"containers": {}})), + None + ); + } + + #[test] + fn vulnrichment_paths_and_cve_ids() { + assert_eq!( + vulnrichment_path("CVE-2021-44228").as_deref(), + Some("2021/44xxx/CVE-2021-44228.json") + ); + assert_eq!( + vulnrichment_path("CVE-2024-3094").as_deref(), + Some("2024/3xxx/CVE-2024-3094.json") + ); + assert_eq!( + vulnrichment_path("CVE-2020-0601").as_deref(), + Some("2020/0xxx/CVE-2020-0601.json") + ); + for id in [ + "GHSA-3cqm-mf7h-prrj", + "CVE-21-1", + "CVE-2021-../x", + "RUSTSEC-2021-0001", + ] { + assert!(!is_cve_id(id), "{id}"); + assert_eq!(vulnrichment_path(id), None); + } + } + + #[test] + fn a_description_names_every_source() { + let e = Exploitation { + kev: Some(KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: true, + }), + epss: Some(EpssScore { + score: 0.94358, + percentile: 0.99932, + date: "2026-10-05".into(), + }), + ssvc_exploitation: Some("active".into()), + }; + assert_eq!( + describe(&e), + "in CISA KEV since 2021-12-10 (known ransomware use); EPSS 0.944 (99.9th percentile); SSVC exploitation: active" + ); + assert_eq!(describe(&Exploitation::default()), "no known exploitation"); + assert!(e.actively_exploited()); + } + + #[test] + fn the_switch_reads_false_as_off() { + assert!(lookup_enabled(None)); + assert!(lookup_enabled(Some("true"))); + assert!(!lookup_enabled(Some("false"))); + assert!(!lookup_enabled(Some(" OFF "))); + } + + #[tokio::test] + async fn alerts_and_sbom_references_are_enriched_and_cached() { + let (base, hits) = fake_sources(false).await; + let cache = Arc::new(MemoryCache::default()); + let enricher = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone())) + .unwrap() + .with_base(&base); + // A GHSA whose CVE is in KEV, and a CVE that is not. + let mut alerts = vec![ + alert("GHSA-jfh8-c2jp-5v3q", &["CVE-2021-44228"]), + alert("CVE-2021-0341", &[]), + ]; + let mut entries = vec![entry_with("GHSA-jfh8-c2jp-5v3q")]; + + let counts = enricher.enrich(&mut alerts, &mut entries).await; + + assert_eq!(counts.cves, 2); + assert_eq!(counts.kev, 1); + assert_eq!(counts.epss, 2); + // CVE-2021-0341 has no Vulnrichment record: a 404, which is an answer. + assert!(counts.failed.is_empty(), "{:?}", counts.failed); + let log4j = alerts[0].exploitation.as_ref().unwrap(); + assert!(log4j.kev.as_ref().unwrap().known_ransomware); + assert_eq!(log4j.ssvc_exploitation.as_deref(), Some("active")); + let other = alerts[1].exploitation.as_ref().unwrap(); + assert!(other.kev.is_none() && other.ssvc_exploitation.is_none()); + assert!(other.epss.is_some()); + assert_eq!( + 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"); + + // 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!(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; + let cache = Arc::new(MemoryCache::default()); + let enricher = CveEnricher::new(NetGuard::allow_private(), Some(cache.clone())) + .unwrap() + .with_base(&base); + let mut alerts = vec![alert("CVE-2021-44228", &[])]; + + let counts = enricher.enrich(&mut alerts, &mut []).await; + + 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!(cache.kev.lock().unwrap().is_some()); + } + + #[tokio::test] + async fn sources_on_an_internal_address_are_refused() { + let (base, hits) = fake_sources(false).await; + let enricher = CveEnricher::new(NetGuard::public_only(), None) + .unwrap() + .with_base(&base); + let mut alerts = vec![alert("CVE-2021-44228", &[])]; + + let counts = enricher.enrich(&mut alerts, &mut []).await; + + assert_eq!(hits.load(Ordering::SeqCst), 0, "a request reached it"); + assert!(alerts[0].exploitation.is_none()); + assert_eq!(counts.failed, ["KEV", "EPSS", "Vulnrichment"]); + } + + #[tokio::test] + async fn advisories_without_a_cve_are_not_looked_up() { + let (base, hits) = fake_sources(false).await; + let enricher = CveEnricher::new(NetGuard::allow_private(), None) + .unwrap() + .with_base(&base); + 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); + } +} diff --git a/compliance-agent/src/pipeline/cve_issues.rs b/compliance-agent/src/pipeline/cve_issues.rs index c4b3c4a..8ab9f50 100644 --- a/compliance-agent/src/pipeline/cve_issues.rs +++ b/compliance-agent/src/pipeline/cve_issues.rs @@ -6,6 +6,11 @@ //! one. When a later complete scan no longer finds the CVE (the dependency was //! updated or removed), the issue is closed with a comment; when it comes back, //! it is reopened. +//! +//! What is known about a CVE's exploitation (#493) moves the threshold: a CVE +//! in CISA's KEV catalog always gets an issue, rated at least high, and one +//! whose EPSS percentile reaches [`epss_percentile`] is rated one step higher +//! (a medium one becomes high and gets an issue). use std::collections::{BTreeMap, HashMap}; @@ -32,6 +37,37 @@ pub(crate) struct CveIssueTarget<'a> { pub target_id: &'a str, /// The dashboard's public URL, for a link back; empty for none. pub dashboard: &'a str, + /// From this EPSS percentile (0 to 1) on a CVE is rated one step higher; + /// `None` leaves EPSS out (see [`epss_percentile`]). + pub epss_percentile: Option, +} + +/// The EPSS percentile from which a CVE is rated one step higher. +const DEFAULT_EPSS_PERCENTILE: f64 = 0.95; + +/// The EPSS percentile from which a CVE is rated one step higher, from +/// `CVE_ISSUE_EPSS_PERCENTILE` (`0.95` by default, a fraction from 0 to 1; +/// `off` leaves EPSS out). A value that cannot be read keeps the default. +pub(crate) fn epss_percentile(value: Option<&str>) -> Option { + let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else { + return Some(DEFAULT_EPSS_PERCENTILE); + }; + if matches!( + value.to_ascii_lowercase().as_str(), + "off" | "false" | "none" + ) { + return None; + } + match value.parse::() { + Ok(p) if (0.0..=1.0).contains(&p) => Some(p), + _ => { + tracing::warn!( + value, + "CVE_ISSUE_EPSS_PERCENTILE is not a fraction from 0 to 1; using {DEFAULT_EPSS_PERCENTILE}" + ); + Some(DEFAULT_EPSS_PERCENTILE) + } + } } /// What [`sync_cve_issues`] did. @@ -59,12 +95,40 @@ fn severity_name(severity: &NotificationSeverity) -> &'static str { } } -/// Whether an alert is severe enough for an issue. -fn issue_worthy(alert: &CveAlert) -> bool { - matches!( - parse_severity(alert.severity.as_deref(), alert.cvss_score), - NotificationSeverity::Critical | NotificationSeverity::High - ) +/// The severity an alert is rated for its issue: the advisory's, at least +/// high for a CVE in CISA's KEV catalog, and one step higher when its EPSS +/// percentile reaches `epss_percentile`. +fn effective_severity(alert: &CveAlert, epss_percentile: Option) -> NotificationSeverity { + use NotificationSeverity::{Critical, High, Low, Medium}; + let mut severity = parse_severity(alert.severity.as_deref(), alert.cvss_score); + let Some(exploitation) = alert.exploitation.as_ref() else { + return severity; + }; + let likely = matches!( + (exploitation.epss.as_ref(), epss_percentile), + (Some(epss), Some(threshold)) if epss.percentile >= threshold + ); + if likely { + severity = match severity { + Low => Medium, + Medium => High, + High | Critical => Critical, + }; + } + if exploitation.kev.is_some() && matches!(severity, Low | Medium) { + severity = High; + } + severity +} + +/// Whether an alert gets an issue: critical or high as rated by +/// [`effective_severity`], and always when it is in CISA's KEV catalog. +fn issue_worthy(alert: &CveAlert, epss_percentile: Option) -> bool { + alert.exploitation.as_ref().is_some_and(|e| e.kev.is_some()) + || matches!( + effective_severity(alert, epss_percentile), + NotificationSeverity::Critical | NotificationSeverity::High + ) } /// Open, reopen and close the CVE issues of one target to match `alerts`. @@ -105,7 +169,10 @@ pub(crate) async fn sync_cve_issues( let label_ids = gitea_label_ids(target).await; let mut counts = CveIssueCounts::default(); - for (key, alert) in present.iter().filter(|(_, a)| issue_worthy(a)) { + for (key, alert) in present + .iter() + .filter(|(_, a)| issue_worthy(a, target.epss_percentile)) + { match existing.get(key) { Some(issue) if is_closed(&issue.status) => { let comment = "**Prüfwerk:** Bei der Prüfung erneut gefunden, daher wieder geöffnet.\n\nFound again by the scan, so reopened."; @@ -168,14 +235,14 @@ async fn create( alert: &CveAlert, label_ids: Option<&HashMap>, ) -> Result { - let severity = severity_name(&parse_severity(alert.severity.as_deref(), alert.cvss_score)); + let severity = severity_name(&effective_severity(alert, target.epss_percentile)); let title = format!( "[CVE] {}@{}: {}", alert.affected_package, alert.affected_version, alert.cve() ); - let body = issue_body(alert, severity, target); + let body = issue_body(alert, severity, target.target_id, target.dashboard); let names = [ LABEL_PRUEFWERK.to_string(), LABEL_CRA_ANNEX_I.to_string(), @@ -210,7 +277,7 @@ async fn create( /// The issue text: what is affected, how badly, what fixes it, and the CRA /// requirements concerned. -fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> String { +fn issue_body(alert: &CveAlert, severity: &str, target_id: &str, dashboard: &str) -> String { let mut body = format!( "**{}** betrifft / affects **{} {}**.\n", alert.cve(), @@ -225,6 +292,32 @@ fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> body.push_str(&format!(" (CVSS {score:.1})")); } body.push('\n'); + if let Some(exploitation) = alert.exploitation.as_ref() { + if let Some(kev) = &exploitation.kev { + body.push_str(&format!( + "- **Aktiv ausgenutzt / Actively exploited:** CISA KEV seit / since {}{}\n", + kev.date_added, + if kev.known_ransomware { + ", bekannt aus Ransomware-Kampagnen / known ransomware use" + } else { + "" + } + )); + } + if let Some(epss) = &exploitation.epss { + body.push_str(&format!( + "- EPSS: {:.1} % (Perzentil / percentile {:.1}), {}\n", + epss.score * 100.0, + epss.percentile * 100.0, + epss.date + )); + } + if let Some(ssvc) = &exploitation.ssvc_exploitation { + body.push_str(&format!( + "- SSVC Exploitation (CISA Vulnrichment): {ssvc}\n" + )); + } + } match alert.fixed_versions.as_slice() { [] => body .push_str("- Behoben in / Fixed in: keine Version bekannt / no fixed version known\n"), @@ -234,6 +327,16 @@ fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> "- Advisory: https://osv.dev/vulnerability/{}\n", alert.cve_id )); + if alert + .exploitation + .as_ref() + .is_some_and(|e| e.epss.is_some()) + { + body.push_str(&format!( + "\n_{}_\n", + crate::pipeline::cve_enrichment::EPSS_ATTRIBUTION + )); + } body.push_str("\n### CRA\n\n"); let map = control_map::ControlMap::cra().ok(); for id in CVE_CONTROLS { @@ -244,11 +347,10 @@ fn issue_body(alert: &CveAlert, severity: &str, target: &CveIssueTarget<'_>) -> .unwrap_or_default(); body.push_str(&format!("- {id} — {title} (Annex I)\n")); } - let dashboard = target.dashboard.trim_end_matches('/'); + let dashboard = dashboard.trim_end_matches('/'); if dashboard.starts_with("https://") { body.push_str(&format!( - "\n[In Prüfwerk öffnen / Open in Prüfwerk]({dashboard}/targets/{})\n", - target.target_id + "\n[In Prüfwerk öffnen / Open in Prüfwerk]({dashboard}/targets/{target_id})\n" )); } body @@ -378,6 +480,76 @@ mod tests { format!("http://{addr}") } + fn exploited(kev: bool, percentile: Option) -> compliance_core::models::Exploitation { + compliance_core::models::Exploitation { + kev: kev.then(|| compliance_core::models::KevEntry { + date_added: "2021-12-10".into(), + known_ransomware: false, + }), + epss: percentile.map(|p| compliance_core::models::EpssScore { + score: 0.4, + percentile: p, + date: "2026-10-05".into(), + }), + ssvc_exploitation: None, + } + } + + #[test] + fn kev_always_opens_an_issue_and_a_high_epss_raises_the_rating() { + use NotificationSeverity::{Critical, High, Medium}; + let threshold = Some(0.95); + // A moderate CVE: no issue on its own. + let mut a = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE"); + assert!(!issue_worthy(&a, threshold)); + // EPSS below the percentile changes nothing; at it, medium → high. + a.exploitation = Some(exploited(false, Some(0.5))); + assert_eq!(effective_severity(&a, threshold), Medium); + a.exploitation = Some(exploited(false, Some(0.97))); + assert_eq!(effective_severity(&a, threshold), High); + assert!(issue_worthy(&a, threshold)); + // EPSS left out by configuration. + assert!(!issue_worthy(&a, None)); + // KEV: an issue, rated at least high, whatever the advisory says. + let mut low = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "LOW"); + low.exploitation = Some(exploited(true, None)); + assert!(issue_worthy(&low, None)); + assert_eq!(effective_severity(&low, None), High); + // High plus a high EPSS: critical. Low plus EPSS: medium. + let mut high = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); + high.exploitation = Some(exploited(false, Some(0.99))); + assert_eq!(effective_severity(&high, threshold), Critical); + let mut low = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "LOW"); + low.exploitation = Some(exploited(false, Some(0.99))); + assert_eq!(effective_severity(&low, threshold), Medium); + } + + #[test] + fn the_epss_percentile_is_read_from_the_environment_value() { + assert_eq!(epss_percentile(None), Some(0.95)); + assert_eq!(epss_percentile(Some("0.9")), Some(0.9)); + assert_eq!(epss_percentile(Some("off")), None); + assert_eq!(epss_percentile(Some("95")), Some(0.95)); + assert_eq!(epss_percentile(Some("")), Some(0.95)); + } + + #[test] + fn the_issue_names_kev_and_epss_with_the_attribution() { + let mut a = alert("log4j-core", "2.14.1", "GHSA-jfh8-c2jp-5v3q", "CRITICAL"); + let mut e = exploited(true, Some(0.999)); + e.kev.as_mut().unwrap().known_ransomware = true; + e.ssvc_exploitation = Some("active".into()); + a.exploitation = Some(e); + let body = issue_body(&a, "critical", "target-1", ""); + assert!(body.contains("Actively exploited:** CISA KEV seit / since 2021-12-10, bekannt aus Ransomware-Kampagnen"), "{body}"); + assert!( + body.contains("EPSS: 40.0 % (Perzentil / percentile 99.9)"), + "{body}" + ); + assert!(body.contains("SSVC Exploitation (CISA Vulnrichment): active")); + assert!(body.contains("https://www.first.org/epss")); + } + fn alert(package: &str, version: &str, id: &str, severity: &str) -> CveAlert { let mut a = CveAlert::new( id.into(), @@ -418,6 +590,7 @@ mod tests { repo: "app", target_id: "target-1", dashboard: "https://pruefwerk.example", + epss_percentile: Some(0.95), }; let okhttp = alert("okhttp", "3.12.0", "GHSA-3cqm-mf7h-prrj", "HIGH"); let minor = alert("gson", "2.8.8", "GHSA-4jrv-ppp4-jm57", "MODERATE"); diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index c9b6637..77edbeb 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -42,6 +42,9 @@ impl PipelineOrchestrator { repo: name, target_id: repo_id, dashboard: &dashboard, + epss_percentile: crate::pipeline::cve_issues::epss_percentile( + std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(), + ), }; let counts = crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?; diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 50d31a2..b8159d7 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -5,6 +5,7 @@ pub mod clamav; pub mod code_review; pub mod cppcheck; pub mod cve; +pub(crate) mod cve_enrichment; pub(crate) mod cve_issues; pub mod dedup; pub mod dotnet; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 0e1b127..d8f7620 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -12,6 +12,7 @@ use crate::error::AgentError; use crate::llm::LlmClient; use crate::pipeline::cppcheck::CppcheckScanner; use crate::pipeline::cve::CveScanner; +use crate::pipeline::cve_enrichment::ExploitCache; use crate::pipeline::git::GitOps; use crate::pipeline::gitleaks::GitleaksScanner; use crate::pipeline::grouping::{group_repetitive, GroupingPolicy}; @@ -48,6 +49,8 @@ pub struct PipelineOrchestrator { pub(super) net_guard: NetGuard, /// The cross-tenant cache of NuGet licenses (#467). pub(super) nuget_license_cache: Option>, + /// The cross-tenant cache of KEV, EPSS and SSVC answers (#493). + pub(super) exploit_cache: Option>, } impl PipelineOrchestrator { @@ -62,6 +65,7 @@ impl PipelineOrchestrator { secrets, net_guard, nuget_license_cache: None, + exploit_cache: None, } } @@ -71,6 +75,12 @@ impl PipelineOrchestrator { self } + /// Cache the CVEs' exploitation answers in `cache` (#493). + pub(crate) fn with_exploit_cache(mut self, cache: Arc) -> Self { + self.exploit_cache = Some(cache); + self + } + #[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))] async fn run_pipeline( &self, @@ -513,6 +523,9 @@ impl PipelineOrchestrator { } } + self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries) + .await; + // Stage 4: Pattern Scanning (GDPR + OAuth) tracing::info!("[{repo_id}] Stage 4: Pattern Scanning"); self.update_phase(scan_run_id, ScanPhase::PatternScanning) @@ -665,10 +678,12 @@ impl PipelineOrchestrator { all_findings.len() ); self.update_phase(scan_run_id, ScanPhase::LlmTriage).await; + let exploitation = crate::pipeline::cve_enrichment::by_cve(&cve_alerts); let triage = crate::llm::triage::triage_findings( self.llm.as_ref(), &mut all_findings, graph_context.as_ref(), + Some(&exploitation), ) .await; tracing::info!("[{repo_id}] {triage}"); @@ -1464,6 +1479,8 @@ impl PipelineOrchestrator { } } + self.enrich_cves(target_id, &mut alerts, &mut entries).await; + for entry in &entries { let filter = doc! { "repo_id": &entry.repo_id, @@ -1491,6 +1508,27 @@ impl PipelineOrchestrator { Ok(()) } + /// Attach the exploitation of each CVE (KEV, EPSS, SSVC; #493) to the + /// alerts and the SBOM's references. Best-effort: a source that fails + /// leaves its part unknown. + async fn enrich_cves( + &self, + target_id: &str, + alerts: &mut [CveAlert], + entries: &mut [SbomEntry], + ) { + match crate::pipeline::cve_enrichment::CveEnricher::new( + self.net_guard, + self.exploit_cache.clone(), + ) { + Ok(enricher) => { + let counts = enricher.enrich(alerts, entries).await; + tracing::info!(target_id, ?counts, "CVE exploitation (KEV, EPSS, SSVC)"); + } + Err(e) => tracing::warn!(target_id, "CVE exploitation not looked up: {e}"), + } + } + /// Upsert CVE alerts for a target and create dedup'd CVE notifications; /// returns the number of newly-created notifications. Shared by the SAST /// pipeline and the PLC control-app SBOM path, so every SBOM source (source, diff --git a/compliance-agent/src/pipeline/sbom/mod.rs b/compliance-agent/src/pipeline/sbom/mod.rs index cb46719..e3d8499 100644 --- a/compliance-agent/src/pipeline/sbom/mod.rs +++ b/compliance-agent/src/pipeline/sbom/mod.rs @@ -480,6 +480,7 @@ fn merge_audit_vulns(entries: &mut [SbomEntry], vulns: Vec lookup.alerts, Err(e) => { tracing::warn!("CVE monitor: scan failed for {repo_name}: {e}"); @@ -294,10 +301,22 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { } }; - // Upsert CVE alerts (existing logic) + // Whether each CVE is exploited (KEV, EPSS, SSVC; #493): cached for + // a day, so the hourly monitor asks the sources at most daily. + if let Some(enricher) = &enricher { + enricher.enrich(&mut alerts, &mut repo_entries).await; + } + + // Upsert CVE alerts (existing logic); an existing alert's + // exploitation is refreshed. for alert in &alerts { let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id }; - let update = doc! { "$setOnInsert": mongodb::bson::to_bson(alert).unwrap_or_default() }; + let mut insert = mongodb::bson::to_document(alert).unwrap_or_default(); + let exploitation = insert.remove("exploitation"); + let mut update = doc! { "$setOnInsert": insert }; + if let Some(exploitation) = exploitation { + update.insert("$set", doc! { "exploitation": exploitation }); + } let _ = db .cve_alerts() .update_one(filter, update) diff --git a/compliance-agent/tests/fixtures/exploitation/CVE-2021-44228.json b/compliance-agent/tests/fixtures/exploitation/CVE-2021-44228.json new file mode 100644 index 0000000..bad4071 --- /dev/null +++ b/compliance-agent/tests/fixtures/exploitation/CVE-2021-44228.json @@ -0,0 +1,78 @@ +{ + "dataType": "CVE_RECORD", + "dataVersion": "5.1", + "cveMetadata": { + "cveId": "CVE-2021-44228", + "state": "PUBLISHED" + }, + "containers": { + "adp": [ + { + "providerMetadata": { + "orgId": "af854a3a-2127-422b-91ae-364da2661108", + "shortName": "CVE", + "dateUpdated": "2024-08-04T04:17:24.696Z" + }, + "title": "CVE Program Container", + "metrics": [] + }, + { + "providerMetadata": { + "orgId": "134c704f-9b21-4f2e-91b3-4a467353bcc0", + "shortName": "CISA-ADP", + "dateUpdated": "2025-02-04T14:24:34.308Z" + }, + "title": "CISA ADP Vulnrichment", + "metrics": [ + { + "cvssV3_1": { + "scope": "CHANGED", + "version": "3.1", + "baseScore": 10, + "attackVector": "NETWORK", + "baseSeverity": "CRITICAL", + "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H", + "integrityImpact": "HIGH", + "userInteraction": "NONE", + "attackComplexity": "LOW", + "availabilityImpact": "HIGH", + "privilegesRequired": "NONE", + "confidentialityImpact": "HIGH" + } + }, + { + "other": { + "type": "ssvc", + "content": { + "id": "CVE-2021-44228", + "role": "CISA Coordinator", + "options": [ + { + "Exploitation": "active" + }, + { + "Automatable": "yes" + }, + { + "Technical Impact": "total" + } + ], + "version": "2.0.3", + "timestamp": "2025-02-04T14:25:34.416117Z" + } + } + }, + { + "other": { + "type": "kev", + "content": { + "dateAdded": "2021-12-10", + "reference": "https://www.cisa.gov/known-exploited-vulnerabilities-catalog?field_cve=CVE-2021-44228" + } + } + } + ] + } + ] + } +} \ No newline at end of file diff --git a/compliance-agent/tests/fixtures/exploitation/epss.json b/compliance-agent/tests/fixtures/exploitation/epss.json new file mode 100644 index 0000000..5e94d3b --- /dev/null +++ b/compliance-agent/tests/fixtures/exploitation/epss.json @@ -0,0 +1,23 @@ +{ + "status": "OK", + "status-code": 200, + "version": "1.0", + "access": "public", + "total": 2, + "offset": 0, + "limit": 100, + "data": [ + { + "cve": "CVE-2021-44228", + "epss": "0.999990000", + "percentile": "1.000000000", + "date": "2026-10-05" + }, + { + "cve": "CVE-2021-0341", + "epss": "0.008700000", + "percentile": "0.573860000", + "date": "2026-10-05" + } + ] +} diff --git a/compliance-agent/tests/fixtures/exploitation/kev.json b/compliance-agent/tests/fixtures/exploitation/kev.json new file mode 100644 index 0000000..58e6007 --- /dev/null +++ b/compliance-agent/tests/fixtures/exploitation/kev.json @@ -0,0 +1,34 @@ +{ + "title": "CISA Catalog of Known Exploited Vulnerabilities", + "catalogVersion": "2026.10.04", + "dateReleased": "2026-10-04T18:52:56.0635Z", + "count": 2, + "vulnerabilities": [ + { + "cveID": "CVE-2022-22965", + "vendorProject": "VMware", + "product": "Spring Framework", + "vulnerabilityName": "Spring Framework JDK 9+ Remote Code Execution Vulnerability", + "dateAdded": "2022-04-04", + "dueDate": "2022-04-25", + "knownRansomwareCampaignUse": "Unknown", + "cwes": [ + "CWE-94" + ] + }, + { + "cveID": "CVE-2021-44228", + "vendorProject": "Apache", + "product": "Log4j2", + "vulnerabilityName": "Apache Log4j2 Remote Code Execution Vulnerability", + "dateAdded": "2021-12-10", + "dueDate": "2021-12-24", + "knownRansomwareCampaignUse": "Known", + "cwes": [ + "CWE-20", + "CWE-400", + "CWE-502" + ] + } + ] +} \ No newline at end of file diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index 5fb885e..30cab8c 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -9,6 +9,59 @@ pub enum CveSource { SearXNG, } +/// What is known about the exploitation of one CVE (#493), from public +/// sources: CISA's Known Exploited Vulnerabilities catalog, FIRST's EPSS and +/// CISA's Vulnrichment SSVC decision points. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Exploitation { + /// The CVE's entry in CISA's KEV catalog: exploited in the wild. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kev: Option, + /// FIRST's EPSS: the probability of exploitation in the next 30 days. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub epss: Option, + /// The SSVC "Exploitation" decision point CISA's Vulnrichment gives the + /// CVE: `none`, `poc` or `active`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ssvc_exploitation: Option, +} + +impl Exploitation { + /// Whether the CVE is known to be exploited: listed in KEV, or SSVC + /// exploitation `active`. + pub fn actively_exploited(&self) -> bool { + self.kev.is_some() || self.ssvc_exploitation.as_deref() == Some("active") + } + + /// Whether nothing is known. + pub fn is_empty(&self) -> bool { + self.kev.is_none() && self.epss.is_none() && self.ssvc_exploitation.is_none() + } +} + +/// A CVE's entry in CISA's Known Exploited Vulnerabilities catalog. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct KevEntry { + /// When CISA added it (`2021-12-10`). + pub date_added: String, + /// Whether it is known to be used in ransomware campaigns (KEV's + /// `knownRansomwareCampaignUse` is `Known`). + #[serde(default)] + pub known_ransomware: bool, +} + +/// A CVE's EPSS score. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct EpssScore { + /// Probability of exploitation activity in the next 30 days, 0 to 1. + pub score: f64, + /// Share of all scored CVEs with a lower or equal score, 0 to 1. + pub percentile: f64, + /// The day the score is for (`2026-10-05`). + #[serde(default)] + pub date: String, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CveAlert { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] @@ -30,6 +83,10 @@ pub struct CveAlert { /// names them. #[serde(default)] pub fixed_versions: Vec, + /// Whether and how likely the CVE is exploited (CISA KEV, FIRST EPSS, + /// CISA Vulnrichment SSVC); `None` when it was not looked up. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exploitation: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, } @@ -68,6 +125,7 @@ impl CveAlert { references: Vec::new(), aliases: Vec::new(), fixed_versions: Vec::new(), + exploitation: None, created_at: Utc::now(), } } diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 36a34f2..c80281b 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -25,7 +25,7 @@ pub mod werkbank; pub use auth::{AuthInfo, SupportTenant}; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; pub use credentials::Credentials; -pub use cve::{CveAlert, CveSource}; +pub use cve::{CveAlert, CveSource, EpssScore, Exploitation, KevEntry}; pub use dast::{ DastAuthConfig, DastEvidence, DastFinding, DastScanPhase, DastScanRun, DastScanStatus, DastTarget, DastTargetType, DastVulnType, diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index 0396f23..a39f683 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -7,6 +7,9 @@ pub struct VulnRef { pub source: String, pub severity: Option, pub url: Option, + /// Exploitation of the advisory's CVE (KEV, EPSS, SSVC; #493). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exploitation: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index a31334f..5eaaff2 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -2743,6 +2743,34 @@ tbody tr:last-child td { letter-spacing: 0.04em; } +.sbom-epss-badge { + background: var(--bg-secondary); + color: var(--text-secondary); + border-color: var(--border); + font-variant-numeric: tabular-nums; +} + +.sbom-kev-marker { + margin-left: 6px; +} + +.sbom-vuln-ssvc { + font-size: 12px; + color: var(--text-secondary); + margin-bottom: 4px; +} + +.sbom-vuln-attribution { + flex-basis: 100%; + margin: 0; + font-size: 11px; + color: var(--text-tertiary); +} + +.sbom-vuln-attribution a { + color: inherit; +} + .sbom-vuln-link { font-size: 12px; color: var(--accent); diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 7855cd2..eced9db 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1952,6 +1952,30 @@ pub mod sbom { de: "Hinweis ansehen →", en: "View advisory →", }; + pub const KEV_BADGE: Text = Text { + de: "Aktiv ausgenutzt (KEV)", + en: "Actively exploited (KEV)", + }; + pub const KEV_SINCE: Text = Text { + de: "Im CISA-Katalog bekannter ausgenutzter Schwachstellen (KEV) seit", + en: "In CISA's Known Exploited Vulnerabilities catalog (KEV) since", + }; + pub const KEV_RANSOMWARE: Text = Text { + de: "bekannt aus Ransomware-Kampagnen", + en: "known ransomware use", + }; + pub const EPSS_HINT: Text = Text { + de: "Wahrscheinlichkeit einer Ausnutzung in den nächsten 30 Tagen (FIRST EPSS); Perzentil unter allen bewerteten CVEs", + en: "Probability of exploitation in the next 30 days (FIRST EPSS); percentile among all scored CVEs", + }; + pub const SSVC_EXPLOITATION: Text = Text { + de: "SSVC-Ausnutzung (CISA Vulnrichment)", + en: "SSVC exploitation (CISA Vulnrichment)", + }; + pub const EPSS_ATTRIBUTION: Text = Text { + de: "EPSS-Daten: FIRST.org, Exploit Prediction Scoring System", + en: "EPSS data: FIRST.org, Exploit Prediction Scoring System", + }; pub const LOAD_FAILED: Text = Text { de: "Die SBOM konnte nicht geladen werden.", en: "Failed to load SBOM.", diff --git a/compliance-dashboard/src/infrastructure/sbom.rs b/compliance-dashboard/src/infrastructure/sbom.rs index 9f5675b..e2918a3 100644 --- a/compliance-dashboard/src/infrastructure/sbom.rs +++ b/compliance-dashboard/src/infrastructure/sbom.rs @@ -9,6 +9,40 @@ pub struct VulnRefData { pub source: String, pub severity: Option, pub url: Option, + /// Whether the advisory's CVE is exploited (KEV, EPSS, SSVC; #493). + #[serde(default)] + pub exploitation: Option, +} + +/// What is known about the exploitation of a CVE. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +pub struct ExploitationData { + /// The CVE's entry in CISA's Known Exploited Vulnerabilities catalog. + #[serde(default)] + pub kev: Option, + /// FIRST's EPSS score. + #[serde(default)] + pub epss: Option, + /// CISA Vulnrichment's SSVC exploitation: `none`, `poc` or `active`. + #[serde(default)] + pub ssvc_exploitation: Option, +} + +/// A CVE's KEV entry. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +pub struct KevData { + pub date_added: String, + #[serde(default)] + pub known_ransomware: bool, +} + +/// A CVE's EPSS score: probability and percentile, 0 to 1. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +pub struct EpssData { + pub score: f64, + pub percentile: f64, + #[serde(default)] + pub date: String, } #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -213,3 +247,29 @@ pub async fn fetch_sbom_diff( .map_err(|e| ServerFnError::new(format!("Parse error: {e} — body: {text}")))?; Ok(body) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_vulnerability_reads_its_exploitation_and_does_without() { + let v: VulnRefData = serde_json::from_value(serde_json::json!({ + "id": "GHSA-jfh8-c2jp-5v3q", "source": "osv", "severity": "CRITICAL", "url": null, + "exploitation": { + "kev": { "date_added": "2021-12-10", "known_ransomware": true }, + "epss": { "score": 0.94, "percentile": 0.999, "date": "2026-10-05" }, + "ssvc_exploitation": "active" + } + })) + .unwrap(); + let e = v.exploitation.unwrap(); + assert!(e.kev.unwrap().known_ransomware); + assert_eq!(e.ssvc_exploitation.as_deref(), Some("active")); + let old: VulnRefData = serde_json::from_value(serde_json::json!({ + "id": "CVE-2021-0341", "source": "nvd", "severity": null, "url": null + })) + .unwrap(); + assert!(old.exploitation.is_none()); + } +} diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index b68ef75..2df4488 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -310,6 +310,13 @@ pub fn SbomPage() -> Element { if n == 1 { "1 CVE ▾".to_string() } else { format!("{n} CVEs ▾") } } } + if entry.known_vulnerabilities.iter().any(|v| v.exploitation.as_ref().is_some_and(|e| e.kev.is_some())) { + span { + class: "badge badge-critical sbom-kev-marker", + title: "{tx::KEV_BADGE.get(lang)}", + "KEV" + } + } } else { span { style: "color: var(--success);", @@ -334,6 +341,25 @@ pub fn SbomPage() -> Element { "{sev}" } } + if let Some(kev) = vuln.exploitation.as_ref().and_then(|e| e.kev.as_ref()) { + span { + class: "badge badge-critical", + title: "{kev_title(kev, lang)}", + {tx::KEV_BADGE.get(lang)} + } + } + if let Some(epss) = vuln.exploitation.as_ref().and_then(|e| e.epss.as_ref()) { + span { + class: "badge sbom-epss-badge", + title: "{tx::EPSS_HINT.get(lang)}", + "{epss_label(epss)}" + } + } + } + if let Some(ssvc) = vuln.exploitation.as_ref().and_then(|e| e.ssvc_exploitation.as_ref()) { + div { class: "sbom-vuln-ssvc", + "{tx::SSVC_EXPLOITATION.get(lang)}: {ssvc}" + } } if let Some(url) = &vuln.url { a { @@ -345,6 +371,16 @@ pub fn SbomPage() -> Element { } } } + if entry.known_vulnerabilities.iter().any(|v| v.exploitation.as_ref().is_some_and(|e| e.epss.is_some())) { + p { class: "sbom-vuln-attribution", + a { + href: "https://www.first.org/epss", + target: "_blank", + rel: "noopener", + {tx::EPSS_ATTRIBUTION.get(lang)} + } + } + } } } } @@ -739,3 +775,22 @@ fn trigger_download(content: &str, filename: &str) { fn trigger_download(_content: &str, _filename: &str) { // Server-side: no-op (downloads only happen in the browser) } + +/// The tooltip of a KEV badge: since when, and whether ransomware uses it. +fn kev_title(kev: &KevData, lang: Lang) -> String { + let mut title = format!("{} {}", tx::KEV_SINCE.get(lang), kev.date_added); + if kev.known_ransomware { + title.push_str(&format!(", {}", tx::KEV_RANSOMWARE.get(lang))); + } + title +} + +/// An EPSS badge's text: the probability and the percentile, in percent +/// (`EPSS 94.4 % · P99`). +fn epss_label(epss: &EpssData) -> String { + format!( + "EPSS {:.1} % · P{:.0}", + epss.score * 100.0, + (epss.percentile * 100.0).floor() + ) +} diff --git a/docs/guide/issues.md b/docs/guide/issues.md index 549b151..3b635ab 100644 --- a/docs/guide/issues.md +++ b/docs/guide/issues.md @@ -13,6 +13,10 @@ When a scan discovers new findings, the following happens automatically: This means every actionable finding gets tracked in the same system your developers already use. +### CVE issues (managed repositories) + +For a repository from a managed git source, known vulnerabilities in its dependencies become issues too: one per package and CVE, labelled `cve`. A critical or high CVE opens one, and so does any CVE in CISA's Known Exploited Vulnerabilities catalog (rated at least high). A CVE whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`) is rated one step higher, so a medium one opens an issue as high. The issue names the KEV entry, the EPSS score with its attribution, and CISA's SSVC exploitation where known. When a complete scan no longer finds the CVE, the issue is closed; when it comes back, it is reopened. + ## Issues List Open **Tickets** (Issues) in the sidebar to see all tracker issues across your targets. diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 89e5503..0433eaf 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -123,6 +123,25 @@ components of all targets, 50 per page. Click the CVE count to expand the details: the vulnerability ID, the source database, the severity where known, and **Hinweis ansehen →** (View advisory). +A component with a CVE that is exploited in the wild carries a red **KEV** +marker next to its count. In the details, each CVE shows what is known about +its exploitation: + +- **Aktiv ausgenutzt (KEV)** (Actively exploited): the CVE is in CISA's + [Known Exploited Vulnerabilities](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) + catalog; the tooltip says since when, and whether it is known from + ransomware campaigns. +- **EPSS 12.3 % · P97**: FIRST's [EPSS](https://www.first.org/epss) estimate + that the CVE is exploited in the next 30 days, and its percentile among all + scored CVEs. The source is credited under the details. +- **SSVC-Ausnutzung (CISA Vulnrichment)**: CISA's SSVC decision on + exploitation (`none`, `poc`, `active`), where CISA has rated the CVE. + +These are looked up once a day; see +[KEV, EPSS and Vulnrichment](/reference/tools#kev-epss-and-vulnrichment-exploitation). +In a managed repository, a CVE in KEV always opens an issue, and one with a +high EPSS percentile is rated one step higher (see [Issues](/guide/issues)). + ## Licenses Tab The **Lizenzen** tab summarises the licenses. diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 214bcb3..d1bbe23 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -134,6 +134,24 @@ Matches are stored as CVE alerts with CVSS scores and re-checked hourly, so newl Only package URLs (purl), CVE ids and CPE product prefixes are sent. Both sources are reached through the net guard like every other outbound request (see [Outbound connections](#outbound-connections-egress)). +## KEV, EPSS and Vulnrichment -- Exploitation + +Every CVE alert is enriched with what is known about its exploitation, after the CVE lookup and before the alerts are stored (`pipeline/cve_enrichment.rs`): + +| 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 | +| [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 | + +The answers are attached to the alert (`exploitation`) and to the SBOM's reference to the same advisory, so the SBOM page, the evidence pack (`cve-alerts.json`), the MCP tools and the LLM triage see them. In the CVE issues of a managed repository (see [Issues](/guide/issues)) a CVE in KEV always opens an issue, rated at least high, and one whose EPSS percentile reaches `CVE_ISSUE_EPSS_PERCENTILE` (default `0.95`; `off` leaves EPSS out) is rated one step higher: a medium CVE then opens an issue as high. A finding that names a CVE gets the same facts in its triage prompt. + +**Cache:** answers are kept for a day in the admin database (`__admin`), shared by all tenants: `cve_exploitation` (one row per CVE id) and `cisa_kev` (the catalog). They are public data keyed by CVE id; nothing of the tenant is stored. A source that does not answer leaves its part unknown, is not cached and is asked again on the next scan; it never fails the scan. One scan looks up at most 500 uncached CVEs (8 Vulnrichment reads at once, 2 minutes in total). + +**Attribution:** wherever an EPSS score is shown (SBOM page, CVE issues) it is credited: *EPSS: FIRST.org, Exploit Prediction Scoring System, https://www.first.org/epss*. + +`CVE_EXPLOIT_LOOKUP=false` keeps the agent from contacting the three sources. + ## nuget.org -- NuGet Licenses Licenses of NuGet packages that no `.nuspec` in the tree gives are read from the [nuget.org registration API](https://learn.microsoft.com/nuget/api/registration-base-url-resource) (`api.nuget.org`). Only the package id and version are sent, never for an id a `nuget.config` routes to another feed (see [.NET projects](/guide/dotnet-en)). The lookup is bounded per scan (8 requests at once, 10 s per request, 60 s and 300 uncached packages in total); answers are cached for all tenants. Set `NUGET_LICENSE_LOOKUP=false` to keep the agent from contacting nuget.org. @@ -248,6 +266,9 @@ 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/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` | | `repo1.maven.org`, `dl.google.com` (POMs) | Maven group, artifact and version (and parent POMs), not when the build names a non-public repository | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org | `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 34a1baf..0ae7428 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -331,6 +331,30 @@ target with history (findings, at least one marked by a person, issues). finding no longer close and reopen it and its issue. A change to the flagged line itself still does. +### 19. #493 KEV, EPSS and Vulnrichment on CVE alerts + +- **Do:** scan a target with a known exploited dependency, e.g. a Maven + project pinning `org.apache.logging.log4j:log4j-core:2.14.1` (Log4Shell, + CVE-2021-44228) next to `com.google.code.gson:gson:2.8.8`; then scan it + again within the hour. +- **Expect:** **SBOM** shows a red **KEV** marker next to log4j-core's CVE + count; expanded, CVE-2021-44228's card has **Aktiv ausgenutzt (KEV)** + (tooltip: since 2021-12-10, ransomware use), **EPSS … · P100** and + "SSVC-Ausnutzung (CISA Vulnrichment): active", with the FIRST EPSS credit + under the cards. gson's CVE has an EPSS badge and no KEV badge. The evidence + pack's `cve-alerts.json` carries `exploitation` on each alert. On a managed + repository, log4j's CVE has an issue whose body names KEV, EPSS (with the + credit) and SSVC. +- **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. +- **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 + CVEs whatever their severity. + ## After the pass - The nightly job on `main` is green with the new mobile targets.