Files
pruefwerk/compliance-core/src/vex_docs.rs
T
sharang 1f02a89226
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Docs (push) Successful in 1m17s
CI / Deploy MCP (push) Successful in 2m38s
fix(vex): keep the alert's purl for components that left the SBOM (#532)
2026-10-08 21:45:37 +00:00

227 lines
9.2 KiB
Rust

//! 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`; one a complete scan no
//! longer finds is `fixed`. 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` |
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};
/// 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<Utc>,
}
/// The status an alert is stated with: its VEX statement's, `fixed` once a
/// complete scan found it gone, else `under_investigation`.
pub fn status_of(alert: &CveAlert) -> VexStatus {
match (&alert.vex, alert.resolved_at) {
(Some(vex), _) => vex.status,
(None, Some(_)) => VexStatus::Fixed,
(None, None) => VexStatus::UnderInvestigation,
}
}
/// 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<Utc>) -> String {
at.to_rfc3339_opts(SecondsFormat::Secs, true)
}
/// 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<serde_json::Value> = input
.alerts
.iter()
.map(|alert| {
let component = component_id(alert, input.sbom);
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 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.vex {
statement["timestamp"] = serde_json::json!(rfc3339(vex.at));
if let Some(j) = vex.justification {
statement["justification"] = serde_json::json!(j);
}
if let Some(text) = vex.impact_statement.as_deref() {
statement["impact_statement"] = 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 alert 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<String> = components
.iter()
.filter_map(|c| c["bom-ref"].as_str().map(str::to_string))
.collect();
let vulnerabilities: Vec<serde_json::Value> = input
.alerts
.iter()
.enumerate()
.map(|(i, alert)| {
let component = component_id(alert, input.sbom);
// 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.vex {
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 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 }],
});
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
}