diff --git a/compliance-agent/src/pipeline/csaf_feed.rs b/compliance-agent/src/pipeline/csaf_feed.rs new file mode 100644 index 0000000..104a100 --- /dev/null +++ b/compliance-agent/src/pipeline/csaf_feed.rs @@ -0,0 +1,810 @@ +//! Vendor security advisories in CSAF 2.0, fetched into an index shared by +//! all tenants (#515): CERT@VDE's vendor providers (CODESYS, WAGO, Phoenix +//! Contact, …), Siemens ProductCERT and, when switched on, CISA's ICS +//! advisories. Scans only read the index; they never fetch. +//! +//! Each provider publishes its metadata (`provider-metadata.json`), which +//! names ROLIE feeds per TLP label. Only `WHITE` feeds are read. A feed lists +//! every advisory with the time it was last updated; an advisory is fetched +//! when it is new or newer than the stored one, its SHA-512 checked against +//! the hash file the provider publishes beside it, read +//! ([`compliance_core::csaf_ingest`]) and stored. The PGP signatures are not +//! checked. Everything goes through the guarded client; a run is bounded by +//! a number of advisories and a time budget, so the first fill spans several +//! runs. + +use std::collections::HashMap; +use std::time::Duration; + +use futures_util::future::BoxFuture; +use futures_util::{StreamExt, TryStreamExt}; +use mongodb::bson::doc; +use sha2::{Digest, Sha512}; + +use compliance_core::csaf_ingest::{self, Advisory}; +use compliance_core::net_guard::NetGuard; + +use crate::pipeline::public_http::{read_body, PublicHttp}; + +/// CERT@VDE's vendor providers, each at `.csaf-tp.certvde.com`. +const CERTVDE_VENDORS: [&str; 13] = [ + "codesys", + "wago", + "phoenixcontact", + "pilz", + "festo", + "helmholz", + "weidmueller", + "murrelektronik", + "janitza", + "beckhoff", + "lenze", + "turck", + "hilscher", +]; + +/// Siemens ProductCERT's metadata. +const SIEMENS: &str = "https://cert-portal.siemens.com/productcert/csaf/provider-metadata.json"; + +/// CISA's metadata (ICS and IT advisories; only the OT feed is read). +const CISA: &str = "https://www.cisa.gov/sites/default/files/csaf/provider-metadata.json"; + +/// How far back CISA's advisories are read (two years), once switched on. +const CISA_MAX_AGE: chrono::Duration = chrono::Duration::days(730); + +/// One provider to read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Provider { + /// Its key in the index (`codesys`, `siemens`, `cisa`). + pub name: String, + pub metadata_url: String, + /// Read only the feeds whose URL has this path segment (CISA: `OT`). + pub feed_filter: Option<&'static str>, + /// Skip advisories last updated before this long ago. + pub max_age: Option, +} + +impl Provider { + fn certvde(vendor: &str) -> Self { + Self { + name: vendor.to_string(), + metadata_url: format!( + "https://{vendor}.csaf-tp.certvde.com/.well-known/csaf/provider-metadata.json" + ), + feed_filter: None, + max_age: None, + } + } + + fn siemens() -> Self { + Self { + name: "siemens".to_string(), + metadata_url: SIEMENS.to_string(), + feed_filter: None, + max_age: None, + } + } + + fn cisa() -> Self { + Self { + name: "cisa".to_string(), + metadata_url: CISA.to_string(), + feed_filter: Some("OT"), + max_age: Some(CISA_MAX_AGE), + } + } +} + +/// The providers `PW_CSAF_PROVIDERS` names: `off` (none), unset or `default` +/// (CERT@VDE's vendors and Siemens), or a comma list of `default`, `cisa`, +/// `siemens` and CERT@VDE vendor names (`codesys,wago`). +pub(crate) fn providers(value: Option<&str>) -> Vec { + let value = value + .map(str::trim) + .filter(|v| !v.is_empty()) + .unwrap_or("default"); + if value.eq_ignore_ascii_case("off") { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + let mut add = |p: Provider| { + if out.iter().all(|o| o.name != p.name) { + out.push(p); + } + }; + for name in value.split(',').map(|n| n.trim().to_ascii_lowercase()) { + match name.as_str() { + "default" => { + for vendor in CERTVDE_VENDORS { + add(Provider::certvde(vendor)); + } + add(Provider::siemens()); + } + "siemens" => add(Provider::siemens()), + "cisa" => add(Provider::cisa()), + vendor if CERTVDE_VENDORS.contains(&vendor) => add(Provider::certvde(vendor)), + other => tracing::warn!(provider = other, "PW_CSAF_PROVIDERS: unknown provider"), + } + } + out +} + +/// GET, behind a trait so tests answer without the network. +pub(crate) trait Fetch: Send + Sync { + /// The body, or `None` for a 404. + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result>, String>>; +} + +/// [`Fetch`] over the guarded client. +pub(crate) struct HttpFetch(PublicHttp); + +impl HttpFetch { + /// A fetcher checking every address with `guard`. + /// + /// # Errors + /// + /// The HTTP client cannot be built. + pub(crate) fn new(guard: NetGuard) -> Result { + PublicHttp::new(guard).map(Self).map_err(|e| e.to_string()) + } +} + +impl Fetch for HttpFetch { + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result>, String>> { + Box::pin(async move { + let resp = self + .0 + .get(url)? + .timeout(Duration::from_secs(60)) + .send() + .await + .map_err(|e| format!("{url}: {e}"))?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !resp.status().is_success() { + return Err(format!("{url}: {}", resp.status())); + } + read_body(resp).await.map(Some) + }) + } +} + +/// The advisory index, behind a trait so tests keep it in memory. +pub(crate) trait AdvisoryStore: Send + Sync { + /// When each stored advisory of `provider` was last updated, by id. + fn known<'a>( + &'a self, + provider: &'a str, + ) -> BoxFuture<'a, Result, String>>; + /// Store `advisory` of `provider` as the feed's version `updated`, + /// replacing an earlier one. + fn put<'a>( + &'a self, + provider: &'a str, + updated: &'a str, + advisory: &'a Advisory, + ) -> BoxFuture<'a, Result<(), String>>; +} + +/// One stored advisory. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub(crate) struct StoredAdvisory { + /// `:`. + #[serde(rename = "_id")] + pub key: String, + pub provider: String, + /// The feed's `updated` of the version stored. + pub updated: String, + pub advisory: Advisory, + pub fetched_at: mongodb::bson::DateTime, +} + +/// The index in the admin database (`csaf_advisories`), shared by all +/// tenants: public advisories, nothing of a tenant. +pub(crate) struct MongoAdvisoryStore { + collection: mongodb::Collection, +} + +impl MongoAdvisoryStore { + /// The collection name in the admin database. + pub(crate) const COLLECTION: &'static str = "csaf_advisories"; + + pub(crate) fn new(admin_db: &mongodb::Database) -> Self { + Self { + collection: admin_db.collection(Self::COLLECTION), + } + } +} + +impl AdvisoryStore for MongoAdvisoryStore { + fn known<'a>( + &'a self, + provider: &'a str, + ) -> BoxFuture<'a, Result, String>> { + Box::pin(async move { + let rows: Vec = self + .collection + .clone_with_type::() + .find(doc! { "provider": provider }) + .projection(doc! { "advisory.id": 1, "updated": 1 }) + .await + .map_err(|e| e.to_string())? + .try_collect() + .await + .map_err(|e| e.to_string())?; + Ok(rows + .iter() + .filter_map(|r| { + let id = r.get_document("advisory").ok()?.get_str("id").ok()?; + Some((id.to_string(), r.get_str("updated").ok()?.to_string())) + }) + .collect()) + }) + } + + fn put<'a>( + &'a self, + provider: &'a str, + updated: &'a str, + advisory: &'a Advisory, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let row = StoredAdvisory { + key: format!("{provider}:{}", advisory.id), + provider: provider.to_string(), + updated: updated.to_string(), + advisory: advisory.clone(), + fetched_at: mongodb::bson::DateTime::now(), + }; + self.collection + .replace_one(doc! { "_id": &row.key }, &row) + .upsert(true) + .await + .map(drop) + .map_err(|e| e.to_string()) + }) + } +} + +/// Bounds of one refresh. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Limits { + /// Advisories fetched per run, over all providers; the rest follow on + /// the next runs. + pub max_advisories: usize, + /// Requests in flight at once. + pub concurrency: usize, + /// Time one run may take. + pub budget: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Self { + max_advisories: 400, + concurrency: 4, + budget: Duration::from_secs(15 * 60), + } + } +} + +/// What one refresh did, per provider. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)] +pub(crate) struct Counts { + /// Advisories the feeds list (within the provider's age limit). + pub listed: usize, + /// Fetched and stored. + pub stored: usize, + /// Stored, though the provider published no hash to check. + pub unverified: usize, + /// Their SHA-512 did not match: not stored. + pub hash_mismatch: usize, + /// Could not be fetched or read. + pub failed: usize, + /// Left for a later run (over the limits). + pub deferred: usize, +} + +/// One advisory a feed lists. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Entry { + id: String, + updated: String, + url: String, + sha512_url: Option, +} + +/// The `WHITE` feeds of a provider's metadata (and, with `filter`, only +/// those whose URL has it as a path segment). +fn white_feeds(metadata: &serde_json::Value, filter: Option<&str>) -> Vec { + metadata["distributions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d["rolie"]["feeds"].as_array()) + .flatten() + .filter(|f| { + f["tlp_label"] + .as_str() + .is_some_and(|l| l.eq_ignore_ascii_case("WHITE") || l.eq_ignore_ascii_case("CLEAR")) + }) + .filter(|f| { + filter.is_none_or(|segment| { + f["url"] + .as_str() + .is_some_and(|u| u.contains(&format!("/{segment}/"))) + }) + }) + .filter_map(|f| f["url"].as_str().map(str::to_string)) + .collect() +} + +/// The advisories a ROLIE feed lists. +fn entries(feed: &serde_json::Value) -> Vec { + feed["feed"]["entry"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| { + let links = e["link"].as_array()?; + let href = |rel: &str, suffix: Option<&str>| { + links + .iter() + .filter(|l| l["rel"] == rel) + .filter_map(|l| l["href"].as_str()) + .find(|h| suffix.is_none_or(|s| h.ends_with(s))) + .map(str::to_string) + }; + Some(Entry { + id: e["id"].as_str()?.to_string(), + updated: e["updated"].as_str().unwrap_or_default().to_string(), + url: href("self", None)?, + sha512_url: href("hash", Some(".sha512")), + }) + }) + .collect() +} + +/// Whether `updated` (RFC 3339) is newer than `stored`. +fn newer(updated: &str, stored: &str) -> bool { + let parse = |t: &str| chrono::DateTime::parse_from_rfc3339(t).ok(); + match (parse(updated), parse(stored)) { + (Some(a), Some(b)) => a > b, + _ => updated != stored, + } +} + +/// The hex digest at the start of a `.sha512` file (` `). +fn published_digest(file: &[u8]) -> Option { + let text = String::from_utf8_lossy(file); + let digest = text.split_whitespace().next()?.to_ascii_lowercase(); + (digest.len() == 128 && digest.bytes().all(|b| b.is_ascii_hexdigit())).then_some(digest) +} + +/// The outcome of fetching one advisory. +enum Fetched { + Stored { verified: bool }, + HashMismatch, + Failed(String), +} + +/// Fetch, check, read and store one advisory. +async fn fetch_one( + fetch: &dyn Fetch, + store: &dyn AdvisoryStore, + provider: &str, + entry: &Entry, +) -> Fetched { + let body = match fetch.get(&entry.url).await { + Ok(Some(body)) => body, + Ok(None) => return Fetched::Failed(format!("{}: not found", entry.url)), + Err(e) => return Fetched::Failed(e), + }; + let mut verified = false; + if let Some(hash_url) = &entry.sha512_url { + match fetch.get(hash_url).await { + Ok(Some(file)) => match published_digest(&file) { + Some(digest) if digest == hex::encode(Sha512::digest(&body)) => verified = true, + Some(_) => return Fetched::HashMismatch, + None => {} + }, + Ok(None) => {} + Err(e) => return Fetched::Failed(e), + } + } + let advisory = match serde_json::from_slice::(&body) + .map_err(|e| e.to_string()) + .and_then(|doc| csaf_ingest::parse(&doc).map_err(|e| e.to_string())) + { + Ok(advisory) => advisory, + Err(e) => return Fetched::Failed(format!("{}: {e}", entry.url)), + }; + // The feed's time decides what is newer next time. + match store.put(provider, &entry.updated, &advisory).await { + Ok(()) => Fetched::Stored { verified }, + Err(e) => Fetched::Failed(e), + } +} + +/// Refresh the index from `providers`, within `limits`. +pub(crate) async fn refresh( + fetch: &dyn Fetch, + store: &dyn AdvisoryStore, + providers: &[Provider], + limits: Limits, +) -> HashMap { + let started = std::time::Instant::now(); + let mut left = limits.max_advisories; + let mut out = HashMap::new(); + for provider in providers { + let mut counts = Counts::default(); + let todo = match pending(fetch, store, provider).await { + Ok(todo) => todo, + Err(e) => { + tracing::warn!(provider = %provider.name, "CSAF provider not read: {e}"); + counts.failed = 1; + out.insert(provider.name.clone(), counts); + continue; + } + }; + counts.listed = todo.listed; + let remaining = limits.budget.saturating_sub(started.elapsed()); + let total = todo.entries.len(); + let take = total.min(left); + counts.deferred = total - take; + left -= take; + let name = provider.name.as_str(); + let results: Vec = futures_util::stream::iter(todo.entries.into_iter().take(take)) + .map(|entry: Entry| async move { fetch_one(fetch, store, name, &entry).await }) + .buffer_unordered(limits.concurrency.max(1)) + .take_until(tokio::time::sleep(remaining)) + .collect() + .await; + counts.deferred += take - results.len(); + let mut first_error = None; + for result in results { + match result { + Fetched::Stored { verified } => { + counts.stored += 1; + counts.unverified += usize::from(!verified); + } + Fetched::HashMismatch => counts.hash_mismatch += 1, + Fetched::Failed(e) => { + counts.failed += 1; + first_error.get_or_insert(e); + } + } + } + if let Some(e) = first_error { + tracing::warn!(provider = %provider.name, "CSAF advisories not read: {e}"); + } + out.insert(provider.name.clone(), counts); + } + tracing::info!(counts = ?out, "CSAF advisories refreshed"); + out +} + +/// What a provider lists that the index lacks or has older. +struct Pending { + listed: usize, + entries: Vec, +} + +async fn pending( + fetch: &dyn Fetch, + store: &dyn AdvisoryStore, + provider: &Provider, +) -> Result { + let json = |body: Vec| -> Result { + serde_json::from_slice(&body).map_err(|e| e.to_string()) + }; + let metadata = fetch + .get(&provider.metadata_url) + .await? + .ok_or("no provider metadata")?; + let metadata = json(metadata)?; + let known = store.known(&provider.name).await?; + let oldest = provider.max_age.map(|age| chrono::Utc::now() - age); + let mut listed = 0; + let mut todo: Vec = Vec::new(); + for feed_url in white_feeds(&metadata, provider.feed_filter) { + let Some(feed) = fetch.get(&feed_url).await? else { + continue; + }; + for entry in entries(&json(feed)?) { + let recent = oldest.is_none_or(|limit| { + chrono::DateTime::parse_from_rfc3339(&entry.updated).is_ok_and(|t| t >= limit) + }); + if !recent { + continue; + } + listed += 1; + let wanted = known + .get(&entry.id) + .is_none_or(|stored| newer(&entry.updated, stored)); + if wanted && todo.iter().all(|t| t.id != entry.id) { + todo.push(entry); + } + } + } + // Newest first, so a bounded run gets the recent advisories. + todo.sort_by(|a, b| b.updated.cmp(&a.updated)); + Ok(Pending { + listed, + entries: todo, + }) +} + +/// Refresh the index with the agent's guard, providers from +/// `PW_CSAF_PROVIDERS`, default limits. Logs and returns on any failure. +pub(crate) async fn refresh_index(admin_db: &mongodb::Database, guard: NetGuard) { + let providers = providers(std::env::var("PW_CSAF_PROVIDERS").ok().as_deref()); + if providers.is_empty() { + return; + } + let fetch = match HttpFetch::new(guard) { + Ok(fetch) => fetch, + Err(e) => { + tracing::warn!("CSAF advisories not refreshed: {e}"); + return; + } + }; + let store = MongoAdvisoryStore::new(admin_db); + refresh(&fetch, &store, &providers, Limits::default()).await; +} + +/// A store for tests: advisories in memory. +#[cfg(test)] +#[derive(Default)] +pub(crate) struct MemoryStore(std::sync::Mutex>); + +#[cfg(test)] +impl AdvisoryStore for MemoryStore { + fn known<'a>( + &'a self, + provider: &'a str, + ) -> BoxFuture<'a, Result, String>> { + let prefix = format!("{provider}:"); + let known = self + .0 + .lock() + .map(|m| { + m.iter() + .filter(|(k, _)| k.starts_with(&prefix)) + .map(|(_, (updated, a))| (a.id.clone(), updated.clone())) + .collect() + }) + .unwrap_or_default(); + Box::pin(async move { Ok(known) }) + } + + fn put<'a>( + &'a self, + provider: &'a str, + updated: &'a str, + advisory: &'a Advisory, + ) -> BoxFuture<'a, Result<(), String>> { + if let Ok(mut m) = self.0.lock() { + m.insert( + format!("{provider}:{}", advisory.id), + (updated.to_string(), advisory.clone()), + ); + } + Box::pin(async { Ok(()) }) + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + /// A provider answering from a table; counts requests. + #[derive(Default)] + struct Fake(HashMap>, std::sync::Mutex>); + + impl Fetch for Fake { + fn get<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result>, String>> { + self.1.lock().unwrap().push(url.to_string()); + let body = self.0.get(url).cloned(); + Box::pin(async move { Ok(body) }) + } + } + + const META: &str = "https://acme.example/.well-known/csaf/provider-metadata.json"; + + fn advisory(id: &str) -> Vec { + serde_json::to_vec(&serde_json::json!({ + "document": { + "csaf_version": "2.0", + "title": format!("Advisory {id}"), + "publisher": { "name": "Acme", "category": "vendor", "namespace": "https://acme.example" }, + "tracking": { "id": id, "current_release_date": "2026-10-01T00:00:00Z" }, + }, + "product_tree": { "branches": [{ "category": "vendor", "name": "Acme", "branches": [ + { "category": "product_name", "name": "Acme PLC", "branches": [ + { "category": "product_version_range", "name": "vers:generic/<2.0", + "product": { "name": "Acme PLC <2.0", "product_id": "P1" } } + ] } + ] }] }, + "vulnerabilities": [{ "cve": "CVE-2026-1", "product_status": { "known_affected": ["P1"] } }], + })) + .unwrap() + } + + fn provider(name: &str) -> Provider { + Provider { + name: name.to_string(), + metadata_url: META.to_string(), + feed_filter: None, + max_age: None, + } + } + + /// A provider with a WHITE and an AMBER feed; the WHITE feed lists two + /// advisories, the first with a correct hash, the second with a wrong + /// one. + fn fake(updated: &str) -> Fake { + let doc1 = advisory("ACME-1"); + let doc2 = advisory("ACME-2"); + let mut table = HashMap::new(); + table.insert( + META.to_string(), + serde_json::to_vec( + &serde_json::json!({ "distributions": [{ "rolie": { "feeds": [ + { "tlp_label": "WHITE", "url": "https://acme.example/white.json" }, + { "tlp_label": "AMBER", "url": "https://acme.example/amber.json" }, + ] } }] }), + ) + .unwrap(), + ); + let entry = |id: &str| { + serde_json::json!({ "id": id, "updated": updated, "link": [ + { "rel": "self", "href": format!("https://acme.example/{id}.json") }, + { "rel": "hash", "href": format!("https://acme.example/{id}.json.sha512") }, + ] }) + }; + table.insert( + "https://acme.example/white.json".to_string(), + serde_json::to_vec( + &serde_json::json!({ "feed": { "entry": [entry("ACME-1"), entry("ACME-2")] } }), + ) + .unwrap(), + ); + table.insert( + "https://acme.example/ACME-1.json.sha512".to_string(), + format!("{} ACME-1.json\n", hex::encode(Sha512::digest(&doc1))).into_bytes(), + ); + table.insert( + "https://acme.example/ACME-2.json.sha512".to_string(), + format!("{} ACME-2.json\n", "0".repeat(128)).into_bytes(), + ); + table.insert("https://acme.example/ACME-1.json".to_string(), doc1); + table.insert("https://acme.example/ACME-2.json".to_string(), doc2); + Fake(table, Default::default()) + } + + #[tokio::test] + async fn white_advisories_are_checked_read_and_stored_once() { + let fetch = fake("2026-10-01T00:00:00Z"); + let store = MemoryStore::default(); + let counts = refresh(&fetch, &store, &[provider("acme")], Limits::default()).await; + let acme = &counts["acme"]; + assert_eq!((acme.listed, acme.stored, acme.hash_mismatch), (2, 1, 1)); + let keys: Vec = store.0.lock().unwrap().keys().cloned().collect(); + assert!(keys.contains(&"acme:ACME-1".to_string())); + assert!( + !keys.contains(&"acme:ACME-2".to_string()), + "a wrong hash is not stored" + ); + // The AMBER feed is never asked for. + assert!(fetch.1.lock().unwrap().iter().all(|u| !u.contains("amber"))); + + // A second run asks only for what is not stored (the mismatching one). + fetch.1.lock().unwrap().clear(); + refresh(&fetch, &store, &[provider("acme")], Limits::default()).await; + let asked = fetch.1.lock().unwrap().clone(); + assert!(!asked.contains(&"https://acme.example/ACME-1.json".to_string())); + assert!(asked.contains(&"https://acme.example/ACME-2.json".to_string())); + } + + #[tokio::test] + async fn a_newer_feed_entry_is_fetched_again_and_runs_are_bounded() { + let store = MemoryStore::default(); + let limits = Limits { + max_advisories: 1, + ..Limits::default() + }; + let counts = refresh( + &fake("2026-10-01T00:00:00Z"), + &store, + &[provider("acme")], + limits, + ) + .await; + assert_eq!( + ( + counts["acme"].stored + counts["acme"].hash_mismatch, + counts["acme"].deferred + ), + (1, 1) + ); + let fetch = fake("2026-10-05T00:00:00Z"); + refresh(&fetch, &store, &[provider("acme")], Limits::default()).await; + assert!(fetch + .1 + .lock() + .unwrap() + .contains(&"https://acme.example/ACME-1.json".to_string())); + assert_eq!( + store.0.lock().unwrap()["acme:ACME-1"].0, + "2026-10-05T00:00:00Z" + ); + } + + /// CODESYS's and Siemens' real feeds, a few advisories each, through the + /// guarded client: `cargo test -p compliance-agent --lib + /// csaf_feed::tests::live -- --ignored --nocapture`. + #[tokio::test] + #[ignore = "fetches from the providers"] + async fn live_providers_are_read() { + let fetch = HttpFetch::new(NetGuard::public_only()).unwrap(); + let store = MemoryStore::default(); + let limits = Limits { + max_advisories: 6, + ..Limits::default() + }; + let chosen = providers(Some("codesys,siemens")); + let counts = refresh(&fetch, &store, &chosen, limits).await; + println!("{counts:?}"); + assert!(counts["codesys"].listed > 0 && counts["siemens"].listed > 0); + assert_eq!( + counts["codesys"].hash_mismatch + counts["siemens"].hash_mismatch, + 0 + ); + assert!(store.0.lock().unwrap().len() >= 6); + } + + #[test] + fn providers_come_from_the_setting() { + let names = + |v: Option<&str>| -> Vec { providers(v).into_iter().map(|p| p.name).collect() }; + let default = names(None); + assert_eq!(default.len(), 14); + assert!( + default.contains(&"codesys".to_string()) && default.contains(&"siemens".to_string()) + ); + assert!( + !default.contains(&"cisa".to_string()), + "CISA is off by default" + ); + assert!(names(Some("default,cisa")).contains(&"cisa".to_string())); + assert_eq!(names(Some("codesys, wago")), ["codesys", "wago"]); + assert!(names(Some("off")).is_empty()); + let cisa = providers(Some("cisa")).remove(0); + assert_eq!(cisa.feed_filter, Some("OT")); + assert!(cisa.max_age.is_some()); + } + + #[test] + fn digests_and_feed_filters() { + let digest = "a".repeat(128); + assert_eq!( + published_digest(format!("{digest} x.json").as_bytes()), + Some(digest) + ); + assert_eq!(published_digest(b"not a digest"), None); + let metadata = serde_json::json!({ "distributions": [{ "rolie": { "feeds": [ + { "tlp_label": "WHITE", "summary": "TLP:WHITE CISA OT Advisories", "url": "https://x/OT/white/feed.json" }, + { "tlp_label": "WHITE", "summary": "TLP:WHITE CISA IT Advisories", "url": "https://x/IT/white/feed.json" }, + ] } }] }); + assert_eq!( + white_feeds(&metadata, Some("OT")), + ["https://x/OT/white/feed.json"] + ); + assert_eq!(white_feeds(&metadata, None).len(), 2); + assert!(newer("2026-10-05T00:00:00Z", "2026-10-01T00:00:00.000Z")); + assert!(!newer("2026-10-01T00:00:00Z", "2026-10-01T00:00:00.000Z")); + } +} diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 9a6820c..c92c20d 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -5,6 +5,7 @@ pub mod change; pub mod clamav; pub mod code_review; pub mod cppcheck; +pub(crate) mod csaf_feed; pub mod cve; pub(crate) mod cve_enrichment; pub(crate) mod cve_issues; diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index f584163..27cedf8 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -65,6 +65,33 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> .await .map_err(|e| AgentError::Scheduler(format!("Failed to add CVE monitor job: {e}")))?; + // Vendor CSAF advisories (#515), shared by all tenants: daily, and once + // shortly after start so a new deployment does not wait a night. + let csaf_schedule = + std::env::var("CSAF_FEED_SCHEDULE").unwrap_or_else(|_| "0 30 3 * * *".to_string()); + let csaf_agent = agent.clone(); + let csaf_job = Job::new_async(csaf_schedule.as_str(), move |_uuid, _lock| { + let agent = csaf_agent.clone(); + Box::pin(async move { + crate::pipeline::csaf_feed::refresh_index(&agent.db_pool.admin_db(), agent.net_guard) + .await; + }) + }) + .map_err(|e| AgentError::Scheduler(format!("Failed to create CSAF job: {e}")))?; + sched + .add(csaf_job) + .await + .map_err(|e| AgentError::Scheduler(format!("Failed to add CSAF job: {e}")))?; + let startup_agent = agent.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(120)).await; + crate::pipeline::csaf_feed::refresh_index( + &startup_agent.db_pool.admin_db(), + startup_agent.net_guard, + ) + .await; + }); + // Managed git sync (#439): the organisation's repositories against the // targets, a safety net for lost webhook deliveries. let sync_agent = agent.clone(); diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 87b1e50..67d681c 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -210,6 +210,35 @@ The answers are attached to the alert (`exploitation`) and to the SBOM's referen **Registry metadata (#508):** the nuget.org, npm and Maven lookups also fetch each package's project URL (the SBOM's component creator), so they now ask for packages that already have a license too, once per package version and within the same per-scan bounds; the cache fills the rest over later scans. Only URLs are kept, never maintainer names or emails. GitHub, Go-module and Swift purls give their repository page without any request. +## Vendor CSAF advisories (#515) + +Industrial vendors publish their security advisories in CSAF 2.0. Prüfwerk +keeps an index of them, shared by all tenants (admin database, +`csaf_advisories`), refreshed daily and once after the agent starts: + +| Provider | Advisories | Default | +|---|---|---| +| CERT@VDE's vendor providers (`.csaf-tp.certvde.com`): CODESYS, WAGO, Phoenix Contact, Pilz, Festo, Helmholz, Weidmüller, Murrelektronik, Janitza, Beckhoff, Lenze, TURCK, Hilscher | each vendor's | on | +| Siemens ProductCERT | about 840 | on | +| CISA ICS (OT) | about 3,950; the last two years are read | off | + +Only the TLP:WHITE feeds are read. An advisory is fetched when it is new or +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). + +`PW_CSAF_PROVIDERS` chooses the providers: unset or `default` (CERT@VDE's +vendors and Siemens), `off`, or a comma list of `default`, `siemens`, `cisa` +and vendor names (`codesys,wago`). `CSAF_FEED_SCHEDULE` sets when the daily +run starts (cron with seconds, default `0 30 3 * * *`). + +**Terms:** Siemens allows using and redistributing its advisories with a link +to the original, which every alert carries; CISA's are US government works; +CERT@VDE's vendors publish theirs with a liability disclaimer. + ## nuget.org -- NuGet Licenses Licenses of NuGet packages that no `.nuspec` in the tree gives, and the project URL (`projectUrl`) of every package, are read from the [nuget.org registration API](https://learn.microsoft.com/nuget/api/registration-base-url-resource) (`api.nuget.org`). Only the package id and version are sent, never for an id a `nuget.config` routes to another feed (see [.NET projects](/guide/dotnet-en)). The lookup is bounded per scan (8 requests at once, 10 s per request, 60 s and 300 uncached packages in total); answers are cached for all tenants. Set `NUGET_LICENSE_LOOKUP=false` to keep the agent from contacting nuget.org. @@ -352,6 +381,7 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie | `api.nuget.org` (registration, catalog) | NuGet package ids and versions, not for ids a `nuget.config` routes to another feed | `pipeline/sbom/nuget_license.rs` | guarded | 10 s per request, 5 s connect, body ≤ 2 MiB, 8 at once, 60 s and 300 uncached packages per scan | `NUGET_LICENSE_LOOKUP=false` | | `registry.npmjs.org` | npm package names and versions, not for a registry or scope `.npmrc`/`.yarnrc.yml` routes elsewhere | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org (bounds per scan; answers cached for all tenants) | `REGISTRY_LICENSE_LOOKUP=false` | | `repo1.maven.org`, `dl.google.com` (POMs) | Maven group, artifact and version (and parent POMs), not when the build names a non-public repository | `pipeline/sbom/registry_license.rs` | guarded | as nuget.org | `REGISTRY_LICENSE_LOOKUP=false` | +| `.csaf-tp.certvde.com` (CERT@VDE's vendor providers), `cert-portal.siemens.com` (Siemens ProductCERT); with `cisa`: `www.cisa.gov`, `raw.githubusercontent.com` | nothing (GETs of public advisories) | `pipeline/csaf_feed.rs` | guarded | 60 s per request, body ≤ 16 MiB, 4 at once, 400 advisories and 15 min per run; daily and once after start | `PW_CSAF_PROVIDERS=off` | | Package registries (Go proxy, npm, PyPI, Maven Central) | package names and versions | Syft (`pipeline/sbom/syft.rs`, remote license lookups) and lockfile generation (`npm`, `cargo`, `pip-compile` in `pipeline/sbom/mod.rs`) | not guarded: subprocesses with their own HTTP | Syft 10 min per scan | lockfile generation follows the execution policy | ### Tenant-chosen addresses 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 b8d393f..70e0ba7 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -34,6 +34,7 @@ together on stage in one pass before the next prod promotion. | #498 (follow-up) | ENISA deadlines evaluated by the agent; one notification per CVE | | #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 | **Customer-visible on the next prod rescan** is marked **[visible]**: these change what a customer sees on their existing targets, without them doing @@ -746,6 +747,25 @@ created or closed issues in a managed repository. - **[visible]** PLC targets' fixed CVEs leave the open list after the next rescan; managed PLC repositories get CVE issues. +### 35. #515 parts A and B: vendor CSAF advisory index + +Internal so far (matching follows in part C). + +- **Do:** deploy; wait 2 minutes after the agent starts. **Log:** `CSAF + advisories refreshed` with counts per provider: the 13 CERT@VDE vendors + and `siemens`, each with `listed`, `stored`, `hash_mismatch: 0`, + `deferred` (Siemens defers most on the first run: 400 per run); no + `cisa`. +- **Mongo:** `__admin.csaf_advisories` has rows `codesys:…`, + `siemens:SSA-…`, each with `advisory.products` and + `advisory.vulnerabilities`; the next run (or the next day) adds the + deferred ones and fetches nothing already stored. +- **Do:** set `PW_CSAF_PROVIDERS=off`, restart. **Expect:** no CSAF log + line, no requests to the providers. With `default,cisa`: a `cisa` entry, + only advisories of the last two years, only the OT feed. +- **Egress:** only `*.csaf-tp.certvde.com` and `cert-portal.siemens.com` + (with CISA: `www.cisa.gov`, `raw.githubusercontent.com`). + ## After the pass - The nightly job on `main` is green with the new mobile targets.