feat(sbom): CVEs for FreeRTOS, lwIP, Mbed TLS and wolfSSL in firmware trees #351

Merged
sharang merged 1 commits from feat/firmware-cves into main 2026-09-23 15:13:10 +00:00
14 changed files with 928 additions and 217 deletions

No files matched your search

+64 -216
View File
@@ -1,6 +1,15 @@
use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef};
use compliance_core::CoreError;
use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER};
use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct};
/// Every CODESYS product: advisories key off the runtime's version.
const CODESYS: NvdProduct = NvdProduct {
match_string: "cpe:2.3:a:codesys",
marker: ":codesys:",
};
pub struct CveScanner {
http: reqwest::Client,
#[allow(dead_code)]
@@ -218,37 +227,62 @@ impl CveScanner {
let Some((name, version)) = codesys_runtime(entries) else {
return Vec::new();
};
let url = "https://services.nvd.nist.gov/rest/json/cves/2.0\
?virtualMatchString=cpe:2.3:a:codesys";
let mut req = self.http.get(url);
if let Some(key) = &self.nvd_api_key {
req = req.header("apiKey", key.as_str());
}
let body: serde_json::Value = match req.send().await {
Ok(r) if r.status().is_success() => match r.json().await {
Ok(b) => b,
let matched =
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), CODESYS, &version)
.await
{
Ok(matched) => matched,
Err(e) => {
tracing::warn!("CODESYS NVD parse failed: {e}");
tracing::warn!("CODESYS NVD lookup failed: {e}");
return Vec::new();
}
},
Ok(r) => {
tracing::warn!("CODESYS NVD returned {}", r.status());
return Vec::new();
}
Err(e) => {
tracing::warn!("CODESYS NVD request failed: {e}");
return Vec::new();
}
};
};
let alerts = record_nvd(repo_id, entries, &name, &version, matched);
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
alerts
}
let matched = parse_codesys_nvd(&body, &version);
/// Match the libraries found by their headers (FreeRTOS, lwIP, mbedTLS,
/// wolfSSL; see [`embedded_versions`]) against NVD by CPE: copied into a
/// firmware tree, they have no purl OSV could look up. Best-effort per
/// library, as for CODESYS.
pub async fn scan_embedded(&self, repo_id: &str, entries: &mut [SbomEntry]) -> Vec<CveAlert> {
let found: Vec<(String, String, NvdProduct)> = entries
.iter()
.filter(|e| e.package_manager == EMBEDDED_MANAGER)
.filter_map(|e| {
embedded_versions::nvd_product(&e.name)
.map(|p| (e.name.clone(), e.version.clone(), p))
})
.collect();
let mut alerts = Vec::new();
for cve in matched {
if let Some(e) = entries
.iter_mut()
.find(|e| e.name == name && e.version == version)
for (name, version, product) in found {
match nvd_cpe::product_cves(&self.http, self.nvd_api_key.as_deref(), product, &version)
.await
{
Ok(cves) => alerts.extend(record_nvd(repo_id, entries, &name, &version, cves)),
Err(e) => tracing::warn!(library = %name, "NVD lookup failed: {e}"),
}
}
alerts
}
}
/// Attach NVD `cves` to the SBOM entry `name@version` and make an alert for
/// each.
fn record_nvd(
repo_id: &str,
entries: &mut [SbomEntry],
name: &str,
version: &str,
cves: Vec<NvdCve>,
) -> Vec<CveAlert> {
let mut entry = entries
.iter_mut()
.find(|e| e.name == name && e.version == version);
cves.into_iter()
.map(|cve| {
if let Some(e) = entry.as_deref_mut() {
e.known_vulnerabilities.push(VulnRef {
id: cve.id.clone(),
source: "nvd".to_string(),
@@ -259,17 +293,15 @@ impl CveScanner {
let mut alert = CveAlert::new(
cve.id,
repo_id.to_string(),
name.clone(),
version.clone(),
name.to_string(),
version.to_string(),
CveSource::Nvd,
);
alert.summary = cve.summary;
alert.cvss_score = cve.cvss;
alerts.push(alert);
}
tracing::info!(runtime = %name, version = %version, cves = alerts.len(), "CODESYS CVE match");
alerts
}
alert
})
.collect()
}
/// The CODESYS runtime component (name + version) from an SBOM, if present. The
@@ -282,126 +314,6 @@ fn codesys_runtime(entries: &[SbomEntry]) -> Option<(String, String)> {
.map(|e| (e.name.clone(), e.version.clone()))
}
/// A parsed NVD CVE that affects the CODESYS runtime.
struct CodesysCve {
id: String,
summary: Option<String>,
cvss: Option<f64>,
}
/// Version constraints from an NVD `cpeMatch` node.
#[derive(Default)]
struct CpeRange {
exact: Option<String>,
start_incl: Option<String>,
start_excl: Option<String>,
end_incl: Option<String>,
end_excl: Option<String>,
}
/// Parse an NVD CVE-list response and keep the CVEs whose CODESYS CPE match covers
/// `runtime_version`.
fn parse_codesys_nvd(body: &serde_json::Value, runtime_version: &str) -> Vec<CodesysCve> {
let mut out = Vec::new();
let Some(vulns) = body["vulnerabilities"].as_array() else {
return out;
};
for v in vulns {
let cve = &v["cve"];
let Some(id) = cve["id"].as_str() else {
continue;
};
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(":codesys:"))
&& version_matches(runtime_version, &cpe_range(cm))
});
if covered {
let 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);
let cvss = cve["metrics"]["cvssMetricV31"]
.as_array()
.and_then(|m| m.first())
.and_then(|m| m["cvssData"]["baseScore"].as_f64());
out.push(CodesysCve {
id: id.to_string(),
summary,
cvss,
});
}
}
out
}
/// Build a [`CpeRange`] from an NVD `cpeMatch` object.
fn cpe_range(cm: &serde_json::Value) -> CpeRange {
let exact = cm["criteria"]
.as_str()
.and_then(cpe_version)
.filter(|v| v != "*" && v != "-" && !v.is_empty());
CpeRange {
exact,
start_incl: cm["versionStartIncluding"].as_str().map(String::from),
start_excl: cm["versionStartExcluding"].as_str().map(String::from),
end_incl: cm["versionEndIncluding"].as_str().map(String::from),
end_excl: cm["versionEndExcluding"].as_str().map(String::from),
}
}
/// The version field (6th component) of a CPE 2.3 string.
fn cpe_version(criteria: &str) -> Option<String> {
criteria.split(':').nth(5).map(String::from)
}
/// Whether `v` satisfies a CPE version range.
fn version_matches(v: &str, r: &CpeRange) -> bool {
use std::cmp::Ordering::{Equal, Greater, Less};
if let Some(exact) = &r.exact {
return cmp_dotted(v, exact) == Equal;
}
let mut ok = true;
if let Some(s) = &r.start_incl {
ok &= cmp_dotted(v, s) != Less;
}
if let Some(s) = &r.start_excl {
ok &= cmp_dotted(v, s) == Greater;
}
if let Some(e) = &r.end_incl {
ok &= cmp_dotted(v, e) != Greater;
}
if let Some(e) = &r.end_excl {
ok &= cmp_dotted(v, e) == Less;
}
ok
}
/// Compare two dotted numeric versions (`4.17.0.0` vs `4.9.0.0`); missing
/// components count as 0, non-numeric components as 0.
fn cmp_dotted(a: &str, b: &str) -> std::cmp::Ordering {
let pa: Vec<u64> = a.split('.').map(|x| x.parse().unwrap_or(0)).collect();
let pb: Vec<u64> = b.split('.').map(|x| x.parse().unwrap_or(0)).collect();
for i in 0..pa.len().max(pb.len()) {
let x = pa.get(i).copied().unwrap_or(0);
let y = pb.get(i).copied().unwrap_or(0);
match x.cmp(&y) {
std::cmp::Ordering::Equal => continue,
other => return other,
}
}
std::cmp::Ordering::Equal
}
#[derive(serde::Deserialize)]
struct OsvBatchResponse {
results: Vec<OsvBatchResult>,
@@ -428,7 +340,6 @@ struct OsvVuln {
#[cfg(test)]
mod tests {
use super::*;
use std::cmp::Ordering::{Equal, Greater, Less};
fn entry(name: &str, ver: &str, pm: &str) -> SbomEntry {
SbomEntry::new("t".into(), name.into(), ver.into(), pm.into())
@@ -447,67 +358,4 @@ mod tests {
// Internal library components are not the runtime.
assert!(codesys_runtime(&[entry("Util", "3.5.21.0", "codesys")]).is_none());
}
#[test]
fn dotted_version_comparison() {
assert_eq!(cmp_dotted("4.17.0.0", "4.9.0.0"), Greater);
assert_eq!(cmp_dotted("4.9.0.0", "4.17.0.0"), Less);
assert_eq!(cmp_dotted("3.5.18.0", "3.5.18.0"), Equal);
assert_eq!(cmp_dotted("4.2", "4.2.0.0"), Equal); // missing components = 0
}
#[test]
fn version_range_matching() {
let end_excl = CpeRange {
end_excl: Some("4.9.0.0".into()),
..Default::default()
};
assert!(!version_matches("4.17.0.0", &end_excl)); // patched
assert!(version_matches("4.5.0.0", &end_excl)); // affected
let exact = CpeRange {
exact: Some("3.5.16.0".into()),
..Default::default()
};
assert!(version_matches("3.5.16.0", &exact));
assert!(!version_matches("3.5.17.0", &exact));
let span = CpeRange {
start_incl: Some("3.0.0.0".into()),
end_incl: Some("3.5.16.0".into()),
..Default::default()
};
assert!(version_matches("3.5.16.0", &span));
assert!(!version_matches("3.5.17.0", &span));
}
#[test]
fn parses_nvd_and_matches_by_runtime_version() {
// Two CODESYS CVEs: one affects < 4.9 (our 4.17 is patched), one affects
// <= 4.20 (our 4.17 is affected). Only the latter should match.
let body = serde_json::json!({
"vulnerabilities": [
{"cve": {"id":"CVE-2023-0001",
"descriptions":[{"lang":"en","value":"old CmpBlkDrvTcp bug"}],
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":7.5}}]},
"configurations":[{"nodes":[{"cpeMatch":[
{"vulnerable":true,
"criteria":"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
"versionEndExcluding":"4.9.0.0"}
]}]}]}},
{"cve": {"id":"CVE-2024-0002",
"descriptions":[{"lang":"en","value":"recent runtime bug"}],
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":9.8}}]},
"configurations":[{"nodes":[{"cpeMatch":[
{"vulnerable":true,
"criteria":"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
"versionEndIncluding":"4.20.0.0"}
]}]}]}}
]
});
let matched = parse_codesys_nvd(&body, "4.17.0.0");
let ids: Vec<&str> = matched.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, vec!["CVE-2024-0002"]);
assert_eq!(matched[0].cvss, Some(9.8));
}
}
@@ -0,0 +1,288 @@
//! Embedded libraries copied into a firmware tree, and their versions.
//!
//! Microcontroller projects vendor their RTOS, TCP/IP stack and TLS library as
//! source: no manifest names them, so no package SBOM sees them, yet they are
//! where the published CVEs are. Each one states its version in a header, and
//! that is where it is read from. The entries are matched against NVD by CPE
//! (see [`crate::pipeline::nvd_cpe`]).
use std::path::Path;
use compliance_core::models::SbomEntry;
use crate::pipeline::nvd_cpe::NvdProduct;
/// The `package_manager` of entries found here.
pub const EMBEDDED_MANAGER: &str = "embedded";
/// Headers larger than this are not a version header.
const MAX_HEADER_BYTES: u64 = 512 * 1024;
/// A library recognised by one of its headers.
struct Library {
/// The name the SBOM shows.
name: &'static str,
/// The header that states the version, and the directory it sits in.
header: &'static str,
parent: Option<&'static str>,
/// Reads the version from the header's text.
read: fn(&str) -> Option<String>,
license: &'static str,
product: NvdProduct,
}
const LIBRARIES: [Library; 5] = [
Library {
name: "FreeRTOS",
header: "task.h",
parent: None,
read: freertos_version,
license: "MIT",
product: NvdProduct {
match_string: "cpe:2.3:*:amazon:freertos",
marker: ":amazon:freertos:",
},
},
Library {
name: "lwIP",
header: "init.h",
parent: Some("lwip"),
read: lwip_version,
license: "BSD-3-Clause",
product: NvdProduct {
match_string: "cpe:2.3:*:lwip_project:lwip",
marker: ":lwip_project:lwip:",
},
},
// Mbed TLS 3.x states it in build_info.h, 2.x in version.h.
Library {
name: "Mbed TLS",
header: "build_info.h",
parent: Some("mbedtls"),
read: mbedtls_version,
license: "Apache-2.0",
product: MBEDTLS,
},
Library {
name: "Mbed TLS",
header: "version.h",
parent: Some("mbedtls"),
read: mbedtls_version,
license: "Apache-2.0",
product: MBEDTLS,
},
Library {
name: "wolfSSL",
header: "version.h",
parent: Some("wolfssl"),
read: wolfssl_version,
license: "GPL-2.0-or-later",
product: NvdProduct {
match_string: "cpe:2.3:*:wolfssl:wolfssl",
marker: ":wolfssl:wolfssl:",
},
},
];
const MBEDTLS: NvdProduct = NvdProduct {
match_string: "cpe:2.3:*:arm:mbed_tls",
marker: ":arm:mbed_tls:",
};
/// The NVD product of a library found here, by its SBOM name.
pub fn nvd_product(name: &str) -> Option<NvdProduct> {
LIBRARIES.iter().find(|l| l.name == name).map(|l| l.product)
}
/// Every known library under `root`, one entry per library and version.
/// Walks the whole tree, vendor directories included: that is where these
/// libraries live. Blocking; call it from `spawn_blocking`.
pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let mut found: Vec<(&'static Library, String)> = Vec::new();
let mut walker = walkdir::WalkDir::new(root).into_iter();
while let Some(entry) = walker.next() {
// An unreadable entry is skipped; it must not end the walk.
let Ok(entry) = entry else {
continue;
};
if entry.file_type().is_dir() {
if entry.file_name() == ".git" {
walker.skip_current_dir();
}
continue;
}
let file_name = entry.file_name().to_string_lossy();
let parent = entry
.path()
.parent()
.and_then(Path::file_name)
.map(|p| p.to_string_lossy().to_ascii_lowercase());
for library in LIBRARIES.iter().filter(|l| {
l.header == file_name && l.parent.is_none_or(|p| parent.as_deref() == Some(p))
}) {
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
let Some(text) = small
.then(|| std::fs::read_to_string(entry.path()).ok())
.flatten()
else {
continue;
};
if let Some(version) = (library.read)(&text) {
if !found
.iter()
.any(|(l, v)| l.name == library.name && *v == version)
{
found.push((library, version));
}
}
}
}
found
.into_iter()
.map(|(library, version)| {
let mut entry = SbomEntry::new(
repo_id.to_string(),
library.name.to_string(),
version,
EMBEDDED_MANAGER.to_string(),
);
entry.license = Some(library.license.to_string());
entry
})
.collect()
}
/// The value of `#define NAME value` in `text`, quotes and a trailing `U`
/// removed.
fn define(text: &str, name: &str) -> Option<String> {
text.lines().find_map(|line| {
let rest = line.trim_start().strip_prefix("#define")?.trim_start();
let value = rest.strip_prefix(name)?;
// `NAME_SUFFIX` is another macro, not this one.
if !value.starts_with(char::is_whitespace) {
return None;
}
let value = value.split("/*").next()?.split("//").next()?.trim();
let value = value.trim_matches('"').trim_end_matches(['U', 'u']).trim();
(!value.is_empty()).then(|| value.to_string())
})
}
/// A plain dotted version (`10.4.6`), nothing else.
fn dotted(version: &str) -> Option<String> {
let ok = !version.is_empty()
&& version
.split('.')
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
ok.then(|| version.to_string())
}
/// `#define tskKERNEL_VERSION_NUMBER "V10.4.6"`.
fn freertos_version(text: &str) -> Option<String> {
let raw = define(text, "tskKERNEL_VERSION_NUMBER")?;
dotted(raw.trim_start_matches(['V', 'v']))
}
/// `LWIP_VERSION_MAJOR`, `_MINOR` and `_REVISION`.
fn lwip_version(text: &str) -> Option<String> {
let part = |name| define(text, name).and_then(|v| dotted(&v));
dotted(&format!(
"{}.{}.{}",
part("LWIP_VERSION_MAJOR")?,
part("LWIP_VERSION_MINOR")?,
part("LWIP_VERSION_REVISION")?
))
}
/// `#define MBEDTLS_VERSION_STRING "3.4.0"`.
fn mbedtls_version(text: &str) -> Option<String> {
dotted(&define(text, "MBEDTLS_VERSION_STRING")?)
}
/// `#define LIBWOLFSSL_VERSION_STRING "5.6.3"`.
fn wolfssl_version(text: &str) -> Option<String> {
dotted(&define(text, "LIBWOLFSSL_VERSION_STRING")?)
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn versions_are_read_from_each_header() {
assert_eq!(
freertos_version("#define tskKERNEL_VERSION_NUMBER \"V10.4.6\"\n").as_deref(),
Some("10.4.6")
);
let lwip = "#define LWIP_VERSION_MAJOR 2\n#define LWIP_VERSION_MINOR 1\n\
#define LWIP_VERSION_REVISION 3U /* comment */\n#define LWIP_VERSION_RC 255\n";
assert_eq!(lwip_version(lwip).as_deref(), Some("2.1.3"));
assert_eq!(
mbedtls_version("#define MBEDTLS_VERSION_STRING \"2.28.1\"").as_deref(),
Some("2.28.1")
);
assert_eq!(
wolfssl_version("#define LIBWOLFSSL_VERSION_STRING \"5.6.3\"").as_deref(),
Some("5.6.3")
);
}
#[test]
fn a_similar_macro_or_a_placeholder_is_not_a_version() {
// `..._NUMBER_X` is another macro; a template value is no version.
assert_eq!(
freertos_version("#define tskKERNEL_VERSION_NUMBER_X \"V1.0\""),
None
);
assert_eq!(
freertos_version("#define tskKERNEL_VERSION_NUMBER \"V@VERSION@\""),
None
);
assert_eq!(lwip_version("#define LWIP_VERSION_MAJOR 2"), None);
}
#[test]
fn libraries_are_found_where_projects_keep_them() {
let root = std::env::temp_dir().join(format!("cs-embedded-{}", uuid::Uuid::new_v4()));
let write = |rel: &str, text: &str| {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
std::fs::write(path, text).expect("write");
};
write(
"Middlewares/Third_Party/FreeRTOS/Source/include/task.h",
"#define tskKERNEL_VERSION_NUMBER \"V10.3.1\"\n",
);
write(
"Middlewares/Third_Party/LwIP/src/include/lwip/init.h",
"#define LWIP_VERSION_MAJOR 2\n#define LWIP_VERSION_MINOR 1\n#define LWIP_VERSION_REVISION 2\n",
);
write(
"lib/mbedtls/include/mbedtls/build_info.h",
"#define MBEDTLS_VERSION_STRING \"3.4.0\"\n",
);
// An unrelated `init.h` and a second copy of the same FreeRTOS.
write("Core/Inc/init.h", "#define LWIP_VERSION_MAJOR 9\n");
write(
"backup/task.h",
"#define tskKERNEL_VERSION_NUMBER \"V10.3.1\"\n",
);
let mut found: Vec<(String, String)> = detect(&root, "t")
.into_iter()
.map(|e| (e.name, e.version))
.collect();
found.sort();
assert_eq!(
found,
[
("FreeRTOS".to_string(), "10.3.1".to_string()),
("Mbed TLS".to_string(), "3.4.0".to_string()),
("lwIP".to_string(), "2.1.2".to_string()),
]
);
assert!(nvd_product("Mbed TLS").is_some());
std::fs::remove_dir_all(&root).ok();
}
}
+2
View File
@@ -2,6 +2,7 @@ pub mod code_review;
pub mod cppcheck;
pub mod cve;
pub mod dedup;
pub mod embedded_versions;
pub mod firmware_sbom;
pub mod git;
pub mod git_submodules;
@@ -9,6 +10,7 @@ pub mod gitleaks;
mod graph_build;
mod issue_creation;
pub mod lint;
pub mod nvd_cpe;
pub mod orchestrator;
pub mod patterns;
pub mod plan;
+266
View File
@@ -0,0 +1,266 @@
//! Known vulnerabilities of a product that is not in a package ecosystem.
//!
//! A CODESYS runtime, FreeRTOS or mbedTLS copied into a firmware tree has no
//! purl OSV could look up. NVD indexes their CVEs by CPE, with the affected
//! versions as ranges. So every CVE of the product is fetched once, and the
//! ranges are matched here against the version in use.
/// A product as NVD names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NvdProduct {
/// The CPE prefix NVD is asked for. `cpe:2.3:*:amazon:freertos` covers
/// both parts NVD files FreeRTOS under: `a` (its TCP/IP stack) and `o`
/// (the kernel).
pub match_string: &'static str,
/// What a vulnerable CPE's criteria must contain to count
/// (`:amazon:freertos:`), so a CVE listing several products only matches
/// through this one.
pub marker: &'static str,
}
/// A CVE that affects the version in use.
#[derive(Debug, Clone, PartialEq)]
pub struct NvdCve {
pub id: String,
pub summary: Option<String>,
pub cvss: Option<f64>,
}
/// The CVEs of `product` whose affected range covers `version`.
///
/// # Errors
///
/// Why NVD could not be asked (network, status, body), for the log.
pub async fn product_cves(
http: &reqwest::Client,
api_key: Option<&str>,
product: NvdProduct,
version: &str,
) -> Result<Vec<NvdCve>, String> {
let mut req = http
.get("https://services.nvd.nist.gov/rest/json/cves/2.0")
.query(&[("virtualMatchString", product.match_string)]);
if let Some(key) = api_key {
req = req.header("apiKey", key);
}
let resp = req.send().await.map_err(|e| e.to_string())?;
if !resp.status().is_success() {
return Err(format!("NVD returned {}", resp.status()));
}
let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
Ok(parse(&body, product.marker, version))
}
/// The CVEs in an NVD response with a vulnerable CPE containing `marker`
/// whose range covers `version`.
pub fn parse(body: &serde_json::Value, marker: &str, version: &str) -> Vec<NvdCve> {
let Some(vulns) = body["vulnerabilities"].as_array() else {
return Vec::new();
};
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()),
})
})
.collect()
}
/// Version constraints from an NVD `cpeMatch` node.
#[derive(Default)]
struct CpeRange {
exact: Option<String>,
start_incl: Option<String>,
start_excl: Option<String>,
end_incl: Option<String>,
end_excl: Option<String>,
}
/// Build a [`CpeRange`] from an NVD `cpeMatch` object.
fn cpe_range(cm: &serde_json::Value) -> CpeRange {
let exact = cm["criteria"]
.as_str()
.and_then(cpe_version)
.filter(|v| v != "*" && v != "-" && !v.is_empty());
CpeRange {
exact,
start_incl: cm["versionStartIncluding"].as_str().map(String::from),
start_excl: cm["versionStartExcluding"].as_str().map(String::from),
end_incl: cm["versionEndIncluding"].as_str().map(String::from),
end_excl: cm["versionEndExcluding"].as_str().map(String::from),
}
}
/// The version field (6th component) of a CPE 2.3 string.
fn cpe_version(criteria: &str) -> Option<String> {
criteria.split(':').nth(5).map(String::from)
}
/// Whether `v` satisfies a CPE version range.
fn version_matches(v: &str, r: &CpeRange) -> bool {
use std::cmp::Ordering::{Equal, Greater, Less};
if let Some(exact) = &r.exact {
return cmp_dotted(v, exact) == Equal;
}
let mut ok = true;
if let Some(s) = &r.start_incl {
ok &= cmp_dotted(v, s) != Less;
}
if let Some(s) = &r.start_excl {
ok &= cmp_dotted(v, s) == Greater;
}
if let Some(e) = &r.end_incl {
ok &= cmp_dotted(v, e) != Greater;
}
if let Some(e) = &r.end_excl {
ok &= cmp_dotted(v, e) == Less;
}
ok
}
/// Compare two dotted numeric versions (`4.17.0.0` vs `4.9.0.0`); missing
/// components count as 0, non-numeric components as 0.
fn cmp_dotted(a: &str, b: &str) -> std::cmp::Ordering {
let pa: Vec<u64> = a.split('.').map(|x| x.parse().unwrap_or(0)).collect();
let pb: Vec<u64> = b.split('.').map(|x| x.parse().unwrap_or(0)).collect();
for i in 0..pa.len().max(pb.len()) {
let x = pa.get(i).copied().unwrap_or(0);
let y = pb.get(i).copied().unwrap_or(0);
match x.cmp(&y) {
std::cmp::Ordering::Equal => continue,
other => return other,
}
}
std::cmp::Ordering::Equal
}
#[cfg(test)]
mod tests {
use super::*;
use std::cmp::Ordering::{Equal, Greater, Less};
#[test]
fn dotted_version_comparison() {
assert_eq!(cmp_dotted("4.17.0.0", "4.9.0.0"), Greater);
assert_eq!(cmp_dotted("4.9.0.0", "4.17.0.0"), Less);
assert_eq!(cmp_dotted("3.5.18.0", "3.5.18.0"), Equal);
assert_eq!(cmp_dotted("4.2", "4.2.0.0"), Equal); // missing components = 0
}
#[test]
fn version_range_matching() {
let end_excl = CpeRange {
end_excl: Some("4.9.0.0".into()),
..Default::default()
};
assert!(!version_matches("4.17.0.0", &end_excl)); // patched
assert!(version_matches("4.5.0.0", &end_excl)); // affected
let exact = CpeRange {
exact: Some("3.5.16.0".into()),
..Default::default()
};
assert!(version_matches("3.5.16.0", &exact));
assert!(!version_matches("3.5.17.0", &exact));
let span = CpeRange {
start_incl: Some("3.0.0.0".into()),
end_incl: Some("3.5.16.0".into()),
..Default::default()
};
assert!(version_matches("3.5.16.0", &span));
assert!(!version_matches("3.5.17.0", &span));
}
/// An NVD response with one CVE fixed before `fixed_below` and one that
/// still affects everything up to `affected_up_to`.
fn two_cves(criteria: &str, fixed_below: &str, affected_up_to: &str) -> serde_json::Value {
serde_json::json!({
"vulnerabilities": [
{"cve": {"id":"CVE-2023-0001",
"descriptions":[{"lang":"en","value":"old bug"}],
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":7.5}}]},
"configurations":[{"nodes":[{"cpeMatch":[
{"vulnerable":true, "criteria": criteria, "versionEndExcluding": fixed_below}
]}]}]}},
{"cve": {"id":"CVE-2024-0002",
"descriptions":[{"lang":"en","value":"recent bug"}],
"metrics":{"cvssMetricV31":[{"cvssData":{"baseScore":9.8}}]},
"configurations":[{"nodes":[{"cpeMatch":[
{"vulnerable":true, "criteria": criteria, "versionEndIncluding": affected_up_to}
]}]}]}}
]
})
}
#[test]
fn only_cves_covering_the_version_match() {
let body = two_cves(
"cpe:2.3:a:codesys:control_for_linux_sl:*:*:*:*:*:*:*:*",
"4.9.0.0",
"4.20.0.0",
);
let matched = parse(&body, ":codesys:", "4.17.0.0");
let ids: Vec<&str> = matched.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, vec!["CVE-2024-0002"]);
assert_eq!(matched[0].cvss, Some(9.8));
}
#[test]
fn a_cve_of_another_product_does_not_match() {
let body = two_cves(
"cpe:2.3:a:amazon:freertos:*:*:*:*:*:*:*:*",
"10.4.3",
"10.6.0",
);
assert_eq!(parse(&body, ":amazon:freertos:", "10.4.1").len(), 2);
assert!(parse(&body, ":arm:mbed_tls:", "10.4.1").is_empty());
}
/// A real NVD excerpt: the 2018 TCP/IP stack CVEs (up to 10.0.1, filed
/// under the application CPE) and two kernel CVEs (filed under the
/// operating-system CPE), fixed in 10.4.3 and 10.6.2.
#[test]
fn real_freertos_ranges_match_by_version() {
let body: serde_json::Value =
serde_json::from_str(include_str!("testdata/nvd_freertos.json")).unwrap_or_default();
let ids = |version: &str| -> Vec<String> {
let mut ids: Vec<String> = parse(&body, ":amazon:freertos:", version)
.into_iter()
.map(|c| c.id)
.collect();
ids.sort();
ids
};
assert_eq!(
ids("10.0.1"),
["CVE-2018-16523", "CVE-2021-31571", "CVE-2024-28115"]
);
assert_eq!(ids("10.3.1"), ["CVE-2021-31571", "CVE-2024-28115"]);
assert_eq!(ids("10.5.1"), ["CVE-2024-28115"]);
assert!(ids("10.6.2").is_empty());
}
}
+29 -1
View File
@@ -216,6 +216,24 @@ impl PipelineOrchestrator {
.await;
}
// Libraries copied into a firmware tree (an RTOS, a TCP/IP stack, a TLS
// library) have no manifest; their headers say which version they are.
let tree = repo_path.clone();
let tree_repo_id = repo_id.clone();
let embedded = tokio::task::spawn_blocking(move || {
crate::pipeline::embedded_versions::detect(&tree, &tree_repo_id)
})
.await
.unwrap_or_default();
for entry in embedded {
let known = sbom_entries
.iter()
.any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version);
if !known {
sbom_entries.push(entry);
}
}
// Stage 3: CVE Scanning
tracing::info!("[{repo_id}] Stage 3: CVE Scanning");
self.update_phase(scan_run_id, ScanPhase::CveScanning).await;
@@ -227,7 +245,7 @@ impl PipelineOrchestrator {
k.expose_secret().to_string()
}),
);
let cve_alerts = match tokio::time::timeout(
let mut cve_alerts = match tokio::time::timeout(
std::time::Duration::from_secs(600),
async {
cve_scanner
@@ -248,6 +266,16 @@ impl PipelineOrchestrator {
Vec::new()
}
};
// OSV has no ecosystem for them: match the embedded libraries in NVD.
match tokio::time::timeout(
std::time::Duration::from_secs(120),
cve_scanner.scan_embedded(&repo_id, &mut sbom_entries),
)
.await
{
Ok(alerts) => cve_alerts.extend(alerts),
Err(_) => tracing::warn!("[{repo_id}] embedded-library CVE match timed out"),
}
// Stage 4: Pattern Scanning (GDPR + OAuth)
tracing::info!("[{repo_id}] Stage 4: Pattern Scanning");
+167
View File
@@ -0,0 +1,167 @@
{
"_source": "NVD CVE API 2.0, virtualMatchString=cpe:2.3:*:amazon:freertos, fetched 2026-09-23; trimmed to three CVEs",
"vulnerabilities": [
{
"cve": {
"id": "CVE-2018-16523",
"descriptions": [
{
"lang": "en",
"value": "Amazon Web Services (AWS) FreeRTOS through 1.3.1, FreeRTOS up to V10.0.1 (with FreeRTOS+TCP), and WITTENSTEIN WHIS Connect middleware TCP/IP component allow division by zero in prvCheckOptions."
}
],
"metrics": {},
"configurations": [
{
"nodes": [
{
"operator": "OR",
"negate": false,
"cpeMatch": [
{
"vulnerable": true,
"criteria": "cpe:2.3:a:amazon:amazon_web_services_freertos:*:*:*:*:*:*:*:*",
"versionEndIncluding": "1.3.1",
"matchCriteriaId": "7EADBC4B-05C5-4588-B0D8-DDAF318DFEB1"
},
{
"vulnerable": true,
"criteria": "cpe:2.3:a:amazon:freertos:*:*:*:*:*:*:*:*",
"versionEndIncluding": "10.0.1",
"matchCriteriaId": "8A645BC4-5A25-47D4-BBA3-BA199C48FE3C"
}
]
}
]
}
]
}
},
{
"cve": {
"id": "CVE-2021-31571",
"descriptions": [
{
"lang": "en",
"value": "The kernel in Amazon Web Services FreeRTOS before 10.4.3 has an integer overflow in queue.c for queue creation."
}
],
"metrics": {
"cvssMetricV31": [
{
"source": "nvd@nist.gov",
"type": "Primary",
"cvssData": {
"version": "3.1",
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"baseScore": 9.8,
"baseSeverity": "CRITICAL",
"attackVector": "NETWORK",
"attackComplexity": "LOW",
"privilegesRequired": "NONE",
"userInteraction": "NONE",
"scope": "UNCHANGED",
"confidentialityImpact": "HIGH",
"integrityImpact": "HIGH",
"availabilityImpact": "HIGH"
},
"exploitabilityScore": 3.9,
"impactScore": 5.9
}
]
},
"configurations": [
{
"nodes": [
{
"operator": "OR",
"negate": false,
"cpeMatch": [
{
"vulnerable": true,
"criteria": "cpe:2.3:o:amazon:freertos:*:*:*:*:*:*:*:*",
"versionEndExcluding": "10.4.3",
"matchCriteriaId": "6F5312AF-71BB-4289-BAB4-CE5931098CCD"
}
]
}
]
}
]
}
},
{
"cve": {
"id": "CVE-2024-28115",
"descriptions": [
{
"lang": "en",
"value": "FreeRTOS is a real-time operating system for microcontrollers. FreeRTOS Kernel versions through 10.6.1 do not sufficiently protect against local privilege escalation via Return Oriented Programming techniques should a vulnerability exist that allows code injection and execution. These issues affect ARMv7-M MPU ports, and ARMv8-M ports with Memory Protected Unit (MPU) support enabled (i.e. `configENABLE_MPU` set to 1). These issues are fixed in version 10.6.2 with a new MPU wrapper. "
}
],
"metrics": {
"cvssMetricV31": [
{
"source": "security-advisories@github.com",
"type": "Secondary",
"cvssData": {
"version": "3.1",
"vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H",
"baseScore": 8.8,
"baseSeverity": "HIGH",
"attackVector": "LOCAL",
"attackComplexity": "LOW",
"privilegesRequired": "LOW",
"userInteraction": "NONE",
"scope": "CHANGED",
"confidentialityImpact": "HIGH",
"integrityImpact": "HIGH",
"availabilityImpact": "HIGH"
},
"exploitabilityScore": 2.0,
"impactScore": 6.0
},
{
"source": "nvd@nist.gov",
"type": "Primary",
"cvssData": {
"version": "3.1",
"vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H",
"baseScore": 7.8,
"baseSeverity": "HIGH",
"attackVector": "LOCAL",
"attackComplexity": "LOW",
"privilegesRequired": "LOW",
"userInteraction": "NONE",
"scope": "UNCHANGED",
"confidentialityImpact": "HIGH",
"integrityImpact": "HIGH",
"availabilityImpact": "HIGH"
},
"exploitabilityScore": 1.8,
"impactScore": 5.9
}
]
},
"configurations": [
{
"nodes": [
{
"operator": "OR",
"negate": false,
"cpeMatch": [
{
"vulnerable": true,
"criteria": "cpe:2.3:o:amazon:freertos:*:*:*:*:*:*:*:*",
"versionEndExcluding": "10.6.2",
"matchCriteriaId": "5BA95DB2-A48A-46A8-B589-F17236ECB4AC"
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,66 @@
{
"scan_status": "completed",
"skipped_stages": [
"sast_vendor_code"
],
"sbom": [
"embedded:FreeRTOS@10.3.1",
"embedded:Mbed TLS@2.16.2",
"embedded:lwIP@2.1.2",
"library:FreeRTOS@",
"toolchain:arm-none-eabi-gcc@"
],
"findings": [],
"cves": [
"CVE-2019-16910",
"CVE-2019-18222",
"CVE-2020-10941",
"CVE-2020-16150",
"CVE-2020-22283",
"CVE-2020-22284",
"CVE-2020-36421",
"CVE-2020-36422",
"CVE-2020-36423",
"CVE-2020-36424",
"CVE-2020-36425",
"CVE-2020-36426",
"CVE-2020-36475",
"CVE-2020-36476",
"CVE-2020-36477",
"CVE-2020-36478",
"CVE-2021-24119",
"CVE-2021-31571",
"CVE-2021-31572",
"CVE-2021-32020",
"CVE-2021-36647",
"CVE-2021-43666",
"CVE-2021-43997",
"CVE-2021-44732",
"CVE-2021-45451",
"CVE-2022-35409",
"CVE-2022-46392",
"CVE-2022-46393",
"CVE-2023-43615",
"CVE-2023-52353",
"CVE-2024-23170",
"CVE-2024-23775",
"CVE-2024-28115",
"CVE-2024-28960",
"CVE-2025-27809",
"CVE-2025-27810",
"CVE-2025-47917",
"CVE-2025-48965",
"CVE-2025-52496",
"CVE-2025-52497",
"CVE-2025-54764",
"CVE-2025-59438",
"CVE-2025-66442",
"CVE-2026-34871",
"CVE-2026-34872",
"CVE-2026-77234",
"CVE-2026-77235",
"CVE-2026-77236",
"CVE-2026-77237"
],
"registry_rules": []
}
+1
View File
@@ -18,6 +18,7 @@ SBOM reads as declared dependencies (#317):
| `freertos-cmake` | (ours) | CMake pulling the FreeRTOS kernel with `FetchContent` at a pinned tag |
| `freertos-lostbuild` | `lostbuild` | source archaeology: no build system, FreeRTOS found from its headers |
| `c-sensor-node` | (ours) | Make; C/C++ SAST (#334): planted flaws in `Core/`, a vendored HAL in `Drivers/` that must not be reported |
| `embedded-libs` | (ours) | Make; FreeRTOS 10.3.1, lwIP 2.1.2 and Mbed TLS 2.16.2 vendored as source: versions read from their headers, CVEs matched in NVD by CPE. The headers hold only the version defines |
| `yocto-layer` | (ours) | none: Yocto is not analysed yet, so the scan must record it |
`make` is also onboarded as a backend service (`fw-make-onboarded-as-service`):
@@ -0,0 +1,8 @@
/* Gateway firmware: FreeRTOS, lwIP and Mbed TLS vendored as source. */
#include "FreeRTOS.h"
int main(void)
{
for (;;) {
}
}
@@ -0,0 +1,7 @@
TARGET = gateway
CC = arm-none-eabi-gcc
CFLAGS = -mcpu=cortex-m4 -mthumb -ICore/Inc -IMiddlewares/Third_Party/FreeRTOS/Source/include
SRCS = Core/Src/main.c
$(TARGET).elf: $(SRCS)
$(CC) $(CFLAGS) -o $@ $^
@@ -0,0 +1,5 @@
/* Version header only; stands in for the FreeRTOS kernel's task.h. */
#define tskKERNEL_VERSION_NUMBER "V10.3.1"
#define tskKERNEL_VERSION_MAJOR 10
#define tskKERNEL_VERSION_MINOR 3
#define tskKERNEL_VERSION_BUILD 1
@@ -0,0 +1,5 @@
/* Version header only; stands in for lwIP's lwip/init.h. */
#define LWIP_VERSION_MAJOR 2
#define LWIP_VERSION_MINOR 1
#define LWIP_VERSION_REVISION 2
#define LWIP_VERSION_RC LWIP_RC_RELEASE
@@ -0,0 +1,5 @@
/* Version header only; stands in for Mbed TLS 2.x's mbedtls/version.h. */
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 16
#define MBEDTLS_VERSION_PATCH 2
#define MBEDTLS_VERSION_STRING "2.16.2"
+15
View File
@@ -246,6 +246,21 @@
]
}
},
{
"key": "fw-embedded-libs",
"name": "Firmware · vendored FreeRTOS, lwIP, Mbed TLS",
"target_type": "firmware_rtos",
"description": "STM32Cube-style tree whose RTOS, TCP/IP stack and TLS library are copied in as source: their versions come from their headers, and their CVEs from NVD by CPE.",
"artifacts": [
{
"kind": "source_archive",
"upload": "fixtures/nightly/firmware/embedded-libs"
}
],
"expect": {
"min_sbom_components": 3
}
},
{
"key": "fw-yocto-layer",
"name": "Firmware · Yocto layer (unsupported)",