Files
pruefwerk/compliance-core/src/csaf_docs.rs
T
sharang 8538b31682
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m23s
CI / Deploy MCP (push) Successful in 2m54s
CI / Deploy Agent (push) Successful in 9m36s
CI / Deploy Dashboard (push) Successful in 11m5s
feat(vex): CSAF 2.0 VEX advisory draft (#498, 3/4) (#510)
2026-10-06 14:38:42 +00:00

364 lines
13 KiB
Rust

//! A CSAF 2.0 VEX advisory for a target (#498): the same statements as the
//! OpenVEX and CycloneDX VEX documents ([`crate::vex_docs`]) in the format
//! CERTs and the CRA's vulnerability reporting use. Always a draft: the
//! manufacturer checks the publisher and the statements before releasing it.
//!
//! The product tree has the target as product and every affected component
//! as `default_component_of` it; the statuses name the component in the
//! product. A `not_affected` carries its justification as a flag (CSAF's flag
//! labels are OpenVEX's justifications) and its impact statement as a threat;
//! an `affected` its action statement as a remediation.
use chrono::{DateTime, Utc};
use crate::models::{CveAlert, VexStatus};
use crate::sbom_docs::product_ref;
use crate::vex_docs::{component_id, rfc3339, status_of, VexInput};
/// The note every draft carries.
pub const DRAFT_NOTE: &str = "Draft, not published: check publisher and statements before release.";
/// The product id of the target in the product tree.
const PRODUCT_ID: &str = "PRODUCT";
/// The tracking id of the advisory for `subject` on `at`
/// (`pruefwerk-vex-pump-remote-20261006`): lowercase letters, digits and
/// dashes, so the file name CSAF derives from it is the id itself.
pub fn tracking_id(subject: &str, at: DateTime<Utc>) -> String {
let mut slug = String::with_capacity(subject.len());
for c in subject.chars() {
if c.is_ascii_alphanumeric() {
slug.push(c.to_ascii_lowercase());
} else if !slug.ends_with('-') {
slug.push('-');
}
}
format!(
"pruefwerk-vex-{}-{}",
slug.trim_matches('-'),
at.format("%Y%m%d")
)
}
/// The publisher namespace of a draft whose publisher gave none: a URL that
/// cannot resolve (`example.invalid`), so it is plainly to be replaced before
/// release.
pub fn placeholder_namespace(publisher: &str) -> String {
let slug: String = publisher
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
format!("https://example.invalid/{}", slug.trim_matches('-'))
}
/// The file name of an advisory with `tracking_id`, as CSAF 2.0 §5.1 derives
/// it.
pub fn filename(tracking_id: &str) -> String {
let name: String = tracking_id
.to_lowercase()
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '+' || c == '-' {
c
} else {
'_'
}
})
.collect();
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();
for alert in input.alerts {
let purl = component_id(alert, input.sbom);
if out.iter().all(|(.., p)| *p != purl) {
let name = format!("{} {}", alert.affected_package, alert.affected_version);
out.push((format!("C{}", out.len() + 1), name, purl));
}
}
out
}
/// The product id of a component in the product.
fn in_product(component: &str) -> String {
format!("{component}-IN-{PRODUCT_ID}")
}
/// The product tree: the target, its components, and each component as
/// part of the target.
fn product_tree(
input: &VexInput<'_>,
components: &[(String, String, String)],
) -> serde_json::Value {
let mut names = vec![serde_json::json!({
"name": input.subject,
"product_id": PRODUCT_ID,
"product_identification_helper": { "purl": product_ref(input.subject) },
})];
let mut relationships = Vec::with_capacity(components.len());
for (id, name, purl) in components {
let mut product = serde_json::json!({ "name": name, "product_id": id });
if purl.starts_with("pkg:") {
product["product_identification_helper"] = serde_json::json!({ "purl": purl });
}
names.push(product);
relationships.push(serde_json::json!({
"category": "default_component_of",
"product_reference": id,
"relates_to_product_reference": PRODUCT_ID,
"full_product_name": {
"name": format!("{name} in {}", input.subject),
"product_id": in_product(id),
},
}));
}
serde_json::json!({ "full_product_names": names, "relationships": relationships })
}
/// The CSAF `product_status` key of a VEX status.
fn status_key(status: VexStatus) -> &'static str {
match status {
VexStatus::UnderInvestigation => "under_investigation",
VexStatus::Affected => "known_affected",
VexStatus::NotAffected => "known_not_affected",
VexStatus::Fixed => "fixed",
}
}
/// Push `product` onto the list under `key` of the object `parent[field]`,
/// creating both on first use.
fn push_product(parent: &mut serde_json::Value, field: &str, key: &str, product: &str) {
let list = &mut parent[field][key];
match list.as_array_mut() {
Some(list) => list.push(serde_json::json!(product)),
None => *list = serde_json::json!([product]),
}
}
/// One vulnerability of the advisory, from all alerts listed under `key`.
fn vulnerability(
key: &str,
alerts: &[&CveAlert],
components: &[(String, String, String)],
input: &VexInput<'_>,
) -> serde_json::Value {
let mut v = serde_json::json!({ "product_status": {} });
if is_cve(key) {
v["cve"] = serde_json::json!(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);
}
}
}
if !ids.is_empty() {
v["ids"] = ids
.iter()
.map(|id| serde_json::json!({ "system_name": id_system(id), "text": id }))
.collect();
}
// The VEX profile requires notes on every vulnerability; without an
// advisory summary they say what is affected.
let text = alerts
.iter()
.find_map(|a| a.summary.clone())
.unwrap_or_else(|| {
let packages: Vec<String> = alerts
.iter()
.map(|a| format!("{} {}", a.affected_package, a.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 {
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 {
VexStatus::NotAffected => {
if let Some(justification) = vex.justification {
flags.push(serde_json::json!({
"label": justification,
"product_ids": [product],
}));
}
if let Some(text) = vex.impact_statement.as_deref() {
threats.push(serde_json::json!({
"category": "impact",
"details": text,
"product_ids": [product],
}));
}
}
VexStatus::Affected => {
let category = if alert.fixed_versions.is_empty() {
"mitigation"
} else {
"vendor_fix"
};
let details = vex.action_statement.clone().unwrap_or_else(|| {
format!(
"Update {} to {}.",
alert.affected_package,
alert.fixed_versions.join(" or ")
)
});
remediations.push(serde_json::json!({
"category": category,
"details": details,
"product_ids": [product],
}));
}
VexStatus::UnderInvestigation | VexStatus::Fixed => {}
}
}
for (field, list) in [
("flags", flags),
("threats", threats),
("remediations", remediations),
] {
if !list.is_empty() {
v[field] = serde_json::Value::Array(list);
}
}
v
}
/// A CSAF 2.0 VEX advisory (draft) for `input`, published by `input.author`
/// under `namespace` (the publisher's URL), in language `lang` (`de`, `en`:
/// the language its statements were written in). Marked TLP:AMBER until the
/// manufacturer has reviewed it for publication.
pub fn csaf_vex(input: &VexInput<'_>, namespace: &str, lang: &str) -> serde_json::Value {
let now = rfc3339(input.now);
let components = components(input);
let mut keys: Vec<&str> = Vec::new();
for alert in input.alerts {
let key = vulnerability_key(alert);
if !keys.contains(&key) {
keys.push(key);
}
}
let vulnerabilities: Vec<serde_json::Value> = keys
.iter()
.map(|key| {
let alerts: Vec<&CveAlert> = input
.alerts
.iter()
.filter(|a| vulnerability_key(a) == *key)
.collect();
vulnerability(key, &alerts, &components, input)
})
.collect();
serde_json::json!({
"document": {
"category": "csaf_vex",
"csaf_version": "2.0",
"lang": lang,
"distribution": { "tlp": { "label": "AMBER" } },
"title": format!("VEX for {} (draft)", input.subject),
"publisher": {
"category": "vendor",
"name": input.author,
"namespace": namespace,
},
"notes": [{ "category": "general", "title": "Draft", "text": DRAFT_NOTE }],
"tracking": {
"id": tracking_id(input.subject, input.now),
"status": "draft",
"version": "1",
"revision_history": [{
"date": now,
"number": "1",
"summary": "Draft generated by Prüfwerk.",
}],
"initial_release_date": now,
"current_release_date": now,
"generator": { "engine": { "name": input.tooling }, "date": now },
},
},
"product_tree": product_tree(input, &components),
"vulnerabilities": vulnerabilities,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_file_names_follow_csaf() {
let at = DateTime::parse_from_rfc3339("2026-10-06T12:00:00Z")
.map(|d| d.with_timezone(&Utc))
.unwrap_or_default();
let id = tracking_id("Pump Remote / HMI", at);
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"
);
}
}