diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 8ee1e50..ef674c2 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -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, + /// The vendor CSAF advisories the scans match against (#515). + pub(crate) advisory_index: Arc, } 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 diff --git a/compliance-agent/src/pipeline/csaf_feed.rs b/compliance-agent/src/pipeline/csaf_feed.rs index 104a100..a952219 100644 --- a/compliance-agent/src/pipeline/csaf_feed.rs +++ b/compliance-agent/src/pipeline/csaf_feed.rs @@ -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 { + &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>); +#[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>( diff --git a/compliance-agent/src/pipeline/csaf_match.rs b/compliance-agent/src/pipeline/csaf_match.rs new file mode 100644 index 0000000..cede0ca --- /dev/null +++ b/compliance-agent/src/pipeline/csaf_match.rs @@ -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, String>>; +} + +impl AdvisoryIndex for MongoAdvisoryStore { + fn relevant<'a>( + &'a self, + providers: &'a [String], + purls: &'a [String], + ) -> BoxFuture<'a, Result, 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 = purls + .iter() + .map(|p| mongodb::bson::Regex { + pattern: format!("^{}(@|$)", regex::escape(p)), + options: String::new(), + }) + .collect(); + let rows: Vec = 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 { + 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 { + let texts: Vec = 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, +) -> usize { + let mut count = 0; + for entry in entries.iter_mut() { + let mut hits: Vec> = 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, Vec) { + let mut providers: Vec = Vec::new(); + let mut purls: Vec = 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::>() + ); + 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()] + ) + ); + } +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index c92c20d..399302a 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -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; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 286e594..7b5353d 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -52,6 +52,8 @@ pub struct PipelineOrchestrator { pub(super) nuget_license_cache: Option>, /// The cross-tenant cache of KEV, EPSS and SSVC answers (#493). pub(super) exploit_cache: Option>, + /// The vendor CSAF advisories (#515); none in tests. + pub(super) advisory_index: Option>, } 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, + ) -> 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, + ) { + 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 { diff --git a/compliance-core/src/models/cve.rs b/compliance-core/src/models/cve.rs index 10f5f8d..6370c67 100644 --- a/compliance-core/src/models/cve.rs +++ b/compliance-core/src/models/cve.rs @@ -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, + /// 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, } /// 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, + /// The vendor advisories that name it (#515). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub advisories: Vec, /// The VEX statement on it (#498); none until someone states one. #[serde(default, skip_serializing_if = "Option::is_none")] pub vex: Option, @@ -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, diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 7d95c10..917e7a9 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -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, diff --git a/compliance-core/src/version.rs b/compliance-core/src/version.rs index 6fe5721..7179505 100644 --- a/compliance-core/src/version.rs +++ b/compliance-core/src/version.rs @@ -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:/` + /// 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 { - 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 = 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); } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 961cc86..2a44165 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -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; diff --git a/compliance-dashboard/src/components/vex_panel.rs b/compliance-dashboard/src/components/vex_panel.rs index 1f04f59..70804ea 100644 --- a/compliance-dashboard/src/components/vex_panel.rs +++ b/compliance-dashboard/src/components/vex_panel.rs @@ -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() { diff --git a/docs/guide/plc.md b/docs/guide/plc.md index 79566fc..f65e8eb 100644 --- a/docs/guide/plc.md +++ b/docs/guide/plc.md @@ -143,7 +143,11 @@ guard-aware), cleartext/insecure communication (CWE-319), insecure protocol port The **SBOM** view lists the CODESYS libraries (`pkg:codesys/@`) 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 diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 67d681c..6b998c0 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -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` diff --git a/docs/release/staging-test-plan-after-v0.4.5.md b/docs/release/staging-test-plan-after-v0.4.5.md index 70e0ba7..60a8438 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -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.