From 44b2f38841b93163d4ff4e422b0a50f2541b4717 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 9 Oct 2026 13:22:05 +0000 Subject: [PATCH] fix(vex): CVE is the primary vulnerability id in VEX, CSAF and CycloneDX, GHSA an alias (#542) --- .../src/pentest/prompt_builder.rs | 1 + compliance-agent/src/pipeline/csaf_match.rs | 2 + compliance-agent/src/pipeline/cve.rs | 3 + .../src/pipeline/cve_enrichment.rs | 21 +-- compliance-agent/src/pipeline/sbom/mod.rs | 1 + compliance-core/src/csaf_docs.rs | 107 ++++-------- compliance-core/src/models/cve.rs | 128 +++++++++++++- compliance-core/src/models/mod.rs | 5 +- compliance-core/src/models/sbom.rs | 11 ++ compliance-core/src/sbom_docs.rs | 114 ++++++++---- compliance-core/src/vex_docs.rs | 109 +++++++++--- compliance-core/tests/vex_schemas.rs | 162 +++++++++++++++++- docs/guide/sbom.md | 9 +- docs/guide/vex-en.md | 7 + docs/guide/vex.md | 8 + 15 files changed, 531 insertions(+), 157 deletions(-) diff --git a/compliance-agent/src/pentest/prompt_builder.rs b/compliance-agent/src/pentest/prompt_builder.rs index 9afa3b9..d6b3d2d 100644 --- a/compliance-agent/src/pentest/prompt_builder.rs +++ b/compliance-agent/src/pentest/prompt_builder.rs @@ -381,6 +381,7 @@ mod tests { severity: None, url: None, exploitation: None, + aliases: Vec::new(), }) .collect(); entry diff --git a/compliance-agent/src/pipeline/csaf_match.rs b/compliance-agent/src/pipeline/csaf_match.rs index cec139a..3123553 100644 --- a/compliance-agent/src/pipeline/csaf_match.rs +++ b/compliance-agent/src/pipeline/csaf_match.rs @@ -192,6 +192,7 @@ pub(crate) fn apply( severity: hit.vulnerability.severity.clone(), url: hit.advisory.url.clone(), exploitation: None, + aliases: Vec::new(), }); } let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name); @@ -333,6 +334,7 @@ mod tests { severity: None, url: None, exploitation: None, + aliases: Vec::new(), }); let mut nvd = CveAlert::new( "CVE-2026-90001".into(), diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index c66bb9d..d2c2fe4 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -79,6 +79,7 @@ impl CveScanner { severity: vuln.severity, url: Some(format!("https://osv.dev/vulnerability/{}", vuln.id)), exploitation: None, + aliases: Vec::new(), }); let mut alert = CveAlert::new( vuln.id, @@ -116,6 +117,7 @@ impl CveScanner { for vuln in &mut entry.known_vulnerabilities { if let Some(detail) = details.get(&vuln.id) { vuln.severity = detail.severity.clone().or(vuln.severity.take()); + vuln.aliases.clone_from(&detail.aliases); } } } @@ -381,6 +383,7 @@ fn record_nvd( severity: None, url: Some(format!("https://nvd.nist.gov/vuln/detail/{}", cve.id)), exploitation: None, + aliases: Vec::new(), }); } let mut alert = CveAlert::new( diff --git a/compliance-agent/src/pipeline/cve_enrichment.rs b/compliance-agent/src/pipeline/cve_enrichment.rs index bae1d6c..ebed5e0 100644 --- a/compliance-agent/src/pipeline/cve_enrichment.rs +++ b/compliance-agent/src/pipeline/cve_enrichment.rs @@ -28,7 +28,7 @@ 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::models::{is_cve, CveAlert, EpssScore, Exploitation, KevEntry, SbomEntry}; use compliance_core::net_guard::NetGuard; use compliance_core::CoreError; use futures_util::future::BoxFuture; @@ -194,7 +194,7 @@ impl CveEnricher { let cves: BTreeSet = alerts .iter() .map(|a| a.cve().to_string()) - .filter(|id| is_cve_id(id)) + .filter(|id| is_cve(id)) .collect(); let mut counts = EnrichCounts { cves: cves.len(), @@ -446,22 +446,10 @@ impl CveEnricher { } } -/// 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) { + if !is_cve(cve) { return None; } let mut parts = cve.splitn(3, '-').skip(1); @@ -930,6 +918,7 @@ mod tests { severity: None, url: None, exploitation: None, + aliases: Vec::new(), }); e } @@ -977,7 +966,7 @@ mod tests { "CVE-2021-../x", "RUSTSEC-2021-0001", ] { - assert!(!is_cve_id(id), "{id}"); + assert!(!is_cve(id), "{id}"); assert_eq!(vulnrichment_path(id), None); } } diff --git a/compliance-agent/src/pipeline/sbom/mod.rs b/compliance-agent/src/pipeline/sbom/mod.rs index 3631258..1015831 100644 --- a/compliance-agent/src/pipeline/sbom/mod.rs +++ b/compliance-agent/src/pipeline/sbom/mod.rs @@ -488,6 +488,7 @@ fn merge_audit_vulns(entries: &mut [SbomEntry], vulns: Vec String { format!("{name}.json") } -/// Whether `id` is a CVE id, which CSAF keeps in its own field. -fn is_cve(id: &str) -> bool { - id.strip_prefix("CVE-") - .and_then(|rest| rest.split_once('-')) - .is_some_and(|(year, number)| { - year.len() == 4 - && number.len() >= 4 - && year - .bytes() - .chain(number.bytes()) - .all(|b| b.is_ascii_digit()) - }) -} - -/// The id CSAF lists a vulnerability under: the alert's CVE, or the CVE -/// among its aliases, else its own id. Alerts with the same key are one -/// vulnerability (CSAF forbids listing a CVE twice). -fn vulnerability_key(alert: &CveAlert) -> &str { - if is_cve(&alert.cve_id) { - return &alert.cve_id; - } - alert - .aliases - .iter() - .find(|a| is_cve(a)) - .map_or(alert.cve_id.as_str(), String::as_str) -} - -/// The system a non-CVE id belongs to (`GHSA-…` is GitHub's advisory -/// database). -fn id_system(id: &str) -> &str { - id.split_once('-').map_or("OSV", |(prefix, _)| prefix) -} - /// The components the alerts are about, each once: `(id, name, purl)`. fn components(input: &VexInput<'_>) -> Vec<(String, String, String)> { let mut out: Vec<(String, String, String)> = Vec::new(); @@ -177,58 +143,62 @@ fn push_product(parent: &mut serde_json::Value, field: &str, key: &str, product: } } -/// One vulnerability of the advisory, from all alerts listed under `key`. +/// One vulnerability of the advisory, from all statements listed under +/// `key` (the CVE, or the advisory's id without one): the CVE in its own +/// field, the other ids (a GitHub advisory) under `ids`. fn vulnerability( key: &str, - alerts: &[&CveAlert], + statements: &[&Statement<'_>], components: &[(String, String, String)], input: &VexInput<'_>, ) -> serde_json::Value { let mut v = serde_json::json!({ "product_status": {} }); + let mut ids: Vec<&str> = Vec::new(); if is_cve(key) { v["cve"] = serde_json::json!(key); + } else { + ids.push(key); } - let mut ids: Vec<&str> = Vec::new(); - for alert in alerts { - for id in std::iter::once(&alert.cve_id).chain(&alert.aliases) { - if !is_cve(id) && !ids.contains(&id.as_str()) { - ids.push(id); - } + for id in statements.iter().flat_map(|st| &st.other_ids) { + if !is_cve(id) && !ids.contains(id) { + ids.push(id); } } if !ids.is_empty() { v["ids"] = ids .iter() - .map(|id| serde_json::json!({ "system_name": id_system(id), "text": id })) + .map(|id| serde_json::json!({ "system_name": advisory_source(id).0, "text": id })) .collect(); } // The VEX profile requires notes on every vulnerability; without an // advisory summary they say what is affected. - let text = alerts + let text = input + .alerts .iter() + .filter(|a| a.cve() == key) .find_map(|a| a.summary.clone()) .unwrap_or_else(|| { - let packages: Vec = alerts + let packages: Vec = statements .iter() - .map(|a| format!("{} {}", a.affected_package, a.affected_version)) + .map(|st| { + format!( + "{} {}", + st.alert.affected_package, st.alert.affected_version + ) + }) .collect(); format!("{key} in {}.", packages.join(", ")) }); v["notes"] = serde_json::json!([{ "category": "description", "text": text }]); let (mut flags, mut threats, mut remediations) = (Vec::new(), Vec::new(), Vec::new()); - for alert in alerts { - let purl = component_id(alert, input.sbom); - let Some((id, ..)) = components.iter().find(|(.., p)| *p == purl) else { + // One statement per component, so each product has one status. + for st in statements { + let alert = st.alert; + let Some((id, ..)) = components.iter().find(|(.., p)| *p == st.component) else { continue; }; let product = in_product(id); let status = status_of(alert); - let listed = v["product_status"][status_key(status)] - .as_array() - .is_some_and(|l| l.iter().any(|p| p == product.as_str())); - if listed { - continue; - } push_product(&mut v, "product_status", status_key(status), &product); let Some(vex) = &alert.vex else { continue }; match status { @@ -288,22 +258,21 @@ fn vulnerability( pub fn csaf_vex(input: &VexInput<'_>, namespace: &str, lang: &str) -> serde_json::Value { let now = rfc3339(input.now); let components = components(input); + let statements = statements(input); + // One vulnerability per CVE (CSAF forbids listing a CVE twice), in the + // order the statements first name it. let mut keys: Vec<&str> = Vec::new(); - for alert in input.alerts { - let key = vulnerability_key(alert); - if !keys.contains(&key) { - keys.push(key); + for st in &statements { + if !keys.contains(&st.id()) { + keys.push(st.id()); } } let vulnerabilities: Vec = keys .iter() .map(|key| { - let alerts: Vec<&CveAlert> = input - .alerts - .iter() - .filter(|a| vulnerability_key(a) == *key) - .collect(); - vulnerability(key, &alerts, &components, input) + let of_key: Vec<&Statement<'_>> = + statements.iter().filter(|st| st.id() == *key).collect(); + vulnerability(key, &of_key, &components, input) }) .collect(); serde_json::json!({ @@ -351,10 +320,6 @@ mod tests { assert_eq!(id, "pruefwerk-vex-pump-remote-hmi-20261006"); assert_eq!(filename(&id), "pruefwerk-vex-pump-remote-hmi-20261006.json"); assert_eq!(filename("ACME_SA:2026/01"), "acme_sa_2026_01.json"); - assert!(is_cve("CVE-2021-44228")); - assert!(!is_cve("GHSA-jfh8-c2jp-5v3q")); - assert!(!is_cve("CVE-21-1")); - assert_eq!(id_system("GHSA-jfh8-c2jp-5v3q"), "GHSA"); assert_eq!( placeholder_namespace("example-pumps"), "https://example.invalid/example-pumps" diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index a544e70..119fd5d 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -139,17 +139,68 @@ pub struct CveAlert { pub created_at: DateTime, } +/// Whether `id` is a CVE id (`CVE-2021-44228`: a four-digit year and at +/// least four digits). +pub fn is_cve(id: &str) -> bool { + id.strip_prefix("CVE-") + .and_then(|rest| rest.split_once('-')) + .is_some_and(|(year, number)| { + year.len() == 4 + && number.len() >= 4 + && year + .bytes() + .chain(number.bytes()) + .all(|b| b.is_ascii_digit()) + }) +} + +/// The id a vulnerability known as `id` (with `aliases`) is listed under: +/// `id` when it is a CVE, else its first CVE alias, else `id` itself. +pub fn primary_id<'a>(id: &'a str, aliases: &'a [String]) -> &'a str { + if is_cve(id) { + return id; + } + aliases + .iter() + .find(|a| is_cve(a)) + .map_or(id, String::as_str) +} + +/// The database an advisory id belongs to and the advisory's page there: +/// NVD for a CVE, GitHub's advisory database for a `GHSA-`, else the id's +/// prefix (`RUSTSEC`, `PYSEC`; `OSV` without one) and its OSV page. +pub fn advisory_source(id: &str) -> (&str, String) { + if is_cve(id) { + return ("NVD", format!("https://nvd.nist.gov/vuln/detail/{id}")); + } + if id.starts_with("GHSA-") { + return ( + "GitHub Security Advisories", + format!("https://github.com/advisories/{id}"), + ); + } + let prefix = id.split_once('-').map_or("OSV", |(prefix, _)| prefix); + (prefix, format!("https://osv.dev/vulnerability/{id}")) +} + impl CveAlert { - /// The CVE id of the advisory: its own id, or a `CVE-` alias of a GHSA - /// or ecosystem advisory; otherwise its own id. + /// The CVE id of the advisory: its own id, or a CVE alias of a GHSA or + /// ecosystem advisory; otherwise its own id. pub fn cve(&self) -> &str { - if self.cve_id.starts_with("CVE-") { - return &self.cve_id; + primary_id(&self.cve_id, &self.aliases) + } + + /// The advisory's ids other than [`Self::cve`], each once: the GHSA of + /// an alert listed under its CVE alias, further aliases. + pub fn other_ids(&self) -> Vec<&str> { + let primary = self.cve(); + let mut ids: Vec<&str> = Vec::with_capacity(self.aliases.len()); + for id in std::iter::once(&self.cve_id).chain(&self.aliases) { + if id != primary && !ids.contains(&id.as_str()) { + ids.push(id); + } } - self.aliases - .iter() - .find(|a| a.starts_with("CVE-")) - .map_or(self.cve_id.as_str(), String::as_str) + ids } pub fn new( @@ -183,3 +234,64 @@ impl CveAlert { } } } + +#[cfg(test)] +mod tests { + use super::*; + + 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 + } + + #[test] + fn a_cve_is_strictly_recognised() { + assert!(is_cve("CVE-2021-44228")); + assert!(!is_cve("GHSA-jfh8-c2jp-5v3q")); + assert!(!is_cve("CVE-21-1")); + assert!(!is_cve("CVE-2021-12a4")); + } + + #[test] + fn the_cve_is_the_primary_id_and_the_rest_are_other_ids() { + // CVE and GHSA: the CVE, whichever of them the alert was found under. + let ghsa = alert("GHSA-jfh8-c2jp-5v3q", &["CVE-2021-44228"]); + assert_eq!(ghsa.cve(), "CVE-2021-44228"); + assert_eq!(ghsa.other_ids(), ["GHSA-jfh8-c2jp-5v3q"]); + let cve = alert("CVE-2021-44228", &["GHSA-jfh8-c2jp-5v3q", "CVE-2021-44228"]); + assert_eq!(cve.cve(), "CVE-2021-44228"); + assert_eq!(cve.other_ids(), ["GHSA-jfh8-c2jp-5v3q"]); + // CVE only. + let only_cve = alert("CVE-2021-44228", &[]); + assert_eq!(only_cve.cve(), "CVE-2021-44228"); + assert!(only_cve.other_ids().is_empty()); + // GHSA only: its own id, as before. + let only_ghsa = alert("GHSA-jfh8-c2jp-5v3q", &["A-171980069"]); + assert_eq!(only_ghsa.cve(), "GHSA-jfh8-c2jp-5v3q"); + assert_eq!(only_ghsa.other_ids(), ["A-171980069"]); + } + + #[test] + fn advisory_ids_name_their_database() { + assert_eq!( + advisory_source("CVE-2021-44228"), + ( + "NVD", + "https://nvd.nist.gov/vuln/detail/CVE-2021-44228".into() + ) + ); + assert_eq!( + advisory_source("GHSA-jfh8-c2jp-5v3q").0, + "GitHub Security Advisories" + ); + assert_eq!(advisory_source("RUSTSEC-2021-0001").0, "RUSTSEC"); + assert_eq!(advisory_source("OSV").0, "OSV"); + } +} diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 917e7a9..a5f31e9 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -26,7 +26,10 @@ pub mod werkbank; pub use auth::{AuthInfo, SupportTenant}; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; pub use credentials::Credentials; -pub use cve::{AdvisoryRef, CveAlert, CveSource, EpssScore, Exploitation, KevEntry}; +pub use cve::{ + advisory_source, is_cve, primary_id, AdvisoryRef, 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 f1cacf2..b7470ff 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -10,6 +10,17 @@ pub struct VulnRef { /// Exploitation of the advisory's CVE (KEV, EPSS, SSVC; #493). #[serde(default, skip_serializing_if = "Option::is_none")] pub exploitation: Option, + /// Other ids of the advisory (a GHSA's `CVE-…`), as OSV lists them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub aliases: Vec, +} + +impl VulnRef { + /// The id the vulnerability is listed under: its CVE when one is known + /// (see [`super::cve::primary_id`]). + pub fn cve(&self) -> &str { + super::cve::primary_id(&self.id, &self.aliases) + } } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index 3cdd4f3..cd6f605 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -8,7 +8,7 @@ //! packages, a dependency graph whose completeness is stated, and licences as //! the suppliers declare them. -use crate::models::{ComponentHash, SbomEntry}; +use crate::models::{advisory_source, is_cve, ComponentHash, SbomEntry}; use crate::purl::Purl; /// The `bom-ref` of a component, which a VEX statement refers to: its purl, @@ -246,56 +246,98 @@ fn cdx_dependencies(doc: &mut serde_json::Value, components: &[serde_json::Value }]); } +/// The identification of a CycloneDX vulnerability known as `primary` and +/// `others`: `id` and `source` of the primary id (NVD for a CVE, else +/// `source`, the scanner that found it), the other ids as `references` to +/// their databases. +pub fn cdx_vulnerability(primary: &str, others: &[&str], source: &str) -> serde_json::Value { + let mut v = if is_cve(primary) { + let (name, url) = advisory_source(primary); + serde_json::json!({ "id": primary, "source": { "name": name, "url": url } }) + } else { + serde_json::json!({ "id": primary, "source": { "name": source } }) + }; + if !others.is_empty() { + v["references"] = others + .iter() + .map(|id| { + let (name, url) = advisory_source(id); + serde_json::json!({ "id": id, "source": { "name": name, "url": url } }) + }) + .collect(); + } + v +} + +/// One vulnerability of a CycloneDX SBOM: its primary id, its other ids, +/// the source and severity it was first found with, and the components it +/// affects. +struct SbomVulnerability<'a> { + id: &'a str, + others: Vec<&'a str>, + source: &'a str, + severity: Option<&'a str>, + affects: Vec, +} + /// A CycloneDX 1.6 document for `entries`, named after `subject`. The known /// vulnerabilities of the components are listed at the top level, each /// naming the components it affects by `bom-ref` (CycloneDX keeps them out of -/// the components). +/// the components). A vulnerability is listed under its CVE when one is +/// known, with its GitHub advisory as a reference. pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { let mut doc = cdx_frame(subject, entries); let components = cdx_components(entries); cdx_dependencies(&mut doc, &components); doc["components"] = serde_json::Value::Array(components); - // One vulnerability per advisory, affecting every component it was - // found in. - let mut vulns: Vec<(String, String, Option, Vec)> = Vec::new(); + // One vulnerability per CVE (or advisory without one), affecting every + // component it was found in, by whichever scanner and id. + let mut vulns: Vec> = Vec::new(); for e in entries { for v in &e.known_vulnerabilities { - let reference = component_ref(e); - match vulns - .iter_mut() - .find(|(id, source, ..)| *id == v.id && *source == v.source) - { - Some((.., refs)) => { - if !refs.contains(&reference) { - refs.push(reference); - } + let id = v.cve(); + let i = match vulns.iter().position(|known| known.id == id) { + Some(i) => i, + None => { + vulns.push(SbomVulnerability { + id, + others: Vec::new(), + source: &v.source, + severity: None, + affects: Vec::new(), + }); + vulns.len() - 1 } - None => vulns.push(( - v.id.clone(), - v.source.clone(), - v.severity.clone(), - vec![reference], - )), + }; + let known = &mut vulns[i]; + for other in std::iter::once(&v.id).chain(&v.aliases) { + if other != id && !known.others.contains(&other.as_str()) { + known.others.push(other); + } + } + known.severity = known.severity.or(v.severity.as_deref()); + let reference = component_ref(e); + if !known.affects.contains(&reference) { + known.affects.push(reference); } } } if !vulns.is_empty() { - doc["vulnerabilities"] = serde_json::Value::Array( - vulns - .into_iter() - .map(|(id, source, severity, refs)| { - let mut v = serde_json::json!({ - "id": id, - "source": { "name": source }, - "affects": refs.into_iter().map(|r| serde_json::json!({ "ref": r })).collect::>(), - }); - if let Some(severity) = severity { - v["ratings"] = serde_json::json!([{ "severity": cdx_severity(&severity) }]); - } - v - }) - .collect(), - ); + doc["vulnerabilities"] = vulns + .into_iter() + .map(|known| { + let mut v = cdx_vulnerability(known.id, &known.others, known.source); + v["affects"] = known + .affects + .into_iter() + .map(|r| serde_json::json!({ "ref": r })) + .collect(); + if let Some(severity) = known.severity { + v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]); + } + v + }) + .collect(); } doc } diff --git a/compliance-core/src/vex_docs.rs b/compliance-core/src/vex_docs.rs index b1ac6bf..209ea90 100644 --- a/compliance-core/src/vex_docs.rs +++ b/compliance-core/src/vex_docs.rs @@ -15,11 +15,19 @@ //! | `vulnerable_code_not_in_execute_path` | `code_not_reachable` | //! | `vulnerable_code_cannot_be_controlled_by_adversary` | `requires_environment` | //! | `inline_mitigations_already_exist` | `protected_by_mitigating_control` | +//! +//! A vulnerability is named by its CVE when one is known (ENISA and BSI work +//! with CVE ids), its GitHub advisory and other ids are aliases (OpenVEX) or +//! references (CycloneDX); without a CVE it keeps the advisory's id. Alerts of +//! the same CVE in the same component (a GitHub advisory and the CVE it +//! aliases, found by different scanners) are one statement. use chrono::{DateTime, SecondsFormat, Utc}; use crate::models::{CveAlert, SbomEntry, VexJustification, VexStatus}; -use crate::sbom_docs::{cdx_components, cdx_frame, cdx_severity, component_ref, product_ref}; +use crate::sbom_docs::{ + cdx_components, cdx_frame, cdx_severity, cdx_vulnerability, component_ref, product_ref, +}; /// What a VEX document is built from. pub struct VexInput<'a> { @@ -74,22 +82,82 @@ pub(crate) fn rfc3339(at: DateTime) -> String { at.to_rfc3339_opts(SecondsFormat::Secs, true) } +/// One statement of a VEX document: a vulnerability in a component, from +/// all alerts of its CVE in that component. +pub(crate) struct Statement<'a> { + /// The alert whose status is stated (see [`statements`]). + pub(crate) alert: &'a CveAlert, + /// The component's id ([`component_id`]). + pub(crate) component: String, + /// The vulnerability's ids other than [`CveAlert::cve`] across the + /// alerts, each once. + pub(crate) other_ids: Vec<&'a str>, +} + +impl Statement<'_> { + /// The id the vulnerability is listed under: its CVE when one is known. + pub(crate) fn id(&self) -> &str { + self.alert.cve() + } +} + +/// How much an alert's status counts when two alerts of the same CVE name +/// the same component: an explicit statement (the latest one) over none, +/// then an open alert over a resolved one. +fn weight(alert: &CveAlert) -> (Option>, bool) { + ( + alert.vex.as_ref().map(|v| v.at), + alert.resolved_at.is_none(), + ) +} + +/// The statements of `input`, one per CVE and component in the order the +/// alerts first name them. Of several alerts of one CVE in one component +/// the one with the highest [`weight`] states the status (the first on a +/// tie). +pub(crate) fn statements<'a>(input: &VexInput<'a>) -> Vec> { + let mut out: Vec> = Vec::with_capacity(input.alerts.len()); + for alert in input.alerts { + let component = component_id(alert, input.sbom); + let known = out + .iter() + .position(|s| s.component == component && s.id() == alert.cve()); + let Some(i) = known else { + out.push(Statement { + alert, + component, + other_ids: alert.other_ids(), + }); + continue; + }; + let statement = &mut out[i]; + for id in alert.other_ids() { + if !statement.other_ids.contains(&id) { + statement.other_ids.push(id); + } + } + if weight(alert) > weight(statement.alert) { + statement.alert = alert; + } + } + out +} + /// An OpenVEX 0.2.0 document: one statement per alert, about the product /// with the affected component as its subcomponent. pub fn openvex(input: &VexInput<'_>) -> serde_json::Value { let product = product_ref(input.subject); - let statements: Vec = input - .alerts - .iter() - .map(|alert| { - let component = component_id(alert, input.sbom); + let statements: Vec = statements(input) + .into_iter() + .map(|st| { + let (alert, component) = (st.alert, &st.component); let mut subcomponent = serde_json::json!({ "@id": component }); if component.starts_with("pkg:") { subcomponent["identifiers"] = serde_json::json!({ "purl": component }); } - let mut vulnerability = serde_json::json!({ "name": alert.cve_id }); - if !alert.aliases.is_empty() { - vulnerability["aliases"] = serde_json::json!(alert.aliases); + let mut vulnerability = serde_json::json!({ "name": st.id() }); + if !st.other_ids.is_empty() { + vulnerability["aliases"] = serde_json::json!(st.other_ids); } let status = status_of(alert); let mut statement = serde_json::json!({ @@ -152,7 +220,7 @@ fn cdx_justification(justification: VexJustification) -> &'static str { } } -/// A CycloneDX 1.6 VEX: the SBOM's components, and every alert as a +/// A CycloneDX 1.6 VEX: the SBOM's components, and every statement as a /// vulnerability with its analysis, affecting its component by `bom-ref`. pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value { let mut doc = cdx_frame(input.subject, input.sbom); @@ -161,12 +229,11 @@ pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value { .iter() .filter_map(|c| c["bom-ref"].as_str().map(str::to_string)) .collect(); - let vulnerabilities: Vec = input - .alerts - .iter() + let vulnerabilities: Vec = statements(input) + .into_iter() .enumerate() - .map(|(i, alert)| { - let component = component_id(alert, input.sbom); + .map(|(i, st)| { + let (alert, component) = (st.alert, &st.component); // A component the SBOM no longer lists (a fixed one) is still // named, so the reference resolves. if refs.insert(component.clone()) { @@ -197,13 +264,11 @@ pub fn cyclonedx_vex(input: &VexInput<'_>) -> serde_json::Value { if status == VexStatus::Affected && !alert.fixed_versions.is_empty() { analysis["response"] = serde_json::json!(["update"]); } - let mut v = serde_json::json!({ - "bom-ref": format!("vex-{i}-{}", alert.cve_id), - "id": alert.cve_id, - "source": { "name": format!("{:?}", alert.source).to_uppercase() }, - "analysis": analysis, - "affects": [{ "ref": component }], - }); + let source = format!("{:?}", alert.source).to_uppercase(); + let mut v = cdx_vulnerability(st.id(), &st.other_ids, &source); + v["bom-ref"] = serde_json::json!(format!("vex-{i}-{}", st.id())); + v["analysis"] = analysis; + v["affects"] = serde_json::json!([{ "ref": component }]); if let Some(severity) = alert.severity.as_deref() { v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]); } diff --git a/compliance-core/tests/vex_schemas.rs b/compliance-core/tests/vex_schemas.rs index 440851e..6c385c9 100644 --- a/compliance-core/tests/vex_schemas.rs +++ b/compliance-core/tests/vex_schemas.rs @@ -78,6 +78,7 @@ fn sbom() -> Vec { severity: Some("CRITICAL".into()), url: None, exploitation: None, + aliases: Vec::new(), }]; let mut lodash = SbomEntry::new("t".into(), "lodash".into(), "4.17.20".into(), "npm".into()); lodash.purl = Some("pkg:npm/lodash@4.17.20".into()); @@ -335,7 +336,11 @@ fn the_csaf_advisory_is_valid_and_carries_the_statements() { assert_eq!(vulns.len(), 4); let log4shell = &vulns[0]; assert_eq!(log4shell["cve"], "CVE-2021-44228"); - assert_eq!(log4shell["ids"][0]["system_name"], "GHSA"); + assert_eq!( + log4shell["ids"][0]["system_name"], + "GitHub Security Advisories" + ); + assert_eq!(log4shell["ids"][0]["text"], "GHSA-jfh8-c2jp-5v3q"); let affected = log4shell["product_status"]["known_affected"] .as_array() .unwrap(); @@ -461,3 +466,158 @@ fn a_fixed_component_that_left_the_sbom_keeps_its_stored_purl() { ); } } + +#[test] +fn the_cve_is_the_vulnerability_id_and_the_github_advisory_an_alias() { + // Arrange: Log4Shell as a CVE alert on log4j-core and as a GitHub + // advisory aliasing it on log4j-api; a CVE-only alert; a GitHub advisory + // without a CVE. + let sbom = sbom(); + let mut alerts = csaf_alerts(); + alerts.push(alert("GHSA-xxxx-yyyy-zzzz", "lodash", "4.17.20")); + let input = vex_input(&alerts, &sbom); + + // Act + let openvex = vex_docs::openvex(&input); + let cdx = vex_docs::cyclonedx_vex(&input); + let csaf = csaf_docs::csaf_vex(&input, "https://example.invalid/pumps", "en"); + + // Assert + assert_eq!(openvex_errors(&openvex), Vec::::new()); + assert_eq!(cyclonedx_errors(&cdx), Vec::::new()); + assert_eq!(csaf_errors(&csaf), Vec::::new()); + let statements = openvex["statements"].as_array().unwrap(); + let vulns = cdx["vulnerabilities"].as_array().unwrap(); + assert_eq!(statements.len(), 6); + assert_eq!(vulns.len(), 6); + // CVE only: the CVE, from NVD, nothing else. + assert_eq!(statements[0]["vulnerability"]["name"], "CVE-2021-44228"); + assert!(statements[0]["vulnerability"].get("aliases").is_none()); + assert_eq!(vulns[0]["id"], "CVE-2021-44228"); + assert_eq!(vulns[0]["source"]["name"], "NVD"); + assert!(vulns[0].get("references").is_none()); + // CVE and GHSA: the CVE, the GHSA as alias and reference. + let ghsa = "GHSA-jfh8-c2jp-5v3q"; + assert_eq!(statements[4]["vulnerability"]["name"], "CVE-2021-44228"); + assert_eq!( + statements[4]["vulnerability"]["aliases"], + serde_json::json!([ghsa]) + ); + assert_eq!(vulns[4]["id"], "CVE-2021-44228"); + assert_eq!( + vulns[4]["source"]["url"], + "https://nvd.nist.gov/vuln/detail/CVE-2021-44228" + ); + assert_eq!(vulns[4]["references"][0]["id"], ghsa); + assert_eq!( + vulns[4]["references"][0]["source"]["name"], + "GitHub Security Advisories" + ); + assert_eq!(csaf["vulnerabilities"][0]["cve"], "CVE-2021-44228"); + assert_eq!(csaf["vulnerabilities"][0]["ids"][0]["text"], ghsa); + // GHSA only: its own id, as the scanner found it. + let only = "GHSA-xxxx-yyyy-zzzz"; + assert_eq!(statements[5]["vulnerability"]["name"], only); + assert!(statements[5]["vulnerability"].get("aliases").is_none()); + assert_eq!(vulns[5]["id"], only); + assert_eq!(vulns[5]["source"]["name"], "OSV"); + assert!(vulns[5].get("references").is_none()); + let csaf_only = &csaf["vulnerabilities"][4]; + assert!(csaf_only.get("cve").is_none()); + assert_eq!(csaf_only["ids"][0]["text"], only); + assert_eq!( + csaf_only["ids"][0]["system_name"], + "GitHub Security Advisories" + ); +} + +#[test] +fn a_cve_found_as_cve_and_as_github_advisory_in_one_component_is_one_statement() { + // Arrange: the GHSA alert of Log4Shell on the same log4j-core as the + // CVE alert, open; the CVE alert carries the statement. + let sbom = sbom(); + let mut alerts = alerts(); + let mut ghsa = alert("GHSA-jfh8-c2jp-5v3q", "log4j-core", "2.14.1"); + ghsa.aliases = vec!["CVE-2021-44228".into()]; + alerts.insert(0, ghsa); + let input = vex_input(&alerts, &sbom); + + // Act + let openvex = vex_docs::openvex(&input); + let cdx = vex_docs::cyclonedx_vex(&input); + let csaf = csaf_docs::csaf_vex(&input, "https://example.invalid/pumps", "en"); + + // Assert: four statements, Log4Shell once with the stated status. + assert_eq!(openvex_errors(&openvex), Vec::::new()); + assert_eq!(cyclonedx_errors(&cdx), Vec::::new()); + assert_eq!(csaf_errors(&csaf), Vec::::new()); + let statements = openvex["statements"].as_array().unwrap(); + assert_eq!(statements.len(), 4); + let log4shell: Vec<_> = statements + .iter() + .filter(|s| s["vulnerability"]["name"] == "CVE-2021-44228") + .collect(); + assert_eq!(log4shell.len(), 1); + assert_eq!(log4shell[0]["status"], "affected"); + assert_eq!( + log4shell[0]["vulnerability"]["aliases"], + serde_json::json!(["GHSA-jfh8-c2jp-5v3q"]) + ); + let vulns = cdx["vulnerabilities"].as_array().unwrap(); + assert_eq!(vulns.len(), 4); + assert_eq!(vulns[0]["id"], "CVE-2021-44228"); + assert_eq!(vulns[0]["analysis"]["state"], "exploitable"); + let csaf_vulns = csaf["vulnerabilities"].as_array().unwrap(); + assert_eq!(csaf_vulns.len(), 4); + assert_eq!(csaf_vulns[0]["cve"], "CVE-2021-44228"); + assert!(csaf_vulns[0]["product_status"] + .get("under_investigation") + .is_none()); + assert_eq!( + csaf_vulns[0]["product_status"]["known_affected"] + .as_array() + .unwrap() + .len(), + 1 + ); +} + +#[test] +fn the_cyclonedx_sbom_lists_a_vulnerability_under_its_cve_once() { + // Arrange: log4j-core's GHSA aliases the CVE NVD also found it under; + // lodash has a GHSA without a CVE. + let mut sbom = sbom(); + sbom[0].known_vulnerabilities[0].aliases = vec!["CVE-2021-44228".into()]; + sbom[0].known_vulnerabilities.push(VulnRef { + id: "CVE-2021-44228".into(), + source: "nvd".into(), + severity: None, + url: None, + exploitation: None, + aliases: Vec::new(), + }); + sbom[1].known_vulnerabilities.push(VulnRef { + id: "GHSA-xxxx-yyyy-zzzz".into(), + source: "osv".into(), + severity: Some("MODERATE".into()), + url: None, + exploitation: None, + aliases: Vec::new(), + }); + + // Act + let doc = sbom_docs::cyclonedx(&sbom, "Pump Remote"); + + // Assert + assert_eq!(cyclonedx_errors(&doc), Vec::::new()); + let vulns = doc["vulnerabilities"].as_array().unwrap(); + assert_eq!(vulns.len(), 2); + assert_eq!(vulns[0]["id"], "CVE-2021-44228"); + assert_eq!(vulns[0]["source"]["name"], "NVD"); + assert_eq!(vulns[0]["references"][0]["id"], "GHSA-jfh8-c2jp-5v3q"); + assert_eq!(vulns[0]["affects"].as_array().unwrap().len(), 1); + assert_eq!(vulns[0]["ratings"][0]["severity"], "critical"); + assert_eq!(vulns[1]["id"], "GHSA-xxxx-yyyy-zzzz"); + assert_eq!(vulns[1]["source"]["name"], "osv"); + assert!(vulns[1].get("references").is_none()); +} diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index bbb77f8..28b0ee5 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -233,7 +233,9 @@ Prüfwerk has the data, BSI TR-03183-2 v2.1: `acknowledgement: declared`: they are what the package declares, not a licence Prüfwerk concluded. - The known vulnerabilities are listed at the top level, each naming the - components it affects. + components it affects. A vulnerability is listed once under its CVE + (`source` NVD) when one is known, with its GitHub advisory under + `references`; one without a CVE under the advisory's id. ## VEX: the status of each vulnerability @@ -269,7 +271,10 @@ checked against their official schemas, and are part of the evidence pack the purl it had when the alert was found, so a `fixed` statement still matches the SBOM version that contained the component after it was updated or removed. Alerts resolved before Prüfwerk recorded that purl name it -`pkg:generic/@`. CycloneDX names the statuses +`pkg:generic/@`. A vulnerability is named by its CVE when one +is known; its GitHub advisory is an alias (OpenVEX `aliases`, CycloneDX +`references`, CSAF `ids`), and alerts of the same CVE in the same component +are one statement. CycloneDX names the statuses differently: | OpenVEX | CycloneDX `analysis.state` / `justification` | diff --git a/docs/guide/vex-en.md b/docs/guide/vex-en.md index 7a2cf85..206f24f 100644 --- a/docs/guide/vex-en.md +++ b/docs/guide/vex-en.md @@ -55,6 +55,13 @@ statements as OpenVEX 0.2.0 and CycloneDX 1.6. Both files are also in the evidence pack (`vex.openvex.json`, `vex.cdx.json`). Formats, how the terms map and the API: see [SBOM](./sbom.md#vex-the-status-of-each-vulnerability). +In every format (OpenVEX, CycloneDX, CSAF) a vulnerability is named by its +CVE when one is known, as ENISA and BSI do. The GitHub advisory id +(`GHSA-…`) goes alongside: under `aliases` in OpenVEX, `references` in +CycloneDX and `ids` in CSAF. A vulnerability without a CVE keeps the +advisory's id. The same CVE found in a component both as a CVE and as a +GitHub advisory is one statement. + ## CSAF draft **Download CSAF draft** saves the same statements as a CSAF 2.0 VEX advisory diff --git a/docs/guide/vex.md b/docs/guide/vex.md index 8ba6141..fc65382 100644 --- a/docs/guide/vex.md +++ b/docs/guide/vex.md @@ -58,6 +58,14 @@ liegen auch im Nachweispaket (`vex.openvex.json`, `vex.cdx.json`). Formate, Zuordnung der Begriffe und API: siehe [Stückliste (SBOM)](./sbom.md#vex-the-status-of-each-vulnerability). +In allen Formaten (OpenVEX, CycloneDX, CSAF) heißt eine Schwachstelle nach +ihrer CVE, wenn eine bekannt ist, wie bei ENISA und BSI üblich. Die +GitHub-Advisory-Kennung (`GHSA-…`) steht daneben: in OpenVEX unter +`aliases`, in CycloneDX unter `references`, in CSAF unter `ids`. Eine +Schwachstelle ohne CVE behält die Kennung des Advisorys. Wurde dieselbe CVE +in einer Komponente als CVE und als GitHub-Advisory gefunden, ist sie eine +Aussage. + ## CSAF-Entwurf **CSAF-Entwurf herunterladen** speichert dieselben Aussagen als CSAF 2.0