From 57b5aaeb970e9b0739dd00b3ccfc7f7526c49fe1 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 9 Oct 2026 18:19:19 +0000 Subject: [PATCH] feat(cve): the daily monitor re-checks NVD/CPE-only components incrementally (#558) --- .env.example | 3 + compliance-agent/src/pipeline/cve.rs | 20 +- .../src/pipeline/issue_creation.rs | 97 +- compliance-agent/src/pipeline/mod.rs | 3 +- compliance-agent/src/pipeline/nvd_cpe.rs | 142 +- compliance-agent/src/pipeline/nvd_monitor.rs | 1491 +++++++++++++++++ compliance-agent/src/pipeline/public_http.rs | 13 +- .../src/pipeline/vex_lifecycle.rs | 45 + compliance-agent/src/scheduler.rs | 41 +- docs/guide/sbom.md | 23 +- docs/guide/yocto.md | 7 +- docs/reference/tools.md | 4 +- 12 files changed, 1772 insertions(+), 117 deletions(-) create mode 100644 compliance-agent/src/pipeline/nvd_monitor.rs diff --git a/.env.example b/.env.example index 86cf27f..c3fef9b 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,9 @@ SEARXNG_URL=http://localhost:8888 # NVD NVD_API_KEY= +# The CVE monitor re-checks components only NVD knows (Yocto recipes, embedded +# libraries, CODESYS runtime) by NVD's changed CVEs; on by default. +# NVD_MONITOR=off # Agent AGENT_PORT=3001 diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index 2cdd405..8f58dff 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -13,7 +13,7 @@ use crate::pipeline::yocto_inventory::NvdQuery; const OSV_API: &str = "https://api.osv.dev"; /// Every CODESYS product: advisories key off the runtime's version. -const CODESYS: NvdProduct = NvdProduct { +pub(crate) const CODESYS: NvdProduct = NvdProduct { match_string: "cpe:2.3:a:codesys", marker: ":codesys:", }; @@ -441,9 +441,10 @@ pub struct CveLookup { pub unchecked: Vec, } -/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for -/// each. -fn record_nvd( +/// Attach NVD `cves` to the SBOM entry `name@version` (once per CVE: an +/// entry read back from the database may carry it already) and make an alert +/// for each. +pub(crate) fn record_nvd( repo_id: &str, entries: &mut [SbomEntry], name: &str, @@ -456,7 +457,10 @@ fn record_nvd( let purl = entry.as_ref().and_then(|e| e.purl.clone()); cves.into_iter() .map(|cve| { - if let Some(e) = entry.as_deref_mut() { + if let Some(e) = entry + .as_deref_mut() + .filter(|e| !e.known_vulnerabilities.iter().any(|v| v.id == cve.id)) + { e.known_vulnerabilities.push(VulnRef { id: cve.id.clone(), source: "nvd".to_string(), @@ -570,7 +574,7 @@ fn without_osv_advisories(entry: &SbomEntry) -> bool { /// The CODESYS runtime component (name + version) from an SBOM, if present. The /// runtime carries the version CODESYS advisories key off; the internal library /// components do not. -fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> { +pub(crate) fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> { entries .iter() .find(|e| e.package_manager == "codesys" && e.name.starts_with("CODESYS Control")) @@ -715,6 +719,10 @@ mod tests { let without = record_nvd("t", &mut entries, "FreeRTOS", "1.0.0", vec![cve("CVE-2")]); assert_eq!(with[0].purl.as_deref(), Some("pkg:generic/lwip@1.0.0")); assert_eq!(without[0].purl, None); + // Recorded again (the monitor re-reads stored entries), the + // component lists the CVE once. + record_nvd("t", &mut entries, "lwIP", "1.0.0", vec![cve("CVE-1")]); + assert_eq!(entries[0].known_vulnerabilities.len(), 1); } fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry { diff --git a/compliance-agent/src/pipeline/issue_creation.rs b/compliance-agent/src/pipeline/issue_creation.rs index ed595ec..efd510e 100644 --- a/compliance-agent/src/pipeline/issue_creation.rs +++ b/compliance-agent/src/pipeline/issue_creation.rs @@ -30,39 +30,13 @@ impl PipelineOrchestrator { alerts: &[CveAlert], complete: bool, ) -> Result<(), AgentError> { - if !repo.managed { - return Ok(()); - } - let (Some(tracker), Some(owner), Some(name)) = ( - self.build_tracker(repo), - repo.tracker_owner.as_deref(), - repo.tracker_repo.as_deref(), - ) else { - return Ok(()); - }; - let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); - let target = crate::pipeline::cve_issues::CveIssueTarget { + let sync = CveIssueSync { + config: &self.config, + net_guard: self.net_guard, db: &self.db, tenant_id: &self.tenant_id, - tracker: &tracker, - owner, - repo: name, - target_id: repo_id, - dashboard: &dashboard, - epss_percentile: crate::pipeline::cve_issues::epss_percentile( - std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(), - ), - autoclose: self.config.issue_autoclose, }; - let counts = - crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?; - tracing::info!( - "[{repo_id}] CVE issues: {} opened, {} reopened, {} closed", - counts.created, - counts.reopened, - counts.closed - ); - Ok(()) + sync.sync(repo, repo_id, alerts, complete).await } /// Create tracker issues for new findings (severity >= Medium). @@ -186,6 +160,69 @@ impl PipelineOrchestrator { } } +/// What opening, reopening and closing a target's CVE issues needs: the +/// tracker configuration, where tracker calls may connect, and the tenant's +/// database. Shared by the scans and the CVE monitor. +pub(crate) struct CveIssueSync<'a> { + pub config: &'a compliance_core::AgentConfig, + pub net_guard: compliance_core::NetGuard, + pub db: &'a Database, + /// The tenant, for the log lines. + pub tenant_id: &'a str, +} + +impl CveIssueSync<'_> { + /// Open, reopen and close the CVE issues of the managed repository + /// `repo` (target `repo_id`) to match `alerts` (see + /// [`crate::pipeline::cve_issues::sync_cve_issues`] for `complete`); + /// other targets, and one without a tracker, get none. + /// + /// # Errors + /// + /// A database error. + pub(crate) async fn sync( + &self, + repo: &RepoView, + repo_id: &str, + alerts: &[CveAlert], + complete: bool, + ) -> Result<(), AgentError> { + if !repo.managed { + return Ok(()); + } + let (Some(tracker), Some(owner), Some(name)) = ( + build_tracker(self.config, self.net_guard, repo), + repo.tracker_owner.as_deref(), + repo.tracker_repo.as_deref(), + ) else { + return Ok(()); + }; + let dashboard = std::env::var("DASHBOARD_PUBLIC_URL").unwrap_or_default(); + let target = crate::pipeline::cve_issues::CveIssueTarget { + db: self.db, + tenant_id: self.tenant_id, + tracker: &tracker, + owner, + repo: name, + target_id: repo_id, + dashboard: &dashboard, + epss_percentile: crate::pipeline::cve_issues::epss_percentile( + std::env::var("CVE_ISSUE_EPSS_PERCENTILE").ok().as_deref(), + ), + autoclose: self.config.issue_autoclose, + }; + let counts = + crate::pipeline::cve_issues::sync_cve_issues(&target, alerts, complete).await?; + tracing::info!( + "[{repo_id}] CVE issues: {} opened, {} reopened, {} closed", + counts.created, + counts.reopened, + counts.closed + ); + Ok(()) + } +} + /// Build an issue tracker client from a repository's tracker configuration. /// Returns `None` if the repo has no tracker configured. /// diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 3a21512..47b5dff 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -26,12 +26,13 @@ mod graph_build; pub mod grouping; pub mod ios_config; mod issue_catchup; -mod issue_creation; +pub(crate) mod issue_creation; pub(crate) mod issue_sync; pub mod languages; pub mod lint; pub mod mobsfscan; pub mod nvd_cpe; +pub(crate) mod nvd_monitor; pub mod orchestrator; pub mod patterns; pub mod plan; diff --git a/compliance-agent/src/pipeline/nvd_cpe.rs b/compliance-agent/src/pipeline/nvd_cpe.rs index 85a2d08..eed2492 100644 --- a/compliance-agent/src/pipeline/nvd_cpe.rs +++ b/compliance-agent/src/pipeline/nvd_cpe.rs @@ -40,7 +40,7 @@ pub(crate) const NVD_CVES_URL: &str = "https://services.nvd.nist.gov/rest/json/c /// Waits before each retry of a failed NVD request. NVD asks for about six /// seconds between requests, and answers 403/429 when a key's budget is /// spent; three retries ride out a short limit without stalling a scan. -const RETRY_DELAYS: [Duration; 3] = [ +pub(crate) const RETRY_DELAYS: [Duration; 3] = [ Duration::from_secs(6), Duration::from_secs(12), Duration::from_secs(24), @@ -113,36 +113,48 @@ async fn product_body( if let Some(body) = cached(match_string) { return Ok(body); } + let query = [("virtualMatchString", match_string.to_string())]; + let body = Arc::new(fetch(http, base_url, api_key, &query, delays).await?); + if let Ok(mut c) = cache().lock() { + c.insert( + match_string.to_string(), + (Instant::now(), Arc::clone(&body)), + ); + } + Ok(body) +} + +/// NVD's answer to `query` at `base_url`, asked again after each of `delays` +/// while NVD's answer is transient ([`is_transient`]) or the request fails. +/// +/// # Errors +/// +/// Why NVD could not be asked (net guard, network, status, body) after the +/// retries; a status NVD gives for good (404 for a query it refuses) and a +/// URL the net guard refuses are not retried. +pub(crate) async fn fetch( + http: &PublicHttp, + base_url: &str, + api_key: Option<&str>, + query: &[(&str, String)], + delays: &[Duration], +) -> Result { let mut last_error = String::new(); for attempt in 0..=delays.len() { if let Some(wait) = attempt.checked_sub(1).and_then(|i| delays.get(i)) { - tracing::info!( - match_string, - attempt, - "retrying NVD after {wait:?}: {last_error}" - ); + tracing::info!(attempt, "retrying NVD after {wait:?}: {last_error}"); tokio::time::sleep(*wait).await; } // A URL the net guard refuses is refused for good: not retried. let mut req = http .get(base_url)? - .query(&[("virtualMatchString", match_string)]) + .query(query) .timeout(NVD_REQUEST_TIMEOUT); if let Some(key) = api_key { req = req.header("apiKey", key); } match req.send().await { - Ok(resp) if resp.status().is_success() => { - let body: serde_json::Value = read_json(resp).await?; - let body = Arc::new(body); - if let Ok(mut c) = cache().lock() { - c.insert( - match_string.to_string(), - (Instant::now(), Arc::clone(&body)), - ); - } - return Ok(body); - } + Ok(resp) if resp.status().is_success() => return read_json(resp).await, Ok(resp) if is_transient(resp.status()) => { last_error = format!("NVD returned {}", resp.status()); } @@ -190,36 +202,59 @@ pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec Option { + let cve = &v["cve"]; + let id = cve["id"].as_str()?; + let covered = cpe_matches(v).any(|cm| { + cm["vulnerable"].as_bool() == Some(true) + && cm["criteria"].as_str().is_some_and(|c| c.contains(marker)) + && version_matches(version, &cpe_range(cm)) + }); + covered.then(|| NvdCve { + id: id.to_string(), + summary: cve["descriptions"] + .as_array() + .and_then(|d| d.iter().find(|x| x["lang"].as_str() == Some("en"))) + .and_then(|x| x["value"].as_str()) + .map(String::from), + cvss: cve["metrics"]["cvssMetricV31"] + .as_array() + .and_then(|m| m.first()) + .and_then(|m| m["cvssData"]["baseScore"].as_f64()), + }) +} + +/// Every `cpeMatch` object of one entry of an NVD response's +/// `vulnerabilities`. +pub(crate) fn cpe_matches(v: &serde_json::Value) -> impl Iterator { + v["cve"]["configurations"] + .as_array() + .into_iter() + .flatten() + .flat_map(|c| c["nodes"].as_array().into_iter().flatten()) + .flat_map(|n| n["cpeMatch"].as_array().into_iter().flatten()) +} + +/// Whether the CPE `criteria` is one NVD returns for the match string +/// `match_string` (`virtualMatchString`): each component the match string +/// names (part, vendor, product, ...) is `*` there or equal in `criteria`. +/// `cpe:2.3:a:codesys` matches every CODESYS application CPE, +/// `cpe:2.3:*:amazon:freertos` FreeRTOS as application and operating system. +pub(crate) fn matches_virtual(match_string: &str, criteria: &str) -> bool { + let mut wanted = match_string.split(':'); + let mut have = criteria.split(':'); + wanted.all(|w| { + have.next() + .is_some_and(|h| w == "*" || w.eq_ignore_ascii_case(h)) + }) +} + /// Version constraints from an NVD `cpeMatch` node. #[derive(Default)] struct CpeRange { @@ -391,6 +426,23 @@ mod tests { assert_eq!(hits.load(Ordering::SeqCst), 0); } + #[test] + fn a_match_string_matches_cpes_as_nvd_lists_them() { + let criteria = "cpe:2.3:o:amazon:freertos:*:*:*:*:*:*:*:*"; + assert!(matches_virtual("cpe:2.3:*:amazon:freertos", criteria)); + assert!(matches_virtual("cpe:2.3:*:*:freertos", criteria)); + assert!(!matches_virtual("cpe:2.3:a:amazon:freertos", criteria)); + assert!(!matches_virtual( + "cpe:2.3:*:amazon:freertos-plus-tcp", + criteria + )); + assert!(matches_virtual( + "cpe:2.3:a:codesys", + "cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*" + )); + assert!(!matches_virtual("cpe:2.3:a:codesys", "cpe:2.3:a")); + } + #[test] fn fatfs_revisions_match_nvds_ranges() { // The shape of CVE-2026-6682: FatFs R0.16 and earlier. diff --git a/compliance-agent/src/pipeline/nvd_monitor.rs b/compliance-agent/src/pipeline/nvd_monitor.rs new file mode 100644 index 0000000..371df0e --- /dev/null +++ b/compliance-agent/src/pipeline/nvd_monitor.rs @@ -0,0 +1,1491 @@ +//! The CVE monitor's NVD pass: components only NVD knows, re-checked between +//! scans. +//! +//! OSV is asked about every component with a purl each time the monitor runs. +//! The components a scan matches in NVD by CPE instead (Yocto recipes, +//! libraries found by their headers, the CODESYS runtime; see +//! [`crate::pipeline::nvd_cpe`]) are re-checked here, incrementally: NVD is +//! asked which CVEs it modified since the last run (`lastModStartDate` / +//! `lastModEndDate`, one window for every tenant, at most +//! [`MAX_WINDOW`] long), and those CVEs are matched locally against every +//! tenant's components, with the scan's rules. +//! +//! One window query instead of one query per CPE: NVD modifies a few thousand +//! CVEs a day, so a day is a handful of pages of [`PAGE_SIZE`] for all tenants +//! together, where asking per CPE would cost one request per product and +//! tenant on every run (hundreds for one Yocto layer tree, hourly). +//! +//! Each run has a time budget ([`RUN_BUDGET`]) and the requests are paced to +//! NVD's rate limit ([`nvd_cpe::request_interval`]). Where a run stops (the +//! budget, an NVD or database error), the window and the page within it are +//! stored in the admin database, and the next run continues there: no window +//! is skipped. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; +use std::time::Duration; + +use chrono::{DateTime, TimeDelta, Utc}; +use futures_util::TryStreamExt; +use mongodb::bson::{doc, Document}; + +use compliance_core::models::{CveAlert, SbomEntry, YOCTO_RECIPE_MANAGER}; +use compliance_core::net_guard::NetGuard; +use compliance_core::secret_box::SecretBox; +use compliance_core::AgentConfig; + +use crate::database::Database; +use crate::error::AgentError; +use crate::pipeline::cve::{codesys_runtime, record_nvd, CODESYS}; +use crate::pipeline::cve_enrichment::CveEnricher; +use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER}; +use crate::pipeline::nvd_cpe::{self, NvdCve}; +use crate::pipeline::public_http::{is_too_large, PublicHttp}; +use crate::pipeline::yocto_inventory::CpeProduct; + +/// CVEs asked for per request. A page of NVD's lastMod listing is about +/// 6 MB for 500 CVEs; a page over the body cap is asked for again with half +/// as many. +const PAGE_SIZE: u64 = 500; + +/// The longest window NVD answers (`lastModEndDate` at most 120 days after +/// `lastModStartDate`). +const MAX_WINDOW: TimeDelta = TimeDelta::days(120); + +/// How far back a window ends: a CVE modified moments ago may not be listed +/// yet, and once a window is read, nothing modified within it is read again. +const SETTLE: TimeDelta = TimeDelta::minutes(15); + +/// Where the very first run starts: the components' last scan matched them, +/// a week back covers the days since scans that are not daily. +const FIRST_LOOKBACK: TimeDelta = TimeDelta::days(7); + +/// Time one run may spend asking NVD: 100 pages without an API key, many +/// more with one. Where it ends, the next run continues. +pub(crate) const RUN_BUDGET: Duration = Duration::from_secs(10 * 60); + +/// The admin collection, and the document in it, holding the cursor. +const CURSOR_COLLECTION: &str = "nvd_monitor"; +const CURSOR_ID: &str = "lastmod"; + +/// The CODESYS SBOM entries the monitor reads: only the runtime's version +/// matters (see [`codesys_runtime`]). +const CODESYS_MANAGER: &str = "codesys"; + +/// Whether the NVD pass runs, from `NVD_MONITOR`: on unless `off` (or +/// `false`, `0`, `no`). On by default: without an API key it is paced to 5 +/// requests per 30 seconds and bounded by [`RUN_BUDGET`], so slow but +/// harmless. +pub(crate) fn enabled(value: Option<&str>) -> bool { + !value.is_some_and(|v| { + matches!( + v.trim().to_ascii_lowercase().as_str(), + "off" | "false" | "0" | "no" + ) + }) +} + +/// How far NVD's modified CVEs have been read. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Cursor { + /// Every CVE NVD modified before this was matched. + done_until: DateTime, + /// The window from `done_until` a run stopped inside of. + open: Option, +} + +/// A window read in part. +#[derive(Debug, Clone, PartialEq)] +struct OpenWindow { + end: DateTime, + /// The index of the next CVE to ask for (`startIndex`). + next_index: u64, + /// NVD's count of the window's CVEs when it was last asked. + total: u64, +} + +impl Cursor { + /// The cursor of the first run at `now`. + fn first(now: DateTime) -> Self { + Self { + done_until: now - FIRST_LOOKBACK, + open: None, + } + } + + /// The window to read next at `now`, start and end: the open one, else + /// from `done_until` to [`SETTLE`] before `now`, at most [`MAX_WINDOW`]. + /// `None` when there is nothing to read yet. + fn window(&self, now: DateTime) -> Option<(DateTime, DateTime)> { + if let Some(open) = &self.open { + return Some((self.done_until, open.end)); + } + let end = (now - SETTLE).min(self.done_until + MAX_WINDOW); + (end > self.done_until).then_some((self.done_until, end)) + } + + /// The `startIndex` of the next page. + fn next_index(&self) -> u64 { + self.open.as_ref().map_or(0, |o| o.next_index) + } + + /// Mark read the page of the window ending `end` asked for at `index`, + /// with `len` CVEs, of `total` in the window as NVD counts them now. + /// + /// The listing is not a snapshot: a CVE modified again after the window + /// leaves it, and every CVE behind it moves up. When the count dropped + /// since the last page, the next page starts that many places earlier, + /// so none is skipped (some are read twice, which changes nothing). + fn after_page(&mut self, end: DateTime, index: u64, len: u64, total: u64) { + let dropped = self + .open + .as_ref() + .map_or(0, |o| o.total.saturating_sub(total)); + let next_index = if dropped > 0 { + index.saturating_sub(dropped) + } else { + index + len + }; + if dropped == 0 && (next_index >= total || len == 0) { + self.done_until = end; + self.open = None; + } else { + self.open = Some(OpenWindow { + end, + next_index, + total, + }); + } + } + + /// The cursor of a run with nothing to match: everything up to `now` (but + /// [`SETTLE`]) counts as read. + fn skip_to(&mut self, now: DateTime) { + let end = now - SETTLE; + if self.open.is_none() && end > self.done_until { + self.done_until = end; + } + } +} + +impl fmt::Display for Cursor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let start = self.done_until.to_rfc3339(); + match &self.open { + None => write!(f, "{start}"), + Some(o) => write!(f, "{start}..{} at {}", o.end.to_rfc3339(), o.next_index), + } + } +} + +/// The stored cursor, if a run stored one. +async fn load_cursor(admin: &mongodb::Database) -> Result, AgentError> { + let Some(stored) = admin + .collection::(CURSOR_COLLECTION) + .find_one(doc! { "_id": CURSOR_ID }) + .await? + else { + return Ok(None); + }; + let time = |key: &str| stored.get_datetime(key).ok().map(|d| d.to_chrono()); + let Some(done_until) = time("done_until") else { + return Ok(None); + }; + let count = |key: &str| stored.get_i64(key).ok().and_then(|n| u64::try_from(n).ok()); + let open = time("open_end").map(|end| OpenWindow { + end, + next_index: count("next_index").unwrap_or(0), + total: count("total").unwrap_or(0), + }); + Ok(Some(Cursor { done_until, open })) +} + +/// Store `cursor`. +async fn save_cursor(admin: &mongodb::Database, cursor: &Cursor) -> Result<(), AgentError> { + let bson_time = mongodb::bson::DateTime::from_chrono; + let count = |n: u64| i64::try_from(n).unwrap_or(i64::MAX); + let mut stored = doc! { "done_until": bson_time(cursor.done_until) }; + if let Some(open) = &cursor.open { + stored.insert("open_end", bson_time(open.end)); + stored.insert("next_index", count(open.next_index)); + stored.insert("total", count(open.total)); + } + admin + .collection::(CURSOR_COLLECTION) + .replace_one(doc! { "_id": CURSOR_ID }, stored) + .upsert(true) + .await?; + Ok(()) +} + +/// A component the scan matches in NVD by CPE, and how. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Watched { + /// Its SBOM entry (an index into the target's entries). + entry: usize, + /// What the scan asks NVD for (`virtualMatchString`). + match_string: String, + /// What a vulnerable CPE's criteria must contain. + marker: String, + /// The version NVD's ranges are compared with. + cve_version: String, +} + +/// The components of one target's `entries` the scan matches in NVD by CPE: +/// Yocto recipes by their CPE (the recipe's first product and its +/// `CVE_VERSION`), the libraries found by their headers, and the CODESYS +/// runtime. A recipe without a version in its CPE is not matched, as by the +/// scan. +pub(crate) fn watched(entries: &[SbomEntry]) -> Vec { + let runtime = codesys_runtime(entries); + entries + .iter() + .enumerate() + .filter_map(|(entry, e)| { + let (match_string, marker, cve_version) = match e.package_manager.as_str() { + YOCTO_RECIPE_MANAGER => { + let (product, version) = recipe_cpe(e.cpe.as_deref()?)?; + (product.match_string(), product.marker(), version) + } + EMBEDDED_MANAGER => { + let product = embedded_versions::nvd_product(&e.name)?; + ( + product.match_string.to_string(), + product.marker.to_string(), + e.version.clone(), + ) + } + CODESYS_MANAGER + if runtime + .as_ref() + .is_some_and(|(n, v)| *n == e.name && *v == e.version) => + { + ( + CODESYS.match_string.to_string(), + CODESYS.marker.to_string(), + e.version.clone(), + ) + } + _ => return None, + }; + Some(Watched { + entry, + match_string, + marker, + cve_version, + }) + }) + .collect() +} + +/// The product and version of a recipe component's CPE 2.3 name +/// (`cpe:2.3:a:vendor:product:version:...`); `None` without a version. +fn recipe_cpe(cpe: &str) -> Option<(CpeProduct, String)> { + let fields = cpe_fields(cpe); + let field = |i: usize| fields.get(i).map(String::as_str); + if field(0) != Some("cpe") || field(1) != Some("2.3") { + return None; + } + let product = field(4).filter(|p| !p.is_empty() && *p != "*")?; + let version = field(5).filter(|v| !matches!(*v, "" | "*" | "-"))?; + let vendor = field(3).filter(|v| !v.is_empty() && *v != "*"); + Some(( + CpeProduct { + vendor: vendor.map(str::to_string), + product: product.to_string(), + }, + version.to_string(), + )) +} + +/// The fields of a CPE 2.3 name, with its backslash quoting removed. +fn cpe_fields(cpe: &str) -> Vec { + let mut fields = vec![String::new()]; + let mut chars = cpe.chars(); + while let Some(c) = chars.next() { + match c { + '\\' => fields + .last_mut() + .into_iter() + .for_each(|f| f.extend(chars.next())), + ':' => fields.push(String::new()), + c => fields.last_mut().into_iter().for_each(|f| f.push(c)), + } + } + fields +} + +/// The field a match string ends with, and its position (3 for a vendor, 4 +/// for a product): a CPE it matches has the same value there. +fn index_key(match_string: &str) -> Option<(usize, String)> { + let fields: Vec<&str> = match_string.split(':').collect(); + let position = fields.len().checked_sub(1)?; + (position >= 3).then(|| (position, fields[position].to_ascii_lowercase())) +} + +/// One target's components the NVD pass matches. +struct RepoWatch { + repo_id: String, + entries: Vec, + watched: Vec, +} + +/// What the NVD pass did for one tenant. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TenantCounts { + pub components: usize, + pub cpes: usize, + pub new_alerts: u32, + pub notified: u32, + pub suppressed_by_vex: u32, +} + +/// Targets' watched components, indexed for matching a page. +struct Watchlist { + repos: Vec, + /// From [`index_key`] to the (target, component) pairs it may match. + index: HashMap<(usize, String), Vec<(usize, usize)>>, +} + +impl Watchlist { + /// The watched components of `entries` (of any targets). + fn new(entries: Vec) -> Self { + let mut by_repo: BTreeMap> = BTreeMap::new(); + for entry in entries { + by_repo + .entry(entry.repo_id.clone()) + .or_default() + .push(entry); + } + let repos: Vec = by_repo + .into_iter() + .map(|(repo_id, entries)| RepoWatch { + watched: watched(&entries), + repo_id, + entries, + }) + .filter(|r| !r.watched.is_empty()) + .collect(); + let mut index: HashMap<(usize, String), Vec<(usize, usize)>> = HashMap::new(); + for (r, repo) in repos.iter().enumerate() { + for (w, watched) in repo.watched.iter().enumerate() { + if let Some(key) = index_key(&watched.match_string) { + index.entry(key).or_default().push((r, w)); + } + } + } + Self { repos, index } + } + + /// How many components are watched, and under how many distinct CPE + /// match strings. + fn size(&self) -> (usize, usize) { + let watched = self.repos.iter().flat_map(|r| &r.watched); + let cpes: BTreeSet<&str> = watched.clone().map(|w| w.match_string.as_str()).collect(); + (watched.count(), cpes.len()) + } + + /// The CVEs among `vulns` (a page's `vulnerabilities`) that affect a + /// component, per target and component, as the scan matches them: NVD + /// would list the CVE for the component's match string, and a vulnerable + /// CPE with its marker covers its version. + fn matches(&self, vulns: &[serde_json::Value]) -> BTreeMap> { + let mut found: BTreeMap> = BTreeMap::new(); + for vuln in vulns { + let mut candidates = BTreeSet::new(); + for criteria in nvd_cpe::cpe_matches(vuln).filter_map(|cm| cm["criteria"].as_str()) { + let fields: Vec<&str> = criteria.split(':').collect(); + for position in [3, 4] { + let Some(value) = fields.get(position) else { + continue; + }; + let key = (position, value.to_ascii_lowercase()); + for &(r, w) in self.index.get(&key).into_iter().flatten() { + if nvd_cpe::matches_virtual( + &self.repos[r].watched[w].match_string, + criteria, + ) { + candidates.insert((r, w)); + } + } + } + } + for (r, w) in candidates { + let watched = &self.repos[r].watched[w]; + if let Some(cve) = nvd_cpe::parse_cve(vuln, &watched.marker, &watched.cve_version) { + found.entry(r).or_default().push((w, cve)); + } + } + } + found + } +} + +/// A tenant's watched components and what the pass did for it. +struct TenantWatch { + tenant_id: String, + db: Database, + list: Watchlist, + counts: TenantCounts, +} + +impl TenantWatch { + /// Read the tenant's components the scan matches in NVD. + /// + /// # Errors + /// + /// A database error. + async fn load(tenant_id: String, db: Database) -> Result { + let entries: Vec = db + .sbom_entries() + .find(doc! { "$or": [ + { "package_manager": { "$in": [YOCTO_RECIPE_MANAGER, EMBEDDED_MANAGER] } }, + { "package_manager": CODESYS_MANAGER, "name": { "$regex": "^CODESYS Control" } }, + ]}) + .await? + .try_collect() + .await?; + let list = Watchlist::new(entries); + let (components, cpes) = list.size(); + Ok(Self { + tenant_id, + db, + list, + counts: TenantCounts { + components, + cpes, + ..TenantCounts::default() + }, + }) + } + + /// Match a page's `vulns` and store what they find. + /// + /// # Errors + /// + /// A database error: the page counts as not read. + async fn apply( + &mut self, + vulns: &[serde_json::Value], + services: &Services<'_>, + ) -> Result<(), AgentError> { + for (r, hits) in self.list.matches(vulns) { + let target = Target { + db: &self.db, + tenant_id: &self.tenant_id, + }; + apply_repo( + &target, + &mut self.list.repos[r], + hits, + services, + &mut self.counts, + ) + .await?; + } + Ok(()) + } +} + +/// The tenant a target's alerts are stored for. +struct Target<'a> { + db: &'a Database, + tenant_id: &'a str, +} + +/// What storing a match needs beyond the database: the exploitation lookups +/// and the tracker access for CVE issues (none in tests). +pub(crate) struct Services<'a> { + pub enricher: Option<&'a CveEnricher>, + pub issues: Option>, +} + +/// What opening CVE issues needs: the tracker configuration, the sealed +/// credentials and where tracker calls may connect. +pub(crate) struct IssueAccess<'a> { + pub config: &'a AgentConfig, + pub net_guard: NetGuard, + pub secrets: &'a SecretBox, +} + +/// Store the CVEs `hits` (per component of `repo`) as the scan does: the +/// SBOM entries list them, each is an alert (new ones inserted, existing +/// ones left as they are), and they notify and open issues unless a VEX +/// statement settles them. +/// +/// # Errors +/// +/// A database error. +async fn apply_repo( + target: &Target<'_>, + repo: &mut RepoWatch, + hits: Vec<(usize, NvdCve)>, + services: &Services<'_>, + counts: &mut TenantCounts, +) -> Result<(), AgentError> { + let db = target.db; + let mut by_entry: BTreeMap> = BTreeMap::new(); + for (w, cve) in hits { + by_entry.entry(repo.watched[w].entry).or_default().push(cve); + } + let mut alerts = Vec::new(); + let mut found_ids: Vec<(usize, Vec)> = Vec::with_capacity(by_entry.len()); + for (entry, cves) in by_entry { + let (name, version) = ( + repo.entries[entry].name.clone(), + repo.entries[entry].version.clone(), + ); + found_ids.push((entry, cves.iter().map(|c| c.id.clone()).collect())); + alerts.extend(record_nvd( + &repo.repo_id, + &mut repo.entries, + &name, + &version, + cves, + )); + } + if let Some(enricher) = services.enricher { + enricher.enrich(&mut alerts, &mut repo.entries).await; + } + // Each CVE is added to its stored entry unless listed already: the + // entries were read at the start of the run, and a scan may have + // rewritten them since. + for (entry, ids) in &found_ids { + let Some(entry) = repo.entries.get(*entry) else { + continue; + }; + let Some(entry_id) = entry.id else { + continue; + }; + for vuln in entry + .known_vulnerabilities + .iter() + .filter(|v| ids.contains(&v.id)) + { + let vuln_ref = mongodb::bson::to_bson(vuln) + .map_err(|e| AgentError::Other(format!("encode SBOM entry: {e}")))?; + db.sbom_entries() + .update_one( + doc! { "_id": entry_id, "known_vulnerabilities.id": { "$ne": &vuln.id } }, + doc! { + "$push": { "known_vulnerabilities": vuln_ref }, + "$set": { "updated_at": mongodb::bson::DateTime::now() }, + }, + ) + .await?; + } + } + let mut new = Vec::new(); + for (i, alert) in alerts.iter().enumerate() { + if crate::pipeline::vex_lifecycle::store_monitored(db, alert).await? { + new.push(i); + } + } + crate::pipeline::vex_lifecycle::attach_stored_vex(db, &repo.repo_id, &mut alerts).await?; + + let stored_target = match mongodb::bson::oid::ObjectId::parse_str(&repo.repo_id) { + Ok(oid) => db.onboarded_targets().find_one(doc! { "_id": oid }).await?, + Err(_) => None, + }; + let repo_name = stored_target + .as_ref() + .map_or(repo.repo_id.as_str(), |t| t.name.as_str()); + counts.new_alerts += u32::try_from(new.len()).unwrap_or(u32::MAX); + counts.suppressed_by_vex += + u32::try_from(alerts.iter().filter(|a| a.is_resolved_by_vex()).count()).unwrap_or(u32::MAX); + counts.notified += + crate::pipeline::cve_notify::notify_new_cves(db, &repo.repo_id, repo_name, &alerts).await; + + // Issues for the new alerts only (the scan keeps the others' issues), as + // for an incomplete scan: nothing is closed for being missing. + let new_alerts: Vec = new.iter().map(|&i| alerts[i].clone()).collect(); + if let (Some(access), Some(stored), false) = + (&services.issues, &stored_target, new_alerts.is_empty()) + { + if let Some(code) = stored.code_artifact() { + let view = + crate::pipeline::repo_view::RepoView::from_target(stored, code, access.secrets); + let sync = crate::pipeline::issue_creation::CveIssueSync { + config: access.config, + net_guard: access.net_guard, + db, + tenant_id: target.tenant_id, + }; + if let Err(e) = sync.sync(&view, &repo.repo_id, &new_alerts, false).await { + tracing::warn!( + tenant_id = target.tenant_id, + "NVD CVE monitor: CVE issue sync failed: {e}" + ); + } + } + } + Ok(()) +} + +/// Where and how NVD is asked. +pub(crate) struct Feed { + pub http: PublicHttp, + /// NVD's CVE API ([`nvd_cpe::NVD_CVES_URL`]; a stand-in in tests). + pub base_url: String, + pub api_key: Option, + /// Waits before the retries of a failed request. + pub retry_delays: Vec, + /// The pause between two requests ([`nvd_cpe::request_interval`]). + pub interval: Duration, + /// Time the run may spend asking ([`RUN_BUDGET`]). + pub budget: Duration, +} + +/// What one run of the NVD pass did. +#[derive(Debug, Default)] +pub(crate) struct PassReport { + pub requests: u32, + /// The budget ran out before the listing was read up to now. + pub budget_spent: bool, + /// Why the run stopped early, other than the budget. + pub error: Option, + /// Where the next run continues. + pub resume_at: Option, + pub tenants: Vec<(String, TenantCounts)>, +} + +/// NVD's timestamp format for `lastModStartDate` / `lastModEndDate`. +fn nvd_time(t: DateTime) -> String { + t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string() +} + +/// One run of the NVD pass at `now` for `tenants` (id and database), with +/// the cursor in `admin`. +/// +/// # Errors +/// +/// A database error reading the cursor or a tenant's components: nothing +/// was read then, and the next run starts at the same place. +pub(crate) async fn run_pass( + admin: &mongodb::Database, + tenants: Vec<(String, Database)>, + feed: &Feed, + services: &Services<'_>, + now: DateTime, +) -> Result { + let mut cursor = load_cursor(admin) + .await? + .unwrap_or_else(|| Cursor::first(now)); + let mut watches = Vec::with_capacity(tenants.len()); + for (tenant_id, db) in tenants { + watches.push(TenantWatch::load(tenant_id, db).await?); + } + let mut report = PassReport::default(); + + if watches.iter().all(|w| w.list.repos.is_empty()) { + // Nothing to match: a component added later is matched by its scan. + cursor.skip_to(now); + save_cursor(admin, &cursor).await?; + } else { + let pass = Pass { + admin, + feed, + services, + now, + }; + pass.read_pages(&mut cursor, &mut watches, &mut report) + .await; + } + report.resume_at = Some(cursor.to_string()); + report.tenants = watches + .into_iter() + .map(|w| (w.tenant_id, w.counts)) + .collect(); + Ok(report) +} + +/// One run's fixed parts: where the cursor is stored, how NVD is asked, +/// what storing a match needs, and the time the run started. +struct Pass<'a> { + admin: &'a mongodb::Database, + feed: &'a Feed, + services: &'a Services<'a>, + now: DateTime, +} + +impl Pass<'_> { + /// Read the pages from `cursor` on, within the feed's budget, applying each + /// to every tenant before the cursor moves past it. + async fn read_pages( + &self, + cursor: &mut Cursor, + watches: &mut [TenantWatch], + report: &mut PassReport, + ) { + let Pass { + admin, + feed, + services, + now, + } = *self; + let deadline = tokio::time::Instant::now() + feed.budget; + let mut next_request = tokio::time::Instant::now(); + let mut page_size = PAGE_SIZE; + while let Some((start, end)) = cursor.window(now) { + if next_request >= deadline { + report.budget_spent = true; + return; + } + tokio::time::sleep_until(next_request).await; + next_request = tokio::time::Instant::now() + feed.interval; + report.requests += 1; + let index = cursor.next_index(); + let query = [ + ("lastModStartDate", nvd_time(start)), + ("lastModEndDate", nvd_time(end)), + ("startIndex", index.to_string()), + ("resultsPerPage", page_size.to_string()), + ]; + let fetch = nvd_cpe::fetch( + &feed.http, + &feed.base_url, + feed.api_key.as_deref(), + &query, + &feed.retry_delays, + ); + let body = match tokio::time::timeout_at(deadline, fetch).await { + Err(_) => { + report.budget_spent = true; + return; + } + Ok(Err(e)) if is_too_large(&e) && page_size > 1 => { + page_size /= 2; + continue; + } + Ok(Err(e)) => { + report.error = Some(format!("NVD: {e}")); + return; + } + Ok(Ok(body)) => body, + }; + let (Some(vulns), Some(total)) = ( + body["vulnerabilities"].as_array(), + body["totalResults"].as_u64(), + ) else { + report.error = + Some("NVD: an answer without vulnerabilities or totalResults".into()); + return; + }; + for watch in watches.iter_mut() { + if let Err(e) = watch.apply(vulns, services).await { + report.error = Some(format!("tenant '{}': {e}", watch.tenant_id)); + return; + } + } + cursor.after_page(end, index, vulns.len() as u64, total); + if let Err(e) = save_cursor(admin, cursor).await { + report.error = Some(format!("storing the cursor: {e}")); + return; + } + } + } +} + +/// The NVD pass of the CVE monitor for `tenants`, logging one line per +/// tenant. Errors are logged; the next run continues where this one stopped. +pub(crate) async fn run(agent: &crate::agent::ComplianceAgent, tenants: &[String]) { + use secrecy::ExposeSecret; + + // No tenant (the registry failed or lists none): the window waits, it + // must not count as read. + if tenants.is_empty() { + return; + } + + let http = match PublicHttp::new(agent.net_guard) { + Ok(http) => http, + Err(e) => { + tracing::error!("NVD CVE monitor: no HTTP client: {e}"); + return; + } + }; + let api_key = agent + .config + .nvd_api_key + .as_ref() + .map(|k| k.expose_secret().to_string()); + let feed = Feed { + http, + base_url: nvd_cpe::NVD_CVES_URL.to_string(), + interval: nvd_cpe::request_interval(api_key.is_some()), + api_key, + retry_delays: nvd_cpe::RETRY_DELAYS.to_vec(), + budget: RUN_BUDGET, + }; + let mut dbs = Vec::with_capacity(tenants.len()); + for tenant_id in tenants { + match agent.db_pool.for_tenant_id(tenant_id).await { + Ok(db) => dbs.push((tenant_id.clone(), db)), + Err(e) => { + // Every tenant reads the same window: rather than one missing + // it, the run waits for the next tick. + tracing::error!("NVD CVE monitor: cannot open tenant '{tenant_id}', not run: {e}"); + return; + } + } + } + let enricher = CveEnricher::new(agent.net_guard, Some(agent.exploit_cache.clone())) + .map_err(|e| tracing::warn!("NVD CVE monitor: no exploitation lookups: {e}")) + .ok(); + let services = Services { + enricher: enricher.as_ref(), + issues: Some(IssueAccess { + config: &agent.config, + net_guard: agent.net_guard, + secrets: &agent.secrets, + }), + }; + let admin = agent.db_pool.admin_db(); + match run_pass(&admin, dbs, &feed, &services, Utc::now()).await { + Ok(report) => log_report(&report), + Err(e) => tracing::error!("NVD CVE monitor: not run: {e}"), + } +} + +/// One INFO line per tenant, counts only, and a warning when the run +/// stopped on an error. +fn log_report(report: &PassReport) { + let resume_at = report.resume_at.as_deref().unwrap_or_default(); + if let Some(error) = &report.error { + tracing::warn!(resume_at, "NVD CVE monitor stopped early: {error}"); + } + for (tenant_id, c) in &report.tenants { + tracing::info!( + tenant_id, + components = c.components, + cpes = c.cpes, + requests = report.requests, + new_alerts = c.new_alerts, + notified = c.notified, + suppressed_by_vex = c.suppressed_by_vex, + budget_spent = report.budget_spent, + error = report.error.as_deref().unwrap_or("none"), + resume_at, + "NVD CVE monitor: CPE-only components re-checked" + ); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + use compliance_core::models::{VexAssessment, VexStatus}; + + fn at(text: &str) -> DateTime { + DateTime::parse_from_rfc3339(text) + .unwrap() + .with_timezone(&Utc) + } + + #[test] + fn the_switch_is_on_unless_turned_off() { + assert!(enabled(None)); + assert!(enabled(Some("on"))); + assert!(enabled(Some(""))); + assert!(!enabled(Some("off"))); + assert!(!enabled(Some(" OFF "))); + assert!(!enabled(Some("false"))); + } + + #[test] + fn the_first_run_reads_the_last_week_up_to_the_settle_time() { + let now = at("2026-10-09T12:00:00Z"); + let cursor = Cursor::first(now); + assert_eq!( + cursor.window(now), + Some((at("2026-10-02T12:00:00Z"), at("2026-10-09T11:45:00Z"))) + ); + } + + #[test] + fn a_long_outage_is_read_in_windows_of_at_most_120_days_without_a_gap() { + let now = at("2026-10-09T12:00:00Z"); + let mut cursor = Cursor { + done_until: at("2025-11-01T00:00:00Z"), + open: None, + }; + let mut windows = Vec::new(); + while let Some((start, end)) = cursor.window(now) { + windows.push((start, end)); + // Each window has three pages of two CVEs, read one by one. + for index in [0, 2, 4] { + cursor.after_page(end, index, 2, 6); + } + } + assert_eq!(windows.len(), 3); + assert_eq!(windows[0].0, at("2025-11-01T00:00:00Z")); + for pair in windows.windows(2) { + assert_eq!(pair[0].1, pair[1].0, "a gap between windows"); + } + assert!(windows.iter().all(|(s, e)| *e - *s <= MAX_WINDOW)); + assert_eq!(cursor.done_until, now - SETTLE); + assert_eq!(cursor.window(now), None, "caught up"); + } + + #[test] + fn a_window_read_in_part_continues_at_the_next_page_in_a_later_run() { + let now = at("2026-10-09T12:00:00Z"); + let mut cursor = Cursor::first(now); + let (start, end) = cursor.window(now).unwrap(); + cursor.after_page(end, 0, 500, 1200); + + // A day later the same window continues, not a new one from now. + let later = now + TimeDelta::days(1); + assert_eq!(cursor.window(later), Some((start, end))); + assert_eq!(cursor.next_index(), 500); + cursor.after_page(end, 500, 500, 1200); + cursor.after_page(end, 1000, 200, 1200); + assert_eq!(cursor.open, None); + assert_eq!(cursor.done_until, end); + assert_eq!( + cursor.window(later).unwrap().0, + end, + "the next one follows on" + ); + } + + #[test] + fn a_shrinking_listing_is_read_again_from_earlier() { + let now = at("2026-10-09T12:00:00Z"); + let mut cursor = Cursor::first(now); + let (_, end) = cursor.window(now).unwrap(); + cursor.after_page(end, 0, 500, 1200); + // Three CVEs of the first page were modified again and left the + // window: three unread ones moved onto the first page. + cursor.after_page(end, 500, 500, 1197); + assert_eq!(cursor.next_index(), 497); + cursor.after_page(end, 497, 500, 1197); + cursor.after_page(end, 997, 200, 1197); + assert_eq!(cursor.open, None); + } + + #[test] + fn an_empty_page_closes_the_window() { + let now = at("2026-10-09T12:00:00Z"); + let mut cursor = Cursor::first(now); + let (_, end) = cursor.window(now).unwrap(); + cursor.after_page(end, 0, 0, 0); + assert_eq!(cursor.done_until, end); + } + + #[test] + fn nothing_to_match_moves_on_but_never_past_an_open_window() { + let now = at("2026-10-09T12:00:00Z"); + let mut cursor = Cursor::first(now); + cursor.skip_to(now); + assert_eq!(cursor.done_until, now - SETTLE); + + let mut open = Cursor::first(now); + let (_, end) = open.window(now).unwrap(); + open.after_page(end, 0, 2, 6); + let before = open.clone(); + open.skip_to(now + TimeDelta::days(1)); + assert_eq!(open, before); + } + + fn entry(repo: &str, name: &str, version: &str, manager: &str) -> SbomEntry { + SbomEntry::new(repo.into(), name.into(), version.into(), manager.into()) + } + + fn recipe(repo: &str, name: &str, cpe: &str) -> SbomEntry { + let mut e = entry(repo, name, "1.35.0", YOCTO_RECIPE_MANAGER); + e.cpe = Some(cpe.into()); + e + } + + #[test] + fn only_components_the_scan_matches_in_nvd_are_watched() { + let entries = vec![ + recipe("r", "busybox", "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*"), + recipe("r", "own-app", "cpe:2.3:a:*:own-app:*:*:*:*:*:*:*:*"), + entry("r", "lwIP", "2.1.2", EMBEDDED_MANAGER), + entry("r", "UnknownLib", "1.0", EMBEDDED_MANAGER), + entry("r", "Standard", "3.5.18.0", CODESYS_MANAGER), + entry( + "r", + "CODESYS Control for Linux SL", + "4.5.0.0", + CODESYS_MANAGER, + ), + entry("r", "left-pad", "1.0.0", "npm"), + ]; + let w = watched(&entries); + let got: Vec<(&str, &str, &str)> = w + .iter() + .map(|w| { + ( + entries[w.entry].name.as_str(), + w.match_string.as_str(), + w.cve_version.as_str(), + ) + }) + .collect(); + assert_eq!( + got, + vec![ + ("busybox", "cpe:2.3:*:*:busybox", "1.35.0"), + ("lwIP", "cpe:2.3:*:lwip_project:lwip", "2.1.2"), + ( + "CODESYS Control for Linux SL", + "cpe:2.3:a:codesys", + "4.5.0.0" + ), + ] + ); + } + + #[test] + fn a_recipe_cpe_gives_its_vendor_product_and_cve_version() { + let (product, version) = + recipe_cpe(r"cpe:2.3:a:denx:u-boot:2023.01\+git:*:*:*:*:*:*:*").unwrap(); + assert_eq!(product.vendor.as_deref(), Some("denx")); + assert_eq!(product.product, "u-boot"); + assert_eq!(version, "2023.01+git"); + assert_eq!(product.marker(), ":denx:u-boot:"); + assert!(recipe_cpe("cpe:2.3:a:denx:u-boot:-:*:*:*:*:*:*:*").is_none()); + assert!(recipe_cpe("not a cpe").is_none()); + } + + /// An NVD entry for `id` whose `criteria` is vulnerable before `fixed`. + fn vuln(id: &str, criteria: &str, fixed: &str) -> serde_json::Value { + serde_json::json!({ "cve": { + "id": id, + "descriptions": [{ "lang": "en", "value": format!("{id} summary") }], + "metrics": { "cvssMetricV31": [{ "cvssData": { "baseScore": 9.8 } }] }, + "configurations": [{ "nodes": [{ "cpeMatch": [{ + "vulnerable": true, + "criteria": criteria, + "versionEndExcluding": fixed, + }]}]}], + }}) + } + + #[test] + fn a_page_matches_like_the_scan_by_product_marker_and_range() { + let list = Watchlist::new(vec![ + recipe("r1", "busybox", "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*"), + entry( + "r2", + "CODESYS Control for Linux SL", + "4.5.0.0", + CODESYS_MANAGER, + ), + ]); + let page = [ + vuln( + "CVE-1", + "cpe:2.3:a:busybox:busybox:*:*:*:*:*:*:*:*", + "1.36.0", + ), + vuln( + "CVE-2", + "cpe:2.3:a:busybox:busybox:*:*:*:*:*:*:*:*", + "1.30.0", + ), + vuln( + "CVE-3", + "cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*", + "4.9.0.0", + ), + vuln( + "CVE-4", + "cpe:2.3:a:wago:busybox_tools:*:*:*:*:*:*:*:*", + "9.0", + ), + vuln("CVE-5", "cpe:2.3:o:codesys:control:*:*:*:*:*:*:*:*", "9.0"), + ]; + let found = list.matches(&page); + let repos = &list.repos; + let ids: Vec<(String, String)> = found + .iter() + .flat_map(|(&r, hits)| { + hits.iter() + .map(move |(_, cve)| (repos[r].repo_id.clone(), cve.id.clone())) + }) + .collect(); + // CVE-2 is fixed before the version in use, CVE-4 is another product, + // CVE-5 is an operating-system CPE the CODESYS match string excludes. + assert_eq!( + ids, + vec![ + ("r1".to_string(), "CVE-1".to_string()), + ("r2".to_string(), "CVE-3".to_string()), + ] + ); + assert_eq!(list.size(), (2, 2)); + } + + /// The query parameters of each request the stand-in received. + type Seen = Arc>>>; + + /// A stand-in for NVD's lastMod listing of `vulns`, two per page. + async fn fake_nvd(vulns: Vec) -> (String, Seen) { + let seen: Seen = Arc::default(); + let log = Arc::clone(&seen); + let app = axum::Router::new().route( + "/", + axum::routing::get( + move |axum::extract::Query(q): axum::extract::Query>| { + let log = Arc::clone(&log); + let vulns = vulns.clone(); + async move { + let start: usize = q["startIndex"].parse().unwrap(); + log.lock().unwrap().push(q); + let page: Vec<_> = vulns.iter().skip(start).take(2).cloned().collect(); + axum::Json(serde_json::json!({ + "totalResults": vulns.len(), + "startIndex": start, + "vulnerabilities": page, + })) + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/", listener.local_addr().unwrap()); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + (url, seen) + } + + fn feed(url: &str, interval: Duration, budget: Duration) -> Feed { + Feed { + http: PublicHttp::new(NetGuard::allow_private()).unwrap(), + base_url: url.to_string(), + api_key: None, + retry_delays: Vec::new(), + interval, + budget, + } + } + + #[tokio::test] + async fn the_monitor_raises_new_nvd_alerts_resumes_and_respects_vex() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "nvdmon_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP nvd_monitor: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id("nvd-monitor").await.unwrap(); + let admin = pool.admin_db(); + + // Arrange: a Yocto recipe, an embedded library, a CODESYS runtime + // and an npm package (OSV's), and a person's `not_affected` on one + // busybox CVE. + let mut busybox = recipe("t1", "busybox", "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*"); + busybox.purl = Some("pkg:generic/busybox@1.35.0".into()); + let entries = vec![ + busybox, + entry("t1", "lwIP", "2.1.2", EMBEDDED_MANAGER), + entry( + "t1", + "CODESYS Control for Linux SL", + "4.5.0.0", + CODESYS_MANAGER, + ), + entry("t1", "left-pad", "1.0.0", "npm"), + ]; + db.sbom_entries().insert_many(&entries).await.unwrap(); + let mut assessed = CveAlert::new( + "CVE-2026-0002".into(), + "t1".into(), + "busybox".into(), + "1.35.0".into(), + compliance_core::models::CveSource::Nvd, + ); + assessed.vex = Some(VexAssessment { + status: VexStatus::NotAffected, + justification: None, + impact_statement: Some("applet not built".into()), + action_statement: None, + by: "user-1".into(), + by_name: None, + at: Utc::now(), + by_scan: false, + }); + db.cve_alerts().insert_one(&assessed).await.unwrap(); + + let busybox_cpe = "cpe:2.3:a:busybox:busybox:*:*:*:*:*:*:*:*"; + let (url, seen) = fake_nvd(vec![ + vuln("CVE-2026-0001", busybox_cpe, "1.36.0"), + vuln("CVE-2026-0002", busybox_cpe, "1.36.0"), + vuln( + "CVE-2026-0003", + "cpe:2.3:a:lwip_project:lwip:*:*:*:*:*:*:*:*", + "2.2.0", + ), + vuln("CVE-2026-0004", busybox_cpe, "1.30.0"), + vuln( + "CVE-2026-0005", + "cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*", + "4.9.0.0", + ), + vuln( + "CVE-2026-0006", + "cpe:2.3:a:left-pad_project:left-pad:*:*:*:*:*:*:*:*", + "9.0", + ), + ]) + .await; + let services = Services { + enricher: None, + issues: None, + }; + let now = at("2026-10-09T12:00:00Z"); + let tenants = || vec![("nvd-monitor".to_string(), db.clone())]; + + // Act 1: a budget for one request only. + let one = feed(&url, Duration::from_secs(3600), Duration::from_secs(30)); + let first = run_pass(&admin, tenants(), &one, &services, now) + .await + .unwrap(); + + // Assert 1: one page read, the window left open where it stopped. + assert_eq!(first.requests, 1); + assert!(first.budget_spent); + assert_eq!(first.error, None); + let cursor = load_cursor(&admin).await.unwrap().unwrap(); + assert_eq!(cursor.next_index(), 2); + assert_eq!(first.tenants[0].1.components, 3); + assert_eq!(first.tenants[0].1.cpes, 3); + + // Act 2: the next run, with time to finish. + let enough = feed(&url, Duration::ZERO, Duration::from_secs(60)); + let second = run_pass(&admin, tenants(), &enough, &services, now) + .await + .unwrap(); + + // Assert 2: the same window continued, page by page, then closed. + assert_eq!(second.requests, 2); + assert!(!second.budget_spent); + let requests = seen.lock().unwrap().clone(); + let starts: Vec<&str> = requests.iter().map(|q| q["startIndex"].as_str()).collect(); + assert_eq!(starts, ["0", "2", "4"]); + assert!(requests.iter().all(|q| { + q["lastModStartDate"] == "2026-10-02T12:00:00.000Z" + && q["lastModEndDate"] == "2026-10-09T11:45:00.000Z" + })); + let cursor = load_cursor(&admin).await.unwrap().unwrap(); + assert_eq!(cursor.done_until, at("2026-10-09T11:45:00Z")); + assert_eq!(cursor.open, None); + + // The new matches are alerts like the scan's, the assessed one kept. + let mut ids: Vec = db + .cve_alerts() + .find(doc! { "repo_id": "t1" }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .into_iter() + .map(|a| a.cve_id) + .collect(); + ids.sort(); + assert_eq!( + ids, + [ + "CVE-2026-0001", + "CVE-2026-0002", + "CVE-2026-0003", + "CVE-2026-0005" + ] + ); + let alert = db + .cve_alerts() + .find_one(doc! { "cve_id": "CVE-2026-0001" }) + .await + .unwrap() + .unwrap(); + assert_eq!(alert.purl.as_deref(), Some("pkg:generic/busybox@1.35.0")); + assert_eq!(alert.cvss_score, Some(9.8)); + let kept = db + .cve_alerts() + .find_one(doc! { "cve_id": "CVE-2026-0002" }) + .await + .unwrap() + .unwrap(); + assert_eq!(kept.vex.map(|v| v.status), Some(VexStatus::NotAffected)); + + // Notifications for the three new CVEs, none for the `not_affected`. + let notified = |cve: &'static str| { + let db = db.clone(); + async move { + db.cve_notifications() + .count_documents(doc! { "cve_id": cve }) + .await + .unwrap() + } + }; + assert_eq!(notified("CVE-2026-0001").await, 1); + assert_eq!(notified("CVE-2026-0003").await, 1); + assert_eq!(notified("CVE-2026-0005").await, 1); + assert_eq!(notified("CVE-2026-0002").await, 0); + let total = |f: fn(&TenantCounts) -> u32| f(&first.tenants[0].1) + f(&second.tenants[0].1); + assert_eq!(total(|c| c.new_alerts), 3); + assert_eq!(total(|c| c.notified), 3); + assert_eq!(total(|c| c.suppressed_by_vex), 1); + let busybox = db + .sbom_entries() + .find_one(doc! { "name": "busybox" }) + .await + .unwrap() + .unwrap(); + let refs: Vec<&str> = busybox + .known_vulnerabilities + .iter() + .map(|v| v.id.as_str()) + .collect(); + assert_eq!(refs, ["CVE-2026-0001", "CVE-2026-0002"]); + + // Act 3: an hour later the next window starts where this one ended, + // and CVEs read again are not stored or notified twice. + let later = now + TimeDelta::hours(1); + let third = run_pass(&admin, tenants(), &enough, &services, later) + .await + .unwrap(); + let last = seen.lock().unwrap().last().cloned().unwrap(); + assert_eq!(last["lastModStartDate"], "2026-10-09T11:45:00.000Z"); + assert_eq!(last["lastModEndDate"], "2026-10-09T12:45:00.000Z"); + assert_eq!(third.tenants[0].1.new_alerts, 0); + assert_eq!(third.tenants[0].1.notified, 0); + assert_eq!( + db.cve_alerts() + .count_documents(doc! { "cve_id": "CVE-2026-0001" }) + .await + .unwrap(), + 1 + ); + + // Act 4: NVD refuses the next window: nothing counts as read. + let before = load_cursor(&admin).await.unwrap(); + let refused = feed( + &format!("{url}missing"), + Duration::ZERO, + Duration::from_secs(60), + ); + let fourth = run_pass( + &admin, + tenants(), + &refused, + &services, + later + TimeDelta::hours(1), + ) + .await + .unwrap(); + assert_eq!( + fourth.error.as_deref(), + Some("NVD: NVD returned 404 Not Found") + ); + assert_eq!(load_cursor(&admin).await.unwrap(), before); + + db.inner().drop().await.unwrap(); + admin.drop().await.unwrap(); + } + + /// A stand-in for NVD whose pages of more than 250 CVEs exceed the body + /// cap, listing one CVE. + async fn fake_nvd_too_large(listed: serde_json::Value) -> (String, Seen) { + let seen: Seen = Arc::default(); + let log = Arc::clone(&seen); + let oversized = Arc::new(" ".repeat(crate::pipeline::public_http::MAX_BODY_BYTES + 1)); + let app = axum::Router::new().route( + "/", + axum::routing::get( + move |axum::extract::Query(q): axum::extract::Query>| { + let log = Arc::clone(&log); + let oversized = Arc::clone(&oversized); + let listed = listed.clone(); + async move { + let per_page: usize = q["resultsPerPage"].parse().unwrap(); + log.lock().unwrap().push(q); + if per_page > 250 { + return oversized.as_str().to_owned(); + } + serde_json::json!({ + "totalResults": 1, + "vulnerabilities": [listed], + }) + .to_string() + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/", listener.local_addr().unwrap()); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + (url, seen) + } + + #[tokio::test] + async fn an_oversized_page_is_asked_for_again_with_fewer_cves() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "nvdbig_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP nvd_monitor: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id("nvd-monitor").await.unwrap(); + let admin = pool.admin_db(); + db.sbom_entries() + .insert_one(entry("t1", "lwIP", "2.1.2", EMBEDDED_MANAGER)) + .await + .unwrap(); + let (url, seen) = fake_nvd_too_large(vuln( + "CVE-2026-0003", + "cpe:2.3:a:lwip_project:lwip:*:*:*:*:*:*:*:*", + "2.2.0", + )) + .await; + let services = Services { + enricher: None, + issues: None, + }; + let now = at("2026-10-09T12:00:00Z"); + + let report = run_pass( + &admin, + vec![("nvd-monitor".to_string(), db.clone())], + &feed(&url, Duration::ZERO, Duration::from_secs(60)), + &services, + now, + ) + .await + .unwrap(); + + let sizes: Vec = seen + .lock() + .unwrap() + .iter() + .map(|q| q["resultsPerPage"].clone()) + .collect(); + assert_eq!(sizes, ["500", "250"]); + assert_eq!(report.error, None); + assert_eq!(report.tenants[0].1.new_alerts, 1); + let cursor = load_cursor(&admin).await.unwrap().unwrap(); + assert_eq!(cursor.done_until, now - SETTLE); + + db.inner().drop().await.unwrap(); + admin.drop().await.unwrap(); + } +} diff --git a/compliance-agent/src/pipeline/public_http.rs b/compliance-agent/src/pipeline/public_http.rs index 18bda00..f967e7b 100644 --- a/compliance-agent/src/pipeline/public_http.rs +++ b/compliance-agent/src/pipeline/public_http.rs @@ -61,18 +61,27 @@ impl PublicHttp { } } +/// How the error of a body over [`MAX_BODY_BYTES`] begins. +const TOO_LARGE: &str = "response larger than"; + +/// Whether `error` (from [`read_body`] or [`read_json`]) says the body +/// exceeded [`MAX_BODY_BYTES`], so a smaller page could still be read. +pub(crate) fn is_too_large(error: &str) -> bool { + error.starts_with(TOO_LARGE) +} + /// The body of `resp`, refused once it exceeds [`MAX_BODY_BYTES`]. pub(crate) async fn read_body(mut resp: reqwest::Response) -> Result, String> { if resp .content_length() .is_some_and(|n| n > MAX_BODY_BYTES as u64) { - return Err(format!("response larger than {MAX_BODY_BYTES} bytes")); + return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes")); } let mut body = Vec::new(); while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? { if body.len() + chunk.len() > MAX_BODY_BYTES { - return Err(format!("response larger than {MAX_BODY_BYTES} bytes")); + return Err(format!("{TOO_LARGE} {MAX_BODY_BYTES} bytes")); } body.extend_from_slice(&chunk); } diff --git a/compliance-agent/src/pipeline/vex_lifecycle.rs b/compliance-agent/src/pipeline/vex_lifecycle.rs index 74a1df9..48abfa8 100644 --- a/compliance-agent/src/pipeline/vex_lifecycle.rs +++ b/compliance-agent/src/pipeline/vex_lifecycle.rs @@ -162,6 +162,51 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen Ok(()) } +/// Store `alert` as found by the CVE monitor between scans: inserted when +/// the target has no alert for the CVE yet (the scan's key, CVE and target), +/// otherwise only its exploitation is refreshed and, when it has none, given +/// the component's purl (same package and version). Unlike +/// [`upsert_reported`] it leaves the rest alone: the VEX statements a scan +/// made from the target's own data (a recipe's `CVE_STATUS`) and whether the +/// alert is resolved are the scan's to change. +/// +/// # Returns +/// +/// Whether the alert was new. +/// +/// # Errors +/// +/// A database or encoding error. +pub async fn store_monitored(db: &Database, alert: &CveAlert) -> Result { + let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id }; + let mut insert = mongodb::bson::to_document(alert) + .map_err(|e| AgentError::Other(format!("encode CVE alert: {e}")))?; + let exploitation = insert.remove("exploitation"); + let mut update = doc! { "$setOnInsert": insert }; + if let Some(exploitation) = exploitation { + update.insert("$set", doc! { "exploitation": exploitation }); + } + let inserted = db + .cve_alerts() + .update_one(filter.clone(), update) + .upsert(true) + .await? + .upserted_id + .is_some(); + // An alert stored before purls were recorded gets its component's purl + // (only for the same package and version). + if let Some(purl) = &alert.purl { + let mut without_purl = filter; + without_purl.insert("affected_package", &alert.affected_package); + without_purl.insert("affected_version", &alert.affected_version); + without_purl.insert("purl", doc! { "$exists": false }); + db.cve_alerts() + .update_one(without_purl, doc! { "$set": { "purl": purl } }) + .await?; + } + Ok(inserted) +} + /// Set the VEX statements this scan makes on `repo_id`'s alerts (a Yocto /// recipe's CVE_STATUS or `CVE:` patch, see /// [`crate::pipeline::yocto_inventory::vex_statements`]), each as diff --git a/compliance-agent/src/scheduler.rs b/compliance-agent/src/scheduler.rs index 555627b..6100863 100644 --- a/compliance-agent/src/scheduler.rs +++ b/compliance-agent/src/scheduler.rs @@ -54,8 +54,13 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError> tenant_count = tenants.len(), "CVE monitor: tenants resolved" ); - for tenant_id in tenants { - monitor_cves(&agent, &tenant_id).await; + for tenant_id in &tenants { + monitor_cves(&agent, tenant_id).await; + } + // Components only NVD knows (by CPE), incrementally; `NVD_MONITOR=off` + // turns it off. + if crate::pipeline::nvd_monitor::enabled(std::env::var("NVD_MONITOR").ok().as_deref()) { + crate::pipeline::nvd_monitor::run(&agent, &tenants).await; } }) }) @@ -333,32 +338,14 @@ async fn monitor_cves(agent: &ComplianceAgent, tenant_id: &str) { enricher.enrich(&mut alerts, &mut repo_entries).await; } - // Upsert CVE alerts (existing logic); an existing alert's - // exploitation is refreshed. + // New alerts are stored; an existing alert's exploitation is + // refreshed. for alert in &alerts { - let filter = doc! { "cve_id": &alert.cve_id, "repo_id": &alert.repo_id }; - let mut insert = mongodb::bson::to_document(alert).unwrap_or_default(); - let exploitation = insert.remove("exploitation"); - let mut update = doc! { "$setOnInsert": insert }; - if let Some(exploitation) = exploitation { - update.insert("$set", doc! { "exploitation": exploitation }); - } - let _ = db - .cve_alerts() - .update_one(filter.clone(), update) - .upsert(true) - .await; - // An alert stored before purls were recorded gets its - // component's purl (only for the same package and version). - if let Some(purl) = &alert.purl { - let mut without_purl = filter; - without_purl.insert("affected_package", &alert.affected_package); - without_purl.insert("affected_version", &alert.affected_version); - without_purl.insert("purl", doc! { "$exists": false }); - let _ = db - .cve_alerts() - .update_one(without_purl, doc! { "$set": { "purl": purl } }) - .await; + if let Err(e) = crate::pipeline::vex_lifecycle::store_monitored(&db, alert).await { + tracing::warn!( + cve = alert.cve_id, + "CVE monitor: storing the alert failed: {e}" + ); } } diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 29b851f..e71bb8f 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -96,8 +96,27 @@ compared with the version in use. OSV publishes no advisories for CocoaPods, so pods are not matched. Components that could not be matched are listed on the scan run under **CVE-Abgleich unvollständig**. -Known components are re-checked daily, so a CVE published against an unchanged -component still raises an alert. +Known components are re-checked between scans (the CVE monitor, hourly by +default, `CVE_MONITOR_SCHEDULE`), so a CVE published against an unchanged +component still raises an alert: + +- **Components with a package identifier** are asked of OSV again. +- **Components only NVD knows** (Yocto recipes by their CPE, the libraries + found by their headers, the CODESYS runtime) are re-checked incrementally: + NVD is asked which CVEs it published or changed since the last run, and + those are matched against the components with the scan's rules (product, + version range). A few requests a day cover every tenant. The requests are + paced to NVD's rate limit (with the deployment's NVD API key 50 per 30 + seconds, without 5), and a run asks for at most 10 minutes; what it did not + reach, the next run reads, so no change is skipped. The first run reads the + last 7 days. `NVD_MONITOR=off` turns this part off (on by default). + +A match raises the same CVE alert as a scan's, at most one per CVE and +target. A vulnerability that is "Not affected" or "Fixed" (see +[Assessing vulnerabilities](./vex-en.md)) raises no notification, and a +critical or high one of a managed repository gets its tracker issue as after +a scan. The monitor only adds: alerts no longer found are resolved by the next +complete scan. ## Packages Tab diff --git a/docs/guide/yocto.md b/docs/guide/yocto.md index 53feccf..0b183ab 100644 --- a/docs/guide/yocto.md +++ b/docs/guide/yocto.md @@ -140,8 +140,11 @@ without a release version, a failed lookup, and recipes the scan's NVD time budget (10 minutes) did not reach are listed under **CVE-Abgleich unvollständig**. The requests are paced to NVD's rate limit: 50 per 30 seconds with the deployment's NVD API key, 5 without; an answer from the last 6 hours -is reused, so the next scan gets further. The daily CVE re-check covers OSV -only and does not yet re-match recipes in NVD; a scan does. +is reused, so the next scan gets further. Between scans the CVE monitor +re-checks the recipes too (see +[Known vulnerabilities](/guide/sbom#known-vulnerabilities)): a CVE NVD +publishes or changes for a recipe's product raises an alert without a new +scan. **What the recipe says about a CVE becomes its VEX statement**, made by the scan, with the recipe (or patch) and its text as the impact statement, so it is diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 9fc45cc..42ca4d9 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -199,7 +199,7 @@ to the SBOM with the package source `embedded` and matched against NVD by CPE. Prüfwerk matches every SBOM component directly against two public vulnerability sources (no separate scanner binary): - [OSV.dev](https://osv.dev/) -- batch queried by package URL (purl) for ecosystem advisories (npm, PyPI, crates.io, Go, Maven, ...) -- [NVD](https://nvd.nist.gov/) -- queried per CVE for the CVSS v3.1 base score, and by CPE for components outside a package ecosystem: the CODESYS runtime found in PLC projects and the embedded libraries above. All CVEs of the product are fetched and their affected version ranges compared with the version in use. +- [NVD](https://nvd.nist.gov/) -- queried per CVE for the CVSS v3.1 base score, and by CPE for components outside a package ecosystem: the CODESYS runtime found in PLC projects and the embedded libraries above, and the Yocto recipes. All CVEs of the product are fetched and their affected version ranges compared with the version in use. Between scans the CVE monitor asks NVD only for the CVEs changed since its last run (one time-window listing for all tenants, resumed where a run stopped) and matches them against the same components with the same rules. Matches are stored as CVE alerts with CVSS scores and re-checked daily, so newly published CVEs against an unchanged dependency still raise a notification. @@ -400,7 +400,7 @@ Every connection the agent opens, in one place. **Guarded** means: the HTTP clie | Destination | What is sent | Module | Guard | Limits | Switch | |---|---|---|---|---|---| | `api.osv.dev` (`/v1/querybatch`, `/v1/vulns/{id}`) | purls of SBOM components, advisory ids | `pipeline/cve.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB, 8 advisory reads at once | none (CVE stage) | -| `services.nvd.nist.gov` (`/rest/json/cves/2.0`) | CVE ids (CVSS score), CPE product prefixes (CODESYS, embedded libraries) | `pipeline/cve.rs`, `pipeline/nvd_cpe.rs` | guarded | 30 s per request, 5 s connect, body ≤ 16 MiB, 3 retries after 6/12/24 s, answers cached 6 h | `NVD_API_KEY` (optional, raises NVD's rate limit) | +| `services.nvd.nist.gov` (`/rest/json/cves/2.0`) | CVE ids (CVSS score), CPE product prefixes (CODESYS, embedded libraries, Yocto recipes); for the CVE monitor a time window (`lastModStartDate`/`lastModEndDate`, at most 120 days, 500 CVEs per page) | `pipeline/cve.rs`, `pipeline/nvd_cpe.rs`, `pipeline/nvd_monitor.rs` | guarded | 30 s per request, 5 s connect, body ≤ 16 MiB, 3 retries after 6/12/24 s, answers cached 6 h; the monitor paced to 0.6 s (key) / 6 s apart, 10 min per run, resumed by the next run | `NVD_API_KEY` (optional, raises NVD's rate limit); `NVD_MONITOR=off` stops the monitor's NVD pass | | `raw.githubusercontent.com` (`/cisagov/kev-data/develop/known_exploited_vulnerabilities.json`), else `www.cisa.gov` (`/sites/default/files/feeds/known_exploited_vulnerabilities.json`) | nothing (a GET of the public KEV catalog) | `pipeline/cve_enrichment.rs` | guarded | 10 s per request, 5 s connect, body ≤ 16 MiB; at most once a day (cached for all tenants) | `CVE_EXPLOIT_LOOKUP=false` | | `api.first.org` (`/data/v1/epss`) | CVE ids of the alerts | `pipeline/cve_enrichment.rs` | guarded | as above, 50 CVE ids per request, 500 uncached CVEs and 2 min per scan; answers cached a day per source (EPSS and Vulnrichment apart, so one that fails is asked again alone) | `CVE_EXPLOIT_LOOKUP=false` | | `raw.githubusercontent.com` (`/cisagov/vulnrichment/develop/…`) | CVE ids of the alerts (in the path) | `pipeline/cve_enrichment.rs` | guarded | as above, 8 at once | `CVE_EXPLOIT_LOOKUP=false` |