feat(csaf): match components against vendor CSAF advisories (#515, part C) #521
No files matched your search
@@ -50,6 +50,8 @@ pub struct ComplianceAgent {
|
||||
/// KEV, EPSS and SSVC answers per CVE, for every tenant (#493): public
|
||||
/// data keyed by CVE id, in the admin database, kept a day.
|
||||
pub(crate) exploit_cache: Arc<crate::pipeline::cve_enrichment::MongoExploitCache>,
|
||||
/// The vendor CSAF advisories the scans match against (#515).
|
||||
pub(crate) advisory_index: Arc<crate::pipeline::csaf_feed::MongoAdvisoryStore>,
|
||||
}
|
||||
|
||||
impl ComplianceAgent {
|
||||
@@ -81,6 +83,9 @@ impl ComplianceAgent {
|
||||
let exploit_cache = Arc::new(crate::pipeline::cve_enrichment::MongoExploitCache::new(
|
||||
&db_pool.admin_db(),
|
||||
));
|
||||
let advisory_index = Arc::new(crate::pipeline::csaf_feed::MongoAdvisoryStore::new(
|
||||
&db_pool.admin_db(),
|
||||
));
|
||||
Self {
|
||||
config,
|
||||
db_pool,
|
||||
@@ -96,6 +101,7 @@ impl ComplianceAgent {
|
||||
git_source,
|
||||
nuget_license_cache,
|
||||
exploit_cache,
|
||||
advisory_index,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,7 +214,8 @@ impl ComplianceAgent {
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone())
|
||||
.with_exploit_cache(self.exploit_cache.clone());
|
||||
.with_exploit_cache(self.exploit_cache.clone())
|
||||
.with_advisory_index(self.advisory_index.clone());
|
||||
let started = chrono::Utc::now();
|
||||
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
// Support's scans are ours, not the customer's usage; a scheduled scan
|
||||
|
||||
@@ -215,6 +215,11 @@ impl MongoAdvisoryStore {
|
||||
collection: admin_db.collection(Self::COLLECTION),
|
||||
}
|
||||
}
|
||||
|
||||
/// The index's collection, for the matching that reads it.
|
||||
pub(crate) fn collection(&self) -> &mongodb::Collection<StoredAdvisory> {
|
||||
&self.collection
|
||||
}
|
||||
}
|
||||
|
||||
impl AdvisoryStore for MongoAdvisoryStore {
|
||||
@@ -559,6 +564,26 @@ pub(crate) async fn refresh_index(admin_db: &mongodb::Database, guard: NetGuard)
|
||||
#[derive(Default)]
|
||||
pub(crate) struct MemoryStore(std::sync::Mutex<HashMap<String, (String, Advisory)>>);
|
||||
|
||||
#[cfg(test)]
|
||||
impl MemoryStore {
|
||||
/// Every stored advisory, as `(provider, advisory)`.
|
||||
pub(crate) fn all(&self) -> Vec<(String, Advisory)> {
|
||||
self.0
|
||||
.lock()
|
||||
.map(|m| {
|
||||
m.iter()
|
||||
.map(|(k, (_, a))| {
|
||||
(
|
||||
k.split(':').next().unwrap_or_default().to_string(),
|
||||
a.clone(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl AdvisoryStore for MemoryStore {
|
||||
fn known<'a>(
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
//! A target's components against the vendor CSAF advisories in the index
|
||||
//! (#515, see [`super::csaf_feed`]): a CODESYS runtime or library by its
|
||||
//! name and version against CODESYS's advisories, any component with a purl
|
||||
//! against an advisory product with the same purl. A match raises a CVE
|
||||
//! alert with source `csaf`, or, where OSV or NVD already reported the CVE,
|
||||
//! adds the advisory to that alert; either way the alert links the advisory
|
||||
//! and carries the vendor's remediation and fixed versions.
|
||||
|
||||
use futures_util::future::BoxFuture;
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_core::csaf_ingest::{Advisory, AdvisoryProduct, AdvisoryVulnerability};
|
||||
use compliance_core::models::{AdvisoryRef, CveAlert, CveSource, SbomEntry, VulnRef};
|
||||
use compliance_core::purl::Purl;
|
||||
use compliance_core::version::Vers;
|
||||
|
||||
use super::csaf_feed::{MongoAdvisoryStore, StoredAdvisory};
|
||||
|
||||
/// The provider whose advisories name the components of a package manager
|
||||
/// by product name.
|
||||
fn provider_for(package_manager: &str) -> Option<&'static str> {
|
||||
match package_manager {
|
||||
"codesys" => Some("codesys"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the advisory index, behind a trait so tests keep it in memory.
|
||||
pub(crate) trait AdvisoryIndex: Send + Sync {
|
||||
/// The advisories of `providers`, and those naming any of `purls`
|
||||
/// (without version), as `(provider, advisory)`.
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
providers: &'a [String],
|
||||
purls: &'a [String],
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>>;
|
||||
}
|
||||
|
||||
impl AdvisoryIndex for MongoAdvisoryStore {
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
providers: &'a [String],
|
||||
purls: &'a [String],
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||
Box::pin(async move {
|
||||
if providers.is_empty() && purls.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// A product's purl may carry a version; compare from the start.
|
||||
let purl_patterns: Vec<mongodb::bson::Regex> = purls
|
||||
.iter()
|
||||
.map(|p| mongodb::bson::Regex {
|
||||
pattern: format!("^{}(@|$)", regex::escape(p)),
|
||||
options: String::new(),
|
||||
})
|
||||
.collect();
|
||||
let rows: Vec<StoredAdvisory> = self
|
||||
.collection()
|
||||
.find(doc! { "$or": [
|
||||
{ "provider": { "$in": providers } },
|
||||
{ "advisory.products.purl": { "$in": purl_patterns } },
|
||||
] })
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
.try_collect()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(rows.into_iter().map(|r| (r.provider, r.advisory)).collect())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A purl without its version, qualifiers and subpath.
|
||||
fn purl_base(purl: &str) -> Option<String> {
|
||||
let p = Purl::parse(purl)?;
|
||||
Some(match p.namespace {
|
||||
Some(ns) => format!("pkg:{}/{ns}/{}", p.ty, p.name),
|
||||
None => format!("pkg:{}/{}", p.ty, p.name),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether advisory product `p` (of `provider`) is `entry`'s component at
|
||||
/// its version.
|
||||
fn names(p: &AdvisoryProduct, provider: &str, entry: &SbomEntry) -> bool {
|
||||
if provider_for(&entry.package_manager) == Some(provider)
|
||||
&& p.covers(&entry.name, &entry.version)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let (Some(theirs), Some(ours)) = (p.purl.as_deref(), entry.purl.as_deref()) else {
|
||||
return false;
|
||||
};
|
||||
if purl_base(theirs).is_none() || purl_base(theirs) != purl_base(ours) {
|
||||
return false;
|
||||
}
|
||||
let pinned = Purl::parse(theirs).and_then(|t| t.version);
|
||||
match (&p.version, &p.version_range, pinned.as_ref()) {
|
||||
(Some(exact), _, _) | (None, None, Some(exact)) => {
|
||||
compliance_core::version::cmp_dotted(exact, &entry.version).is_eq()
|
||||
}
|
||||
(None, Some(range), _) => Vers::parse(range).is_some_and(|r| r.contains(&entry.version)),
|
||||
(None, None, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the vendor recommends for the products `ids`: each remediation that
|
||||
/// names one, `category: details`.
|
||||
fn remediation(v: &AdvisoryVulnerability, ids: &[&str]) -> Option<String> {
|
||||
let texts: Vec<String> = v
|
||||
.remediations
|
||||
.iter()
|
||||
.filter(|r| r.product_ids.iter().any(|p| ids.contains(&p.as_str())))
|
||||
.map(|r| match &r.url {
|
||||
Some(url) => format!("{}: {} ({url})", r.category, r.details),
|
||||
None => format!("{}: {}", r.category, r.details),
|
||||
})
|
||||
.collect();
|
||||
(!texts.is_empty()).then(|| texts.join("\n"))
|
||||
}
|
||||
|
||||
/// What one match contributes.
|
||||
struct Hit<'a> {
|
||||
provider: &'a str,
|
||||
advisory: &'a Advisory,
|
||||
vulnerability: &'a AdvisoryVulnerability,
|
||||
cve: &'a str,
|
||||
products: Vec<&'a str>,
|
||||
}
|
||||
|
||||
/// The advisory reference of a hit.
|
||||
fn reference(hit: &Hit<'_>) -> AdvisoryRef {
|
||||
AdvisoryRef {
|
||||
provider: hit.provider.to_string(),
|
||||
id: hit.advisory.id.clone(),
|
||||
title: hit.advisory.title.clone(),
|
||||
url: hit.advisory.url.clone(),
|
||||
remediation: remediation(hit.vulnerability, &hit.products),
|
||||
}
|
||||
}
|
||||
|
||||
/// Match `entries` against `advisories` and record what matches: on the
|
||||
/// entry's vulnerabilities, and in `alerts`, merged into the alert of the
|
||||
/// same CVE where OSV or NVD reported it.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// How many (component, CVE) matches the advisories gave.
|
||||
pub(crate) fn apply(
|
||||
target_id: &str,
|
||||
entries: &mut [SbomEntry],
|
||||
advisories: &[(String, Advisory)],
|
||||
alerts: &mut Vec<CveAlert>,
|
||||
) -> usize {
|
||||
let mut count = 0;
|
||||
for entry in entries.iter_mut() {
|
||||
let mut hits: Vec<Hit<'_>> = Vec::new();
|
||||
for (provider, advisory) in advisories {
|
||||
for v in &advisory.vulnerabilities {
|
||||
// Only a CVE can be merged with OSV/NVD and alerted.
|
||||
let Some(cve) = v.cve.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
let products: Vec<&str> = v
|
||||
.affected
|
||||
.iter()
|
||||
.filter(|id| {
|
||||
advisory
|
||||
.product(id)
|
||||
.is_some_and(|p| names(p, provider, entry))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !products.is_empty() {
|
||||
hits.push(Hit {
|
||||
provider,
|
||||
advisory,
|
||||
vulnerability: v,
|
||||
cve,
|
||||
products,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for hit in hits {
|
||||
count += 1;
|
||||
let reference = reference(&hit);
|
||||
if entry.known_vulnerabilities.iter().all(|r| r.id != hit.cve) {
|
||||
entry.known_vulnerabilities.push(VulnRef {
|
||||
id: hit.cve.to_string(),
|
||||
source: "csaf".to_string(),
|
||||
severity: hit.vulnerability.severity.clone(),
|
||||
url: hit.advisory.url.clone(),
|
||||
exploitation: None,
|
||||
});
|
||||
}
|
||||
let fixed = hit.advisory.fixed_versions(hit.vulnerability, &entry.name);
|
||||
let alert = match alerts.iter_mut().position(|a| a.cve_id == hit.cve) {
|
||||
Some(i) => &mut alerts[i],
|
||||
None => {
|
||||
let mut alert = CveAlert::new(
|
||||
hit.cve.to_string(),
|
||||
target_id.to_string(),
|
||||
entry.name.clone(),
|
||||
entry.version.clone(),
|
||||
CveSource::Csaf,
|
||||
);
|
||||
alert.summary = hit
|
||||
.vulnerability
|
||||
.summary
|
||||
.clone()
|
||||
.or_else(|| hit.vulnerability.title.clone());
|
||||
alert.cvss_score = hit.vulnerability.cvss_score;
|
||||
alerts.push(alert);
|
||||
let last = alerts.len() - 1;
|
||||
&mut alerts[last]
|
||||
}
|
||||
};
|
||||
if alert.severity.is_none() {
|
||||
alert.severity.clone_from(&hit.vulnerability.severity);
|
||||
}
|
||||
if alert.fixed_versions.is_empty() {
|
||||
alert.fixed_versions = fixed;
|
||||
}
|
||||
if let Some(url) = &hit.advisory.url {
|
||||
if !alert.references.contains(url) {
|
||||
alert.references.push(url.clone());
|
||||
}
|
||||
}
|
||||
if alert
|
||||
.advisories
|
||||
.iter()
|
||||
.all(|a| a.provider != reference.provider || a.id != reference.id)
|
||||
{
|
||||
alert.advisories.push(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// The providers and purls the index is asked for, for `entries`.
|
||||
pub(crate) fn wanted(entries: &[SbomEntry]) -> (Vec<String>, Vec<String>) {
|
||||
let mut providers: Vec<String> = Vec::new();
|
||||
let mut purls: Vec<String> = Vec::new();
|
||||
for entry in entries {
|
||||
if let Some(p) = provider_for(&entry.package_manager) {
|
||||
if !providers.iter().any(|q| q == p) {
|
||||
providers.push(p.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(base) = entry.purl.as_deref().and_then(purl_base) {
|
||||
if !purls.contains(&base) {
|
||||
purls.push(base);
|
||||
}
|
||||
}
|
||||
}
|
||||
(providers, purls)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The synthetic VDE-shaped advisory of the core fixtures, as CODESYS'.
|
||||
fn codesys_advisory() -> Advisory {
|
||||
let mut doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../compliance-core/tests/fixtures/csaf/vde-synthetic.json"
|
||||
))
|
||||
.unwrap();
|
||||
// Name the product as the CODESYS archive does.
|
||||
doc["product_tree"]["branches"][0]["branches"][0]["branches"][0]["name"] =
|
||||
serde_json::json!("CODESYS Control for Linux SL");
|
||||
compliance_core::csaf_ingest::parse(&doc).unwrap()
|
||||
}
|
||||
|
||||
fn codesys(name: &str, version: &str) -> SbomEntry {
|
||||
let mut e = SbomEntry::new("t".into(), name.into(), version.into(), "codesys".into());
|
||||
e.purl = Some(format!(
|
||||
"pkg:codesys/{}@{version}",
|
||||
name.replace(' ', "%20")
|
||||
));
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_codesys_runtime_below_the_fix_gets_the_advisory() {
|
||||
let advisories = vec![("codesys".to_string(), codesys_advisory())];
|
||||
let mut entries = vec![
|
||||
codesys("CODESYS Control for Linux SL", "3.5.16.0"),
|
||||
codesys("CODESYS Control for Linux SL", "3.5.22.40"),
|
||||
codesys("CmpCodeMeter", "3.5.16.0"),
|
||||
];
|
||||
let mut alerts = Vec::new();
|
||||
let n = apply("t", &mut entries, &advisories, &mut alerts);
|
||||
assert_eq!(n, 1, "only the runtime below the fix");
|
||||
let alert = &alerts[0];
|
||||
assert_eq!(alert.cve_id, "CVE-2026-90001");
|
||||
assert_eq!(alert.source, CveSource::Csaf);
|
||||
assert_eq!(alert.affected_version, "3.5.16.0");
|
||||
assert_eq!(alert.fixed_versions, ["3.5.22.40"]);
|
||||
assert_eq!(alert.severity.as_deref(), Some("HIGH"));
|
||||
let adv = &alert.advisories[0];
|
||||
assert_eq!(adv.id, "VDE-2026-9001");
|
||||
assert_eq!(
|
||||
adv.url.as_deref(),
|
||||
Some("https://certvde.com/en/advisories/VDE-2026-9001")
|
||||
);
|
||||
assert!(adv
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|r| r.starts_with("vendor_fix: Update to version 3.5.22.40.")));
|
||||
assert_eq!(entries[0].known_vulnerabilities[0].source, "csaf");
|
||||
assert!(entries[1].known_vulnerabilities.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_nvd_alert_of_the_same_cve_gets_the_advisory_added() {
|
||||
let advisories = vec![("codesys".to_string(), codesys_advisory())];
|
||||
let mut entries = vec![codesys("CODESYS Control for Linux SL", "3.5.16.0")];
|
||||
entries[0].known_vulnerabilities.push(VulnRef {
|
||||
id: "CVE-2026-90001".into(),
|
||||
source: "nvd".into(),
|
||||
severity: None,
|
||||
url: None,
|
||||
exploitation: None,
|
||||
});
|
||||
let mut nvd = CveAlert::new(
|
||||
"CVE-2026-90001".into(),
|
||||
"t".into(),
|
||||
"CODESYS Control for Linux SL".into(),
|
||||
"3.5.16.0".into(),
|
||||
CveSource::Nvd,
|
||||
);
|
||||
nvd.summary = Some("NVD's text".into());
|
||||
let mut alerts = vec![nvd];
|
||||
apply("t", &mut entries, &advisories, &mut alerts);
|
||||
assert_eq!(alerts.len(), 1, "merged, not a second alert");
|
||||
assert_eq!(alerts[0].source, CveSource::Nvd);
|
||||
assert_eq!(alerts[0].summary.as_deref(), Some("NVD's text"));
|
||||
assert_eq!(alerts[0].advisories.len(), 1);
|
||||
assert_eq!(alerts[0].fixed_versions, ["3.5.22.40"]);
|
||||
assert_eq!(entries[0].known_vulnerabilities.len(), 1);
|
||||
}
|
||||
|
||||
/// CODESYS' real advisories against the runtime of the nightly PLC
|
||||
/// fixture: `cargo test -p compliance-agent --lib csaf_match::tests::live
|
||||
/// -- --ignored --nocapture`.
|
||||
#[tokio::test]
|
||||
#[ignore = "fetches from CERT@VDE"]
|
||||
async fn live_codesys_advisories_match_an_old_runtime() {
|
||||
use crate::pipeline::csaf_feed::{self, HttpFetch, Limits, MemoryStore};
|
||||
let fetch = HttpFetch::new(compliance_core::net_guard::NetGuard::public_only()).unwrap();
|
||||
let store = MemoryStore::default();
|
||||
let providers = csaf_feed::providers(Some("codesys"));
|
||||
csaf_feed::refresh(&fetch, &store, &providers, Limits::default()).await;
|
||||
let advisories = store.all();
|
||||
let mut entries = vec![codesys("CODESYS Control for Linux SL", "3.5.16.0")];
|
||||
let mut alerts = Vec::new();
|
||||
let n = apply("t", &mut entries, &advisories, &mut alerts);
|
||||
println!(
|
||||
"{} advisories, {n} matches: {:?}",
|
||||
advisories.len(),
|
||||
alerts.iter().map(|a| a.cve_id.as_str()).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(n > 0);
|
||||
assert!(alerts.iter().all(|a| !a.advisories.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_purl_matches_whatever_the_package_manager() {
|
||||
let mut doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../compliance-core/tests/fixtures/csaf/vde-synthetic.json"
|
||||
))
|
||||
.unwrap();
|
||||
doc["product_tree"]["branches"][0]["branches"][0]["branches"][0]["branches"][0]
|
||||
["product"]["product_identification_helper"] =
|
||||
serde_json::json!({ "purl": "pkg:generic/example/fieldbus-stack" });
|
||||
let advisories = vec![(
|
||||
"wago".to_string(),
|
||||
compliance_core::csaf_ingest::parse(&doc).unwrap(),
|
||||
)];
|
||||
let mut stack = SbomEntry::new(
|
||||
"t".into(),
|
||||
"fieldbus-stack".into(),
|
||||
"3.1.0".into(),
|
||||
"firmware".into(),
|
||||
);
|
||||
stack.purl = Some("pkg:generic/example/fieldbus-stack@3.1.0".into());
|
||||
let mut other = stack.clone();
|
||||
other.version = "4.0.0".into();
|
||||
other.purl = Some("pkg:generic/example/fieldbus-stack@4.0.0".into());
|
||||
let mut entries = vec![stack, other];
|
||||
let mut alerts = Vec::new();
|
||||
apply("t", &mut entries, &advisories, &mut alerts);
|
||||
assert_eq!(alerts.len(), 1);
|
||||
assert_eq!(alerts[0].affected_version, "3.1.0");
|
||||
assert_eq!(
|
||||
wanted(&entries),
|
||||
(
|
||||
Vec::new(),
|
||||
vec!["pkg:generic/example/fieldbus-stack".to_string()]
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod clamav;
|
||||
pub mod code_review;
|
||||
pub mod cppcheck;
|
||||
pub(crate) mod csaf_feed;
|
||||
pub(crate) mod csaf_match;
|
||||
pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
|
||||
@@ -52,6 +52,8 @@ pub struct PipelineOrchestrator {
|
||||
pub(super) nuget_license_cache: Option<Arc<dyn LicenseCache>>,
|
||||
/// The cross-tenant cache of KEV, EPSS and SSVC answers (#493).
|
||||
pub(super) exploit_cache: Option<Arc<dyn ExploitCache>>,
|
||||
/// The vendor CSAF advisories (#515); none in tests.
|
||||
pub(super) advisory_index: Option<Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>>,
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
@@ -67,6 +69,7 @@ impl PipelineOrchestrator {
|
||||
net_guard,
|
||||
nuget_license_cache: None,
|
||||
exploit_cache: None,
|
||||
advisory_index: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +85,44 @@ impl PipelineOrchestrator {
|
||||
self
|
||||
}
|
||||
|
||||
/// Match the components against the vendor advisories in `index` (#515).
|
||||
pub(crate) fn with_advisory_index(
|
||||
mut self,
|
||||
index: Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>,
|
||||
) -> Self {
|
||||
self.advisory_index = Some(index);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add what the vendor advisories say about `entries` to `alerts`
|
||||
/// (#515). Best-effort: an index that cannot be read leaves them as
|
||||
/// they are.
|
||||
async fn match_advisories(
|
||||
&self,
|
||||
target_id: &str,
|
||||
entries: &mut [SbomEntry],
|
||||
alerts: &mut Vec<CveAlert>,
|
||||
) {
|
||||
let Some(index) = &self.advisory_index else {
|
||||
return;
|
||||
};
|
||||
let (providers, purls) = crate::pipeline::csaf_match::wanted(entries);
|
||||
match index.relevant(&providers, &purls).await {
|
||||
Ok(advisories) if advisories.is_empty() => {}
|
||||
Ok(advisories) => {
|
||||
let matched =
|
||||
crate::pipeline::csaf_match::apply(target_id, entries, &advisories, alerts);
|
||||
tracing::info!(
|
||||
target_id,
|
||||
advisories = advisories.len(),
|
||||
matched,
|
||||
"vendor CSAF advisories matched"
|
||||
);
|
||||
}
|
||||
Err(e) => tracing::warn!(target_id, "CSAF advisory index not read: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, fields(repo_id = repo.name.as_str()))]
|
||||
async fn run_pipeline(
|
||||
&self,
|
||||
@@ -551,6 +592,9 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts)
|
||||
.await;
|
||||
|
||||
self.enrich_cves(&repo_id, &mut cve_alerts, &mut sbom_entries)
|
||||
.await;
|
||||
|
||||
@@ -1534,6 +1578,8 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
self.match_advisories(target_id, &mut entries, &mut alerts)
|
||||
.await;
|
||||
self.enrich_cves(target_id, &mut alerts, &mut entries).await;
|
||||
|
||||
for entry in &entries {
|
||||
|
||||
@@ -7,6 +7,25 @@ pub enum CveSource {
|
||||
Osv,
|
||||
Nvd,
|
||||
SearXNG,
|
||||
/// A vendor's CSAF advisory (CERT@VDE, Siemens ProductCERT, CISA; #515).
|
||||
Csaf,
|
||||
}
|
||||
|
||||
/// A vendor advisory that names a CVE alert's component (#515).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AdvisoryRef {
|
||||
/// The provider's key in the advisory index (`codesys`, `siemens`).
|
||||
pub provider: String,
|
||||
/// The advisory's id (`VDE-2026-094`, `SSA-019113`).
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
/// The advisory's page; Siemens' terms ask every use to link it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
/// What the vendor recommends for the component (`vendor_fix: Update to
|
||||
/// version 3.5.22.40.`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub remediation: Option<String>,
|
||||
}
|
||||
|
||||
/// What is known about the exploitation of one CVE (#493), from public
|
||||
@@ -87,6 +106,9 @@ pub struct CveAlert {
|
||||
/// CISA Vulnrichment SSVC); `None` when it was not looked up.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exploitation: Option<Exploitation>,
|
||||
/// The vendor advisories that name it (#515).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub advisories: Vec<AdvisoryRef>,
|
||||
/// The VEX statement on it (#498); none until someone states one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub vex: Option<super::vex::VexAssessment>,
|
||||
@@ -146,6 +168,7 @@ impl CveAlert {
|
||||
aliases: Vec::new(),
|
||||
fixed_versions: Vec::new(),
|
||||
exploitation: None,
|
||||
advisories: Vec::new(),
|
||||
vex: None,
|
||||
resolved_at: None,
|
||||
exploited_seen_at: None,
|
||||
|
||||
@@ -26,7 +26,7 @@ pub mod werkbank;
|
||||
pub use auth::{AuthInfo, SupportTenant};
|
||||
pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference};
|
||||
pub use credentials::Credentials;
|
||||
pub use cve::{CveAlert, CveSource, EpssScore, Exploitation, KevEntry};
|
||||
pub use cve::{AdvisoryRef, CveAlert, CveSource, EpssScore, Exploitation, KevEntry};
|
||||
pub use dast::{
|
||||
DastAuthConfig, DastEvidence, DastFinding, DastScanPhase, DastScanRun, DastScanStatus,
|
||||
DastTarget, DastTargetType, DastVulnType,
|
||||
|
||||
@@ -58,18 +58,43 @@ pub struct Vers {
|
||||
}
|
||||
|
||||
impl Vers {
|
||||
/// Parse `text`; `None` for anything that is not a `vers:` range with at
|
||||
/// least one constraint.
|
||||
/// Parse `text`; `None` for anything that is not a range with at least
|
||||
/// one constraint.
|
||||
///
|
||||
/// Vendors do not always write `vers` as specified, so two forms CERT@VDE
|
||||
/// advisories use are read too: constraints without the `vers:<scheme>/`
|
||||
/// prefix (`<4.17.0.0`), and a range written `4.15.0.0<4.21.0.0` (for
|
||||
/// `>=4.15.0.0|<4.21.0.0`). A plain version without a comparator is not
|
||||
/// a range.
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
let rest = text.trim().strip_prefix("vers:")?;
|
||||
let (_scheme, constraints) = rest.split_once('/')?;
|
||||
let mut all = false;
|
||||
let mut parsed = Vec::new();
|
||||
let text = text.trim();
|
||||
let constraints = match text.strip_prefix("vers:") {
|
||||
Some(rest) => rest.split_once('/')?.1,
|
||||
None if text.contains(['<', '>', '=', '|', '*']) => text,
|
||||
None => return None,
|
||||
};
|
||||
// `A<B` / `A<=B`: from A (inclusive) to below / up to B.
|
||||
let mut raws: Vec<String> = Vec::new();
|
||||
for raw in constraints
|
||||
.split('|')
|
||||
.map(str::trim)
|
||||
.filter(|c| !c.is_empty())
|
||||
{
|
||||
let lead = raw
|
||||
.chars()
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphanumeric());
|
||||
match raw.find('<').filter(|_| lead) {
|
||||
Some(at) => {
|
||||
raws.push(format!(">={}", &raw[..at]));
|
||||
raws.push(raw[at..].to_string());
|
||||
}
|
||||
None => raws.push(raw.to_string()),
|
||||
}
|
||||
}
|
||||
let mut all = false;
|
||||
let mut parsed = Vec::new();
|
||||
for raw in raws.iter().map(|r| r.trim()) {
|
||||
if raw == "*" {
|
||||
all = true;
|
||||
continue;
|
||||
@@ -196,6 +221,13 @@ mod tests {
|
||||
assert!(cisa.contains("1.5"));
|
||||
assert!(cisa.contains("0.9"));
|
||||
assert!(!cisa.contains("1.6"));
|
||||
// As CERT@VDE's vendors also write them.
|
||||
let sloppy = vers("vers:generic/4.15.0.0<4.21.0.0");
|
||||
assert!(sloppy.contains("4.16.0.0"));
|
||||
assert!(!sloppy.contains("4.14.0.0") && !sloppy.contains("4.21.0.0"));
|
||||
assert!(vers("4.16.0.0<4.17.0.0").contains("4.16.5.0"));
|
||||
assert!(vers("<4.17.0.0").contains("3.5.16.0"));
|
||||
assert!(!vers("<4.17.0.0").contains("4.17.0.0"));
|
||||
// Two intervals, an exclusion, a single version, everything.
|
||||
let two = vers("vers:generic/>=1.0|<1.4|>=2.0|<2.2");
|
||||
assert!(two.contains("1.2") && two.contains("2.1"));
|
||||
@@ -209,6 +241,7 @@ mod tests {
|
||||
#[test]
|
||||
fn what_is_not_a_range_is_refused() {
|
||||
assert_eq!(Vers::parse("3.5.16.0"), None);
|
||||
assert_eq!(Vers::parse("4.15.0.0<"), None);
|
||||
assert_eq!(Vers::parse("vers:generic/"), None);
|
||||
assert_eq!(Vers::parse("vers:generic/>="), None);
|
||||
}
|
||||
|
||||
@@ -5038,6 +5038,12 @@ tbody tr:last-child td {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.vex-advisory {
|
||||
display: block;
|
||||
font-size: 11.5px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.vex-table code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
|
||||
@@ -158,7 +158,21 @@ pub fn VexPanel(target_id: String) -> Element {
|
||||
let edit_id = alert_id.clone();
|
||||
rsx! {
|
||||
tr { key: "{alert_id}",
|
||||
td { code { "{alert.cve_id}" } }
|
||||
td {
|
||||
code { "{alert.cve_id}" }
|
||||
// The vendor advisories that name it (#515), linked as
|
||||
// their terms ask; the remediation on hover.
|
||||
for adv in alert.advisories.iter() {
|
||||
a {
|
||||
class: "vex-advisory",
|
||||
href: adv.url.clone().unwrap_or_default(),
|
||||
target: "_blank",
|
||||
rel: "noopener noreferrer",
|
||||
title: adv.remediation.clone().unwrap_or_else(|| adv.title.clone()),
|
||||
"{adv.id}"
|
||||
}
|
||||
}
|
||||
}
|
||||
td { "{alert.affected_package} {alert.affected_version}" }
|
||||
td {
|
||||
if let Some(sev) = alert.severity.as_deref() {
|
||||
|
||||
+5
-1
@@ -143,7 +143,11 @@ guard-aware), cleartext/insecure communication (CWE-319), insecure protocol port
|
||||
|
||||
The **SBOM** view lists the CODESYS libraries (`pkg:codesys/<name>@<version>`) and
|
||||
the runtime; matching runtime components (e.g. the `Cmp*` / `3SLicense` libraries)
|
||||
surface real CODESYS advisories as CVE alerts.
|
||||
surface real CODESYS advisories as CVE alerts. Besides NVD, the runtime and
|
||||
libraries are matched against CODESYS's own CSAF advisories (published through
|
||||
CERT@VDE): the alert links the advisory (e.g. `VDE-2026-094`) and carries the
|
||||
vendor's remediation and the fixed version.
|
||||
|
||||
A CVE alert a later scan no longer finds (the project now references a fixed
|
||||
runtime or library version) is marked resolved, and its VEX status becomes
|
||||
`fixed`, as for code targets; this needs both lookups (OSV and NVD) to have
|
||||
|
||||
+13
-2
@@ -227,8 +227,19 @@ newer than the stored one; its SHA-512 must match the hash file the provider
|
||||
publishes beside it (an advisory without one is stored and counted as
|
||||
unverified); the PGP signatures are not checked. A run fetches at most 400
|
||||
advisories within 15 minutes, newest first, so the first fill spans a few
|
||||
runs. Scans never fetch; they match the target's components against the index
|
||||
(#515, part C).
|
||||
runs. Scans never fetch; they match the target's components against the index:
|
||||
|
||||
- a CODESYS runtime or library (from a `.projectarchive`) by its name and
|
||||
version against CODESYS's advisories, including the range forms CERT@VDE's
|
||||
vendors write besides proper `vers` (`4.15.0.0<4.21.0.0`, `<4.17.0.0`);
|
||||
- any component with a purl against an advisory product with the same purl.
|
||||
|
||||
A match raises a CVE alert with source `csaf`, or, where OSV or NVD reported
|
||||
the same CVE, is added to that alert. Either way the alert names the advisory
|
||||
(id, title, link) with the vendor's remediation and the fixed versions, and
|
||||
the component lists the CVE with the advisory's link. Siemens order numbers
|
||||
(MLFB) are indexed but not matched yet: no component carries one until TIA
|
||||
exports are read.
|
||||
|
||||
`PW_CSAF_PROVIDERS` chooses the providers: unset or `default` (CERT@VDE's
|
||||
vendors and Siemens), `off`, or a comma list of `default`, `siemens`, `cisa`
|
||||
|
||||
@@ -35,6 +35,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #516 | Secret scanning with Betterleaks instead of gitleaks |
|
||||
| PLC CVE fix | CVE alerts of PLC targets resolve; their issues sync |
|
||||
| #515 (A, B) | Vendor CSAF advisories read and indexed |
|
||||
| #515 (C) | Components matched against the vendor CSAF advisories |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -766,6 +767,25 @@ Internal so far (matching follows in part C).
|
||||
- **Egress:** only `*.csaf-tp.certvde.com` and `cert-portal.siemens.com`
|
||||
(with CISA: `www.cisa.gov`, `raw.githubusercontent.com`).
|
||||
|
||||
### 36. #515 part C: CODESYS components against the vendor advisories
|
||||
|
||||
Needs the index of check 35 filled (the `codesys` provider at least).
|
||||
|
||||
- **Do:** rescan the PLC target of check 34 with its original runtime
|
||||
(`line_control.projectarchive`, CODESYS Control for Linux SL 3.5.16.0).
|
||||
**Log:** `vendor CSAF advisories matched` with `advisories` (CODESYS's,
|
||||
about 36) and `matched` (about 25 for 3.5.16.0).
|
||||
- **Expect:** in **Schwachstellen und VEX**, CVEs such as CVE-2023-37545 …
|
||||
CVE-2023-37559 or CVE-2025-41658 show the advisory id (`VDE-…`) as a link
|
||||
to certvde.com; hovering it shows the vendor's remediation; alerts NVD
|
||||
also reported are not doubled (one row per CVE), now with the fixed
|
||||
version. Alerts only CSAF knows have source `csaf`. The SBOM page lists
|
||||
them on the runtime with source `csaf` and the advisory link.
|
||||
- **Do:** set the runtime to 3.5.22.40 (as in check 34), rescan.
|
||||
**Expect:** the CVEs fixed before it resolve (check 34's behaviour).
|
||||
- **[visible]** PLC targets get CVE alerts from CODESYS's own advisories,
|
||||
with the advisory linked and the vendor's fix.
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user