feat(yocto): recipes an image recipe installs are marked as in the image (declared) #557
No files matched your search
@@ -7,3 +7,6 @@
|
||||
.playwright-mcp/
|
||||
report-preview-full.png
|
||||
compliance-dashboard/attack-chain-final.html
|
||||
|
||||
# Python bytecode (the agent image helpers)
|
||||
__pycache__/
|
||||
@@ -226,6 +226,10 @@ pub struct SbomFilter {
|
||||
pub has_vulns: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Only components an image is known to contain (`true`), or only the
|
||||
/// others (`false`); see [`compliance_core::models::InImage`].
|
||||
#[serde(default)]
|
||||
pub in_image: Option<bool>,
|
||||
#[serde(default = "default_page", deserialize_with = "de_page")]
|
||||
pub page: u64,
|
||||
#[serde(default = "default_limit", deserialize_with = "de_limit")]
|
||||
|
||||
@@ -84,6 +84,9 @@ pub async fn list_sbom(
|
||||
if let Some(license) = &filter.license {
|
||||
query.insert("license", license);
|
||||
}
|
||||
if let Some(in_image) = filter.in_image {
|
||||
query.insert("in_image", doc! { "$exists": in_image });
|
||||
}
|
||||
|
||||
let skip = filter.skip();
|
||||
let total = db
|
||||
@@ -95,7 +98,7 @@ pub async fn list_sbom(
|
||||
let entries = match db
|
||||
.sbom_entries()
|
||||
.find(query)
|
||||
.sort(doc! { "name": 1 })
|
||||
.sort(list_order())
|
||||
.skip(skip)
|
||||
.limit(filter.limit)
|
||||
.await
|
||||
@@ -114,6 +117,12 @@ pub async fn list_sbom(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The order of the SBOM list: the components an image contains first (a
|
||||
/// missing `in_image` sorts as null, below any value), then by name.
|
||||
fn list_order() -> mongodb::bson::Document {
|
||||
doc! { "in_image.basis": -1, "name": 1 }
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn export_sbom(
|
||||
Extension(agent): AgentExt,
|
||||
|
||||
@@ -24,7 +24,7 @@ use crate::pipeline::plan::build_scan_plan;
|
||||
use crate::pipeline::repo_view::RepoView;
|
||||
use crate::pipeline::sbom::{LicenseCache, NugetRegistry, SbomScanner};
|
||||
use crate::pipeline::semgrep::SemgrepScanner;
|
||||
use crate::pipeline::yocto_inventory::{self, Recipe};
|
||||
use crate::pipeline::yocto_inventory::{self, Inventory};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// Context from graph analysis passed to LLM triage for enhanced filtering
|
||||
@@ -500,12 +500,32 @@ impl PipelineOrchestrator {
|
||||
.unwrap_or_default();
|
||||
// A Yocto layer tree: its recipes, read without a build and labelled
|
||||
// as the recipe inventory (not the image SBOM).
|
||||
let yocto_recipes = if repo.yocto_layers {
|
||||
let yocto = if repo.yocto_layers {
|
||||
self.yocto_recipes(&repo_path, scan_run_id).await
|
||||
} else {
|
||||
Vec::new()
|
||||
Inventory::default()
|
||||
};
|
||||
let yocto_entries = yocto_inventory::entries(&yocto_recipes, &repo_id);
|
||||
// The recipes the image recipes name are marked as in the image
|
||||
// (declared); what an image names that is not in the tree is listed.
|
||||
let declarations = yocto_inventory::declared_in_images(&yocto);
|
||||
if !declarations.unresolved.is_empty() {
|
||||
let names: Vec<String> = declarations.unresolved.iter().cloned().collect();
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
yocto_inventory::IMAGE_STAGE,
|
||||
SkipCode::NotInTree,
|
||||
format!(
|
||||
"named by an image but not a recipe or package group in the tree: {}",
|
||||
component_list(&names)
|
||||
),
|
||||
)
|
||||
.about(component_list(&names)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let yocto_entries = yocto_inventory::entries(&yocto.recipes, &declarations, &repo_id);
|
||||
let yocto_recipes = yocto.recipes;
|
||||
for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) {
|
||||
let known = sbom_entries
|
||||
.iter()
|
||||
@@ -2347,9 +2367,10 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// The recipes of a Yocto layer tree. A parser that failed, a tree with
|
||||
/// no layer, or recipes the parser could not read are recorded on the run.
|
||||
async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Vec<Recipe> {
|
||||
/// The recipes, images and package groups of a Yocto layer tree. A parser
|
||||
/// that failed, a tree with no layer, or recipes the parser could not read
|
||||
/// are recorded on the run.
|
||||
async fn yocto_recipes(&self, tree: &std::path::Path, scan_run_id: &str) -> Inventory {
|
||||
match yocto_inventory::read(tree).await {
|
||||
Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => {
|
||||
self.skip_stage(
|
||||
@@ -2362,7 +2383,7 @@ impl PipelineOrchestrator {
|
||||
),
|
||||
)
|
||||
.await;
|
||||
Vec::new()
|
||||
Inventory::default()
|
||||
}
|
||||
Ok(inventory) => {
|
||||
if !inventory.errors.is_empty() {
|
||||
@@ -2383,11 +2404,11 @@ impl PipelineOrchestrator {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
inventory.recipes
|
||||
inventory
|
||||
}
|
||||
Err(skipped) => {
|
||||
self.skip_stage(scan_run_id, skipped).await;
|
||||
Vec::new()
|
||||
Inventory::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,27 +8,37 @@
|
||||
//! SRCREV), its LICENSE, and the CPE NVD knows it by (CVE_PRODUCT, CVE_VERSION).
|
||||
//!
|
||||
//! It is labelled [`YOCTO_RECIPE_SOURCE`] everywhere it shows: layer
|
||||
//! overrides, PACKAGECONFIG, the distro and machine configuration and what an
|
||||
//! image installs are not resolved, so the inventory lists every recipe in the
|
||||
//! tree, more than an image contains.
|
||||
//! overrides, PACKAGECONFIG, the distro and machine configuration are not
|
||||
//! resolved, so the inventory lists every recipe in the tree, more than an
|
||||
//! image contains.
|
||||
//!
|
||||
//! The recipes an image recipe names (IMAGE_INSTALL, a package group it
|
||||
//! installs, one level deep, the package groups of its IMAGE_FEATURES) are
|
||||
//! marked as in the image, declared ([`declared_in_images`]): read from the
|
||||
//! recipes as written, not resolved by BitBake.
|
||||
//!
|
||||
//! What a recipe says about its CVEs becomes the alert's VEX statement
|
||||
//! ([`vex_statements`]): a CVE_STATUS (or CVE_STATUS_GROUPS, or the older
|
||||
//! CVE_CHECK_IGNORE) and a patch in SRC_URI with a `CVE:` tag, as Yocto's own
|
||||
//! cve-check reads them.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use compliance_core::models::{
|
||||
CveAlert, SbomEntry, SkipCode, SkippedStage, StatusChange, VexAssessment, VexJustification,
|
||||
VexStatus, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
CveAlert, InImage, InImageBasis, SbomEntry, SkipCode, SkippedStage, StatusChange,
|
||||
VexAssessment, VexJustification, VexStatus, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
};
|
||||
use compliance_core::purl::encode;
|
||||
|
||||
/// The scan run's stage id for the recipe inventory.
|
||||
pub const STAGE: &str = "recipe_inventory";
|
||||
|
||||
/// The scan run's stage id for the names an image declares that are not
|
||||
/// recipes in the tree.
|
||||
pub const IMAGE_STAGE: &str = "image_install";
|
||||
|
||||
/// The helper the agent image installs (see `Dockerfile.agent`).
|
||||
const HELPER: &str = "/opt/pruefwerk/pruefwerk_yocto_recipes.py";
|
||||
|
||||
@@ -57,6 +67,10 @@ pub struct Recipe {
|
||||
pub pn: String,
|
||||
/// The base recipe name (BPN): PN without a `-native` or multilib part.
|
||||
pub bpn: String,
|
||||
/// The packages PACKAGES names besides the defaults (`pump-web-ui`), as
|
||||
/// far as they are written without a variable.
|
||||
#[serde(default)]
|
||||
pub packages: Vec<String>,
|
||||
/// PV as assigned, expanded as far as the tree allows, or from the file
|
||||
/// name; `None` when neither gives one.
|
||||
#[serde(default)]
|
||||
@@ -105,10 +119,63 @@ pub struct Patch {
|
||||
pub cves: Vec<String>,
|
||||
}
|
||||
|
||||
/// An image recipe (or a bbappend of an image not in the tree) and what it
|
||||
/// declares the image installs.
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
pub struct ImageRecipe {
|
||||
/// The `.bb` (or `.bbappend`) file, relative to the tree.
|
||||
pub file: String,
|
||||
/// The image's name (`pump-image`).
|
||||
pub pn: String,
|
||||
/// IMAGE_INSTALL and CORE_IMAGE_EXTRA_INSTALL, every operation and
|
||||
/// override counted (`:append`, `_append`, `+=`).
|
||||
#[serde(default)]
|
||||
pub install: Vec<String>,
|
||||
/// IMAGE_FEATURES and EXTRA_IMAGE_FEATURES.
|
||||
#[serde(default)]
|
||||
pub features: Vec<String>,
|
||||
}
|
||||
|
||||
/// A local.conf.sample or distro configuration, which declares installs for
|
||||
/// every image.
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
pub struct ImageConfig {
|
||||
/// The file, relative to the tree.
|
||||
pub file: String,
|
||||
#[serde(default)]
|
||||
pub install: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub features: Vec<String>,
|
||||
}
|
||||
|
||||
/// A package group recipe: what each of its packages pulls in.
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
pub struct PackageGroup {
|
||||
/// The `.bb` file, relative to the tree.
|
||||
pub file: String,
|
||||
/// The recipe name (`packagegroup-pump`).
|
||||
pub pn: String,
|
||||
/// Its packages (`packagegroup-pump`, `packagegroup-pump-web`).
|
||||
#[serde(default)]
|
||||
pub packages: Vec<String>,
|
||||
/// RDEPENDS and RRECOMMENDS per package, `${PN}` expanded.
|
||||
#[serde(default)]
|
||||
pub rdepends: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
/// What the helper read from a tree.
|
||||
#[derive(Debug, Default, PartialEq, serde::Deserialize)]
|
||||
pub struct Inventory {
|
||||
pub recipes: Vec<Recipe>,
|
||||
/// Image recipes.
|
||||
#[serde(default)]
|
||||
pub images: Vec<ImageRecipe>,
|
||||
/// Package group recipes.
|
||||
#[serde(default)]
|
||||
pub packagegroups: Vec<PackageGroup>,
|
||||
/// Configurations declaring installs for every image.
|
||||
#[serde(default)]
|
||||
pub configs: Vec<ImageConfig>,
|
||||
/// Recipes the parser could not read.
|
||||
#[serde(default)]
|
||||
pub errors: Vec<RecipeError>,
|
||||
@@ -162,13 +229,54 @@ fn failed(reason: String) -> SkippedStage {
|
||||
fn parse(json: &[u8]) -> Result<Inventory, serde_json::Error> {
|
||||
let mut inventory: Inventory = serde_json::from_slice(json)?;
|
||||
inventory.recipes.retain(plausible);
|
||||
inventory
|
||||
.images
|
||||
.retain(|i| short(&i.file) && short(&i.pn) && !i.pn.is_empty());
|
||||
inventory.configs.retain(|c| short(&c.file));
|
||||
inventory
|
||||
.packagegroups
|
||||
.retain(|g| short(&g.file) && short(&g.pn) && !g.pn.is_empty());
|
||||
for image in &mut inventory.images {
|
||||
image.install.retain(|w| is_package_name(w));
|
||||
image.features.retain(|w| is_package_name(w));
|
||||
}
|
||||
for config in &mut inventory.configs {
|
||||
config.install.retain(|w| is_package_name(w));
|
||||
config.features.retain(|w| is_package_name(w));
|
||||
}
|
||||
for group in &mut inventory.packagegroups {
|
||||
group.packages.retain(|w| is_package_name(w));
|
||||
group.rdepends.retain(|package, _| is_package_name(package));
|
||||
for words in group.rdepends.values_mut() {
|
||||
words.retain(|w| is_package_name(w));
|
||||
}
|
||||
}
|
||||
for recipe in &mut inventory.recipes {
|
||||
recipe.packages.retain(|w| is_package_name(w));
|
||||
}
|
||||
Ok(inventory)
|
||||
}
|
||||
|
||||
/// Whether `text` is short and on one line, with no control characters.
|
||||
fn short(text: &str) -> bool {
|
||||
text.len() <= MAX_VALUE && !text.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
/// Whether `word` reads as a package, recipe or feature name
|
||||
/// (`packagegroup-core-boot`, `libstdc++`, `python3.12-dev`): not a variable
|
||||
/// left unexpanded, nor a piece of inline Python or a version constraint.
|
||||
fn is_package_name(word: &str) -> bool {
|
||||
word.len() <= MAX_VALUE
|
||||
&& word.starts_with(|c: char| c.is_ascii_alphanumeric())
|
||||
&& word
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.' | '_'))
|
||||
}
|
||||
|
||||
/// Whether every value of `recipe` reads as a value: short, one line, no
|
||||
/// control characters. Anything else is dropped rather than stored.
|
||||
fn plausible(recipe: &Recipe) -> bool {
|
||||
let ok = |text: &str| text.len() <= MAX_VALUE && !text.chars().any(char::is_control);
|
||||
let ok = short;
|
||||
let optional = |text: &Option<String>| text.as_deref().is_none_or(ok);
|
||||
ok(&recipe.file)
|
||||
&& ok(&recipe.pn)
|
||||
@@ -416,8 +524,209 @@ fn spdx_license(license: &str) -> String {
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// The SBOM components of `recipes`, one per base recipe name and version.
|
||||
pub fn entries(recipes: &[Recipe], repo_id: &str) -> Vec<SbomEntry> {
|
||||
/// The package groups an image feature installs (`FEATURE_PACKAGES_*` in
|
||||
/// OpenEmbedded-Core's image.bbclass). Features whose packages a variable
|
||||
/// sets (`hwcodecs`, `package-management`, `splash`) are in
|
||||
/// [`VARIABLE_FEATURES`]; any other feature (`debug-tweaks`) installs nothing.
|
||||
const FEATURE_PACKAGES: &[(&str, &[&str])] = &[
|
||||
("weston", &["packagegroup-core-weston"]),
|
||||
("x11", &["packagegroup-core-x11"]),
|
||||
("x11-base", &["packagegroup-core-x11-base"]),
|
||||
("x11-sato", &["packagegroup-core-x11-sato"]),
|
||||
("tools-debug", &["packagegroup-core-tools-debug"]),
|
||||
("eclipse-debug", &["packagegroup-core-eclipse-debug"]),
|
||||
("tools-profile", &["packagegroup-core-tools-profile"]),
|
||||
("tools-testapps", &["packagegroup-core-tools-testapps"]),
|
||||
(
|
||||
"tools-sdk",
|
||||
&[
|
||||
"packagegroup-core-sdk",
|
||||
"packagegroup-core-standalone-sdk-target",
|
||||
],
|
||||
),
|
||||
("nfs-server", &["packagegroup-core-nfs-server"]),
|
||||
("nfs-client", &["packagegroup-core-nfs-client"]),
|
||||
("ssh-server-dropbear", &["packagegroup-core-ssh-dropbear"]),
|
||||
("ssh-server-openssh", &["packagegroup-core-ssh-openssh"]),
|
||||
];
|
||||
|
||||
/// The image features whose packages a variable of the build sets.
|
||||
const VARIABLE_FEATURES: &[&str] = &["hwcodecs", "package-management", "splash"];
|
||||
|
||||
/// The packages BitBake makes of every recipe by default (`PACKAGES` in
|
||||
/// bitbake.conf), by their suffix: `busybox-dev` comes from `busybox`.
|
||||
const DEFAULT_PACKAGE_SUFFIXES: &[&str] = &[
|
||||
"-src",
|
||||
"-dbg",
|
||||
"-staticdev",
|
||||
"-dev",
|
||||
"-doc",
|
||||
"-locale",
|
||||
"-ptest",
|
||||
];
|
||||
|
||||
/// What the image recipes declare, by recipe.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Declarations {
|
||||
/// Per recipe (BPN), the images that declare it.
|
||||
pub images: BTreeMap<String, BTreeSet<String>>,
|
||||
/// What an image names that is not a recipe or package group in the tree
|
||||
/// (`packagegroup-core-boot`, `ssh-server-dropbear (IMAGE_FEATURES)`).
|
||||
pub unresolved: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Maps the package names of the tree to their recipes and package groups.
|
||||
struct PackageIndex<'a> {
|
||||
/// Package (and recipe) name to BPN.
|
||||
recipes: HashMap<&'a str, &'a str>,
|
||||
/// Package of a package group to what it pulls in.
|
||||
groups: HashMap<&'a str, &'a [String]>,
|
||||
/// Every package and name of the package groups.
|
||||
group_names: BTreeSet<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> PackageIndex<'a> {
|
||||
fn new(inventory: &'a Inventory) -> Self {
|
||||
let mut recipes = HashMap::new();
|
||||
// A package PACKAGES names, unless a recipe of that name exists.
|
||||
for recipe in &inventory.recipes {
|
||||
for package in &recipe.packages {
|
||||
recipes
|
||||
.entry(package.as_str())
|
||||
.or_insert(recipe.bpn.as_str());
|
||||
}
|
||||
}
|
||||
for recipe in &inventory.recipes {
|
||||
recipes.insert(recipe.pn.as_str(), recipe.bpn.as_str());
|
||||
recipes.insert(recipe.bpn.as_str(), recipe.bpn.as_str());
|
||||
}
|
||||
let mut groups = HashMap::new();
|
||||
let mut group_names = BTreeSet::new();
|
||||
for group in &inventory.packagegroups {
|
||||
group_names.insert(group.pn.as_str());
|
||||
group_names.extend(group.packages.iter().map(String::as_str));
|
||||
for (package, pulled) in &group.rdepends {
|
||||
group_names.insert(package.as_str());
|
||||
groups.insert(package.as_str(), pulled.as_slice());
|
||||
}
|
||||
}
|
||||
Self {
|
||||
recipes,
|
||||
groups,
|
||||
group_names,
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe (BPN) that makes `package`: a recipe of that name, a
|
||||
/// package its PACKAGES names, or a default package (`-dev`, `-dbg`).
|
||||
fn recipe_of(&self, package: &str) -> Option<&'a str> {
|
||||
self.recipes.get(package).copied().or_else(|| {
|
||||
DEFAULT_PACKAGE_SUFFIXES.iter().find_map(|suffix| {
|
||||
package
|
||||
.strip_suffix(suffix)
|
||||
.and_then(|base| self.recipes.get(base).copied())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The recipes `name` installs: itself, or, for a package group, the
|
||||
/// recipes it pulls in (one level: a group in a group is not expanded).
|
||||
/// What is not in the tree goes to `unresolved`.
|
||||
fn install(
|
||||
&self,
|
||||
name: &str,
|
||||
found: &mut BTreeSet<&'a str>,
|
||||
unresolved: &mut BTreeSet<String>,
|
||||
) {
|
||||
if let Some(pulled) = self.groups.get(name) {
|
||||
for package in pulled.iter() {
|
||||
match self.recipe_of(package) {
|
||||
Some(bpn) => {
|
||||
found.insert(bpn);
|
||||
}
|
||||
None if self.group_names.contains(package.as_str()) => {
|
||||
unresolved.insert(format!("{package} (a package group in {name})"));
|
||||
}
|
||||
None => {
|
||||
unresolved.insert(format!("{package} (in {name})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(bpn) = self.recipe_of(name) {
|
||||
found.insert(bpn);
|
||||
} else if !self.group_names.contains(name) {
|
||||
unresolved.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipes the image `feature` installs through its package groups,
|
||||
/// where they are in the tree.
|
||||
fn feature(
|
||||
&self,
|
||||
feature: &str,
|
||||
found: &mut BTreeSet<&'a str>,
|
||||
unresolved: &mut BTreeSet<String>,
|
||||
) {
|
||||
if VARIABLE_FEATURES.contains(&feature) {
|
||||
unresolved.insert(format!("{feature} (IMAGE_FEATURES)"));
|
||||
return;
|
||||
}
|
||||
let Some((_, groups)) = FEATURE_PACKAGES.iter().find(|(f, _)| *f == feature) else {
|
||||
return;
|
||||
};
|
||||
for group in groups.iter() {
|
||||
if self.group_names.contains(group) {
|
||||
self.install(group, found, unresolved);
|
||||
} else {
|
||||
unresolved.insert(format!("{feature} (IMAGE_FEATURES)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which recipes of `inventory` the images declare: what IMAGE_INSTALL (and
|
||||
/// CORE_IMAGE_EXTRA_INSTALL) names, the package groups among them expanded
|
||||
/// one level, and the package groups of IMAGE_FEATURES where they are in the
|
||||
/// tree. A local.conf.sample or distro configuration declares for every
|
||||
/// image; with no image recipe in the tree, under its own file name.
|
||||
pub fn declared_in_images(inventory: &Inventory) -> Declarations {
|
||||
let index = PackageIndex::new(inventory);
|
||||
let all_images: Vec<&str> = inventory.images.iter().map(|i| i.pn.as_str()).collect();
|
||||
let declarers = inventory
|
||||
.images
|
||||
.iter()
|
||||
.map(|i| (vec![i.pn.as_str()], &i.install, &i.features))
|
||||
.chain(inventory.configs.iter().map(|c| {
|
||||
let images = if all_images.is_empty() {
|
||||
vec![c.file.as_str()]
|
||||
} else {
|
||||
all_images.clone()
|
||||
};
|
||||
(images, &c.install, &c.features)
|
||||
}));
|
||||
let mut declarations = Declarations::default();
|
||||
for (images, install, features) in declarers {
|
||||
let mut found = BTreeSet::new();
|
||||
for name in install {
|
||||
index.install(name, &mut found, &mut declarations.unresolved);
|
||||
}
|
||||
for feature in features {
|
||||
index.feature(feature, &mut found, &mut declarations.unresolved);
|
||||
}
|
||||
for bpn in found {
|
||||
declarations
|
||||
.images
|
||||
.entry(bpn.to_string())
|
||||
.or_default()
|
||||
.extend(images.iter().map(|i| i.to_string()));
|
||||
}
|
||||
}
|
||||
declarations
|
||||
}
|
||||
|
||||
/// The SBOM components of `recipes`, one per base recipe name and version,
|
||||
/// marked with the images that declare them.
|
||||
pub fn entries(recipes: &[Recipe], declarations: &Declarations, repo_id: &str) -> Vec<SbomEntry> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::with_capacity(recipes.len());
|
||||
for recipe in recipes {
|
||||
@@ -451,6 +760,13 @@ pub fn entries(recipes: &[Recipe], repo_id: &str) -> Vec<SbomEntry> {
|
||||
evidence.push_str(&format!(" (+ {})", recipe.appends.join(", ")));
|
||||
}
|
||||
entry.evidence.push(evidence);
|
||||
entry.in_image = declarations.images.get(&recipe.bpn).map(|images| InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: images.iter().cloned().collect(),
|
||||
});
|
||||
if let Some(in_image) = &entry.in_image {
|
||||
entry.evidence.push(in_image.describe());
|
||||
}
|
||||
out.push(entry);
|
||||
}
|
||||
out
|
||||
@@ -692,7 +1008,11 @@ mod tests {
|
||||
|
||||
let mut busybox = recipe("busybox", Some("1.35.0"));
|
||||
busybox.cve_version = Some("1.35".into());
|
||||
let entry = &entries(std::slice::from_ref(&busybox), "t")[0];
|
||||
let entry = &entries(
|
||||
std::slice::from_ref(&busybox),
|
||||
&Declarations::default(),
|
||||
"t",
|
||||
)[0];
|
||||
assert_eq!(
|
||||
entry.cpe.as_deref(),
|
||||
Some("cpe:2.3:a:*:busybox:1.35:*:*:*:*:*:*:*")
|
||||
@@ -705,7 +1025,7 @@ mod tests {
|
||||
let mut r = recipe("busybox", Some("1.35.0"));
|
||||
r.license = Some("GPL-2.0-only & bzip2-1.0.4".into());
|
||||
r.appends = vec!["recipes-core/busybox/busybox_%.bbappend".into()];
|
||||
let entries = entries(&[r.clone(), r], "t");
|
||||
let entries = entries(&[r.clone(), r], &Declarations::default(), "t");
|
||||
assert_eq!(entries.len(), 1, "one component per name and version");
|
||||
let entry = &entries[0];
|
||||
assert_eq!(entry.package_manager, YOCTO_RECIPE_MANAGER);
|
||||
@@ -860,10 +1180,222 @@ mod tests {
|
||||
assert_eq!(inventory.errors.len(), 1);
|
||||
}
|
||||
|
||||
/// The helper on the nightly fixture, where Python and oelint-parser are
|
||||
/// installed (the agent image); skipped elsewhere.
|
||||
fn image(pn: &str, install: &[&str], features: &[&str]) -> ImageRecipe {
|
||||
ImageRecipe {
|
||||
file: format!("recipes-core/images/{pn}.bb"),
|
||||
pn: pn.into(),
|
||||
install: install.iter().map(|w| w.to_string()).collect(),
|
||||
features: features.iter().map(|w| w.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(pn: &str, rdepends: &[(&str, &[&str])]) -> PackageGroup {
|
||||
PackageGroup {
|
||||
file: format!("recipes-core/packagegroups/{pn}.bb"),
|
||||
pn: pn.into(),
|
||||
packages: rdepends.iter().map(|(p, _)| p.to_string()).collect(),
|
||||
rdepends: rdepends
|
||||
.iter()
|
||||
.map(|(p, words)| (p.to_string(), words.iter().map(|w| w.to_string()).collect()))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn declared(declarations: &Declarations) -> Vec<(&str, Vec<&str>)> {
|
||||
declarations
|
||||
.images
|
||||
.iter()
|
||||
.map(|(bpn, images)| (bpn.as_str(), images.iter().map(String::as_str).collect()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_helper_reads_the_fixture() {
|
||||
fn a_package_maps_to_the_recipe_that_makes_it() {
|
||||
let mut web = recipe("pump-web", Some("2.1"));
|
||||
web.packages = vec!["pump-web-ui".into(), "libpumpweb".into()];
|
||||
let inventory = Inventory {
|
||||
recipes: vec![
|
||||
web,
|
||||
recipe("busybox", Some("1.35.0")),
|
||||
recipe("libpumpweb", None),
|
||||
],
|
||||
..Inventory::default()
|
||||
};
|
||||
let index = PackageIndex::new(&inventory);
|
||||
assert_eq!(index.recipe_of("pump-web"), Some("pump-web"));
|
||||
assert_eq!(index.recipe_of("pump-web-ui"), Some("pump-web"), "PACKAGES");
|
||||
assert_eq!(
|
||||
index.recipe_of("busybox-dev"),
|
||||
Some("busybox"),
|
||||
"a default package"
|
||||
);
|
||||
assert_eq!(index.recipe_of("busybox-ptest"), Some("busybox"));
|
||||
assert_eq!(
|
||||
index.recipe_of("libpumpweb"),
|
||||
Some("libpumpweb"),
|
||||
"a recipe of that name wins over another recipe's PACKAGES"
|
||||
);
|
||||
assert_eq!(index.recipe_of("busybox-extra"), None);
|
||||
assert_eq!(index.recipe_of("openssh"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_group_is_expanded_one_level() {
|
||||
let mut ctl = recipe("pump-ctl", Some("1.0"));
|
||||
ctl.packages = vec!["pump-ctl-tools".into()];
|
||||
let inventory = Inventory {
|
||||
recipes: vec![
|
||||
ctl,
|
||||
recipe("pump-web", Some("2.1")),
|
||||
recipe("libmodbus", Some("3.1.6")),
|
||||
recipe("pump-fw", Some("1.0")),
|
||||
],
|
||||
images: vec![image("pump-image", &["packagegroup-pump", "busybox"], &[])],
|
||||
packagegroups: vec![
|
||||
group(
|
||||
"packagegroup-pump",
|
||||
&[
|
||||
(
|
||||
"packagegroup-pump",
|
||||
&["pump-ctl-tools", "packagegroup-base", "zlib"],
|
||||
),
|
||||
("packagegroup-pump-web", &["pump-web"]),
|
||||
],
|
||||
),
|
||||
group(
|
||||
"packagegroup-base",
|
||||
&[("packagegroup-base", &["libmodbus"])],
|
||||
),
|
||||
],
|
||||
..Inventory::default()
|
||||
};
|
||||
let declarations = declared_in_images(&inventory);
|
||||
assert_eq!(
|
||||
declared(&declarations),
|
||||
[("pump-ctl", vec!["pump-image"])],
|
||||
"only the package the image names (not -web), and not the group inside the group"
|
||||
);
|
||||
assert_eq!(
|
||||
declarations.unresolved.iter().collect::<Vec<_>>(),
|
||||
[
|
||||
"busybox",
|
||||
"packagegroup-base (a package group in packagegroup-pump)",
|
||||
"zlib (in packagegroup-pump)"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_features_install_their_package_groups_only_when_in_the_tree() {
|
||||
let inventory = Inventory {
|
||||
recipes: vec![recipe("dropbear", Some("2022.83"))],
|
||||
images: vec![image(
|
||||
"pump-image",
|
||||
&[],
|
||||
&[
|
||||
"ssh-server-dropbear",
|
||||
"tools-debug",
|
||||
"splash",
|
||||
"debug-tweaks",
|
||||
],
|
||||
)],
|
||||
packagegroups: vec![group(
|
||||
"packagegroup-core-ssh-dropbear",
|
||||
&[("packagegroup-core-ssh-dropbear", &["dropbear"])],
|
||||
)],
|
||||
..Inventory::default()
|
||||
};
|
||||
let declarations = declared_in_images(&inventory);
|
||||
assert_eq!(declared(&declarations), [("dropbear", vec!["pump-image"])]);
|
||||
assert_eq!(
|
||||
declarations.unresolved.iter().collect::<Vec<_>>(),
|
||||
["splash (IMAGE_FEATURES)", "tools-debug (IMAGE_FEATURES)"],
|
||||
"debug-tweaks installs nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configuration_declares_for_every_image_or_under_its_own_name() {
|
||||
let config = ImageConfig {
|
||||
file: "conf/local.conf.sample".into(),
|
||||
install: vec!["busybox".into()],
|
||||
features: Vec::new(),
|
||||
};
|
||||
let mut inventory = Inventory {
|
||||
recipes: vec![recipe("busybox", Some("1.35.0")), recipe("pump-ctl", None)],
|
||||
images: vec![
|
||||
image("pump-image", &["pump-ctl"], &[]),
|
||||
image("rescue-image", &[], &[]),
|
||||
],
|
||||
configs: vec![config],
|
||||
..Inventory::default()
|
||||
};
|
||||
assert_eq!(
|
||||
declared(&declared_in_images(&inventory)),
|
||||
[
|
||||
("busybox", vec!["pump-image", "rescue-image"]),
|
||||
("pump-ctl", vec!["pump-image"]),
|
||||
]
|
||||
);
|
||||
inventory.images.clear();
|
||||
assert_eq!(
|
||||
declared(&declared_in_images(&inventory)),
|
||||
[("busybox", vec!["conf/local.conf.sample"])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_names_are_kept_from_what_an_image_declares() {
|
||||
let json = br#"{"recipes": [{"file": "a.bb", "pn": "a", "bpn": "a",
|
||||
"packages": ["a-tools", "^a-plugin-.*"]}],
|
||||
"images": [{"file": "i.bb", "pn": "i",
|
||||
"install": ["a", "${CORE_IMAGE_BASE_INSTALL}", "'", "d)}", "libstdc++", "python3.12"],
|
||||
"features": ["debug-tweaks"]}],
|
||||
"packagegroups": [{"file": "p.bb", "pn": "p", "packages": ["p"],
|
||||
"rdepends": {"p": ["a (>= 1.0)", "a"]}}]}"#;
|
||||
let inventory = parse(json).expect("the helper's shape");
|
||||
assert_eq!(inventory.recipes[0].packages, ["a-tools"]);
|
||||
assert_eq!(
|
||||
inventory.images[0].install,
|
||||
["a", "libstdc++", "python3.12"]
|
||||
);
|
||||
assert_eq!(inventory.packagegroups[0].rdepends["p"], ["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_recipe_is_marked_with_its_images_and_says_so() {
|
||||
let mut declarations = Declarations::default();
|
||||
declarations.images.insert(
|
||||
"busybox".into(),
|
||||
["pump-image".to_string(), "rescue-image".to_string()].into(),
|
||||
);
|
||||
let entries = entries(
|
||||
&[
|
||||
recipe("busybox", Some("1.35.0")),
|
||||
recipe("pump-fw", Some("1.0")),
|
||||
],
|
||||
&declarations,
|
||||
"t",
|
||||
);
|
||||
assert_eq!(
|
||||
entries[0].in_image,
|
||||
Some(InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: vec!["pump-image".into(), "rescue-image".into()],
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
entries[0].evidence[1],
|
||||
"In the image (declared in the recipes, not resolved by bitbake): pump-image, \
|
||||
rescue-image"
|
||||
);
|
||||
assert_eq!(entries[1].in_image, None);
|
||||
assert_eq!(entries[1].evidence.len(), 1);
|
||||
}
|
||||
|
||||
/// The helper's reading of `tree`, where Python and oelint-parser are
|
||||
/// installed (the agent image); `None` elsewhere, and the test passes.
|
||||
fn run_helper(tree: &Path) -> Option<Inventory> {
|
||||
let helper =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../docker/pruefwerk_yocto_recipes.py");
|
||||
let available = std::process::Command::new("python3")
|
||||
@@ -872,12 +1404,12 @@ mod tests {
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !available {
|
||||
eprintln!("skipped: python3 with oelint-parser is not installed");
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let output = std::process::Command::new("python3")
|
||||
.arg("-I")
|
||||
.args(["-I", "-B"])
|
||||
.arg(&helper)
|
||||
.arg(fixture())
|
||||
.arg(tree)
|
||||
.output()
|
||||
.expect("the helper runs");
|
||||
assert!(
|
||||
@@ -885,7 +1417,98 @@ mod tests {
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let inventory = parse(&output.stdout).expect("the helper's shape");
|
||||
Some(parse(&output.stdout).expect("the helper's shape"))
|
||||
}
|
||||
|
||||
/// Every way an install is written: `=`, `+=`, `:append`, the old
|
||||
/// `_append` (which oelint-parser splits only in a file without `:`
|
||||
/// overrides), an override's append, `:remove`, inline Python and a
|
||||
/// variable; old-syntax RDEPENDS of a package group; and a configuration.
|
||||
#[test]
|
||||
fn the_helper_reads_what_images_declare_in_every_syntax() {
|
||||
let t = crate::pipeline::recipe_lint::tests::tree(&[
|
||||
("conf/layer.conf", "BBFILE_COLLECTIONS += \"t\"\n"),
|
||||
(
|
||||
"conf/local.conf.sample",
|
||||
"CORE_IMAGE_EXTRA_INSTALL += \"conf-tool\"\nIMAGE_INSTALL_append = \" old-conf\"\n",
|
||||
),
|
||||
(
|
||||
"recipes-core/images/new-image.bb",
|
||||
"inherit core-image\n\
|
||||
IMAGE_INSTALL = \"a b gone\"\n\
|
||||
IMAGE_INSTALL += \"c\"\n\
|
||||
IMAGE_INSTALL:append = \" d ${@bb.utils.contains('DISTRO_FEATURES', 'x11', 'xterm', '', d)}\"\n\
|
||||
IMAGE_INSTALL_append = \" e\"\n\
|
||||
IMAGE_INSTALL:append:qemux86 = \" f\"\n\
|
||||
IMAGE_INSTALL:remove = \"gone\"\n\
|
||||
IMAGE_INSTALL += \"${UNSET_VARIABLE}\"\n\
|
||||
IMAGE_FEATURES += \"ssh-server-openssh\"\n\
|
||||
IMAGE_FEATURES_REPLACES_ssh-server-openssh = \"ssh-server-dropbear\"\n",
|
||||
),
|
||||
(
|
||||
"recipes-core/images/old-image.bb",
|
||||
"inherit image\nIMAGE_INSTALL = \"a\"\nIMAGE_INSTALL_append = \" g\"\n",
|
||||
),
|
||||
(
|
||||
"recipes-core/packagegroups/packagegroup-old.bb",
|
||||
"inherit packagegroup\n\
|
||||
PACKAGES = \"${PN} ${PN}-extra\"\n\
|
||||
RDEPENDS_${PN} = \"a (>= 1.0)\"\n\
|
||||
RDEPENDS_${PN}-extra = \"b\"\n\
|
||||
RDEPENDS_${PN}-extra_append = \" c\"\n\
|
||||
RRECOMMENDS_${PN} += \"d\"\n",
|
||||
),
|
||||
(
|
||||
"recipes-core/a/a_1.0.bb",
|
||||
"PACKAGES =+ \"${PN}-tools\"\nPACKAGES_DYNAMIC = \"a-plugin-x\"\n",
|
||||
),
|
||||
]);
|
||||
let Some(inventory) = run_helper(&t.0) else {
|
||||
return;
|
||||
};
|
||||
assert!(inventory.errors.is_empty(), "{:?}", inventory.errors);
|
||||
let installs: Vec<(&str, Vec<&str>)> = inventory
|
||||
.images
|
||||
.iter()
|
||||
.map(|i| {
|
||||
(
|
||||
i.pn.as_str(),
|
||||
i.install.iter().map(String::as_str).collect(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
installs,
|
||||
[
|
||||
("new-image", vec!["a", "b", "c", "d", "e", "f"]),
|
||||
("old-image", vec!["a", "g"]),
|
||||
],
|
||||
"the inline Python and the unset variable are left out"
|
||||
);
|
||||
assert_eq!(inventory.images[0].features, ["ssh-server-openssh"]);
|
||||
assert_eq!(inventory.configs.len(), 1);
|
||||
assert_eq!(inventory.configs[0].install, ["old-conf", "conf-tool"]);
|
||||
let group = &inventory.packagegroups[0];
|
||||
assert_eq!(
|
||||
group.packages,
|
||||
["packagegroup-old", "packagegroup-old-extra"]
|
||||
);
|
||||
assert_eq!(group.rdepends["packagegroup-old"], ["a", "d"]);
|
||||
assert_eq!(group.rdepends["packagegroup-old-extra"], ["b", "c"]);
|
||||
assert_eq!(
|
||||
inventory.recipes[0].packages,
|
||||
["a-tools"],
|
||||
"PACKAGES_DYNAMIC is not PACKAGES"
|
||||
);
|
||||
}
|
||||
|
||||
/// The helper on the nightly fixture, where Python and oelint-parser are
|
||||
/// installed (the agent image); skipped elsewhere.
|
||||
#[test]
|
||||
fn the_helper_reads_the_fixture() {
|
||||
let Some(inventory) = run_helper(&fixture()) else {
|
||||
return;
|
||||
};
|
||||
assert!(inventory.errors.is_empty(), "{:?}", inventory.errors);
|
||||
|
||||
let names: Vec<&str> = inventory.recipes.iter().map(|r| r.bpn.as_str()).collect();
|
||||
@@ -917,7 +1540,39 @@ mod tests {
|
||||
);
|
||||
assert_eq!(busybox.patches[0].cves, ["CVE-2022-30065"]);
|
||||
|
||||
let entries = entries(&inventory.recipes, "t");
|
||||
assert_eq!(inventory.images.len(), 1);
|
||||
assert_eq!(inventory.images[0].pn, "pump-image");
|
||||
assert_eq!(
|
||||
inventory.images[0].install,
|
||||
[
|
||||
"packagegroup-core-boot",
|
||||
"busybox",
|
||||
"libmodbus",
|
||||
"pump-ctl",
|
||||
"packagegroup-pump"
|
||||
],
|
||||
"IMAGE_INSTALL and its :append"
|
||||
);
|
||||
assert_eq!(inventory.packagegroups[0].pn, "packagegroup-pump");
|
||||
assert_eq!(inventory.recipes[2].packages, ["pump-web-ui"]);
|
||||
let declarations = declared_in_images(&inventory);
|
||||
let declared: Vec<&str> = declarations.images.keys().map(String::as_str).collect();
|
||||
assert_eq!(
|
||||
declared,
|
||||
["busybox", "libmodbus", "pump-ctl", "pump-web"],
|
||||
"pump-fw is in no image"
|
||||
);
|
||||
assert_eq!(
|
||||
declarations.unresolved.iter().collect::<Vec<_>>(),
|
||||
[
|
||||
"packagegroup-core-boot",
|
||||
"ssh-server-dropbear (IMAGE_FEATURES)"
|
||||
]
|
||||
);
|
||||
|
||||
let entries = entries(&inventory.recipes, &declarations, "t");
|
||||
let in_image: Vec<bool> = entries.iter().map(|e| e.in_image.is_some()).collect();
|
||||
assert_eq!(in_image, [true, false, true, true, true]);
|
||||
let purls: Vec<&str> = entries.iter().filter_map(|e| e.purl.as_deref()).collect();
|
||||
assert_eq!(
|
||||
purls,
|
||||
|
||||
@@ -3,4 +3,5 @@ mod dast;
|
||||
mod findings;
|
||||
mod health;
|
||||
mod onboarding;
|
||||
mod sbom;
|
||||
mod stats;
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::common::TestServer;
|
||||
use compliance_core::models::{InImage, InImageBasis, SbomEntry, YOCTO_RECIPE_MANAGER};
|
||||
|
||||
/// A Yocto recipe component, in `pump-image` when `in_image`.
|
||||
fn recipe(name: &str, in_image: bool) -> SbomEntry {
|
||||
let mut entry = SbomEntry::new(
|
||||
"yocto-target".into(),
|
||||
name.into(),
|
||||
"1.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
entry.purl = Some(format!("pkg:generic/{name}@1.0"));
|
||||
entry.in_image = in_image.then(|| InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: vec!["pump-image".into()],
|
||||
});
|
||||
entry
|
||||
}
|
||||
|
||||
/// The names of the components a list request returns, in its order.
|
||||
async fn names(server: &TestServer, query: &str) -> Vec<String> {
|
||||
let resp = server
|
||||
.get(&format!("/api/v1/sbom?repo_id=yocto-target{query}"))
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
body["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e["name"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_sbom_lists_components_in_the_image_first_and_filters_by_it() {
|
||||
let server = TestServer::start().await;
|
||||
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
|
||||
// The dev tenant's database, which the API reads.
|
||||
let db = client.database(&format!("{}_dev", server.db_name()));
|
||||
let entries = [
|
||||
recipe("aaa-tools", false),
|
||||
recipe("busybox", true),
|
||||
recipe("pump-fw", false),
|
||||
recipe("zlib", true),
|
||||
];
|
||||
db.collection::<SbomEntry>("sbom_entries")
|
||||
.insert_many(&entries)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
names(&server, "").await,
|
||||
["busybox", "zlib", "aaa-tools", "pump-fw"],
|
||||
"nothing is dropped; the image's components come first"
|
||||
);
|
||||
assert_eq!(names(&server, "&in_image=true").await, ["busybox", "zlib"]);
|
||||
assert_eq!(
|
||||
names(&server, "&in_image=false").await,
|
||||
["aaa-tools", "pump-fw"]
|
||||
);
|
||||
|
||||
let resp = server
|
||||
.get("/api/v1/sbom/export?repo_id=yocto-target&format=cyclonedx")
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let cdx: serde_json::Value = resp.json().await.unwrap();
|
||||
let busybox = cdx["components"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|c| c["name"] == "busybox")
|
||||
.expect("busybox");
|
||||
assert!(busybox["properties"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(
|
||||
|p| p["name"] == "pruefwerk:component:in_image" && p["value"] == "declared: pump-image"
|
||||
));
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -331,7 +331,8 @@ struct Snapshot {
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
error: String,
|
||||
skipped_stages: BTreeSet<String>,
|
||||
/// `package_manager:name@version`, compared exactly.
|
||||
/// `package_manager:name@version`, with ` [in image: <images>]` for a
|
||||
/// component an image declares, compared exactly.
|
||||
sbom: BTreeSet<String>,
|
||||
/// Deterministic findings as `scanner:rule file:line`, compared exactly.
|
||||
findings: BTreeSet<String>,
|
||||
@@ -477,8 +478,15 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected {
|
||||
}
|
||||
}
|
||||
for e in &sbom {
|
||||
let in_image = e["in_image"]["images"]
|
||||
.as_array()
|
||||
.map(|images| {
|
||||
let names: Vec<&str> = images.iter().filter_map(Value::as_str).collect();
|
||||
format!(" [in image: {}]", names.join(", "))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
snapshot.sbom.insert(format!(
|
||||
"{}:{}@{}",
|
||||
"{}:{}@{}{in_image}",
|
||||
text(e, "package_manager"),
|
||||
text(e, "name"),
|
||||
text(e, "version")
|
||||
|
||||
@@ -64,8 +64,8 @@ pub use pentest::{
|
||||
pub use project::{Project, ProjectKind};
|
||||
pub use repository::ScanTrigger;
|
||||
pub use sbom::{
|
||||
ComponentHash, SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef,
|
||||
YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
ComponentHash, InImage, InImageBasis, SbomEntry, SbomQuality, SbomQualityCheck,
|
||||
SbomQualityProfile, VulnRef, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE,
|
||||
};
|
||||
pub use scan::{
|
||||
RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage,
|
||||
|
||||
@@ -33,6 +33,48 @@ pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe";
|
||||
/// an image contains.
|
||||
pub const YOCTO_RECIPE_SOURCE: &str = "Yocto recipe inventory (not the image SBOM)";
|
||||
|
||||
/// How a component is known to be in the product's image.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InImageBasis {
|
||||
/// An image recipe names it (IMAGE_INSTALL, a package group it installs),
|
||||
/// read from the recipes without BitBake: what the image declares, not
|
||||
/// what a build resolved.
|
||||
Declared,
|
||||
}
|
||||
|
||||
impl InImageBasis {
|
||||
/// Its stored name (`declared`).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Declared => "declared",
|
||||
}
|
||||
}
|
||||
|
||||
/// How the exports and the evidence say it.
|
||||
pub fn describe(self) -> &'static str {
|
||||
match self {
|
||||
Self::Declared => "In the image (declared in the recipes, not resolved by bitbake)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The images a component is in, and how that is known.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct InImage {
|
||||
pub basis: InImageBasis,
|
||||
/// The image recipes (`pump-image`) that install it, or the
|
||||
/// configuration file that does for every image (`conf/local.conf.sample`).
|
||||
pub images: Vec<String>,
|
||||
}
|
||||
|
||||
impl InImage {
|
||||
/// `In the image (declared …): pump-image, rescue-image`.
|
||||
pub fn describe(&self) -> String {
|
||||
format!("{}: {}", self.basis.describe(), self.images.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SbomEntry {
|
||||
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||
@@ -72,6 +114,11 @@ pub struct SbomEntry {
|
||||
/// advisory database could look up (a Yocto recipe's CVE_PRODUCT).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpe: Option<String>,
|
||||
/// The images the component is in, where that is known (a Yocto recipe
|
||||
/// an image recipe installs); `None` when it is not, and on components
|
||||
/// stored before it was recorded.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub in_image: Option<InImage>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub created_at: DateTime<Utc>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
@@ -105,6 +152,7 @@ impl SbomEntry {
|
||||
download_url: None,
|
||||
manufacturer_url: None,
|
||||
cpe: None,
|
||||
in_image: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -241,6 +241,10 @@ pub enum SkipCode {
|
||||
/// (`# nooelint` in a Yocto recipe), so they are not shown; `subject` is
|
||||
/// how many.
|
||||
SuppressedInSource,
|
||||
/// Names an image recipe declares it installs that are not recipes or
|
||||
/// package groups in the scanned tree (they come from layers that are not
|
||||
/// in it, such as Poky's); `subject` lists them.
|
||||
NotInTree,
|
||||
}
|
||||
|
||||
/// Why a scan run failed, stable for the dashboard to word.
|
||||
|
||||
@@ -90,11 +90,41 @@ fn bsi_properties(purl: &Purl) -> Option<serde_json::Value> {
|
||||
/// necessarily in the image.
|
||||
const SOURCE_PROPERTY: &str = "pruefwerk:component:source";
|
||||
|
||||
/// The property naming the images a component is in and how that is known
|
||||
/// (`declared: pump-image`).
|
||||
const IN_IMAGE_PROPERTY: &str = "pruefwerk:component:in_image";
|
||||
|
||||
/// Where `entry` comes from, when the reader must know it to weigh it.
|
||||
fn source_note(entry: &SbomEntry) -> Option<&'static str> {
|
||||
(entry.package_manager == YOCTO_RECIPE_MANAGER).then_some(YOCTO_RECIPE_SOURCE)
|
||||
}
|
||||
|
||||
/// The CycloneDX properties saying where `entry` comes from and which images
|
||||
/// it is in.
|
||||
fn provenance_properties(entry: &SbomEntry) -> Vec<serde_json::Value> {
|
||||
let source = source_note(entry)
|
||||
.map(|source| serde_json::json!({ "name": SOURCE_PROPERTY, "value": source }));
|
||||
let in_image = entry.in_image.as_ref().map(|in_image| {
|
||||
let value = format!(
|
||||
"{}: {}",
|
||||
in_image.basis.as_str(),
|
||||
in_image.images.join(", ")
|
||||
);
|
||||
serde_json::json!({ "name": IN_IMAGE_PROPERTY, "value": value })
|
||||
});
|
||||
source.into_iter().chain(in_image).collect()
|
||||
}
|
||||
|
||||
/// The SPDX package comment saying the same: the source, and the images.
|
||||
fn provenance_comment(entry: &SbomEntry) -> Option<String> {
|
||||
let notes: Vec<String> = source_note(entry)
|
||||
.map(str::to_string)
|
||||
.into_iter()
|
||||
.chain(entry.in_image.as_ref().map(|in_image| in_image.describe()))
|
||||
.collect();
|
||||
(!notes.is_empty()).then(|| notes.join(". "))
|
||||
}
|
||||
|
||||
/// A CycloneDX severity from an advisory's (`HIGH`, `MODERATE`, `critical`).
|
||||
pub fn cdx_severity(severity: &str) -> &'static str {
|
||||
match severity.trim().to_ascii_lowercase().as_str() {
|
||||
@@ -145,11 +175,11 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
||||
if let Some(cpe) = &e.cpe {
|
||||
comp["cpe"] = serde_json::Value::String(cpe.clone());
|
||||
}
|
||||
if let Some(source) = source_note(e) {
|
||||
let property = serde_json::json!({ "name": SOURCE_PROPERTY, "value": source });
|
||||
let provenance = provenance_properties(e);
|
||||
if !provenance.is_empty() {
|
||||
match comp["properties"].as_array_mut() {
|
||||
Some(properties) => properties.push(property),
|
||||
None => comp["properties"] = serde_json::json!([property]),
|
||||
Some(properties) => properties.extend(provenance),
|
||||
None => comp["properties"] = serde_json::Value::Array(provenance),
|
||||
}
|
||||
}
|
||||
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
||||
@@ -377,8 +407,8 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||
"referenceLocator": cpe,
|
||||
}));
|
||||
}
|
||||
if let Some(source) = source_note(e) {
|
||||
package["comment"] = serde_json::Value::String(source.to_string());
|
||||
if let Some(comment) = provenance_comment(e) {
|
||||
package["comment"] = serde_json::Value::String(comment);
|
||||
}
|
||||
package
|
||||
})
|
||||
@@ -397,6 +427,7 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::models::{InImage, InImageBasis};
|
||||
|
||||
#[test]
|
||||
fn both_formats_list_every_component() {
|
||||
@@ -483,4 +514,48 @@ mod tests {
|
||||
assert_eq!(package["externalRefs"][1]["referenceType"], "cpe23Type");
|
||||
assert!(spdx["packages"][1].get("comment").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recipe_an_image_installs_says_so_in_both_formats() {
|
||||
let mut recipe = SbomEntry::new(
|
||||
"t".into(),
|
||||
"busybox".into(),
|
||||
"1.35.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
recipe.in_image = Some(InImage {
|
||||
basis: InImageBasis::Declared,
|
||||
images: vec!["pump-image".into(), "rescue-image".into()],
|
||||
});
|
||||
let inventory_only = SbomEntry::new(
|
||||
"t".into(),
|
||||
"pump-fw".into(),
|
||||
"1.0".into(),
|
||||
YOCTO_RECIPE_MANAGER.into(),
|
||||
);
|
||||
let entries = [recipe, inventory_only];
|
||||
|
||||
let cdx = cyclonedx(&entries, "t");
|
||||
assert_eq!(
|
||||
cdx["components"][0]["properties"],
|
||||
serde_json::json!([
|
||||
{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE },
|
||||
{ "name": IN_IMAGE_PROPERTY, "value": "declared: pump-image, rescue-image" },
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
cdx["components"][1]["properties"],
|
||||
serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }])
|
||||
);
|
||||
|
||||
let spdx = spdx(&entries, "t");
|
||||
assert_eq!(
|
||||
spdx["packages"][0]["comment"],
|
||||
format!(
|
||||
"{YOCTO_RECIPE_SOURCE}. In the image (declared in the recipes, not resolved \
|
||||
by bitbake): pump-image, rescue-image"
|
||||
)
|
||||
);
|
||||
assert_eq!(spdx["packages"][1]["comment"], YOCTO_RECIPE_SOURCE);
|
||||
}
|
||||
}
|
||||
@@ -505,6 +505,10 @@ pub mod scans {
|
||||
de: "Rezept-Prüfung: unterdrückte Befunde",
|
||||
en: "Recipe lint: suppressed findings",
|
||||
},
|
||||
"image_install" => Text {
|
||||
de: "Im Image (deklariert)",
|
||||
en: "In the image (declared)",
|
||||
},
|
||||
"recipe_lint_upstream" => Text {
|
||||
de: "Upstream-Layer (Poky, OpenEmbedded, BSP)",
|
||||
en: "Upstream layers (Poky, OpenEmbedded, BSP)",
|
||||
@@ -673,6 +677,16 @@ pub mod scans {
|
||||
"{subject} findings are suppressed by comments in the recipes (# nooelint) and \
|
||||
are not shown."
|
||||
),
|
||||
(SkipCode::NotInTree, Lang::De) => format!(
|
||||
"Von einem Image-Rezept genannt, aber kein Rezept und keine Paketgruppe im \
|
||||
Layer-Baum (aus Layern, die nicht im Baum liegen, etwa Poky), daher nicht \
|
||||
als Komponente markiert: {subject}"
|
||||
),
|
||||
(SkipCode::NotInTree, Lang::En) => format!(
|
||||
"Named by an image recipe but not a recipe or package group in the layer tree \
|
||||
(from layers that are not in it, such as Poky), so not marked as a component: \
|
||||
{subject}"
|
||||
),
|
||||
(SkipCode::PlatformProjectGenerated, Lang::De) => format!(
|
||||
"Für {subject} erzeugt Unity das App-Projekt erst beim Build; es liegt nicht \
|
||||
im Repository. Info.plist bzw. Manifest, Berechtigungen und nativer Code sind \
|
||||
@@ -2082,8 +2096,23 @@ pub mod sbom {
|
||||
en: "Yocto recipe",
|
||||
};
|
||||
pub const YOCTO_RECIPE_HINT: Text = Text {
|
||||
de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides, PACKAGECONFIG und was das Image installiert sind nicht aufgelöst; es listet daher mehr, als das Image enthält.",
|
||||
en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides, PACKAGECONFIG and what the image installs are not resolved, so it lists more than the image contains.",
|
||||
de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides und PACKAGECONFIG sind nicht aufgelöst; es listet daher mehr, als das Image enthält. Was ein Image-Rezept installiert, ist mit „Im Image (deklariert)“ markiert.",
|
||||
en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides and PACKAGECONFIG are not resolved, so it lists more than the image contains. What an image recipe installs is marked \"In the image (declared)\".",
|
||||
};
|
||||
/// A component an image recipe installs (its badge and filter).
|
||||
pub const IN_IMAGE: Text = Text {
|
||||
de: "Im Image (deklariert)",
|
||||
en: "In the image (declared)",
|
||||
};
|
||||
/// The badge's and the filter's tooltip; the badge adds the images.
|
||||
pub const IN_IMAGE_HINT: Text = Text {
|
||||
de: "Aus den Rezepten gelesen (IMAGE_INSTALL, Paketgruppen eine Ebene tief, IMAGE_FEATURES), nicht von BitBake aufgelöst: Overrides, PACKAGECONFIG und von DISTRO_FEATURES abhängige Pakete sind nicht berücksichtigt.",
|
||||
en: "Read from the recipes (IMAGE_INSTALL, package groups one level deep, IMAGE_FEATURES), not resolved by bitbake: overrides, PACKAGECONFIG and packages that depend on DISTRO_FEATURES are not taken into account.",
|
||||
};
|
||||
/// The in-image filter's other choice.
|
||||
pub const ALL_COMPONENTS: Text = Text {
|
||||
de: "Alle Komponenten",
|
||||
en: "All components",
|
||||
};
|
||||
pub const LICENSE: Text = Text {
|
||||
de: "Lizenz",
|
||||
@@ -3520,6 +3549,14 @@ mod skipped_reason_tests {
|
||||
.starts_with("Für Pump Game – iOS (Xcode) erzeugt Unity das App-Projekt erst"));
|
||||
assert!(skipped_reason(&unity, Lang::En)
|
||||
.starts_with("For Pump Game – iOS (Xcode), Unity generates the app project"));
|
||||
let not_in_tree = SkippedStage::new(
|
||||
"image_install",
|
||||
SkipCode::NotInTree,
|
||||
"named by an image but not a recipe or package group in the tree",
|
||||
)
|
||||
.about("packagegroup-core-boot");
|
||||
assert!(skipped_reason(¬_in_tree, Lang::De).ends_with(": packagegroup-core-boot"));
|
||||
assert!(skipped_reason(¬_in_tree, Lang::En).starts_with("Named by an image recipe"));
|
||||
let suppressed = SkippedStage::new(
|
||||
"recipe_lint_suppressed",
|
||||
SkipCode::SuppressedInSource,
|
||||
|
||||
@@ -61,6 +61,9 @@ pub struct SbomEntryData {
|
||||
pub purl: Option<String>,
|
||||
#[serde(default)]
|
||||
pub known_vulnerabilities: Vec<VulnRefData>,
|
||||
/// The images an image recipe declares it in (a Yocto recipe).
|
||||
#[serde(default)]
|
||||
pub in_image: Option<compliance_core::models::InImage>,
|
||||
#[serde(default)]
|
||||
pub created_at: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
@@ -146,6 +149,7 @@ pub async fn fetch_sbom_filtered(
|
||||
q: Option<String>,
|
||||
has_vulns: Option<bool>,
|
||||
license: Option<String>,
|
||||
in_image: Option<bool>,
|
||||
page: u64,
|
||||
) -> Result<SbomListResponse, ServerFnError> {
|
||||
let mut params = vec![format!("page={page}"), "limit=50".to_string()];
|
||||
@@ -172,6 +176,9 @@ pub async fn fetch_sbom_filtered(
|
||||
params.push(format!("license={}", l.replace(' ', "%20")));
|
||||
}
|
||||
}
|
||||
if let Some(in_image) = in_image {
|
||||
params.push(format!("in_image={in_image}"));
|
||||
}
|
||||
|
||||
let path = format!("/api/v1/sbom?{}", params.join("&"));
|
||||
let resp = super::agent_client::agent_get(&path)
|
||||
|
||||
@@ -20,6 +20,8 @@ pub fn SbomPage(target: String) -> Element {
|
||||
let mut search_q = use_signal(String::new);
|
||||
let mut vuln_toggle = use_signal(|| Option::<bool>::None);
|
||||
let mut license_filter = use_signal(String::new);
|
||||
// Only the components an image declares (`Some(true)`), or all.
|
||||
let mut in_image_filter = use_signal(|| Option::<bool>::None);
|
||||
|
||||
// ── Active tab: "packages" | "licenses" | "diff" ──
|
||||
let mut active_tab = use_signal(|| "packages".to_string());
|
||||
@@ -53,6 +55,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
let q = search_q();
|
||||
let hv = vuln_toggle();
|
||||
let lic = license_filter();
|
||||
let in_image = in_image_filter();
|
||||
async move {
|
||||
fetch_sbom_filtered(
|
||||
if repo.is_empty() { None } else { Some(repo) },
|
||||
@@ -60,6 +63,7 @@ pub fn SbomPage(target: String) -> Element {
|
||||
if q.is_empty() { None } else { Some(q) },
|
||||
hv,
|
||||
if lic.is_empty() { None } else { Some(lic) },
|
||||
in_image,
|
||||
p,
|
||||
)
|
||||
.await
|
||||
@@ -188,6 +192,16 @@ pub fn SbomPage(target: String) -> Element {
|
||||
option { value: "true", {tx::WITH_VULNS.get(lang)} }
|
||||
option { value: "false", {tx::NO_VULNS.get(lang)} }
|
||||
}
|
||||
select {
|
||||
class: "sbom-filter-select",
|
||||
title: tx::IN_IMAGE_HINT.get(lang),
|
||||
onchange: move |e| {
|
||||
in_image_filter.set((e.value() == "true").then_some(true));
|
||||
page.set(1);
|
||||
},
|
||||
option { value: "", {tx::ALL_COMPONENTS.get(lang)} }
|
||||
option { value: "true", {tx::IN_IMAGE.get(lang)} }
|
||||
}
|
||||
select {
|
||||
class: "sbom-filter-select",
|
||||
onchange: move |e| { license_filter.set(e.value()); page.set(1); },
|
||||
@@ -294,11 +308,23 @@ pub fn SbomPage(target: String) -> Element {
|
||||
let has_vulns = !entry.known_vulnerabilities.is_empty();
|
||||
let license_class = license_css_class(entry.license.as_deref());
|
||||
let row_key_click = row_key.clone();
|
||||
// Which images declare it, on the badge's tooltip.
|
||||
let in_image_title = entry.in_image.as_ref().map(|i| {
|
||||
format!("{} (Images: {})", tx::IN_IMAGE_HINT.get(lang), i.images.join(", "))
|
||||
});
|
||||
rsx! {
|
||||
tr {
|
||||
td {
|
||||
style: "font-weight: 500;",
|
||||
"{entry.name}"
|
||||
if let Some(title) = in_image_title {
|
||||
" "
|
||||
span {
|
||||
class: "badge badge-success",
|
||||
title: "{title}",
|
||||
{tx::IN_IMAGE.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
td {
|
||||
style: "font-family: var(--font-mono, monospace); font-size: 13px;",
|
||||
|
||||
Binary file not shown.
@@ -7,11 +7,17 @@ oelint-parser (BSD-2-Clause), which reads BitBake syntax and never executes the
|
||||
recipes' Python or shell code.
|
||||
|
||||
Each recipe is parsed with its own bbappends. Layer overrides between layers,
|
||||
PACKAGECONFIG, the distro and machine configuration and what an image installs
|
||||
are not resolved: this is an inventory of the recipes in the tree, not the
|
||||
image's SBOM.
|
||||
PACKAGECONFIG, the distro and machine configuration are not resolved: this is
|
||||
an inventory of the recipes in the tree, not the image's SBOM.
|
||||
|
||||
Output: {"recipes": [...], "errors": [{"file", "error"}]}, sorted by file.
|
||||
What the image recipes, local.conf.sample and the distro configurations
|
||||
declare an image installs (IMAGE_INSTALL, CORE_IMAGE_EXTRA_INSTALL,
|
||||
IMAGE_FEATURES) is read as written, with the package groups' RDEPENDS and
|
||||
RRECOMMENDS, so that the agent can mark the recipes an image names. Every
|
||||
override's assignment counts; nothing is resolved the way BitBake would.
|
||||
|
||||
Output: {"recipes", "images", "packagegroups", "configs": [...],
|
||||
"errors": [{"file", "error"}]}, each sorted by file.
|
||||
"""
|
||||
|
||||
import glob
|
||||
@@ -33,6 +39,15 @@ SKIPPED_DIRS = {".git", ".hg", ".svn", "build", "tmp", "sstate-cache", "download
|
||||
# How much of a patch is read for its CVE: tags; the header comes first.
|
||||
PATCH_HEADER_BYTES = 64 * 1024
|
||||
|
||||
# The variables saying what an image installs, and its features.
|
||||
INSTALL_VARIABLES = ("IMAGE_INSTALL", "CORE_IMAGE_EXTRA_INSTALL")
|
||||
FEATURE_VARIABLES = ("IMAGE_FEATURES", "EXTRA_IMAGE_FEATURES")
|
||||
|
||||
# The operations an override suffix can name (`:append`, old `_append`).
|
||||
OPERATIONS = ("append", "prepend", "remove")
|
||||
|
||||
VERSION_CONSTRAINT = re.compile(r"\([^()]*\)")
|
||||
|
||||
CVE_ID = re.compile(r"CVE-\d{4}-\d{4,}")
|
||||
CVE_TAG = re.compile(r"^CVE:\s*(.*)$", re.MULTILINE)
|
||||
|
||||
@@ -59,11 +74,23 @@ def confine(tree: str) -> None:
|
||||
setattr(cls_stash, "__oe_utils_read_file_regex__", regex.compile(r"(?!)"))
|
||||
|
||||
|
||||
def walk(tree: str) -> tuple[list[str], list[str], list[str]]:
|
||||
"""The layer roots (directories with conf/layer.conf), recipes and appends."""
|
||||
def is_config(root: str, name: str) -> bool:
|
||||
"""Whether `name` in directory `root` is a configuration that can declare
|
||||
what images install: a local.conf.sample or a distro configuration."""
|
||||
if name == "local.conf.sample":
|
||||
return True
|
||||
return name.endswith(".conf") and os.path.basename(root) == "distro" and (
|
||||
os.path.basename(os.path.dirname(root)) == "conf"
|
||||
)
|
||||
|
||||
|
||||
def walk(tree: str) -> tuple[list[str], list[str], list[str], list[str]]:
|
||||
"""The layer roots (directories with conf/layer.conf), recipes, appends
|
||||
and the configurations that can declare what images install."""
|
||||
layers: list[str] = []
|
||||
recipes: list[str] = []
|
||||
appends: list[str] = []
|
||||
configs: list[str] = []
|
||||
for root, dirs, files in os.walk(tree):
|
||||
dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS)
|
||||
if os.path.basename(root) == "conf" and "layer.conf" in files:
|
||||
@@ -76,7 +103,9 @@ def walk(tree: str) -> tuple[list[str], list[str], list[str]]:
|
||||
recipes.append(path)
|
||||
elif name.endswith(".bbappend"):
|
||||
appends.append(path)
|
||||
return sorted(layers), sorted(recipes), sorted(appends)
|
||||
elif is_config(root, name):
|
||||
configs.append(path)
|
||||
return sorted(layers), sorted(recipes), sorted(appends), sorted(configs)
|
||||
|
||||
|
||||
def appends_for(recipe: str, appends: list[str]) -> list[str]:
|
||||
@@ -91,6 +120,22 @@ def appends_for(recipe: str, appends: list[str]) -> list[str]:
|
||||
return matching
|
||||
|
||||
|
||||
def file_stem(path: str) -> str:
|
||||
"""The recipe name part of a .bb or .bbappend file name: before the
|
||||
version (`busybox_1.35.0.bb`), without an append's `%` wildcard."""
|
||||
name = os.path.basename(path)
|
||||
for suffix in (".bbappend", ".bb"):
|
||||
if name.endswith(suffix):
|
||||
name = name[: -len(suffix)]
|
||||
break
|
||||
return name.split("_", 1)[0].replace("%", "")
|
||||
|
||||
|
||||
def is_image_name(path: str) -> bool:
|
||||
"""Whether the file is named like an image recipe (`*-image*.bb`)."""
|
||||
return "-image" in file_stem(path)
|
||||
|
||||
|
||||
def is_build_host_recipe(name: str) -> bool:
|
||||
"""Whether the recipe only builds a tool for the build host or SDK."""
|
||||
return name.endswith(("-native", "-cross", "-crosssdk")) or name.startswith("nativesdk-")
|
||||
@@ -176,6 +221,134 @@ def flags(stash: Stash, recipe: str, name: str) -> dict[str, str]:
|
||||
return found
|
||||
|
||||
|
||||
def assignment_parts(
|
||||
item: Variable, name: str, scoped: bool
|
||||
) -> tuple[list[str], str | None, list[str]] | None:
|
||||
"""What an assignment to `name` is: the words before its operation (a
|
||||
package such as `${PN}-utils`, or an override such as `qemux86`), the
|
||||
operation (`append`, `prepend`, `remove` or None) and the overrides after
|
||||
it. None for an assignment of another variable.
|
||||
|
||||
oelint-parser splits `IMAGE_INSTALL_append` (the syntax before Kirkstone)
|
||||
into the variable and `append` only in a file without any `:` override;
|
||||
otherwise it keeps the whole name, which is split here. Another variable
|
||||
with a longer name (`IMAGE_FEATURES_REPLACES_…`) is not an assignment of
|
||||
`name`: in the old syntax only an operation may follow the name directly,
|
||||
or, for a per-package variable (RDEPENDS), the package."""
|
||||
if item.VarName == name:
|
||||
subs = list(item.SubItems)
|
||||
elif item.VarName.startswith(name + "_"):
|
||||
subs = item.VarName[len(name) + 1 :].split("_") + list(item.SubItems)
|
||||
if not scoped and subs[0] not in OPERATIONS:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
operation = next((s for s in subs if s in OPERATIONS), None)
|
||||
if operation is None:
|
||||
return subs, None, []
|
||||
at = subs.index(operation)
|
||||
return subs[:at], operation, subs[at + 1 :]
|
||||
|
||||
|
||||
def without_inline_python(text: str) -> str:
|
||||
"""`text` without its inline Python (`${@bb.utils.contains(...)}`): what
|
||||
it would add depends on the configuration, which is not resolved."""
|
||||
kept = []
|
||||
at = 0
|
||||
while (start := text.find("${@", at)) != -1:
|
||||
kept.append(text[at:start])
|
||||
depth = 0
|
||||
end = start + 1
|
||||
while end < len(text):
|
||||
if text[end] == "{":
|
||||
depth += 1
|
||||
elif text[end] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
end += 1
|
||||
at = end + 1
|
||||
kept.append(text[at:])
|
||||
return " ".join(kept)
|
||||
|
||||
|
||||
def fold(stash: Stash, path: str, items: list[Variable], name: str, scoped: bool) -> list[str]:
|
||||
"""The words `items` (assignments of `name`) give together: `=`, `?=`,
|
||||
`+=` in order, then every `:append`/`:prepend` and every override's
|
||||
assignment added, then `:remove` taken away. With `scoped`, the first word
|
||||
before the operation is the package and the rest are overrides."""
|
||||
base: list[str] | None = None
|
||||
added: list[str] = []
|
||||
removed: set[str] = set()
|
||||
for item in sorted(items, key=lambda i: i.Line):
|
||||
parts = assignment_parts(item, name, scoped)
|
||||
if parts is None:
|
||||
continue
|
||||
before, operation, after = parts
|
||||
overrides = before[1:] if scoped else before
|
||||
text = without_inline_python(stash.ExpandTerm(path, raw(stash, item)))
|
||||
# A version constraint (`foo (>= 1.2)`) is not a package.
|
||||
found = Item.safe_linesplit(VERSION_CONSTRAINT.sub(" ", text))
|
||||
if operation == "remove" and not overrides and not after:
|
||||
removed.update(found)
|
||||
elif operation is not None or overrides:
|
||||
# An override (a machine, a distro) is not resolved: it counts.
|
||||
if operation != "remove":
|
||||
added.extend(found)
|
||||
else:
|
||||
op = item.VarOp.strip()
|
||||
if op in ("=", ":="):
|
||||
base = found
|
||||
elif op in ("?=", "??="):
|
||||
base = found if base is None else base
|
||||
else:
|
||||
base = (base or []) + found
|
||||
words_found = [w for w in (base or []) + added if w not in removed]
|
||||
return list(dict.fromkeys(words_found))
|
||||
|
||||
|
||||
def variables(stash: Stash, path: str) -> list[Variable]:
|
||||
"""Every variable assignment in `path`, its includes and appends."""
|
||||
return stash.GetItemsFor(filename=path, classifier=Variable.CLASSIFIER)
|
||||
|
||||
|
||||
def declared(stash: Stash, path: str, names: tuple[str, ...]) -> list[str]:
|
||||
"""The words the variables `names` declare in `path`, in order, once."""
|
||||
items = variables(stash, path)
|
||||
found = [w for name in names for w in fold(stash, path, items, name, scoped=False)]
|
||||
return list(dict.fromkeys(found))
|
||||
|
||||
|
||||
def per_package(stash: Stash, path: str, names: tuple[str, ...]) -> dict[str, list[str]]:
|
||||
"""The words the per-package variables `names` (RDEPENDS:${PN}-x) give
|
||||
each package of `path`, keyed by the package name as expanded."""
|
||||
items = variables(stash, path)
|
||||
keyed: dict[str, list[Variable]] = {}
|
||||
for name in names:
|
||||
for item in items:
|
||||
parts = assignment_parts(item, name, scoped=True)
|
||||
if parts is None or not parts[0]:
|
||||
continue
|
||||
package = stash.ExpandTerm(path, parts[0][0]).strip()
|
||||
keyed.setdefault(package, [])
|
||||
if item not in keyed[package]:
|
||||
keyed[package].append(item)
|
||||
found: dict[str, list[str]] = {}
|
||||
for package, group in sorted(keyed.items()):
|
||||
words_found = [w for name in names for w in fold(stash, path, group, name, scoped=True)]
|
||||
if words_found:
|
||||
found[package] = list(dict.fromkeys(words_found))
|
||||
return found
|
||||
|
||||
|
||||
def image_declarations(stash: Stash, path: str) -> dict[str, list[str]]:
|
||||
"""What `path` declares an image installs, and its features."""
|
||||
return {
|
||||
"install": declared(stash, path, INSTALL_VARIABLES),
|
||||
"features": declared(stash, path, FEATURE_VARIABLES),
|
||||
}
|
||||
|
||||
|
||||
def status_entry(cve: str, value: str) -> dict[str, str]:
|
||||
"""A CVE_STATUS value `reason: detail` as its parts."""
|
||||
reason, _, detail = value.partition(":")
|
||||
@@ -243,26 +416,94 @@ def sources(origins: list[str], tree: str, src_uri: list[str]) -> tuple[str | No
|
||||
return upstream, patches
|
||||
|
||||
|
||||
def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) -> dict | None:
|
||||
"""One recipe as JSON, or None for an image, a package group or a
|
||||
build-host tool, which are not components of the product."""
|
||||
stash = Stash(quiet=True, layer_paths=layers)
|
||||
for path in [recipe, *appends]:
|
||||
def parsed(paths: list[str], layers: list[str], negative: bool = False) -> Stash:
|
||||
"""A stash of `paths` (a recipe and its appends, or a configuration).
|
||||
oelint-parser emulates `bb.utils.contains` by taking its true branch, or
|
||||
with `negative` its false one; it never runs the Python."""
|
||||
stash = Stash(quiet=True, layer_paths=layers, negative_inline=negative)
|
||||
for path in paths:
|
||||
stash.AddFile(path)
|
||||
stash.Finalize()
|
||||
if stash.IsImage(recipe) or stash.IsPackageGroup(recipe):
|
||||
return None
|
||||
return stash
|
||||
|
||||
|
||||
def static_words(found: list[str]) -> list[str]:
|
||||
"""The words that are names as written, not a variable left unexpanded."""
|
||||
return [w for w in found if "${" not in w and "@" not in w]
|
||||
|
||||
|
||||
def common(positive, negative):
|
||||
"""What two readings agree on: the words of a list in both (in the first
|
||||
one's order), a dictionary key by key, any other value as first read."""
|
||||
if isinstance(positive, list):
|
||||
kept = set(negative) if isinstance(negative, list) else set()
|
||||
return [w for w in positive if w in kept]
|
||||
if isinstance(positive, dict):
|
||||
other = negative if isinstance(negative, dict) else {}
|
||||
return {key: common(value, other.get(key)) for key, value in positive.items()}
|
||||
return positive
|
||||
|
||||
|
||||
def unconditional(paths: list[str], layers: list[str], read) -> dict:
|
||||
"""`read(stash)` of `paths` with what both branches of every inline
|
||||
condition give: an install only when `DISTRO_FEATURES` contains `x11`
|
||||
is not declared for the image as such."""
|
||||
return common(read(parsed(paths, layers)), read(parsed(paths, layers, negative=True)))
|
||||
|
||||
|
||||
def read_image(stash: Stash, recipe: str, appends: list[str], tree: str) -> dict:
|
||||
"""An image recipe (or a bbappend of one not in the tree): its name and
|
||||
what it declares it installs."""
|
||||
return {
|
||||
"file": os.path.relpath(recipe, tree),
|
||||
"appends": [os.path.relpath(a, tree) for a in appends],
|
||||
"pn": file_stem(recipe),
|
||||
**image_declarations(stash, recipe),
|
||||
}
|
||||
|
||||
|
||||
def read_packagegroup(stash: Stash, recipe: str, tree: str) -> dict:
|
||||
"""A package group: the packages it makes and what each one pulls in
|
||||
(RDEPENDS, and RRECOMMENDS, which are installed unless excluded)."""
|
||||
pn = stash.GuessRecipeName(recipe)
|
||||
return {
|
||||
"file": os.path.relpath(recipe, tree),
|
||||
"pn": pn,
|
||||
"packages": static_words(declared(stash, recipe, ("PACKAGES",))) or [pn],
|
||||
"rdepends": per_package(stash, recipe, ("RDEPENDS", "RRECOMMENDS")),
|
||||
}
|
||||
|
||||
|
||||
def read_recipe(
|
||||
recipe: str, appends: list[str], layers: list[str], tree: str
|
||||
) -> tuple[str, dict] | None:
|
||||
"""One recipe as JSON with its kind: `recipe` for a component of the
|
||||
product, `image` or `packagegroup`; None for a build-host tool."""
|
||||
paths = [recipe, *appends]
|
||||
stash = parsed(paths, layers)
|
||||
if stash.IsPackageGroup(recipe):
|
||||
return "packagegroup", unconditional(
|
||||
paths, layers, lambda s: read_packagegroup(s, recipe, tree)
|
||||
)
|
||||
if stash.IsImage(recipe) or is_image_name(recipe):
|
||||
image = unconditional(paths, layers, lambda s: read_image(s, recipe, appends, tree))
|
||||
# Named like an image (`*-image*.bb`) without inheriting an image
|
||||
# class: an image only if it declares what to install
|
||||
# (`xcb-util-image` is a library).
|
||||
if stash.IsImage(recipe) or image["install"] or image["features"]:
|
||||
return "image", image
|
||||
pn = stash.GuessRecipeName(recipe)
|
||||
if is_build_host_recipe(pn):
|
||||
return None
|
||||
pv = value(stash, recipe, "PV") or stash.GuessRecipeVersion(recipe)
|
||||
origins = [recipe, *appends]
|
||||
upstream, patches = sources(origins, tree, words(stash, recipe, "SRC_URI"))
|
||||
return {
|
||||
return "recipe", {
|
||||
"file": os.path.relpath(recipe, tree),
|
||||
"appends": [os.path.relpath(a, tree) for a in appends],
|
||||
"pn": pn,
|
||||
"bpn": stash.GuessBaseRecipeName(recipe),
|
||||
"packages": static_words(declared(stash, recipe, ("PACKAGES",))),
|
||||
"pv": pv,
|
||||
"srcrev": value(stash, recipe, "SRCREV") or None,
|
||||
"src_uri": upstream,
|
||||
@@ -274,21 +515,63 @@ def read_recipe(recipe: str, appends: list[str], layers: list[str], tree: str) -
|
||||
}
|
||||
|
||||
|
||||
def orphan_image_appends(recipe_files: list[str], appends: list[str]) -> list[str]:
|
||||
"""The bbappends of images whose recipe is not in the tree
|
||||
(`core-image-minimal.bbappend` extending Poky's image)."""
|
||||
return [
|
||||
append
|
||||
for append in appends
|
||||
if is_image_name(append)
|
||||
and not any(append in appends_for(recipe, [append]) for recipe in recipe_files)
|
||||
]
|
||||
|
||||
|
||||
def declaring_image(append: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
|
||||
"""The bbappend of an image not in the tree, if it declares anything."""
|
||||
image = unconditional([append], layers, lambda s: read_image(s, append, [], tree))
|
||||
return ("image", image) if image["install"] or image["features"] else None
|
||||
|
||||
|
||||
def read_config(config: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
|
||||
"""What a local.conf.sample or distro configuration declares every image
|
||||
installs; None when it declares nothing."""
|
||||
declarations = unconditional([config], layers, lambda s: image_declarations(s, config))
|
||||
if not declarations["install"] and not declarations["features"]:
|
||||
return None
|
||||
return "config", {"file": os.path.relpath(config, tree), **declarations}
|
||||
|
||||
|
||||
def main(tree: str) -> int:
|
||||
tree = os.path.realpath(tree)
|
||||
confine(tree)
|
||||
layers, recipe_files, appends = walk(tree)
|
||||
recipes = []
|
||||
layers, recipe_files, appends, configs = walk(tree)
|
||||
layers = layers or [tree]
|
||||
read: dict[str, list[dict]] = {"recipe": [], "image": [], "packagegroup": [], "config": []}
|
||||
errors = []
|
||||
for recipe in recipe_files:
|
||||
|
||||
def attempt(path: str, reader) -> None:
|
||||
try:
|
||||
read = read_recipe(recipe, appends_for(recipe, appends), layers or [tree], tree)
|
||||
except Exception as error: # noqa: BLE001 - one unreadable recipe must not stop the rest
|
||||
errors.append({"file": os.path.relpath(recipe, tree), "error": type(error).__name__})
|
||||
continue
|
||||
if read is not None:
|
||||
recipes.append(read)
|
||||
json.dump({"recipes": recipes, "errors": errors}, sys.stdout, sort_keys=True)
|
||||
result = reader()
|
||||
except Exception as error: # noqa: BLE001 - one unreadable file must not stop the rest
|
||||
errors.append({"file": os.path.relpath(path, tree), "error": type(error).__name__})
|
||||
return
|
||||
if result is not None:
|
||||
read[result[0]].append(result[1])
|
||||
|
||||
for recipe in recipe_files:
|
||||
attempt(recipe, lambda: read_recipe(recipe, appends_for(recipe, appends), layers, tree))
|
||||
for append in orphan_image_appends(recipe_files, appends):
|
||||
attempt(append, lambda: declaring_image(append, layers, tree))
|
||||
for config in configs:
|
||||
attempt(config, lambda: read_config(config, layers, tree))
|
||||
output = {
|
||||
"recipes": read["recipe"],
|
||||
"images": sorted(read["image"], key=lambda i: i["file"]),
|
||||
"packagegroups": read["packagegroup"],
|
||||
"configs": read["config"],
|
||||
"errors": errors,
|
||||
}
|
||||
json.dump(output, sys.stdout, sort_keys=True)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+59
-5
@@ -38,6 +38,7 @@ searched.
|
||||
| Firmware SBOM (Firmwerk) | not run: listed under **Nicht ausgeführt** as "Yocto build analysis is planned (tier 2)" |
|
||||
| Recipe lint (oelint-adv and our own rules) | runs over your layers, see below |
|
||||
| Recipe inventory | runs: SBOM components and NVD CVEs from the recipes, `CVE_STATUS` and `CVE:` patches as VEX; see [Recipe inventory](#recipe-inventory) |
|
||||
| In the image (declared) | runs: the recipes your image recipes install are marked; see [Im Image (deklariert)](#im-image-deklariert) |
|
||||
| Image SBOM / CVE | needs build artefacts (SPDX / manifest), planned (tier 2) |
|
||||
| DAST | opt-in, with an http(s) address of the running device |
|
||||
| Penetration test | not offered until an image can be booted in an emulation sandbox |
|
||||
@@ -122,10 +123,10 @@ Image recipes, package groups and tools built only for the build host
|
||||
checked on a target's components (SBOM, known vulnerabilities) are
|
||||
**Teilweise bewertet** (*partly assessed*, "recipe inventory only, not the
|
||||
image SBOM") until an image SBOM can be imported (tier 2). Layer overrides between layers,
|
||||
`PACKAGECONFIG`, the distro and machine configuration and what an image
|
||||
actually installs are not resolved, so the inventory lists every recipe in the
|
||||
tree: more than an image contains, and nothing from layers that are not in the
|
||||
tree. The components say so wherever they appear: the **Yocto-Rezept** badge in
|
||||
`PACKAGECONFIG` and the distro and machine configuration are not resolved, so
|
||||
the inventory lists every recipe in the tree: more than an image contains, and
|
||||
nothing from layers that are not in the tree. The recipes an image recipe names
|
||||
are marked, see [Im Image (deklariert)](#im-image-deklariert). The components say so wherever they appear: the **Yocto-Rezept** badge in
|
||||
the SBOM view, the component property `pruefwerk:component:source` in the
|
||||
CycloneDX export and the package `comment` in the SPDX export (both read
|
||||
"Yocto recipe inventory (not the image SBOM)"), and the component's evidence
|
||||
@@ -162,10 +163,63 @@ analysis `detail`. `CVE_STATUS_GROUPS` count like single `CVE_STATUS` flags. The
|
||||
again on every scan and withdraws one the recipe no longer makes; a statement
|
||||
a person made is never replaced.
|
||||
|
||||
## Im Image (deklariert)
|
||||
|
||||
The inventory keeps every recipe, but marks those your image recipes say they
|
||||
install: **Im Image (deklariert)** (*In the image (declared)*). It is read from
|
||||
the recipes as they are written, with the same parser and without a build; it
|
||||
is what the image recipes declare, not what BitBake would resolve.
|
||||
|
||||
**What is read.** Image recipes are the `.bb` files that inherit `core-image`,
|
||||
`image` (or another image class) or set `IMAGE_INSTALL` / `IMAGE_FEATURES`,
|
||||
files named `*-image*.bb` that declare what to install, and a `*-image*.bbappend`
|
||||
of an image that is not in the tree (`core-image-minimal.bbappend`). From them,
|
||||
and from every `conf/local.conf.sample` and `conf/distro/*.conf`:
|
||||
|
||||
- `IMAGE_INSTALL` and `CORE_IMAGE_EXTRA_INSTALL` with every operation: `=`,
|
||||
`?=`, `+=`, `:append` and the older `_append`, `:remove`;
|
||||
- `IMAGE_FEATURES` and `EXTRA_IMAGE_FEATURES`.
|
||||
|
||||
A local.conf.sample or distro configuration counts for every image recipe in
|
||||
the tree (with none, the component names the configuration file instead).
|
||||
|
||||
**How a name becomes a recipe.**
|
||||
|
||||
| The image names | Marked |
|
||||
|---|---|
|
||||
| a recipe (`busybox`) | that recipe |
|
||||
| a package a recipe's `PACKAGES` names (`pump-web-ui`) | that recipe |
|
||||
| a default package (`busybox-dev`, `-dbg`, `-doc`, `-locale`, `-src`, `-staticdev`, `-ptest`) | its recipe |
|
||||
| a package group in the tree (`packagegroup-pump`) | what that package's `RDEPENDS` and `RRECOMMENDS` name, one level: a package group inside it is not expanded |
|
||||
| an image feature (`ssh-server-dropbear`) | its package group from OpenEmbedded-Core's `FEATURE_PACKAGES_*` (`packagegroup-core-ssh-dropbear`), if that package group is in the tree |
|
||||
|
||||
**Where it shows.** A badge **Im Image (deklariert)** next to the component in
|
||||
the SBOM view, whose tooltip names the images and says it is read from the
|
||||
recipes, not resolved by bitbake; a filter of the same name; and the SBOM list
|
||||
puts these components first. The component's evidence line names the images,
|
||||
the CycloneDX export carries the property `pruefwerk:component:in_image`
|
||||
(`declared: pump-image`), and the SPDX export adds it to the package `comment`.
|
||||
What an image names that is neither a recipe nor a package group in the tree
|
||||
(`packagegroup-core-boot` from Poky, a feature whose package group is not in
|
||||
the tree, a feature such as `splash` whose packages a variable chooses) is
|
||||
listed on the run under **Im Image (deklariert)**; no component is invented for
|
||||
it.
|
||||
|
||||
**What is not resolved.** Overrides (`IMAGE_INSTALL:append:qemux86` counts as
|
||||
if it applied to every machine), `PACKAGECONFIG`, installs that depend on
|
||||
`DISTRO_FEATURES` or other inline Python (a package only one branch of
|
||||
`${@bb.utils.contains(...)}` names is left out; the Python is never run), variables the tree does not set (`${CORE_IMAGE_BASE_INSTALL}`), package
|
||||
groups more than one level deep, `RPROVIDES` and virtual packages, a
|
||||
`FEATURE_PACKAGES_*` of your own, `BAD_RECOMMENDATIONS`, and which distro a
|
||||
build selects (every distro configuration counts). Nothing is built, and no
|
||||
recipe from a layer that is not in the tree is marked. The CRA state of the
|
||||
SBOM requirement stays **Teilweise bewertet** until an image SBOM from a build
|
||||
can be imported (tier 2).
|
||||
|
||||
## What is planned
|
||||
|
||||
| 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. **Recipe lint**: done, see above |
|
||||
| **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** | `tmp/deploy/spdx` (SPDX 3.0, or 2.2 up to Scarthgap), `*.vex.json`, the image `.manifest`, the kernel `.config` | **SPDX import** into the SBOM view and CycloneDX export; **sbom-cve-check** with the Yocto VEX annotations; kernel CVEs filtered by the configuration; a nightly re-check without a rebuild |
|
||||
| **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 |
|
||||
@@ -2,14 +2,15 @@
|
||||
"scan_status": "completed",
|
||||
"skipped_stages": [
|
||||
"firmware_sbom",
|
||||
"image_install",
|
||||
"malware"
|
||||
],
|
||||
"sbom": [
|
||||
"yocto-recipe:busybox@1.35.0",
|
||||
"yocto-recipe:libmodbus@3.1.6",
|
||||
"yocto-recipe:pump-ctl@1.0",
|
||||
"yocto-recipe:busybox@1.35.0 [in image: pump-image]",
|
||||
"yocto-recipe:libmodbus@3.1.6 [in image: pump-image]",
|
||||
"yocto-recipe:pump-ctl@1.0 [in image: pump-image]",
|
||||
"yocto-recipe:pump-fw@1.0",
|
||||
"yocto-recipe:pump-web@2.1"
|
||||
"yocto-recipe:pump-web@2.1 [in image: pump-image]"
|
||||
],
|
||||
"findings": [
|
||||
"oelint-adv:oelint.task.network pump-web_2.1.bb:8",
|
||||
|
||||
@@ -19,7 +19,7 @@ SBOM reads as declared dependencies (#317):
|
||||
| `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: detected as a BitBake layer tree (`build_system = bitbake`); the recipe lint reports the image's debug-tweaks and allow-empty-password, a password hash in `EXTRA_USERS_PARAMS`, an `http://` fetch without a checksum, a task with network access, `AUTOREV`, `PermitRootLogin yes` and a distro without `security_flags.inc`; the recipe inventory lists the recipes (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs; BusyBox carries a `CVE_STATUS`, a `CVE_STATUS_GROUPS` entry in a `.bbappend` and a `CVE:` patch) yet |
|
||||
| `yocto-layer` | (ours) | none: detected as a BitBake layer tree (`build_system = bitbake`); the recipe lint reports the image's debug-tweaks and allow-empty-password, a password hash in `EXTRA_USERS_PARAMS`, an `http://` fetch without a checksum, a task with network access, `AUTOREV`, `PermitRootLogin yes` and a distro without `security_flags.inc`; the recipe inventory lists the recipes (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs; BusyBox carries a `CVE_STATUS`, a `CVE_STATUS_GROUPS` entry in a `.bbappend` and a `CVE:` patch) and marks four of them as in `pump-image` (declared: three in `IMAGE_INSTALL`, pump-web through `packagegroup-pump` by its package `pump-web-ui`), pump-fw in no image |
|
||||
|
||||
`make` is also onboarded as a backend service (`fw-make-onboarded-as-service`):
|
||||
the firmware SBOM follows detection, not the type picked in the wizard.
|
||||
|
||||
@@ -9,3 +9,8 @@ do_compile[network] = "1"
|
||||
do_compile() {
|
||||
oe_runmake
|
||||
}
|
||||
|
||||
# The web UI's static files are their own package, which the product's
|
||||
# package group installs.
|
||||
PACKAGES =+ "${PN}-ui"
|
||||
FILES:${PN}-ui = "${datadir}/pump-web"
|
||||
@@ -11,3 +11,7 @@ inherit core-image extrausers
|
||||
|
||||
# A password hash baked into the image: the same root password on every device.
|
||||
EXTRA_USERS_PARAMS = "usermod -p '\$6\$pumpsalt\$Qm1sZWFzZWQtZml4dHVyZS1oYXNoLW5vdC1yZWFs' root;"
|
||||
|
||||
# The application packages come through the product's package group; pump-fw
|
||||
# (the firmware tools) is built but no image installs it.
|
||||
IMAGE_INSTALL:append = " packagegroup-pump"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Nightly fixture: the product's package group. It pulls in the web UI by its
|
||||
# package name (pump-web-ui, made by the pump-web recipe); an image naming the
|
||||
# group installs what it RDEPENDS on.
|
||||
SUMMARY = "Pump controller application packages"
|
||||
LICENSE = "MIT"
|
||||
|
||||
inherit packagegroup
|
||||
|
||||
RDEPENDS:${PN} = "pump-web-ui"
|
||||
@@ -266,7 +266,7 @@
|
||||
"key": "fw-yocto-layer",
|
||||
"name": "Firmware · Yocto layer",
|
||||
"target_type": "embedded_linux_yocto",
|
||||
"description": "A Yocto layer with an insecure product image, recipes and distro. Detected as a BitBake layer tree; recipe lint (oelint-adv and our own rules) reports each insecure setting; the recipe inventory lists the recipes as SBOM components (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs by CPE, one CVE_STATUS, a CVE_STATUS group and a CVE: patch as VEX). The firmware SBOM (a build) is recorded as skipped with its reason.",
|
||||
"description": "A Yocto layer with an insecure product image, recipes and distro. Detected as a BitBake layer tree; recipe lint (oelint-adv and our own rules) reports each insecure setting; the recipe inventory lists the recipes as SBOM components (BusyBox 1.35.0 and libmodbus 3.1.6 with NVD CVEs by CPE, one CVE_STATUS, a CVE_STATUS group and a CVE: patch as VEX); the recipes pump-image installs (IMAGE_INSTALL, one package group) are marked as in the image (declared), pump-fw is not. The firmware SBOM (a build) is recorded as skipped with its reason.",
|
||||
"artifacts": [
|
||||
{
|
||||
"kind": "source_archive",
|
||||
|
||||
Reference in new issue
Block a user