//! VEX documents for a target (#498): what its manufacturer states about each //! known vulnerability of its components, in OpenVEX 0.2.0 and in CycloneDX //! 1.6 (the SBOM with its vulnerabilities and their analysis). //! //! An alert nobody assessed is `under_investigation`, also when a complete //! scan no longer finds it: a CVE can disappear without a fix, so only a //! statement says `fixed` (#994). The CycloneDX analysis uses CycloneDX's //! terms: //! //! | OpenVEX | CycloneDX | //! |---|---| //! | `under_investigation` | `in_triage` | //! | `affected` | `exploitable` | //! | `not_affected` | `not_affected` | //! | `fixed` | `resolved` | //! | `component_not_present`, `vulnerable_code_not_present` | `code_not_present` | //! | `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, cdx_vulnerability, component_ref, product_ref, }; /// What a VEX document is built from. pub struct VexInput<'a> { /// The product: the target's name. pub subject: &'a str, /// Who states it (the manufacturer: the workspace's name). pub author: &'a str, /// The tool and version that wrote it (`Prüfwerk 0.4.5`). pub tooling: &'a str, pub alerts: &'a [CveAlert], pub sbom: &'a [SbomEntry], pub now: DateTime, } /// The status an alert is stated with: its VEX statement's /// ([`CveAlert::statement`]), else `under_investigation`. A CVE a complete /// scan no longer finds is not thereby `fixed` (#994). pub fn status_of(alert: &CveAlert) -> VexStatus { alert .statement() .map_or(VexStatus::UnderInvestigation, |vex| vex.status) } /// The SBOM entry an alert is about, if it is in the SBOM. fn entry_of<'a>(alert: &CveAlert, sbom: &'a [SbomEntry]) -> Option<&'a SbomEntry> { sbom.iter().find(|e| { e.name.eq_ignore_ascii_case(&alert.affected_package) && e.version == alert.affected_version }) } /// The identifier of the component an alert is about: the purl stored on /// the alert, else the SBOM's `bom-ref` (its purl), else a generic purl of /// the package and version. The stored purl comes first because a fixed /// alert's component has usually left the SBOM. pub(crate) fn component_id(alert: &CveAlert, sbom: &[SbomEntry]) -> String { if let Some(purl) = &alert.purl { return purl.clone(); } entry_of(alert, sbom).map_or_else( || { let mut name = product_ref(&alert.affected_package); name.push('@'); name.push_str(&alert.affected_version); name }, component_ref, ) } 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.statement().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 = 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": 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!({ "vulnerability": vulnerability, "products": [{ "@id": product, "identifiers": { "purl": product }, "subcomponents": [subcomponent], }], "status": status, }); if let Some(vex) = alert.statement() { statement["timestamp"] = serde_json::json!(rfc3339(vex.at)); if let Some(j) = vex.justification { statement["justification"] = serde_json::json!(j); } // OpenVEX's impact statement belongs to `not_affected`; the // reason of another status (a scan's note) is its status note. if let Some(text) = vex.impact_statement.as_deref() { let field = if status == VexStatus::NotAffected { "impact_statement" } else { "status_notes" }; statement[field] = serde_json::json!(text); } if let Some(text) = vex.action_statement.as_deref() { statement["action_statement"] = serde_json::json!(text); } } else if status == VexStatus::Fixed { statement["status_notes"] = serde_json::json!("The component or version is no longer in the product."); } statement }) .collect(); serde_json::json!({ "@context": "https://openvex.dev/ns/v0.2.0", "@id": format!("urn:uuid:{}", uuid::Uuid::new_v4()), "author": input.author, "timestamp": rfc3339(input.now), "version": 1, "tooling": input.tooling, "statements": statements, }) } /// CycloneDX's analysis state for a VEX status. fn cdx_state(status: VexStatus) -> &'static str { match status { VexStatus::UnderInvestigation => "in_triage", VexStatus::Affected => "exploitable", VexStatus::NotAffected => "not_affected", VexStatus::Fixed => "resolved", } } /// CycloneDX's justification for an OpenVEX one. fn cdx_justification(justification: VexJustification) -> &'static str { match justification { VexJustification::ComponentNotPresent | VexJustification::VulnerableCodeNotPresent => { "code_not_present" } VexJustification::VulnerableCodeNotInExecutePath => "code_not_reachable", VexJustification::VulnerableCodeCannotBeControlledByAdversary => "requires_environment", VexJustification::InlineMitigationsAlreadyExist => "protected_by_mitigating_control", } } /// 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); let mut components = cdx_components(input.sbom); let mut refs: std::collections::HashSet = components .iter() .filter_map(|c| c["bom-ref"].as_str().map(str::to_string)) .collect(); let vulnerabilities: Vec = statements(input) .into_iter() .enumerate() .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()) { components.push(serde_json::json!({ "type": "library", "bom-ref": component, "name": alert.affected_package, "version": alert.affected_version, })); } let status = status_of(alert); let mut analysis = serde_json::json!({ "state": cdx_state(status) }); if let Some(vex) = alert.statement() { if let Some(j) = vex.justification { analysis["justification"] = serde_json::json!(cdx_justification(j)); } let detail: Vec<&str> = [ vex.impact_statement.as_deref(), vex.action_statement.as_deref(), ] .into_iter() .flatten() .collect(); if !detail.is_empty() { analysis["detail"] = serde_json::json!(detail.join("\n\n")); } } if status == VexStatus::Affected && !alert.fixed_versions.is_empty() { analysis["response"] = serde_json::json!(["update"]); } 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) }]); } if let Some(summary) = alert.summary.as_deref() { v["description"] = serde_json::json!(summary); } if !alert.fixed_versions.is_empty() { v["recommendation"] = serde_json::json!(format!( "Update {} to {}.", alert.affected_package, alert.fixed_versions.join(" or ") )); } v }) .collect(); doc["components"] = serde_json::Value::Array(components); doc["vulnerabilities"] = serde_json::Value::Array(vulnerabilities); doc }