feat(cve): the daily monitor re-checks NVD/CPE-only components incrementally #558
No files matched your search
@@ -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
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<serde_json::Value, String> {
|
||||
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<NvdCv
|
||||
};
|
||||
vulns
|
||||
.iter()
|
||||
.filter_map(|v| {
|
||||
let cve = &v["cve"];
|
||||
let id = cve["id"].as_str()?;
|
||||
let covered = 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())
|
||||
.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()),
|
||||
})
|
||||
})
|
||||
.filter_map(|v| parse_cve(v, marker, version))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One entry of an NVD response's `vulnerabilities`, when a vulnerable CPE
|
||||
/// of it contains `marker` and its range covers `version`.
|
||||
pub(crate) fn parse_cve(v: &serde_json::Value, marker: &str, version: &str) -> Option<NvdCve> {
|
||||
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<Item = &serde_json::Value> {
|
||||
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.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Vec<u8>, 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);
|
||||
}
|
||||
|
||||
@@ -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<bool, AgentError> {
|
||||
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
|
||||
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-2
@@ -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
|
||||
|
||||
|
||||
+5
-2
@@ -139,8 +139,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
|
||||
|
||||
@@ -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` |
|
||||
|
||||
Reference in new issue
Block a user