feat(yocto): read the build's SPDX 3.0 image document (#150) (#859)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m30s
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m7s
CI / Deploy Agent (push) Successful in 5m30s
This commit was merged in pull request #859.
This commit is contained in:
1 parent
360c905894
commit
3d7deee4a8
7 files changed
+2933
-25
No files matched your search
@@ -59,3 +59,4 @@ pub mod yocto_cve_check;
|
||||
pub mod yocto_inventory;
|
||||
pub mod yocto_pins;
|
||||
pub mod yocto_spdx;
|
||||
pub mod yocto_spdx3;
|
||||
@@ -2746,6 +2746,12 @@ impl PipelineOrchestrator {
|
||||
.and_then(|mut f| f.read(&mut head))
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
// An SPDX 3.0 image document is JSON too: recognised first.
|
||||
if crate::pipeline::yocto_spdx3::is_spdx3(&head[..n]) {
|
||||
return crate::pipeline::yocto_spdx3::read(&file, &id)
|
||||
.map(Read::Images)
|
||||
.map_err(|e| e.to_string());
|
||||
}
|
||||
if crate::pipeline::yocto_cve_check::is_cve_check(&head[..n]) {
|
||||
return crate::pipeline::yocto_cve_check::read(&file)
|
||||
.map(Read::Check)
|
||||
@@ -2772,8 +2778,8 @@ impl PipelineOrchestrator {
|
||||
SkipCode::ArtifactNotIngested,
|
||||
format!(
|
||||
"{name} was not read as a Yocto image SPDX archive \
|
||||
(<image>.spdx.tar.zst) or cve-check report \
|
||||
(<image>.json): {e}"
|
||||
(<image>.spdx.tar.zst), SPDX 3.0 image document \
|
||||
(<image>.spdx.json) or cve-check report (<image>.json): {e}"
|
||||
),
|
||||
)
|
||||
.about(name),
|
||||
|
||||
@@ -26,7 +26,7 @@ use compliance_core::models::{
|
||||
use crate::pipeline::nvd_cpe::NvdCve;
|
||||
use crate::pipeline::yocto_cve_check::{CheckStatus, CheckedIssue, CveCheck};
|
||||
use crate::pipeline::yocto_inventory::{self, CpeProduct, NvdQuery, Recipe};
|
||||
use crate::pipeline::yocto_spdx::BuiltImage;
|
||||
use crate::pipeline::yocto_spdx::{BuiltImage, NotAffectedCve};
|
||||
|
||||
/// What the build installed, across its images, by recipe name.
|
||||
#[derive(Debug, Default)]
|
||||
@@ -37,6 +37,8 @@ pub struct Built<'a> {
|
||||
images: BTreeSet<String>,
|
||||
/// The CVEs fixed per recipe name.
|
||||
fixed: HashMap<String, BTreeSet<&'a str>>,
|
||||
/// What the build's SPDX 3.0 VEX says does not affect each recipe, by CVE.
|
||||
not_affected: HashMap<&'a str, HashMap<&'a str, &'a NotAffectedCve>>,
|
||||
/// Yocto's cve-check verdicts per recipe name, by CVE.
|
||||
checked: HashMap<&'a str, HashMap<&'a str, &'a CheckedIssue>>,
|
||||
/// The version cve-check names each recipe at.
|
||||
@@ -74,6 +76,13 @@ impl<'a> Built<'a> {
|
||||
.or_default()
|
||||
.insert(fixed.cve.as_str());
|
||||
}
|
||||
for na in &image.not_affected {
|
||||
built
|
||||
.not_affected
|
||||
.entry(na.component.as_str())
|
||||
.or_default()
|
||||
.insert(na.cve.as_str(), na);
|
||||
}
|
||||
}
|
||||
built
|
||||
}
|
||||
@@ -307,6 +316,13 @@ impl<'a> Built<'a> {
|
||||
{
|
||||
return Some((alert.cve_id.clone(), checked));
|
||||
}
|
||||
if let Some(na) = self
|
||||
.not_affected
|
||||
.get(alert.affected_package.as_str())
|
||||
.and_then(|cves| cves.get(alert.cve_id.as_str()))
|
||||
{
|
||||
return Some((alert.cve_id.clone(), not_affected_statement(na)));
|
||||
}
|
||||
let fixed = self
|
||||
.fixed
|
||||
.get(&alert.affected_package)
|
||||
@@ -336,6 +352,30 @@ impl<'a> Built<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement the build's SPDX 3.0 makes that `na` does not affect its
|
||||
/// component, with its justification and impact statement.
|
||||
fn not_affected_statement(na: &NotAffectedCve) -> VexAssessment {
|
||||
let justification = match na.justification.as_deref() {
|
||||
Some("componentNotPresent") => Some(VexJustification::ComponentNotPresent),
|
||||
Some("vulnerableCodeNotPresent") => Some(VexJustification::VulnerableCodeNotPresent),
|
||||
Some("vulnerableCodeNotInExecutePath") => {
|
||||
Some(VexJustification::VulnerableCodeNotInExecutePath)
|
||||
}
|
||||
Some("vulnerableCodeCannotBeControlledByAdversary") => {
|
||||
Some(VexJustification::VulnerableCodeCannotBeControlledByAdversary)
|
||||
}
|
||||
Some("inlineMitigationsAlreadyExist") => {
|
||||
Some(VexJustification::InlineMitigationsAlreadyExist)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut because = "Yocto SPDX 3.0 VEX: not affected".to_string();
|
||||
if let Some(statement) = na.statement.as_deref().filter(|s| !s.is_empty()) {
|
||||
because.push_str(&format!(": {statement}"));
|
||||
}
|
||||
yocto_inventory::scan_statement(VexStatus::NotAffected, justification, because)
|
||||
}
|
||||
|
||||
/// Add `image` to `entry`'s built marking and its evidence line.
|
||||
fn add_image(entry: &mut SbomEntry, image: &str) {
|
||||
let Some(in_image) = entry.in_image.as_mut() else {
|
||||
@@ -648,4 +688,28 @@ mod tests {
|
||||
// In range and not patched: open.
|
||||
assert_eq!(status("CVE-2024-42067"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spdx3_vex_settles_what_it_says_does_not_affect() {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json");
|
||||
let images = crate::pipeline::yocto_spdx3::read(&path, "t").unwrap();
|
||||
let built = Built::new(&images, &[]);
|
||||
let statements = built.statements(
|
||||
&[],
|
||||
&[
|
||||
alert("glibc", "2.39+git", "CVE-2019-1010022"),
|
||||
alert("busybox", "1.36.1", "CVE-2022-48174"),
|
||||
],
|
||||
);
|
||||
let by_cve = |cve: &str| statements.iter().find(|(c, _)| c == cve).map(|(_, v)| v);
|
||||
let glibc = by_cve("CVE-2019-1010022").unwrap();
|
||||
assert_eq!(glibc.status, VexStatus::NotAffected);
|
||||
assert!(glibc
|
||||
.impact_statement
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.starts_with("Yocto SPDX 3.0 VEX: not affected"));
|
||||
assert_eq!(by_cve("CVE-2022-48174").unwrap().status, VexStatus::Fixed);
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,21 @@ pub struct BuiltImage {
|
||||
/// Packages the image contains whose documents are not in the archive,
|
||||
/// or whose recipe is not (`missing-pkg`), sorted.
|
||||
pub unresolved: Vec<String>,
|
||||
/// The CVEs the build's SPDX states do not affect a component (SPDX 3.0
|
||||
/// VEX), sorted; SPDX 2.2 states none.
|
||||
pub not_affected: Vec<NotAffectedCve>,
|
||||
}
|
||||
|
||||
/// A CVE the build's SPDX says does not affect a component, and why.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct NotAffectedCve {
|
||||
pub component: String,
|
||||
pub version: String,
|
||||
pub cve: String,
|
||||
/// The SPDX 3.0 justification (`vulnerableCodeNotPresent`, …).
|
||||
pub justification: Option<String>,
|
||||
/// The impact statement (`This issue has kernel fixes …`).
|
||||
pub statement: Option<String>,
|
||||
}
|
||||
|
||||
/// A CVE a recipe's patch fixes in the component built from it.
|
||||
@@ -341,7 +356,16 @@ fn built_image(
|
||||
let mut entries = Vec::with_capacity(recipes.len());
|
||||
let mut fixed = Vec::new();
|
||||
for ((name, version), found) in &recipes {
|
||||
entries.push(entry(name, version, found, &image.name, &image.id, repo_id));
|
||||
let facts = ComponentFacts {
|
||||
name,
|
||||
version,
|
||||
license: found.recipe.license.as_deref(),
|
||||
cpe: cpes(found.recipe).into_iter().next(),
|
||||
homepage: found.recipe.homepage.as_deref(),
|
||||
packages: found.packages.iter().copied().collect(),
|
||||
};
|
||||
let label = image.id.trim_start_matches("SPDXRef-Image-");
|
||||
entries.push(component(facts, &image.name, label, repo_id));
|
||||
fixed.extend(fixed_cves(found.recipe).into_iter().map(|cve| FixedCve {
|
||||
component: name.clone(),
|
||||
version: version.clone(),
|
||||
@@ -355,19 +379,32 @@ fn built_image(
|
||||
entries,
|
||||
fixed,
|
||||
unresolved: unresolved.into_iter().collect(),
|
||||
not_affected: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The SBOM component of one recipe in the image.
|
||||
fn entry(
|
||||
name: &str,
|
||||
version: &str,
|
||||
found: &RecipeInImage<'_>,
|
||||
/// What the build's SPDX (2.2 or 3.0) says about one recipe in the image.
|
||||
pub(crate) struct ComponentFacts<'a> {
|
||||
pub name: &'a str,
|
||||
pub version: &'a str,
|
||||
/// The declared licence as written (document prefixes are dropped here).
|
||||
pub license: Option<&'a str>,
|
||||
/// The first CPE 2.3 name it is known by.
|
||||
pub cpe: Option<String>,
|
||||
pub homepage: Option<&'a str>,
|
||||
/// Its packages in the image, sorted.
|
||||
pub packages: Vec<&'a str>,
|
||||
}
|
||||
|
||||
/// The SBOM component of one recipe in the image `image`, whose SPDX the
|
||||
/// evidence names as `label` (the image document's id).
|
||||
pub(crate) fn component(
|
||||
facts: ComponentFacts<'_>,
|
||||
image: &str,
|
||||
image_id: &str,
|
||||
label: &str,
|
||||
repo_id: &str,
|
||||
) -> SbomEntry {
|
||||
let recipe = found.recipe;
|
||||
let (name, version) = (facts.name, facts.version);
|
||||
let mut entry = SbomEntry::new(
|
||||
repo_id.to_string(),
|
||||
name.to_string(),
|
||||
@@ -379,17 +416,15 @@ fn entry(
|
||||
} else {
|
||||
format!("pkg:generic/{}@{}", encode(name), encode(version))
|
||||
});
|
||||
entry.license = recipe.license.as_deref().and_then(license);
|
||||
entry.cpe = cpes(recipe).into_iter().next();
|
||||
entry.manufacturer_url = recipe
|
||||
entry.license = facts.license.and_then(license);
|
||||
entry.cpe = facts.cpe;
|
||||
entry.manufacturer_url = facts
|
||||
.homepage
|
||||
.clone()
|
||||
.filter(|h| h.starts_with("https://") || h.starts_with("http://"));
|
||||
let packages: Vec<&str> = found.packages.iter().copied().collect();
|
||||
.filter(|h| h.starts_with("https://") || h.starts_with("http://"))
|
||||
.map(str::to_string);
|
||||
entry.evidence.push(format!(
|
||||
"{SOURCE} ({}): packages {}",
|
||||
image_id.trim_start_matches("SPDXRef-Image-"),
|
||||
packages.join(", ")
|
||||
"{SOURCE} ({label}): packages {}",
|
||||
facts.packages.join(", ")
|
||||
));
|
||||
let in_image = InImage {
|
||||
basis: InImageBasis::Built,
|
||||
@@ -414,7 +449,7 @@ fn package_name(reference: &str) -> String {
|
||||
/// a licence defined in another document (`DocumentRef-recipe-busybox:
|
||||
/// LicenseRef-bzip2-1.0.4` → `LicenseRef-bzip2-1.0.4`); `None` for
|
||||
/// NOASSERTION, NONE or nothing.
|
||||
fn license(declared: &str) -> Option<String> {
|
||||
pub(crate) fn license(declared: &str) -> Option<String> {
|
||||
let cleaned: Vec<String> = declared
|
||||
.split_whitespace()
|
||||
.map(|token| {
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! What a Yocto build put into an image, read from the build's own SPDX 3.0.
|
||||
//!
|
||||
//! With `create-spdx-3.0` (the default from Styhead 5.1 on, available in
|
||||
//! Scarthgap) a build writes one JSON-LD document per image,
|
||||
//! `<image>.rootfs.spdx.json`, holding the whole graph:
|
||||
//!
|
||||
//! - the image is a `software_Package` whose purpose is `archive`, output
|
||||
//! (`hasOutput`) of the rootfs `build_Build`;
|
||||
//! - the packages installed in it are that build's inputs (`hasInput`), each
|
||||
//! a `software_Package` of purpose `install` with its version, CPE and
|
||||
//! homepage, its licence through `hasConcludedLicense`;
|
||||
//! - each package is output of its recipe's build,
|
||||
//! `<recipe>:do_create_spdx:recipe`;
|
||||
//! - the build's VEX: `security_Vulnerability` elements with their CVE id,
|
||||
//! `fixedIn` and `doesNotAffect` assessments on the packages.
|
||||
//!
|
||||
//! [`read`] returns the same [`BuiltImage`] as the SPDX 2.2 reader
|
||||
//! ([`crate::pipeline::yocto_spdx`]), with the not-affected statements too.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::pipeline::yocto_spdx::{
|
||||
component, BuiltImage, ComponentFacts, FixedCve, NotAffectedCve, YoctoSpdxError,
|
||||
};
|
||||
|
||||
/// Bytes an SPDX 3.0 image document may have (core-image-minimal's is
|
||||
/// ~7 MB; a product image with sources listed can be far larger).
|
||||
pub const MAX_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
/// Whether the file starting with `head` is an SPDX 3 JSON-LD document.
|
||||
pub fn is_spdx3(head: &[u8]) -> bool {
|
||||
let text = String::from_utf8_lossy(head);
|
||||
text.trim_start().starts_with('{')
|
||||
&& text.contains("\"@context\"")
|
||||
&& text.contains("spdx.org/rdf/3")
|
||||
}
|
||||
|
||||
/// One element of the graph, as far as it is read here.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Element {
|
||||
#[serde(rename = "type", default)]
|
||||
kind: String,
|
||||
#[serde(rename = "spdxId", default)]
|
||||
id: Option<String>,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(rename = "software_primaryPurpose", default)]
|
||||
purpose: Option<String>,
|
||||
#[serde(rename = "software_packageVersion", default)]
|
||||
version: Option<String>,
|
||||
#[serde(rename = "software_homePage", default)]
|
||||
homepage: Option<String>,
|
||||
#[serde(rename = "externalIdentifier", default)]
|
||||
identifiers: Vec<Identifier>,
|
||||
#[serde(default)]
|
||||
from: Option<String>,
|
||||
#[serde(default, deserialize_with = "one_or_many")]
|
||||
to: Vec<String>,
|
||||
#[serde(rename = "relationshipType", default)]
|
||||
relationship: Option<String>,
|
||||
#[serde(rename = "simplelicensing_licenseExpression", default)]
|
||||
license_expression: Option<String>,
|
||||
#[serde(rename = "security_impactStatement", default)]
|
||||
impact: Option<String>,
|
||||
#[serde(rename = "security_justificationType", default)]
|
||||
justification: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Identifier {
|
||||
#[serde(rename = "externalIdentifierType")]
|
||||
kind: String,
|
||||
identifier: String,
|
||||
}
|
||||
|
||||
/// `to` is a list, or one id.
|
||||
fn one_or_many<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum OneOrMany {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
Ok(match Option::<OneOrMany>::deserialize(deserializer)? {
|
||||
Some(OneOrMany::One(id)) => vec![id],
|
||||
Some(OneOrMany::Many(ids)) => ids,
|
||||
None => Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Document {
|
||||
#[serde(rename = "@graph")]
|
||||
graph: Vec<Element>,
|
||||
}
|
||||
|
||||
/// Read the images of an SPDX 3.0 image document.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The file cannot be read, is larger than [`MAX_BYTES`], is not an SPDX 3
|
||||
/// JSON-LD document, or names no image.
|
||||
pub fn read(path: &Path, repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)?
|
||||
.take(MAX_BYTES + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return Err(YoctoSpdxError::TooLarge(
|
||||
"the SPDX 3.0 document is too large",
|
||||
));
|
||||
}
|
||||
let file = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let doc: Document = serde_json::from_slice(&bytes).map_err(|e| YoctoSpdxError::NotSpdx {
|
||||
file,
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
images(&doc.graph, repo_id)
|
||||
}
|
||||
|
||||
/// The graph's elements by id, and its relationships.
|
||||
struct Graph<'a> {
|
||||
by_id: HashMap<&'a str, &'a Element>,
|
||||
relationships: Vec<&'a Element>,
|
||||
}
|
||||
|
||||
impl<'a> Graph<'a> {
|
||||
fn new(elements: &'a [Element]) -> Self {
|
||||
let mut by_id = HashMap::with_capacity(elements.len());
|
||||
let mut relationships = Vec::new();
|
||||
for e in elements {
|
||||
if let Some(id) = e.id.as_deref() {
|
||||
by_id.insert(id, e);
|
||||
}
|
||||
if e.relationship.is_some() {
|
||||
relationships.push(e);
|
||||
}
|
||||
}
|
||||
Self {
|
||||
by_id,
|
||||
relationships,
|
||||
}
|
||||
}
|
||||
|
||||
/// The relationships of `kind`.
|
||||
fn of(&self, kind: &'a str) -> impl Iterator<Item = &'a Element> + '_ {
|
||||
self.relationships
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(move |r| r.relationship.as_deref() == Some(kind))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every image of `elements`.
|
||||
fn images(elements: &[Element], repo_id: &str) -> Result<Vec<BuiltImage>, YoctoSpdxError> {
|
||||
let graph = Graph::new(elements);
|
||||
let mut out: Vec<BuiltImage> = elements
|
||||
.iter()
|
||||
.filter(|e| e.kind == "software_Package" && e.purpose.as_deref() == Some("archive"))
|
||||
.filter_map(|image| built_image(&graph, image, repo_id))
|
||||
.collect();
|
||||
if out.is_empty() {
|
||||
return Err(YoctoSpdxError::NoImage);
|
||||
}
|
||||
out.sort_by(|a, b| a.image_id.cmp(&b.image_id));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The image `image`, if a build outputs it.
|
||||
fn built_image(graph: &Graph<'_>, image: &Element, repo_id: &str) -> Option<BuiltImage> {
|
||||
let image_id = image.id.as_deref()?;
|
||||
let image_name = image.name.clone().unwrap_or_default();
|
||||
// The builds whose output the image is (the rootfs build).
|
||||
let rootfs: BTreeSet<&str> = graph
|
||||
.of("hasOutput")
|
||||
.filter(|r| r.to.iter().any(|t| t == image_id))
|
||||
.filter_map(|r| r.from.as_deref())
|
||||
.collect();
|
||||
let installed: BTreeSet<&str> = graph
|
||||
.of("hasInput")
|
||||
.filter(|r| r.from.as_deref().is_some_and(|f| rootfs.contains(f)))
|
||||
.flat_map(|r| r.to.iter().map(String::as_str))
|
||||
.collect();
|
||||
if rootfs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each package's recipe: the name of the recipe build that outputs it.
|
||||
let mut recipe_of: HashMap<&str, &str> = HashMap::new();
|
||||
for r in graph.of("hasOutput") {
|
||||
let Some(build) = r.from.as_deref().and_then(|f| graph.by_id.get(f)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(recipe) = build
|
||||
.name
|
||||
.as_deref()
|
||||
.and_then(|n| n.strip_suffix(":do_create_spdx:recipe"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for t in &r.to {
|
||||
recipe_of.insert(t.as_str(), recipe);
|
||||
}
|
||||
}
|
||||
let license_of: HashMap<&str, &str> = graph
|
||||
.of("hasConcludedLicense")
|
||||
.filter_map(|r| {
|
||||
let expression =
|
||||
r.to.iter()
|
||||
.filter_map(|t| graph.by_id.get(t.as_str()))
|
||||
.find_map(|e| e.license_expression.as_deref())?;
|
||||
Some((r.from.as_deref()?, expression))
|
||||
})
|
||||
.collect();
|
||||
|
||||
/// A recipe with packages in the image.
|
||||
struct Found<'a> {
|
||||
package: &'a Element,
|
||||
packages: BTreeSet<&'a str>,
|
||||
ids: BTreeSet<&'a str>,
|
||||
}
|
||||
let mut recipes: BTreeMap<(&str, &str), Found<'_>> = BTreeMap::new();
|
||||
let mut unresolved = BTreeSet::new();
|
||||
for id in &installed {
|
||||
let package = graph.by_id.get(id).copied();
|
||||
let recipe = package.and_then(|_| recipe_of.get(id).copied());
|
||||
let (Some(package), Some(recipe)) = (package, recipe) else {
|
||||
unresolved.insert(package_name(id));
|
||||
continue;
|
||||
};
|
||||
if package.purpose.as_deref() != Some("install") {
|
||||
continue;
|
||||
}
|
||||
let version = package.version.as_deref().unwrap_or_default();
|
||||
let found = recipes.entry((recipe, version)).or_insert_with(|| Found {
|
||||
package,
|
||||
packages: BTreeSet::new(),
|
||||
ids: BTreeSet::new(),
|
||||
});
|
||||
found
|
||||
.packages
|
||||
.insert(package.name.as_deref().unwrap_or_default());
|
||||
found.ids.insert(*id);
|
||||
}
|
||||
|
||||
// The CVE ids of the vulnerabilities, and what the VEX says per package.
|
||||
let cve_of = |id: &str| -> Option<&str> {
|
||||
graph.by_id.get(id)?.identifiers.iter().find_map(|i| {
|
||||
(i.kind == "cve" || i.identifier.starts_with("CVE-")).then_some(i.identifier.as_str())
|
||||
})
|
||||
};
|
||||
let mut entries = Vec::with_capacity(recipes.len());
|
||||
let mut fixed = BTreeSet::new();
|
||||
let mut not_affected = BTreeSet::new();
|
||||
for ((recipe, version), found) in &recipes {
|
||||
let facts = ComponentFacts {
|
||||
name: recipe,
|
||||
version,
|
||||
license: found.ids.iter().find_map(|id| license_of.get(id).copied()),
|
||||
cpe: found
|
||||
.package
|
||||
.identifiers
|
||||
.iter()
|
||||
.find(|i| i.kind == "cpe23")
|
||||
.map(|i| i.identifier.clone()),
|
||||
homepage: found.package.homepage.as_deref(),
|
||||
packages: found.packages.iter().copied().collect(),
|
||||
};
|
||||
let label = format!("{image_name}, SPDX 3.0");
|
||||
entries.push(component(facts, &image_name, &label, repo_id));
|
||||
for r in graph.of("fixedIn") {
|
||||
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
|
||||
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
|
||||
fixed.insert(FixedCve {
|
||||
component: recipe.to_string(),
|
||||
version: version.to_string(),
|
||||
cve: cve.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in graph.of("doesNotAffect") {
|
||||
if r.to.iter().any(|t| found.ids.contains(t.as_str())) {
|
||||
if let Some(cve) = r.from.as_deref().and_then(cve_of) {
|
||||
not_affected.insert(NotAffectedCve {
|
||||
component: recipe.to_string(),
|
||||
version: version.to_string(),
|
||||
cve: cve.to_string(),
|
||||
justification: r.justification.clone(),
|
||||
statement: r.impact.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(BuiltImage {
|
||||
image: image_name,
|
||||
image_id: image_id.to_string(),
|
||||
entries,
|
||||
fixed: fixed.into_iter().collect(),
|
||||
unresolved: unresolved.into_iter().collect(),
|
||||
not_affected: not_affected.into_iter().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The package name at the end of a package id (`…/package/busybox`).
|
||||
fn package_name(id: &str) -> String {
|
||||
id.rsplit('/').next().unwrap_or(id).to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::{InImageBasis, YOCTO_RECIPE_MANAGER};
|
||||
|
||||
/// A trimmed copy of a real Scarthgap (5.0.21) core-image-minimal for
|
||||
/// qemuarm64 built with create-spdx-3.0: six recipes and one installed
|
||||
/// package whose element is missing.
|
||||
fn fixture() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../fixtures/yocto/core-image-minimal-qemuarm64.rootfs.spdx3.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spdx3_image_lists_what_the_build_installed() {
|
||||
let images = read(&fixture(), "t").unwrap();
|
||||
assert_eq!(images.len(), 1);
|
||||
let image = &images[0];
|
||||
assert_eq!(image.image, "core-image-minimal");
|
||||
|
||||
let names: Vec<(&str, &str)> = image
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| (e.name.as_str(), e.version.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
("base-files", "3.0.14"),
|
||||
("busybox", "1.36.1"),
|
||||
("glibc", "2.39+git"),
|
||||
("libxml2", "2.12.10"),
|
||||
("openssl", "3.5.9"),
|
||||
("packagegroup-core-boot", "1.0"),
|
||||
]
|
||||
);
|
||||
let busybox = &image.entries[1];
|
||||
assert_eq!(busybox.package_manager, YOCTO_RECIPE_MANAGER);
|
||||
assert_eq!(
|
||||
busybox.cpe.as_deref(),
|
||||
Some("cpe:2.3:*:*:busybox:1.36.1:*:*:*:*:*:*:*")
|
||||
);
|
||||
assert!(busybox.license.is_some());
|
||||
assert_eq!(
|
||||
busybox.in_image.as_ref().map(|i| i.basis),
|
||||
Some(InImageBasis::Built)
|
||||
);
|
||||
assert!(
|
||||
busybox.evidence[0].ends_with("packages busybox, busybox-syslog, busybox-udhcpc"),
|
||||
"{:?}",
|
||||
busybox.evidence
|
||||
);
|
||||
// libc6 and ldconfig are one glibc component.
|
||||
assert!(image.entries[2].evidence[0].ends_with("packages ldconfig, libc6"));
|
||||
|
||||
assert!(image
|
||||
.fixed
|
||||
.iter()
|
||||
.any(|f| f.component == "busybox" && f.cve == "CVE-2022-48174"));
|
||||
let glibc_not_affected: Vec<&NotAffectedCve> = image
|
||||
.not_affected
|
||||
.iter()
|
||||
.filter(|n| n.component == "glibc")
|
||||
.collect();
|
||||
assert!(!glibc_not_affected.is_empty());
|
||||
assert!(glibc_not_affected.iter().all(|n| n.cve.starts_with("CVE-")));
|
||||
assert_eq!(image.unresolved, ["missing-pkg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_spdx3_document_is_recognised_by_its_start() {
|
||||
let head = std::fs::read(fixture()).unwrap();
|
||||
assert!(is_spdx3(&head[..400.min(head.len())]));
|
||||
assert!(!is_spdx3(br#"{"package": [], "version": "1"}"#));
|
||||
assert!(!is_spdx3(&[0x28, 0xb5, 0x2f, 0xfd]));
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -306,9 +306,15 @@ Prüfwerk takes that over the declared marking. Add each file to the target as
|
||||
**Build-Ergebnisse (Yocto: Image-SPDX .spdx.tar.zst, cve-check .json)**, in the
|
||||
wizard or under **Datei hinzufügen** on the target:
|
||||
|
||||
- **The image SPDX archive**: `tmp/deploy/images/<machine>/<image>.spdx.tar.zst`.
|
||||
Yocto's `create-spdx` class (the default) writes it with every build. Since
|
||||
Scarthgap (5.0) it is SPDX 2.2; Prüfwerk reads it as it is.
|
||||
- **The image SBOM**, as the build wrote it:
|
||||
- SPDX 2.2: `tmp/deploy/images/<machine>/<image>.spdx.tar.zst`, written by
|
||||
Yocto's `create-spdx` class, the default up to Scarthgap (5.0);
|
||||
- SPDX 3.0: `tmp/deploy/images/<machine>/<image>.spdx.json`, written by
|
||||
`create-spdx-3.0`, the default from Styhead (5.1) and available in Scarthgap.
|
||||
Its VEX statements (fixed, and not affected with the justification) are
|
||||
taken over too.
|
||||
|
||||
Prüfwerk reads either as it is.
|
||||
- **The cve-check report** (optional): `tmp/deploy/images/<machine>/<image>.json`,
|
||||
written when the build inherits `cve-check` (`INHERIT += "cve-check"` in
|
||||
`local.conf`).
|
||||
@@ -384,5 +390,5 @@ joined as described above.
|
||||
| Tier | Input | Analysis |
|
||||
| --- | --- | --- |
|
||||
| **1: layer tree** (in progress) | the layers in git, no build | **Recipe inventory**: every recipe's name, version, `SRC_URI`, `CVE_PRODUCT` and `CVE_STATUS`, matched against NVD; labelled as a recipe inventory, not the image's SBOM; the recipes an image recipe installs marked as declared. **Recipe lint**: done, see above |
|
||||
| **2: build artefacts** (in progress) | the image `.spdx.tar.zst` (SPDX 2.2), the cve-check `.json`; later SPDX 3.0, `*.vex.json`, the kernel `.config` | **Done:** the image SPDX joins the SBOM (installed by the build), the cve-check verdicts become VEX, see *Im Image (gebaut)*. **Planned:** SPDX 3.0 (Styhead and later), kernel CVEs filtered by the configuration |
|
||||
| **2: build artefacts** | the image SPDX (2.2 `.spdx.tar.zst` or 3.0 `.spdx.json`), the cve-check `.json`, the kernel CVE report from `improve_kernel_cve_report.py` | **Done:** the image SPDX joins the SBOM (installed by the build) with its VEX, the cve-check verdicts become VEX, kernel CVEs the configuration does not build are not affected, with or without the layer tree; see *Im Image (gebaut)* |
|
||||
| **3: image / rootfs** | `.wic`, tar, ext4, squashfs | unpacking, ELF hardening of every binary, secrets and default credentials in the root filesystem; DAST and pentest only for a qemu build in an isolated sandbox |
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user