446 lines
15 KiB
Rust
446 lines
15 KiB
Rust
//! Vendor security advisories in CSAF 2.0 (CERT@VDE's vendor providers,
|
|
//! Siemens ProductCERT, CISA ICS; #515), read into what matching a target's
|
|
//! components needs: each product the advisory names (vendor, name, version
|
|
//! or `vers` range, CPE, purl, order numbers) and, per vulnerability, which
|
|
//! products are affected or fixed and what the vendor recommends.
|
|
//!
|
|
//! The product tree is walked as CSAF builds it: a `product_version` or
|
|
//! `product_version_range` branch is a product whose vendor, family and name
|
|
//! are its ancestors'; `full_product_names` and the products relationships
|
|
//! define (a component `installed_on` a platform) are products too.
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::version::{cmp_dotted, Vers};
|
|
|
|
/// The version of this reading. Bump it when [`parse`] reads more or
|
|
/// differently, so the advisory index reads its stored advisories again.
|
|
///
|
|
/// 2: remediations name their products through product groups too.
|
|
pub const PARSER_VERSION: u32 = 2;
|
|
|
|
/// A product an advisory names.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct AdvisoryProduct {
|
|
/// Its id in the advisory (`CSAFPID-51001`).
|
|
pub product_id: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub vendor: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub family: Option<String>,
|
|
/// The product's name without its version (`CODESYS Control for Linux
|
|
/// SL`), or the full name where the tree gives no more.
|
|
pub name: String,
|
|
/// An exact version (`3.5.22.40`).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub version: Option<String>,
|
|
/// A version range in `vers` notation (`vers:generic/>=3.0.0.0|<3.5.22.40`).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub version_range: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub cpe: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub purl: Option<String>,
|
|
/// Order numbers (Siemens MLFB `6ES7518-4AX00-1AB0`) and SKUs.
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
pub model_numbers: Vec<String>,
|
|
}
|
|
|
|
impl AdvisoryProduct {
|
|
/// Whether the product is `name` (compared as [`normalised_name`]) at
|
|
/// `version`: its exact version, or one its range contains. A product
|
|
/// without either covers every version of it.
|
|
pub fn covers(&self, name: &str, version: &str) -> bool {
|
|
if normalised_name(&self.name) != normalised_name(name) {
|
|
return false;
|
|
}
|
|
match (&self.version, &self.version_range) {
|
|
(Some(exact), _) => cmp_dotted(exact, version).is_eq(),
|
|
(None, Some(range)) => Vers::parse(range).is_some_and(|r| r.contains(version)),
|
|
(None, None) => true,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A product name as advisories and SBOMs compare: lowercase, single spaces,
|
|
/// trimmed (`CODESYS Gateway ` is `codesys gateway`).
|
|
pub fn normalised_name(name: &str) -> String {
|
|
name.split_whitespace()
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
.to_lowercase()
|
|
}
|
|
|
|
/// What the vendor recommends for some products.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Remediation {
|
|
/// CSAF's category: `vendor_fix`, `mitigation`, `workaround`,
|
|
/// `none_available`, `no_fix_planned`.
|
|
pub category: String,
|
|
pub details: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub url: Option<String>,
|
|
#[serde(default)]
|
|
pub product_ids: Vec<String>,
|
|
}
|
|
|
|
/// One vulnerability of an advisory, as its products stand.
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
pub struct AdvisoryVulnerability {
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub cve: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub title: Option<String>,
|
|
/// The vendor's description.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub summary: Option<String>,
|
|
/// CVSS base severity (`HIGH`) and score, the highest the advisory gives.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub severity: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub cvss_score: Option<f64>,
|
|
/// `known_affected`, `first_affected`, `last_affected`.
|
|
#[serde(default)]
|
|
pub affected: Vec<String>,
|
|
/// `fixed`, `first_fixed`.
|
|
#[serde(default)]
|
|
pub fixed: Vec<String>,
|
|
#[serde(default)]
|
|
pub not_affected: Vec<String>,
|
|
#[serde(default)]
|
|
pub under_investigation: Vec<String>,
|
|
#[serde(default)]
|
|
pub recommended: Vec<String>,
|
|
#[serde(default)]
|
|
pub remediations: Vec<Remediation>,
|
|
}
|
|
|
|
/// An advisory, read for matching.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct Advisory {
|
|
/// Its tracking id (`SSA-019113`, `VDE-2026-094`, `ICSA-26-260-07`).
|
|
pub id: String,
|
|
pub title: String,
|
|
pub publisher: String,
|
|
/// Where the vendor publishes it for people to read (a `self`
|
|
/// reference), the link its terms ask redistributions to carry.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub url: Option<String>,
|
|
/// TLP label of its distribution (`WHITE`).
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub tlp: Option<String>,
|
|
/// `current_release_date`, as written.
|
|
pub updated: String,
|
|
pub products: Vec<AdvisoryProduct>,
|
|
pub vulnerabilities: Vec<AdvisoryVulnerability>,
|
|
}
|
|
|
|
/// Why a document is not an advisory to read.
|
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
pub enum CsafError {
|
|
#[error("not a CSAF 2.0 document: {0}")]
|
|
NotCsaf(&'static str),
|
|
}
|
|
|
|
impl Advisory {
|
|
/// The product with id `product_id`.
|
|
pub fn product(&self, product_id: &str) -> Option<&AdvisoryProduct> {
|
|
self.products.iter().find(|p| p.product_id == product_id)
|
|
}
|
|
|
|
/// The exact versions of product `name` the vulnerability lists as fixed
|
|
/// (`3.5.22.40`), lowest first.
|
|
pub fn fixed_versions(&self, vulnerability: &AdvisoryVulnerability, name: &str) -> Vec<String> {
|
|
let wanted = normalised_name(name);
|
|
let mut versions: Vec<String> = vulnerability
|
|
.fixed
|
|
.iter()
|
|
.filter_map(|id| self.product(id))
|
|
.filter(|p| normalised_name(&p.name) == wanted)
|
|
.filter_map(|p| p.version.clone())
|
|
.collect();
|
|
versions.sort_by(|a, b| cmp_dotted(a, b));
|
|
versions.dedup();
|
|
versions
|
|
}
|
|
}
|
|
|
|
/// The text at `key` of `value`, trimmed, if not empty.
|
|
fn text(value: &serde_json::Value, key: &str) -> Option<String> {
|
|
value
|
|
.get(key)
|
|
.and_then(|v| v.as_str())
|
|
.map(str::trim)
|
|
.filter(|t| !t.is_empty())
|
|
.map(str::to_string)
|
|
}
|
|
|
|
/// The strings of the array at `key` of `value`.
|
|
fn strings(value: &serde_json::Value, key: &str) -> Vec<String> {
|
|
value
|
|
.get(key)
|
|
.and_then(|v| v.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|v| v.as_str().map(str::to_string))
|
|
.collect()
|
|
}
|
|
|
|
/// A product from its `full_product_name` object and the names above it.
|
|
fn product(
|
|
full: &serde_json::Value,
|
|
vendor: Option<&str>,
|
|
family: Option<&str>,
|
|
name: Option<&str>,
|
|
version: Option<&str>,
|
|
version_range: Option<&str>,
|
|
) -> Option<AdvisoryProduct> {
|
|
let product_id = text(full, "product_id")?;
|
|
let helper = full
|
|
.get("product_identification_helper")
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
let mut model_numbers = strings(&helper, "model_numbers");
|
|
model_numbers.extend(strings(&helper, "skus"));
|
|
Some(AdvisoryProduct {
|
|
product_id,
|
|
vendor: vendor.map(str::to_string),
|
|
family: family.map(str::to_string),
|
|
name: name
|
|
.map(str::to_string)
|
|
.or_else(|| text(full, "name"))
|
|
.unwrap_or_default(),
|
|
version: version.map(str::to_string),
|
|
version_range: version_range.map(str::to_string),
|
|
cpe: text(&helper, "cpe"),
|
|
purl: text(&helper, "purl"),
|
|
model_numbers,
|
|
})
|
|
}
|
|
|
|
/// The products of a branch and those below it.
|
|
fn walk(
|
|
branch: &serde_json::Value,
|
|
vendor: Option<&str>,
|
|
family: Option<&str>,
|
|
name: Option<&str>,
|
|
out: &mut Vec<AdvisoryProduct>,
|
|
) {
|
|
let category = branch
|
|
.get("category")
|
|
.and_then(|c| c.as_str())
|
|
.unwrap_or("");
|
|
let here = text(branch, "name");
|
|
let here = here.as_deref();
|
|
let (vendor, family, name) = match category {
|
|
"vendor" => (here, family, name),
|
|
"product_family" => (vendor, here, name),
|
|
"product_name" => (vendor, family, here),
|
|
_ => (vendor, family, name),
|
|
};
|
|
if let Some(full) = branch.get("product") {
|
|
let (version, range) = match category {
|
|
"product_version" => (here, None),
|
|
"product_version_range" => (None, here),
|
|
_ => (None, None),
|
|
};
|
|
if let Some(p) = product(full, vendor, family, name, version, range) {
|
|
out.push(p);
|
|
}
|
|
}
|
|
for child in branch
|
|
.get("branches")
|
|
.and_then(|b| b.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
walk(child, vendor, family, name, out);
|
|
}
|
|
}
|
|
|
|
/// Every product of `tree`.
|
|
fn products(tree: &serde_json::Value) -> Vec<AdvisoryProduct> {
|
|
let mut out = Vec::new();
|
|
walk(tree, None, None, None, &mut out);
|
|
let listed = tree
|
|
.get("full_product_names")
|
|
.and_then(|f| f.as_array())
|
|
.into_iter()
|
|
.flatten();
|
|
let related = tree
|
|
.get("relationships")
|
|
.and_then(|r| r.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|r| r.get("full_product_name"));
|
|
for full in listed.chain(related) {
|
|
if let Some(p) = product(full, None, None, None, None, None) {
|
|
if out.iter().all(|o| o.product_id != p.product_id) {
|
|
out.push(p);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The product groups of `tree`: group id to its product ids.
|
|
fn product_groups(tree: &serde_json::Value) -> HashMap<String, Vec<String>> {
|
|
tree.get("product_groups")
|
|
.and_then(|g| g.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|g| Some((text(g, "group_id")?, strings(g, "product_ids"))))
|
|
.collect()
|
|
}
|
|
|
|
/// One vulnerability; `groups` resolves the product groups a remediation
|
|
/// names (CERT@VDE's vendors name theirs that way).
|
|
fn vulnerability(
|
|
v: &serde_json::Value,
|
|
groups: &HashMap<String, Vec<String>>,
|
|
) -> AdvisoryVulnerability {
|
|
let status = v.get("product_status").cloned().unwrap_or_default();
|
|
let ids = |keys: &[&str]| -> Vec<String> {
|
|
let mut out: Vec<String> = Vec::new();
|
|
for key in keys {
|
|
for id in strings(&status, key) {
|
|
if !out.contains(&id) {
|
|
out.push(id);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
};
|
|
let summary = v
|
|
.get("notes")
|
|
.and_then(|n| n.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.find(|n| {
|
|
matches!(
|
|
n.get("category").and_then(|c| c.as_str()),
|
|
Some("description" | "summary")
|
|
)
|
|
})
|
|
.and_then(|n| text(n, "text"));
|
|
// The highest CVSS v3 (else v2) score the advisory gives.
|
|
let mut severity: Option<String> = None;
|
|
let mut cvss_score: Option<f64> = None;
|
|
for score in v
|
|
.get("scores")
|
|
.and_then(|s| s.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
let cvss = score.get("cvss_v3").or_else(|| score.get("cvss_v2"));
|
|
let Some(base) = cvss
|
|
.and_then(|c| c.get("baseScore"))
|
|
.and_then(|b| b.as_f64())
|
|
else {
|
|
continue;
|
|
};
|
|
if cvss_score.is_none_or(|s| base > s) {
|
|
cvss_score = Some(base);
|
|
severity = cvss.and_then(|c| text(c, "baseSeverity"));
|
|
}
|
|
}
|
|
let remediations = v
|
|
.get("remediations")
|
|
.and_then(|r| r.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|r| {
|
|
let mut product_ids = strings(r, "product_ids");
|
|
for group in strings(r, "group_ids") {
|
|
for id in groups.get(&group).into_iter().flatten() {
|
|
if !product_ids.contains(id) {
|
|
product_ids.push(id.clone());
|
|
}
|
|
}
|
|
}
|
|
Some(Remediation {
|
|
category: text(r, "category")?,
|
|
details: text(r, "details").unwrap_or_default(),
|
|
url: text(r, "url"),
|
|
product_ids,
|
|
})
|
|
})
|
|
.collect();
|
|
AdvisoryVulnerability {
|
|
cve: text(v, "cve"),
|
|
title: text(v, "title"),
|
|
summary,
|
|
severity,
|
|
cvss_score,
|
|
affected: ids(&["known_affected", "first_affected", "last_affected"]),
|
|
fixed: ids(&["fixed", "first_fixed"]),
|
|
not_affected: ids(&["known_not_affected"]),
|
|
under_investigation: ids(&["under_investigation"]),
|
|
recommended: ids(&["recommended"]),
|
|
remediations,
|
|
}
|
|
}
|
|
|
|
/// Read a CSAF 2.0 document.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// [`CsafError::NotCsaf`] for a document without `document.csaf_version`
|
|
/// 2.0 or without a tracking id.
|
|
pub fn parse(doc: &serde_json::Value) -> Result<Advisory, CsafError> {
|
|
let document = doc
|
|
.get("document")
|
|
.ok_or(CsafError::NotCsaf("no document"))?;
|
|
if document.get("csaf_version").and_then(|v| v.as_str()) != Some("2.0") {
|
|
return Err(CsafError::NotCsaf("csaf_version is not 2.0"));
|
|
}
|
|
let tracking = document.get("tracking").cloned().unwrap_or_default();
|
|
let id = text(&tracking, "id").ok_or(CsafError::NotCsaf("no tracking id"))?;
|
|
// The page people read: of the `self` references (often the JSON, a
|
|
// PDF and a web page), the first that is neither, else the first.
|
|
let selves: Vec<String> = document
|
|
.get("references")
|
|
.and_then(|r| r.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter(|r| r.get("category").and_then(|c| c.as_str()) == Some("self"))
|
|
.filter_map(|r| text(r, "url"))
|
|
.collect();
|
|
let url = selves
|
|
.iter()
|
|
.find(|u| {
|
|
let lower = u.to_ascii_lowercase();
|
|
!lower.ends_with(".json") && !lower.ends_with(".pdf")
|
|
})
|
|
.or(selves.first())
|
|
.cloned();
|
|
let groups = doc
|
|
.get("product_tree")
|
|
.map(product_groups)
|
|
.unwrap_or_default();
|
|
Ok(Advisory {
|
|
id,
|
|
title: text(document, "title").unwrap_or_default(),
|
|
publisher: document
|
|
.get("publisher")
|
|
.and_then(|p| text(p, "name"))
|
|
.unwrap_or_default(),
|
|
url,
|
|
tlp: document
|
|
.get("distribution")
|
|
.and_then(|d| d.get("tlp"))
|
|
.and_then(|t| text(t, "label")),
|
|
updated: text(&tracking, "current_release_date").unwrap_or_default(),
|
|
products: doc.get("product_tree").map(products).unwrap_or_default(),
|
|
vulnerabilities: doc
|
|
.get("vulnerabilities")
|
|
.and_then(|v| v.as_array())
|
|
.into_iter()
|
|
.flatten()
|
|
.map(|v| vulnerability(v, &groups))
|
|
.collect(),
|
|
})
|
|
}
|