diff --git a/Dockerfile.agent b/Dockerfile.agent index 1e9ffaf..ddff4f8 100644 --- a/Dockerfile.agent +++ b/Dockerfile.agent @@ -18,6 +18,8 @@ ARG RUFF_VERSION=0.16.8 ARG MOBSFSCAN_VERSION=1.0.1 # Yocto recipe lint (BSD-2-Clause): only its security rules run. ARG OELINT_ADV_VERSION=9.11.2 +# The recipe inventory reads the recipes with the same oelint-parser. +ARG OELINT_PARSER_VERSION=8.13.2 # DevSkim (MIT) is published as a .NET tool on nuget.org, not as a release # binary: the package is pinned by checksum and run on the .NET runtime (MIT). ARG DEVSKIM_VERSION=1.0.100 @@ -66,6 +68,7 @@ ARG SEMGREP_VERSION ARG RUFF_VERSION ARG MOBSFSCAN_VERSION ARG OELINT_ADV_VERSION +ARG OELINT_PARSER_VERSION ARG DEVSKIM_VERSION ARG DEVSKIM_SHA256 ARG DOTNET_RUNTIME_VERSION @@ -120,13 +123,15 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \ "tabulate==0.10.0" "xmltodict==1.0.4" COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py -# Yocto recipe lint; see compliance-agent/src/pipeline/recipe_lint/oelint.rs. +# Yocto recipe lint and recipe inventory; see +# compliance-agent/src/pipeline/recipe_lint/oelint.rs and yocto_inventory.rs. # Its dependencies are pinned with it (oelint-parser reads the recipes; # deprecated's wrapt is the 1.x semgrep's OpenTelemetry already installed). RUN pip3 install --break-system-packages --no-cache-dir \ - "oelint-adv==${OELINT_ADV_VERSION}" "oelint-parser==8.13.2" "oelint-data==1.5.23" \ + "oelint-adv==${OELINT_ADV_VERSION}" "oelint-parser==${OELINT_PARSER_VERSION}" "oelint-data==1.5.23" \ "anytree==2.13.0" "argcomplete==3.7.2" "urllib3==2.8.0" "regex==2026.9.29" \ "deprecated==1.3.1" +COPY docker/pruefwerk_yocto_recipes.py /opt/pruefwerk/pruefwerk_yocto_recipes.py # .NET SAST without a build (#494): DevSkim on C#, VB.NET and .config files. # The .NET runtime only (no SDK), with invariant globalisation so it needs no @@ -150,10 +155,10 @@ RUN curl -sSfL -o /tmp/dotnet.tar.gz \ COPY --chmod=0755 docker/devskim.sh /usr/local/bin/devskim RUN mkdir -p /opt/pruefwerk \ - && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","oelint-adv":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \ + && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","betterleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","oelint-adv":"%s","oelint-parser":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \ "${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${BETTERLEAKS_VERSION}" \ "${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \ - "${MOBSFSCAN_VERSION}" "${OELINT_ADV_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" \ + "${MOBSFSCAN_VERSION}" "${OELINT_ADV_VERSION}" "${OELINT_PARSER_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" \ "${DOTNET_RUNTIME_VERSION}" \ > /opt/pruefwerk/tool-versions.json diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index 27f78ee..faa0b78 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -95,6 +95,7 @@ fn state_counts(controls: &[crate::evidence::compliance::ControlStatus]) -> serd "not_satisfied": count(ControlState::NotSatisfied), "no_violation_found": count(ControlState::NoViolationFound), "not_assessed": count(ControlState::NotAssessed), + "partial": count(ControlState::Partial), "not_code_checkable": count(ControlState::NotCodeCheckable), }) } diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index 6682edc..bf2d190 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -21,6 +21,9 @@ pub enum ControlState { /// Checkable in code, but not by this scan: none completed yet, no tool /// checks it, or none of its rules covers the scanned code's languages. NotAssessed, + /// Assessed on part of what the control covers only: a Yocto target's + /// components come from its recipe inventory, not from the image's SBOM. + Partial, /// A design property no code scan can decide (breakpilot-compliance). NotCodeCheckable, } @@ -48,6 +51,11 @@ pub enum NotAssessedReason { /// `manifests` declare could not be listed (no lockfile, or one no tool /// reads), so the SBOM is incomplete. DependenciesUnresolved { manifests: Vec }, + /// The control is checked on the target's components, and they are the + /// Yocto recipe inventory only, not the image's SBOM: every recipe in the + /// layer tree, not what the image contains (the reason of + /// [`ControlState::Partial`]). + RecipeInventoryOnly, } /// How far the target's SBOM speaks for its components. @@ -59,6 +67,8 @@ pub enum SbomCoverage { Empty, /// The dependencies these manifests declare could not be listed. Unresolved(Vec), + /// The components are a Yocto recipe inventory; no image SBOM exists. + RecipeInventoryOnly, } /// The tools that check a target's components rather than its code. @@ -97,7 +107,8 @@ pub struct ControlStatus { pub state: ControlState, /// Why a control is not code-checkable, from the map. pub note: Option, - /// Why a checkable control was not assessed; set only in that state. + /// Why a checkable control was not assessed, or assessed only in part; + /// set only in those states. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, /// How severe a violation is, as the catalog rates it. @@ -201,6 +212,10 @@ pub fn control_statuses( ControlState::NotAssessed, Some(NotAssessedReason::NoComponents), ), + SbomCoverage::RecipeInventoryOnly => ( + ControlState::Partial, + Some(NotAssessedReason::RecipeInventoryOnly), + ), SbomCoverage::Unresolved(manifests) => ( ControlState::NotAssessed, Some(NotAssessedReason::DependenciesUnresolved { @@ -412,6 +427,27 @@ mod tests { assert_eq!(state_of(&with, "cra-ai-23"), ControlState::NoViolationFound); } + #[test] + fn a_recipe_inventory_assesses_the_component_controls_only_in_part() { + let map = ControlMap::cra().expect("map"); + let statuses = control_statuses( + &map, + &[], + Some(&c_only()), + &[], + &SbomCoverage::RecipeInventoryOnly, + ); + for control in ["cra-ai-22", "cra-ai-23", "cra-ai-33"] { + let status = status_of(&statuses, control); + assert_eq!(status.state, ControlState::Partial, "{control}"); + assert_eq!(status.reason, Some(NotAssessedReason::RecipeInventoryOnly)); + } + assert_eq!( + state_of(&statuses, "cra-ai-20"), + ControlState::NoViolationFound + ); + } + #[test] fn unresolved_dependencies_claim_nothing_about_components() { let map = ControlMap::cra().expect("map"); diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index caf62da..2d63a86 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -240,6 +240,15 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage { compliance::SbomCoverage::Unresolved(unresolved) } else if inputs.sbom.is_empty() { compliance::SbomCoverage::Empty + } else if inputs + .sbom + .iter() + .any(|e| e.package_manager == compliance_core::models::YOCTO_RECIPE_MANAGER) + { + // No image SBOM can be imported yet (Yocto tier 2), so a recipe + // inventory is all there is: it lists the layer tree's recipes, not + // what the image contains. + compliance::SbomCoverage::RecipeInventoryOnly } else { compliance::SbomCoverage::Complete } @@ -367,6 +376,22 @@ mod tests { } } + #[test] + fn a_recipe_inventory_is_not_a_complete_sbom() { + let mut with = inputs(); + assert_eq!(sbom_coverage(&with), compliance::SbomCoverage::Complete); + with.sbom.push(SbomEntry::new( + "t1".into(), + "busybox".into(), + "1.35.0".into(), + compliance_core::models::YOCTO_RECIPE_MANAGER.into(), + )); + assert_eq!( + sbom_coverage(&with), + compliance::SbomCoverage::RecipeInventoryOnly + ); + } + #[test] fn an_actively_exploited_vulnerability_adds_its_draft_notification() { let mut with_kev = inputs(); diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index d2c2fe4..2cdd405 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -1,12 +1,13 @@ use std::collections::{BTreeSet, HashMap}; -use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef}; +use compliance_core::models::{CveAlert, CveSource, SbomEntry, VulnRef, YOCTO_RECIPE_MANAGER}; use compliance_core::net_guard::NetGuard; use compliance_core::CoreError; use crate::pipeline::embedded_versions::{self, EMBEDDED_MANAGER}; use crate::pipeline::nvd_cpe::{self, NvdCve, NvdProduct}; use crate::pipeline::public_http::{read_body, read_json, PublicHttp}; +use crate::pipeline::yocto_inventory::NvdQuery; /// OSV's API. const OSV_API: &str = "https://api.osv.dev"; @@ -157,10 +158,13 @@ impl CveScanner { let mut refused = Vec::new(); // Each query keeps the index of its entry: an entry without a purl is // not asked about, and must not shift the answers onto its neighbours. + // Yocto recipes are matched by CPE in NVD instead ([`Self::scan_yocto`]). let queries: Vec<(usize, &str)> = entries .iter() .enumerate() - .filter(|(_, e)| !without_osv_advisories(e)) + .filter(|(_, e)| { + !without_osv_advisories(e) && e.package_manager != YOCTO_RECIPE_MANAGER + }) .filter_map(|(i, e)| e.purl.as_deref().map(|purl| (i, purl))) .collect(); @@ -351,6 +355,82 @@ impl CveScanner { } } +impl CveScanner { + /// Match the components of a Yocto recipe inventory against NVD by CPE + /// (`queries`, see [`crate::pipeline::yocto_inventory::nvd_queries`]), + /// one product after the other, within `budget`. A recipe whose lookup + /// fails, or that the budget leaves unasked, is reported in + /// [`CveLookup::unchecked`]; the others are still matched. + /// + /// NVD answers about 5 requests per 30 seconds without an API key and 50 + /// with one (`NVD_API_KEY`, sent as the `apiKey` header): the requests are + /// paced to that ([`nvd_cpe::request_interval`]), a cached answer costs + /// none, and a layer tree can name hundreds of products: the budget keeps + /// the scan bounded, and the 6-hour cache lets the next scan of the same + /// products go further. + pub async fn scan_yocto( + &self, + repo_id: &str, + entries: &mut [SbomEntry], + queries: &[NvdQuery], + budget: std::time::Duration, + ) -> CveLookup { + let deadline = tokio::time::Instant::now() + budget; + let interval = nvd_cpe::request_interval(self.nvd_api_key.is_some()); + let mut next_request = tokio::time::Instant::now(); + let mut lookup = CveLookup::default(); + for query in queries { + let mut found: Vec = Vec::new(); + let mut checked = true; + for product in &query.products { + let (match_string, marker) = (product.match_string(), product.marker()); + if !nvd_cpe::is_cached(&match_string) { + if next_request >= deadline { + checked = false; + continue; + } + tokio::time::sleep_until(next_request).await; + next_request = tokio::time::Instant::now() + interval; + } + let lookup = nvd_cpe::match_cves( + &self.http, + self.nvd_api_key.as_deref(), + &match_string, + &marker, + &query.cve_version, + ); + match tokio::time::timeout_at(deadline, lookup).await { + Ok(Ok(cves)) => { + for cve in cves { + if !found.iter().any(|f| f.id == cve.id) { + found.push(cve); + } + } + } + Ok(Err(e)) => { + tracing::warn!(recipe = %query.name, "NVD lookup failed: {e}"); + checked = false; + } + Err(_) => checked = false, + } + } + if !checked { + lookup + .unchecked + .push(format!("{} {}", query.name, query.version)); + } + lookup.alerts.extend(record_nvd( + repo_id, + entries, + &query.name, + &query.version, + found, + )); + } + lookup + } +} + /// What a CVE lookup found, and what it could not check. #[derive(Debug, Default)] pub struct CveLookup { @@ -603,6 +683,23 @@ mod tests { ); } + #[tokio::test] + async fn yocto_recipes_are_left_to_nvd_not_asked_of_osv() { + let (url, hits) = fake_osv().await; + let scanner = CveScanner::new(NetGuard::allow_private(), None) + .unwrap() + .with_osv_api(url); + let mut recipe = with_purl("busybox", "pkg:generic/busybox@1.35.0"); + recipe.package_manager = YOCTO_RECIPE_MANAGER.into(); + let mut entries = vec![recipe]; + + let lookup = scanner.scan_dependencies("t", &mut entries).await.unwrap(); + + assert_eq!(hits.load(Ordering::SeqCst), 0, "OSV was asked"); + assert!(lookup.alerts.is_empty()); + assert!(lookup.unchecked.is_empty(), "NVD checks it, not OSV"); + } + #[test] fn an_nvd_alert_keeps_the_purl_of_its_component() { let mut entries = vec![ diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 95af293..33eccf8 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -48,3 +48,4 @@ pub(crate) mod unity_settings; pub mod variants; pub mod vendor; pub mod vex_lifecycle; +pub mod yocto_inventory; diff --git a/compliance-agent/src/pipeline/nvd_cpe.rs b/compliance-agent/src/pipeline/nvd_cpe.rs index e460ab9..85a2d08 100644 --- a/compliance-agent/src/pipeline/nvd_cpe.rs +++ b/compliance-agent/src/pipeline/nvd_cpe.rs @@ -80,15 +80,25 @@ pub(crate) async fn product_cves( product: NvdProduct, version: &str, ) -> Result, String> { - let body = product_body( - http, - NVD_CVES_URL, - api_key, - product.match_string, - &RETRY_DELAYS, - ) - .await?; - Ok(parse(&body, product.marker, version)) + match_cves(http, api_key, product.match_string, product.marker, version).await +} + +/// [`product_cves`] for a product named at run time (a Yocto recipe's +/// CVE_PRODUCT): the CVEs NVD lists for `match_string` whose vulnerable CPE +/// contains `marker` and whose range covers `version`. +/// +/// # Errors +/// +/// Why NVD could not be asked, as for [`product_cves`]. +pub(crate) async fn match_cves( + http: &PublicHttp, + api_key: Option<&str>, + match_string: &str, + marker: &str, + version: &str, +) -> Result, String> { + let body = product_body(http, NVD_CVES_URL, api_key, match_string, &RETRY_DELAYS).await?; + Ok(parse(&body, marker, version)) } /// NVD's answer for `match_string`: cached, or fetched from `base_url` with @@ -143,6 +153,22 @@ async fn product_body( Err(last_error) } +/// Whether a fresh answer for `match_string` is cached, so asking costs no +/// request against NVD's rate limit. +pub(crate) fn is_cached(match_string: &str) -> bool { + cached(match_string).is_some() +} + +/// The pause between two requests that keeps within NVD's rate limit: 50 +/// requests per 30 seconds with an API key, 5 without. +pub(crate) fn request_interval(with_key: bool) -> Duration { + if with_key { + Duration::from_millis(600) + } else { + Duration::from_secs(6) + } +} + /// A fresh cached answer for `match_string`, if there is one. fn cached(match_string: &str) -> Option> { let cache = cache().lock().ok()?; @@ -249,6 +275,12 @@ fn version_matches(v: &str, r: &CpeRange) -> bool { #[cfg(test)] mod tests { use super::*; + + #[test] + fn an_api_key_allows_ten_times_the_requests() { + assert_eq!(request_interval(false), Duration::from_secs(6)); + assert_eq!(request_interval(true) * 10, request_interval(false)); + } use std::cmp::Ordering::{Equal, Greater, Less}; use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index c910edd..9dedc93 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -24,6 +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::secrets::SecretBox; /// Context from graph analysis passed to LLM triage for enhanced filtering @@ -497,7 +498,15 @@ impl PipelineOrchestrator { }) .await .unwrap_or_default(); - for entry in embedded.into_iter().chain(codesys) { + // 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 { + self.yocto_recipes(&repo_path, scan_run_id).await + } else { + Vec::new() + }; + let yocto_entries = yocto_inventory::entries(&yocto_recipes, &repo_id); + for entry in embedded.into_iter().chain(codesys).chain(yocto_entries) { let known = sbom_entries .iter() .any(|e| e.name.eq_ignore_ascii_case(&entry.name) && e.version == entry.version); @@ -624,6 +633,32 @@ impl PipelineOrchestrator { } } + // A Yocto recipe inventory's components: NVD by CPE, within a budget + // of their own (a layer tree can name hundreds of products). + if !yocto_recipes.is_empty() { + let (queries, unversioned) = yocto_inventory::nvd_queries(&yocto_recipes); + let lookup = cve_scanner + .scan_yocto( + &repo_id, + &mut sbom_entries, + &queries, + yocto_inventory::NVD_BUDGET, + ) + .await; + cve_alerts.extend(lookup.alerts); + let unchecked: Vec = unversioned.into_iter().chain(lookup.unchecked).collect(); + if !unchecked.is_empty() { + cve_complete = false; + self.record_cve_gap( + scan_run_id, + &format!("NVD (Yocto recipes): {}", component_list(&unchecked)), + "these recipes were not matched in NVD: they have no release version, or \ + the lookup failed or did not fit in the time NVD's rate limit allows", + ) + .await; + } + } + self.match_advisories(&repo_id, &mut sbom_entries, &mut cve_alerts) .await; @@ -917,6 +952,21 @@ impl PipelineOrchestrator { if new_notif_count > 0 { tracing::info!("[{repo_id}] Created {new_notif_count} CVE notification(s)"); } + // What the recipes say about their CVEs (CVE_STATUS, `CVE:` patches), + // stated again after the alerts were stored, never over a person's. + let statements = yocto_inventory::vex_statements(&yocto_recipes, &cve_alerts); + if !statements.is_empty() { + match crate::pipeline::vex_lifecycle::apply_scan_statements( + &self.db, + &repo_id, + &statements, + ) + .await + { + Ok(set) => tracing::info!("[{repo_id}] {set} VEX statement(s) from Yocto recipes"), + Err(e) => tracing::warn!("[{repo_id}] VEX statements from Yocto recipes: {e}"), + } + } // Stage 6: Issue Creation tracing::info!("[{repo_id}] Stage 6: Issue Creation"); @@ -1138,9 +1188,12 @@ impl PipelineOrchestrator { // Ingest + classify (Firmwerk for firmware) and store the detected type. // The ingested paths are where an uploaded archive was unpacked. - let working_paths = self + let (working_paths, classified_yocto) = self .classify_and_store(target, &target_id, scan_run_id) .await; + // The recipe inventory runs on a tree classified as a Yocto layer + // tree, and on any target the plan gives it to (a Yocto target). + let yocto_layers = classified_yocto || plan.has(ScanType::RecipeInventory); // Provision a DAST target from a LiveUrl artifact so DAST fires for // wizard-created targets, not just migrated ones. self.ensure_dast_target(target, &plan).await; @@ -1217,7 +1270,8 @@ impl PipelineOrchestrator { ) .await; } - let repo = RepoView::from_target(target, code, &self.secrets); + let mut repo = RepoView::from_target(target, code, &self.secrets); + repo.yocto_layers = yocto_layers; let n = self.run_pipeline(&repo, scan_run_id, trigger).await?; self.finalize_target(target, &repo, n).await?; new_count += n; @@ -1231,7 +1285,8 @@ impl PipelineOrchestrator { // run scans what was uploaded. match working_paths.get(&code.id) { Some(tree) => { - let repo = RepoView::from_target(target, code, &self.secrets); + let mut repo = RepoView::from_target(target, code, &self.secrets); + repo.yocto_layers = yocto_layers; let upload = crate::pipeline::plc::sbom::uploaded_archive(code); let n = self.scan_tree(tree, upload, &repo, scan_run_id).await?; self.finalize_target(target, &repo, n).await?; @@ -1777,7 +1832,7 @@ impl PipelineOrchestrator { target: &OnboardedTarget, target_id: &str, scan_run_id: &str, - ) -> std::collections::HashMap { + ) -> (std::collections::HashMap, bool) { self.update_phase(scan_run_id, ScanPhase::Classification) .await; let ingest_set = self.ingest_with_steps(target, target_id, scan_run_id).await; @@ -1922,7 +1977,7 @@ impl PipelineOrchestrator { } } } - working_paths + (working_paths, yocto) } /// Store on each upload that has none the sha256 ingest computed, so the @@ -2292,6 +2347,51 @@ 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 { + match yocto_inventory::read(tree).await { + Ok(inventory) if inventory.recipes.is_empty() && inventory.errors.is_empty() => { + self.skip_stage( + scan_run_id, + SkippedStage::new( + yocto_inventory::STAGE, + SkipCode::NotAnalysedYet, + "no BitBake recipe of a product component was found in the tree \ + (a layer has conf/layer.conf and .bb recipes)", + ), + ) + .await; + Vec::new() + } + Ok(inventory) => { + if !inventory.errors.is_empty() { + let files: Vec = + inventory.errors.iter().map(|e| e.file.clone()).collect(); + self.skip_stage( + scan_run_id, + SkippedStage::new( + yocto_inventory::STAGE, + SkipCode::ToolFailed, + format!( + "these recipes could not be parsed and are not in the recipe \ + inventory: {}", + component_list(&files) + ), + ) + .about("oelint-parser"), + ) + .await; + } + inventory.recipes + } + Err(skipped) => { + self.skip_stage(scan_run_id, skipped).await; + Vec::new() + } + } + } + /// Record that CVE matching is incomplete for this run, and why: a lookup /// that failed must not read as components without CVEs. async fn record_cve_gap(&self, scan_run_id: &str, lookup: &str, reason: &str) { diff --git a/compliance-agent/src/pipeline/plan.rs b/compliance-agent/src/pipeline/plan.rs index a544513..cbe21fa 100644 --- a/compliance-agent/src/pipeline/plan.rs +++ b/compliance-agent/src/pipeline/plan.rs @@ -176,7 +176,7 @@ mod tests { } #[test] - fn a_yocto_layer_tree_runs_its_source_scans_and_recipe_lint() { + fn a_yocto_layer_tree_runs_its_source_scans_recipe_inventory_and_lint() { let t = target( TargetType::EmbeddedLinuxYocto, vec![Artifact::source_archive("meta-pump.zip")], @@ -188,12 +188,11 @@ mod tests { step_for(&plan, ScanType::RecipeLint).map(|s| &s.phase), Some(&ScanPhase::Sast) ); + assert!(plan.has(ScanType::RecipeInventory)); assert!(!plan.has(ScanType::Dast)); - let recorded: Vec = plan.unavailable.iter().map(|u| u.scan_type).collect(); - assert_eq!( - recorded, - [ScanType::RecipeInventory], - "only the planned inventory: no image is attached" + assert!( + plan.unavailable.is_empty(), + "nothing is recorded as not run: no image is attached" ); } diff --git a/compliance-agent/src/pipeline/repo_view.rs b/compliance-agent/src/pipeline/repo_view.rs index 955dc6e..82477da 100644 --- a/compliance-agent/src/pipeline/repo_view.rs +++ b/compliance-agent/src/pipeline/repo_view.rs @@ -45,6 +45,10 @@ pub struct RepoView { /// Whether the target's uploaded files let a scheduled scan without new /// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]). pub uploads_allow_skip: bool, + /// Whether the tree is read as Yocto layers (its recipe inventory): it + /// was classified as one, or the target is a Yocto target. Set by the + /// caller after classification; `false` from [`Self::from_target`]. + pub yocto_layers: bool, } impl RepoView { @@ -74,6 +78,7 @@ impl RepoView { findings_count: target.findings_count, managed: target.source_repo.is_some(), uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target), + yocto_layers: false, }; if let Some(git) = &code.git { view.default_branch = git.default_branch.clone(); diff --git a/compliance-agent/src/pipeline/vex_lifecycle.rs b/compliance-agent/src/pipeline/vex_lifecycle.rs index b00c498..f571723 100644 --- a/compliance-agent/src/pipeline/vex_lifecycle.rs +++ b/compliance-agent/src/pipeline/vex_lifecycle.rs @@ -5,7 +5,10 @@ //! complete lookup no longer reports it (the component removed or updated //! past the fix), it is marked resolved, and one nobody assessed, or //! assessed as affected, gets the VEX status `fixed` from the scan. A -//! person's `not_affected` or `fixed` is never changed by a scan. The first +//! person's `not_affected` or `fixed` is never changed by a scan. What a +//! scan states from the target's own data (a Yocto recipe's CVE_STATUS or +//! `CVE:` patch) is stated again on every scan, and likewise never replaces +//! a person's statement. The first //! scan that finds it actively exploited records when (`exploited_seen_at`), //! the start of the CRA's reporting deadlines. //! @@ -148,15 +151,64 @@ pub async fn upsert_reported(db: &Database, alert: &CveAlert) -> Result<(), Agen ) .await?; } - let mut scan_fixed = filter; - scan_fixed.insert("vex.by_scan", true); - scan_fixed.insert("vex.status", "fixed"); + // Reported again, the scan's own statement is withdrawn: a `fixed` + // because the component was gone, or what a recipe said last time + // ([`apply_scan_statements`] states it again if it still does). + let mut by_scan = filter; + by_scan.insert("vex.by_scan", true); db.cve_alerts() - .update_one(scan_fixed, doc! { "$unset": { "vex": "" } }) + .update_one(by_scan, doc! { "$unset": { "vex": "" } }) .await?; Ok(()) } +/// Set the VEX statements this scan makes on `repo_id`'s alerts (a Yocto +/// recipe's CVE_STATUS or `CVE:` patch, see +/// [`crate::pipeline::yocto_inventory::vex_statements`]), each as +/// `(cve_id, statement)`. Only an alert nobody assessed, or one whose +/// statement a scan made, gets it: a person's statement is never replaced. +/// Run after [`upsert_reported`], which withdraws the scan's last statements. +/// +/// # Returns +/// +/// How many alerts got a statement. +/// +/// # Errors +/// +/// A database error. +pub async fn apply_scan_statements( + db: &Database, + repo_id: &str, + statements: &[(String, VexAssessment)], +) -> Result { + let mut set = 0; + for (cve_id, statement) in statements { + let vex = mongodb::bson::to_bson(statement) + .map_err(|e| AgentError::Other(format!("encode VEX: {e}")))?; + let result = db + .cve_alerts() + .update_one( + scan_may_state(repo_id, cve_id), + doc! { "$set": { "vex": vex } }, + ) + .await?; + set += result.modified_count; + } + Ok(set) +} + +/// The alert `cve_id` of `repo_id`, while no person has assessed it. +fn scan_may_state(repo_id: &str, cve_id: &str) -> mongodb::bson::Document { + doc! { + "repo_id": repo_id, + "cve_id": cve_id, + "$or": [ + { "vex": { "$exists": false } }, + { "vex.by_scan": true }, + ], + } +} + /// Mark resolved the stored alerts of `repo_id` a complete lookup /// (`complete`) no longer reports in `current`. /// diff --git a/compliance-agent/src/pipeline/yocto_inventory.rs b/compliance-agent/src/pipeline/yocto_inventory.rs new file mode 100644 index 0000000..30647b7 --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_inventory.rs @@ -0,0 +1,936 @@ +//! The recipe inventory of a Yocto/OpenEmbedded layer tree, without a build. +//! +//! The image's helper (`docker/pruefwerk_yocto_recipes.py`) parses every +//! recipe with oelint-parser (BSD-2-Clause), which reads BitBake syntax and +//! never runs a recipe's Python or shell code. Each recipe becomes an SBOM +//! component: its version (PV, or the file name `name_version.bb`), its +//! upstream source (the first remote SRC_URI entry, a git fetch with its +//! 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. +//! +//! 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::path::Path; +use std::time::Duration; + +use compliance_core::models::{ + CveAlert, 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 helper the agent image installs (see `Dockerfile.agent`). +const HELPER: &str = "/opt/pruefwerk/pruefwerk_yocto_recipes.py"; + +/// How long the helper may parse a tree. A Poky checkout's `meta` layer (about +/// 800 recipes) takes about a minute. +const TIMEOUT: Duration = Duration::from_secs(600); + +/// How long the recipes may be matched in NVD per scan. NVD answers about 5 +/// requests per 30 seconds without an API key and 50 with one; what does not +/// fit is reported as unchecked, and the next scan reuses the answers it got. +pub const NVD_BUDGET: Duration = Duration::from_secs(600); + +/// The longest value taken from a recipe. The values are the customer's +/// input: a version or a name longer than this is not one. +const MAX_VALUE: usize = 512; + +/// One recipe as the helper reports it. +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct Recipe { + /// The `.bb` file, relative to the tree. + pub file: String, + /// The `.bbappend` files that apply to it. + #[serde(default)] + pub appends: Vec, + /// The recipe name (PN) from the file name. + pub pn: String, + /// The base recipe name (BPN): PN without a `-native` or multilib part. + pub bpn: String, + /// PV as assigned, expanded as far as the tree allows, or from the file + /// name; `None` when neither gives one. + #[serde(default)] + pub pv: Option, + /// The fetched commit of a git source. + #[serde(default)] + pub srcrev: Option, + /// The first upstream SRC_URI entry, with its `;` options. + #[serde(default)] + pub src_uri: Option, + /// LICENSE as written (`GPL-2.0-only & bzip2-1.0.4`). + #[serde(default)] + pub license: Option, + /// CVE_PRODUCT: `product` or `vendor:product`, possibly several. + #[serde(default)] + pub cve_product: Vec, + /// CVE_VERSION, where it differs from PV. + #[serde(default)] + pub cve_version: Option, + /// The recipe's CVE_STATUS assessments. + #[serde(default)] + pub cve_status: Vec, + /// The patches SRC_URI applies. + #[serde(default)] + pub patches: Vec, +} + +/// One `CVE_STATUS[CVE-…] = "reason: detail"`. +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct CveStatus { + pub cve: String, + /// The reason (`not-applicable-config`, `backported-patch`). + pub status: String, + /// The text after the reason. + #[serde(default)] + pub detail: String, +} + +/// A patch in SRC_URI and the CVEs it fixes (its `CVE:` tags and the ids in +/// its file name). +#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)] +pub struct Patch { + /// The patch file, relative to the tree (its name, when it was not found). + pub file: String, + #[serde(default)] + pub cves: Vec, +} + +/// What the helper read from a tree. +#[derive(Debug, Default, PartialEq, serde::Deserialize)] +pub struct Inventory { + pub recipes: Vec, + /// Recipes the parser could not read. + #[serde(default)] + pub errors: Vec, +} + +/// A recipe the parser could not read, and the kind of error. +#[derive(Debug, Clone, PartialEq, serde::Deserialize)] +pub struct RecipeError { + pub file: String, + pub error: String, +} + +/// Read the recipes of the layer tree at `tree` with the image's helper. +/// +/// # Errors +/// +/// Why no inventory could be formed (the helper is missing, failed, timed out +/// or printed something unreadable), as the skipped stage to record on the +/// scan run. +pub async fn read(tree: &Path) -> Result { + let mut cmd = crate::pipeline::tool_cmd::tool("python3", &[]); + // `-I`: the interpreter ignores PYTHON* variables and never imports from + // the scanned tree. + cmd.arg("-I").arg(HELPER).arg(tree).current_dir(tree); + let output = crate::pipeline::tool_cmd::run_bounded_for(&mut cmd, "oelint-parser", TIMEOUT) + .await + .map_err(|e| failed(format!("the recipe parser did not run: {e}")))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + // The last line names the error; it never quotes a recipe. + let last = stderr.lines().last().unwrap_or_default(); + tracing::warn!(status = %output.status, "Yocto recipe parser failed: {last}"); + return Err(failed(format!( + "the recipe parser exited with {}", + output.status + ))); + } + parse(&output.stdout).map_err(|e| failed(format!("the recipe parser's output: {e}"))) +} + +/// A recipe inventory that could not be formed. +fn failed(reason: String) -> SkippedStage { + SkippedStage::new(STAGE, SkipCode::ToolFailed, reason).about("oelint-parser") +} + +/// The helper's JSON, keeping only recipes whose values are plausible. +/// +/// # Errors +/// +/// The JSON does not have the helper's shape. +fn parse(json: &[u8]) -> Result { + let mut inventory: Inventory = serde_json::from_slice(json)?; + inventory.recipes.retain(plausible); + Ok(inventory) +} + +/// 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 optional = |text: &Option| text.as_deref().is_none_or(ok); + ok(&recipe.file) + && ok(&recipe.pn) + && ok(&recipe.bpn) + && !recipe.bpn.is_empty() + && optional(&recipe.pv) + && optional(&recipe.srcrev) + && optional(&recipe.src_uri) + && optional(&recipe.license) + && optional(&recipe.cve_version) + && recipe.cve_product.iter().all(|p| ok(p)) + && recipe.appends.iter().all(|a| ok(a)) + && recipe + .cve_status + .iter() + .all(|s| ok(&s.cve) && ok(&s.status) && ok(&s.detail)) + && recipe + .patches + .iter() + .all(|p| ok(&p.file) && p.cves.iter().all(|c| ok(c))) +} + +/// The version a recipe's component is listed and matched with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RecipeVersion { + /// A release version (`1.35.0`; `1.0` of `1.0+gitAUTOINC+…`). + Release(String), + /// Only the fetched commit is known (`PV = "git"`). + Commit(String), + /// Neither. + Unknown, +} + +impl RecipeVersion { + /// The version as the SBOM lists it. + fn as_str(&self) -> &str { + match self { + Self::Release(v) | Self::Commit(v) => v, + Self::Unknown => "", + } + } +} + +/// The release part of a PV: what precedes a git or SCM suffix or a variable +/// the tree does not define (`1.0+git${SRCPV}` → `1.0`). `None` when nothing +/// is left (`git`, `+git`). +fn release_of(pv: &str) -> Option { + let end = ["${", "+git", "AUTOINC", "+svn", "+hg", "+cvs"] + .iter() + .filter_map(|marker| pv.find(marker)) + .min() + .unwrap_or(pv.len()); + let release = pv[..end].trim_end_matches(['+', '-', '.', '_']).trim(); + (!release.is_empty() && release != "git").then(|| release.to_string()) +} + +/// The version of `recipe`: the release part of PV, else the SRCREV of its +/// git source, else unknown. +pub fn version(recipe: &Recipe) -> RecipeVersion { + if let Some(release) = recipe.pv.as_deref().and_then(release_of) { + return RecipeVersion::Release(release); + } + match recipe.srcrev.as_deref() { + Some(rev) if !rev.is_empty() && rev.chars().all(|c| c.is_ascii_hexdigit()) => { + RecipeVersion::Commit(rev.to_string()) + } + _ => RecipeVersion::Unknown, + } +} + +/// The URL of a SRC_URI entry without its `;` options, and those options. +fn split_src_uri(entry: &str) -> (&str, Vec<(&str, &str)>) { + let mut parts = entry.split(';'); + let url = parts.next().unwrap_or_default(); + let options = parts.filter_map(|o| o.split_once('=')).collect(); + (url, options) +} + +/// The `owner/repo` of a source on GitHub (`git://github.com/o/r.git`, +/// `https://github.com/o/r/archive/…`, `…/releases/download/…`), lowercased +/// as the purl spec asks for GitHub names. +fn github_repo(src_uri: &str) -> Option<(String, String)> { + let (url, _) = split_src_uri(src_uri); + let (_, rest) = url.split_once("://")?; + let path = rest.strip_prefix("github.com/")?; + let mut parts = path.split('/'); + let owner = parts.next().filter(|o| !o.is_empty())?; + let repo = parts.next()?.trim_end_matches(".git"); + (!repo.is_empty()).then(|| (owner.to_ascii_lowercase(), repo.to_ascii_lowercase())) +} + +/// Where the source of `src_uri` is fetched from, as a purl qualifier: a +/// tarball's `download_url`, a git repository's `vcs_url`. `None` while a +/// variable in it is unresolved (`${KERNELORG_MIRROR}/…`). +fn source_qualifier(src_uri: &str, srcrev: Option<&str>) -> Option<(&'static str, String)> { + let (url, options) = split_src_uri(src_uri); + if url.contains("${") { + return None; + } + let (scheme, rest) = url.split_once("://")?; + match scheme { + "http" | "https" | "ftp" => Some(("download_url", url.to_string())), + "git" | "gitsm" => { + let protocol = options + .iter() + .find(|(k, _)| *k == "protocol") + .map_or("git", |(_, v)| v); + // Only a fixed commit names the source; `${AUTOREV}` does not. + let at = srcrev + .filter(|rev| !rev.is_empty() && rev.chars().all(|c| c.is_ascii_hexdigit())) + .map(|rev| format!("@{rev}")) + .unwrap_or_default(); + Some(("vcs_url", format!("git+{protocol}://{rest}{at}"))) + } + _ => None, + } +} + +/// The purl of a recipe's component: `pkg:github/owner/repo@version` for a +/// source on GitHub, else `pkg:generic/@` with where the source +/// comes from. +fn purl(recipe: &Recipe, version: &RecipeVersion) -> String { + let at = match version { + RecipeVersion::Unknown => String::new(), + known => format!("@{}", encode(known.as_str())), + }; + if let Some((owner, repo)) = recipe.src_uri.as_deref().and_then(github_repo) { + return format!("pkg:github/{}/{}{at}", encode(&owner), encode(&repo)); + } + let mut purl = format!("pkg:generic/{}{at}", encode(&recipe.bpn)); + if let Some((key, value)) = recipe + .src_uri + .as_deref() + .and_then(|uri| source_qualifier(uri, recipe.srcrev.as_deref())) + { + purl.push_str(&format!("?{key}={}", encode(&value))); + } + purl +} + +/// A product as NVD names it in a CPE: CVE_PRODUCT's `vendor:product` or +/// `product`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CpeProduct { + pub vendor: Option, + pub product: String, +} + +impl CpeProduct { + /// A CPE 2.3 name of this product at `version` (any vendor when none is + /// given). + pub fn cpe(&self, version: &str) -> String { + format!( + "cpe:2.3:a:{}:{}:{}:*:*:*:*:*:*:*", + self.vendor.as_deref().map_or("*".to_string(), cpe_value), + cpe_value(&self.product), + cpe_value(version), + ) + } + + /// The match string NVD is asked with: any part (`a`, `o`), the vendor + /// or any vendor. + pub fn match_string(&self) -> String { + format!( + "cpe:2.3:*:{}:{}", + self.vendor.as_deref().map_or("*".to_string(), cpe_value), + cpe_value(&self.product) + ) + } + + /// What a vulnerable CPE's criteria must contain to count for it. + pub fn marker(&self) -> String { + match &self.vendor { + Some(vendor) => format!(":{}:{}:", cpe_value(vendor), cpe_value(&self.product)), + None => format!(":{}:", cpe_value(&self.product)), + } + } +} + +/// `text` as a CPE 2.3 value: lowercase, with every character but letters, +/// digits, `_`, `.` and `-` quoted by a backslash. +fn cpe_value(text: &str) -> String { + text.to_ascii_lowercase() + .chars() + .flat_map(|c| { + let quote = !(c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')); + quote.then_some('\\').into_iter().chain(std::iter::once(c)) + }) + .collect() +} + +/// The products NVD may list `recipe` under: its CVE_PRODUCT, else its BPN +/// (as Yocto's cve-check does). +pub fn cpe_products(recipe: &Recipe) -> Vec { + let named: Vec = recipe + .cve_product + .iter() + .filter(|p| !p.is_empty() && !p.contains("${")) + .map(|p| match p.split_once(':') { + Some((vendor, product)) => CpeProduct { + vendor: Some(vendor.to_string()).filter(|v| !v.is_empty() && v != "*"), + product: product.to_string(), + }, + None => CpeProduct { + vendor: None, + product: p.clone(), + }, + }) + .filter(|p| !p.product.is_empty()) + .collect(); + if named.is_empty() { + vec![CpeProduct { + vendor: None, + product: recipe.bpn.clone(), + }] + } else { + named + } +} + +/// The version NVD's ranges are compared with: CVE_VERSION, else the release +/// version. `None` when only a commit or nothing is known. +fn cve_version(recipe: &Recipe, version: &RecipeVersion) -> Option { + recipe + .cve_version + .as_deref() + .filter(|v| !v.is_empty() && !v.contains("${")) + .map(str::to_string) + .or_else(|| match version { + RecipeVersion::Release(v) => Some(v.clone()), + RecipeVersion::Commit(_) | RecipeVersion::Unknown => None, + }) +} + +/// LICENSE as an SPDX expression: Yocto writes `&` for AND and `|` for OR. +fn spdx_license(license: &str) -> String { + license + .split_whitespace() + .map(|token| match token { + "&" => "AND", + "|" => "OR", + other => other, + }) + .collect::>() + .join(" ") +} + +/// The SBOM components of `recipes`, one per base recipe name and version. +pub fn entries(recipes: &[Recipe], repo_id: &str) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut out = Vec::with_capacity(recipes.len()); + for recipe in recipes { + let version = version(recipe); + if !seen.insert((recipe.bpn.clone(), version.as_str().to_string())) { + continue; + } + let mut entry = SbomEntry::new( + repo_id.to_string(), + recipe.bpn.clone(), + version.as_str().to_string(), + YOCTO_RECIPE_MANAGER.to_string(), + ); + entry.purl = Some(purl(recipe, &version)); + entry.license = recipe + .license + .as_deref() + .filter(|l| !l.is_empty()) + .map(spdx_license); + entry.cpe = cpe_products(recipe) + .first() + .map(|p| p.cpe(&cve_version(recipe, &version).unwrap_or_else(|| "*".into()))); + entry.download_url = recipe + .src_uri + .as_deref() + .and_then(|uri| source_qualifier(uri, None)) + .filter(|(key, _)| *key == "download_url") + .map(|(_, url)| url); + let mut evidence = format!("{YOCTO_RECIPE_SOURCE}: {}", recipe.file); + if !recipe.appends.is_empty() { + evidence.push_str(&format!(" (+ {})", recipe.appends.join(", "))); + } + entry.evidence.push(evidence); + out.push(entry); + } + out +} + +/// One recipe's question to NVD: the CVEs of its products at its version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NvdQuery { + /// The component (name and version) the CVEs are recorded on. + pub name: String, + pub version: String, + /// The version NVD's ranges are compared with. + pub cve_version: String, + pub products: Vec, +} + +/// What to ask NVD about `recipes`, and the components that cannot be asked +/// about (`"busybox (no release version)"`). +/// +/// A recipe is asked about when NVD could know it: it names a CVE_PRODUCT or +/// fetches from upstream. A recipe of the customer's own code (only `file://` +/// sources, no CVE_PRODUCT) is not. +pub fn nvd_queries(recipes: &[Recipe]) -> (Vec, Vec) { + let mut queries: Vec = Vec::new(); + let mut unversioned = Vec::new(); + for recipe in recipes { + if recipe.cve_product.is_empty() && recipe.src_uri.is_none() { + continue; + } + let version = version(recipe); + let Some(cve_version) = cve_version(recipe, &version) else { + unversioned.push(format!("{} (no release version)", recipe.bpn)); + continue; + }; + let query = NvdQuery { + name: recipe.bpn.clone(), + version: version.as_str().to_string(), + cve_version, + products: cpe_products(recipe), + }; + if !queries.contains(&query) { + queries.push(query); + } + } + (queries, unversioned) +} + +/// The VEX statement a Yocto CVE_STATUS reason makes, as cve-check maps them +/// (`meta/conf/cve-check-map.conf`): the patched ones `fixed`, the ones that +/// do not apply to this build `not_affected`, and the ones the recipe merely +/// set aside (`upstream-wontfix`, `disputed`, `ignored`) `under_investigation` +/// with the reason as a note. `unpatched` and `vulnerable-investigation` make +/// none: the alert stays open for a person to assess. +fn status_statement(status: &str) -> Option<(VexStatus, Option)> { + match status { + "backported-patch" | "cpe-stable-backport" | "fixed-version" => { + Some((VexStatus::Fixed, None)) + } + "cpe-incorrect" => Some(( + VexStatus::NotAffected, + Some(VexJustification::ComponentNotPresent), + )), + "not-applicable-platform" | "not-applicable-config" => Some(( + VexStatus::NotAffected, + Some(VexJustification::VulnerableCodeNotPresent), + )), + // The recipe's author set it aside, which says nothing on whether the + // product is affected: it stays to be assessed, with the reason as + // the statement's note. + "upstream-wontfix" | "disputed" | "ignored" => Some((VexStatus::UnderInvestigation, None)), + _ => None, + } +} + +/// A statement the scan makes, saying where it comes from. +fn scan_statement( + status: VexStatus, + justification: Option, + because: String, +) -> VexAssessment { + VexAssessment { + status, + justification, + impact_statement: Some(because), + action_statement: None, + by: StatusChange::SCAN_ACTOR.to_string(), + by_name: None, + at: chrono::Utc::now(), + by_scan: true, + } +} + +/// What `recipe` says about `cve`: its CVE_STATUS, else a patch whose `CVE:` +/// tag names it. +pub fn recipe_statement(recipe: &Recipe, cve: &str) -> Option { + if let Some(entry) = recipe.cve_status.iter().find(|s| s.cve == cve) { + let (status, justification) = status_statement(&entry.status)?; + let detail = if entry.detail.is_empty() { + String::new() + } else { + format!(": {}", entry.detail) + }; + return Some(scan_statement( + status, + justification, + format!( + "Yocto CVE_STATUS \"{}\" in {}{detail}", + entry.status, recipe.file + ), + )); + } + let patch = recipe + .patches + .iter() + .find(|p| p.cves.iter().any(|c| c == cve))?; + Some(scan_statement( + VexStatus::Fixed, + None, + format!( + "Fixed by the backported patch {} (CVE: tag) that {} applies", + patch.file, recipe.file + ), + )) +} + +/// The VEX statements the recipes make on this scan's `alerts`: one per +/// alert of a recipe component whose recipe assesses its CVE. +pub fn vex_statements(recipes: &[Recipe], alerts: &[CveAlert]) -> Vec<(String, VexAssessment)> { + alerts + .iter() + .filter_map(|alert| { + let recipe = recipes.iter().find(|r| { + r.bpn == alert.affected_package && version(r).as_str() == alert.affected_version + })?; + recipe_statement(recipe, &alert.cve_id).map(|vex| (alert.cve_id.clone(), vex)) + }) + .collect() +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use compliance_core::models::CveSource; + + fn recipe(bpn: &str, pv: Option<&str>) -> Recipe { + Recipe { + file: format!("recipes-core/{bpn}/{bpn}.bb"), + pn: bpn.into(), + bpn: bpn.into(), + pv: pv.map(String::from), + ..Recipe::default() + } + } + + fn fixture() -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer") + } + + #[test] + fn a_pv_keeps_its_release_and_drops_scm_suffixes() { + assert_eq!(release_of("1.35.0").as_deref(), Some("1.35.0")); + assert_eq!(release_of("1.0+git${SRCPV}").as_deref(), Some("1.0")); + assert_eq!(release_of("2.39+git").as_deref(), Some("2.39")); + assert_eq!( + release_of("0.1+gitAUTOINC+64bc7c8fae").as_deref(), + Some("0.1") + ); + assert_eq!(release_of("git"), None); + assert_eq!(release_of("+git"), None); + assert_eq!(release_of("${SRCPV}"), None); + } + + #[test] + fn without_a_release_the_version_is_the_commit_or_unknown() { + let mut r = recipe("dbus-wait", Some("git")); + r.srcrev = Some("64bc7c8fae61ded0c4e555aa775911f84c56e438".into()); + assert_eq!( + version(&r), + RecipeVersion::Commit("64bc7c8fae61ded0c4e555aa775911f84c56e438".into()) + ); + r.srcrev = Some("${AUTOREV}".into()); + assert_eq!(version(&r), RecipeVersion::Unknown); + assert_eq!(version(&recipe("x", None)), RecipeVersion::Unknown); + } + + #[test] + fn a_github_source_gets_a_github_purl() { + let mut r = recipe("libmodbus", Some("3.1.6")); + r.src_uri = + Some("git://github.com/Stephane/libmodbus.git;protocol=https;branch=master".into()); + assert_eq!( + purl(&r, &version(&r)), + "pkg:github/stephane/libmodbus@3.1.6" + ); + r.src_uri = + Some("https://github.com/avahi/avahi/releases/download/v0.8/avahi-0.8.tar.gz".into()); + assert_eq!(purl(&r, &version(&r)), "pkg:github/avahi/avahi@3.1.6"); + } + + #[test] + fn another_source_gets_a_generic_purl_saying_where_it_comes_from() { + let mut r = recipe("busybox", Some("1.35.0")); + r.src_uri = Some("https://busybox.net/downloads/busybox-1.35.0.tar.bz2".into()); + assert_eq!( + purl(&r, &version(&r)), + "pkg:generic/busybox@1.35.0?download_url=https%3A%2F%2Fbusybox.net%2Fdownloads%2Fbusybox-1.35.0.tar.bz2" + ); + r.src_uri = + Some("git://git.kernel.org/pub/scm/network/nfc/neard.git;protocol=https".into()); + r.srcrev = Some("a1dc8a75".into()); + assert_eq!( + purl(&r, &version(&r)), + "pkg:generic/busybox@1.35.0?vcs_url=git%2Bhttps%3A%2F%2Fgit.kernel.org%2Fpub%2Fscm%2Fnetwork%2Fnfc%2Fneard.git%40a1dc8a75" + ); + // An unresolved mirror variable says nothing about where. + r.src_uri = Some("${KERNELORG_MIRROR}/linux/bluez-5.72.tar.xz".into()); + assert_eq!(purl(&r, &version(&r)), "pkg:generic/busybox@1.35.0"); + assert_eq!( + purl(&recipe("x", None), &RecipeVersion::Unknown), + "pkg:generic/x" + ); + } + + #[test] + fn the_cpe_names_cve_product_and_cve_version_or_the_recipe() { + let mut r = recipe("u-boot", Some("2024.01")); + r.cve_product = vec!["denx:u-boot".into(), "u-boot".into()]; + let products = cpe_products(&r); + assert_eq!(products.len(), 2); + assert_eq!( + products[0].cpe("2024.01"), + "cpe:2.3:a:denx:u-boot:2024.01:*:*:*:*:*:*:*" + ); + assert_eq!(products[0].match_string(), "cpe:2.3:*:denx:u-boot"); + assert_eq!(products[0].marker(), ":denx:u-boot:"); + assert_eq!(products[1].match_string(), "cpe:2.3:*:*:u-boot"); + assert_eq!(products[1].marker(), ":u-boot:"); + + 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]; + assert_eq!( + entry.cpe.as_deref(), + Some("cpe:2.3:a:*:busybox:1.35:*:*:*:*:*:*:*") + ); + assert_eq!(cpe_value("c++"), "c\\+\\+"); + } + + #[test] + fn a_component_is_labelled_as_the_recipe_inventory() { + 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"); + assert_eq!(entries.len(), 1, "one component per name and version"); + let entry = &entries[0]; + assert_eq!(entry.package_manager, YOCTO_RECIPE_MANAGER); + assert_eq!( + entry.license.as_deref(), + Some("GPL-2.0-only AND bzip2-1.0.4") + ); + assert_eq!( + entry.evidence, + vec![format!( + "{YOCTO_RECIPE_SOURCE}: recipes-core/busybox/busybox.bb \ + (+ recipes-core/busybox/busybox_%.bbappend)" + )] + ); + } + + #[test] + fn only_versioned_recipes_from_upstream_are_asked_about() { + let own = recipe("pump-ctl", Some("1.0")); + let mut upstream = recipe("busybox", Some("1.35.0")); + upstream.src_uri = Some("https://busybox.net/busybox-1.35.0.tar.bz2".into()); + let mut unversioned = recipe("tool", Some("git")); + unversioned.cve_product = vec!["vendor:tool".into()]; + let (queries, unchecked) = nvd_queries(&[own, upstream, unversioned]); + assert_eq!(queries.len(), 1); + assert_eq!(queries[0].name, "busybox"); + assert_eq!(queries[0].cve_version, "1.35.0"); + assert_eq!(unchecked, vec!["tool (no release version)".to_string()]); + } + + #[test] + fn cve_status_reasons_map_to_openvex() { + let fixed = ["backported-patch", "cpe-stable-backport", "fixed-version"]; + for status in fixed { + assert_eq!( + status_statement(status), + Some((VexStatus::Fixed, None)), + "{status}" + ); + } + assert_eq!( + status_statement("cpe-incorrect"), + Some(( + VexStatus::NotAffected, + Some(VexJustification::ComponentNotPresent) + )) + ); + for status in ["not-applicable-platform", "not-applicable-config"] { + assert_eq!( + status_statement(status), + Some(( + VexStatus::NotAffected, + Some(VexJustification::VulnerableCodeNotPresent) + )) + ); + } + for status in ["upstream-wontfix", "disputed", "ignored"] { + assert_eq!( + status_statement(status), + Some((VexStatus::UnderInvestigation, None)) + ); + } + assert_eq!(status_statement("unpatched"), None); + assert_eq!(status_statement("vulnerable-investigation"), None); + } + + #[test] + fn a_status_or_a_patch_becomes_a_valid_scan_statement() { + let mut r = recipe("busybox", Some("1.35.0")); + r.cve_status = vec![ + CveStatus { + cve: "CVE-2022-28391".into(), + status: "not-applicable-config".into(), + detail: "netstat is disabled".into(), + }, + CveStatus { + cve: "CVE-2023-1".into(), + status: "disputed".into(), + detail: String::new(), + }, + ]; + r.patches = vec![Patch { + file: "recipes-core/busybox/busybox/fix.patch".into(), + cves: vec!["CVE-2022-30065".into()], + }]; + + let status = recipe_statement(&r, "CVE-2022-28391").expect("CVE_STATUS"); + assert_eq!(status.status, VexStatus::NotAffected); + assert!(status.by_scan); + assert_eq!(status.by, StatusChange::SCAN_ACTOR); + assert_eq!( + status.impact_statement.as_deref(), + Some( + "Yocto CVE_STATUS \"not-applicable-config\" in recipes-core/busybox/busybox.bb: \ + netstat is disabled" + ) + ); + let disputed = recipe_statement(&r, "CVE-2023-1").expect("CVE_STATUS"); + assert_eq!(disputed.status, VexStatus::UnderInvestigation); + assert_eq!( + disputed.impact_statement.as_deref(), + Some("Yocto CVE_STATUS \"disputed\" in recipes-core/busybox/busybox.bb") + ); + assert!(disputed.validate().is_ok()); + + let patched = recipe_statement(&r, "CVE-2022-30065").expect("CVE: tag"); + assert_eq!(patched.status, VexStatus::Fixed); + assert!(patched + .impact_statement + .as_deref() + .is_some_and(|s| s.contains("fix.patch"))); + assert!(recipe_statement(&r, "CVE-2099-1").is_none()); + } + + #[test] + fn statements_go_to_the_alerts_of_the_recipe_component() { + let mut r = recipe("busybox", Some("1.35.0")); + r.patches = vec![Patch { + file: "fix.patch".into(), + cves: vec!["CVE-2022-30065".into()], + }]; + let alert = |cve: &str, version: &str| { + CveAlert::new( + cve.into(), + "t".into(), + "busybox".into(), + version.into(), + CveSource::Nvd, + ) + }; + let statements = vex_statements( + &[r], + &[ + alert("CVE-2022-30065", "1.35.0"), + alert("CVE-2022-30065", "1.36.0"), + alert("CVE-2022-48174", "1.35.0"), + ], + ); + assert_eq!(statements.len(), 1); + assert_eq!(statements[0].0, "CVE-2022-30065"); + } + + #[test] + fn implausible_values_are_dropped_not_stored() { + let json = br#"{"recipes": [ + {"file": "a.bb", "pn": "a", "bpn": "a", "pv": "1.0"}, + {"file": "b.bb", "pn": "b", "bpn": "b", "pv": "MONGO=x\nKEY=y"} + ], "errors": [{"file": "c.bb", "error": "ValueError"}]}"#; + let inventory = parse(json).expect("the helper's shape"); + assert_eq!(inventory.recipes.len(), 1); + assert_eq!(inventory.recipes[0].bpn, "a"); + assert_eq!(inventory.errors.len(), 1); + } + + /// 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 helper = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../docker/pruefwerk_yocto_recipes.py"); + let available = std::process::Command::new("python3") + .args(["-I", "-c", "import oelint_parser"]) + .output() + .is_ok_and(|o| o.status.success()); + if !available { + eprintln!("skipped: python3 with oelint-parser is not installed"); + return; + } + let output = std::process::Command::new("python3") + .arg("-I") + .arg(&helper) + .arg(fixture()) + .output() + .expect("the helper runs"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let inventory = parse(&output.stdout).expect("the helper's shape"); + assert!(inventory.errors.is_empty(), "{:?}", inventory.errors); + + let names: Vec<&str> = inventory.recipes.iter().map(|r| r.bpn.as_str()).collect(); + assert_eq!( + names, + ["pump-ctl", "pump-fw", "pump-web", "libmodbus", "busybox"], + "the image is no component" + ); + + let busybox = &inventory.recipes[4]; + assert_eq!(busybox.pv.as_deref(), Some("1.35.0")); + assert_eq!( + busybox.src_uri.as_deref(), + Some("https://busybox.net/downloads/busybox-1.35.0.tar.bz2") + ); + let statuses: Vec<(&str, &str)> = busybox + .cve_status + .iter() + .map(|s| (s.cve.as_str(), s.status.as_str())) + .collect(); + assert_eq!( + statuses, + [ + ("CVE-2022-28391", "not-applicable-config"), + ("CVE-2025-46394", "not-applicable-config"), + ("CVE-2025-60876", "not-applicable-config"), + ], + "CVE_STATUS and the bbappend's CVE_STATUS_GROUPS" + ); + assert_eq!(busybox.patches[0].cves, ["CVE-2022-30065"]); + + let entries = entries(&inventory.recipes, "t"); + let purls: Vec<&str> = entries.iter().filter_map(|e| e.purl.as_deref()).collect(); + assert_eq!( + purls, + [ + "pkg:generic/pump-ctl@1.0", + "pkg:generic/pump-fw@1.0?vcs_url=git%2Bhttps%3A%2F%2Fgit.example.com%2Fpump-fw.git", + "pkg:generic/pump-web@2.1?download_url=http%3A%2F%2Fdownloads.example.com%2Fpump-web-2.1.tar.gz", + "pkg:github/stephane/libmodbus@3.1.6", + "pkg:generic/busybox@1.35.0?download_url=https%3A%2F%2Fbusybox.net%2Fdownloads%2Fbusybox-1.35.0.tar.bz2", + ] + ); + let (queries, unchecked) = nvd_queries(&inventory.recipes); + assert_eq!(queries.len(), 4, "pump-ctl is the customer's own code"); + assert!(unchecked.is_empty()); + } +} diff --git a/compliance-agent/tests/vex_lifecycle.rs b/compliance-agent/tests/vex_lifecycle.rs index ca9c380..71d8eac 100644 --- a/compliance-agent/tests/vex_lifecycle.rs +++ b/compliance-agent/tests/vex_lifecycle.rs @@ -8,7 +8,10 @@ #![allow(clippy::expect_used, clippy::unwrap_used)] use compliance_agent::database::{Database, DatabasePool}; -use compliance_agent::pipeline::vex_lifecycle::{backfill_purls, resolve_gone, upsert_reported}; +use compliance_agent::pipeline::vex_lifecycle::{ + apply_scan_statements, backfill_purls, resolve_gone, upsert_reported, +}; +use compliance_agent::pipeline::yocto_inventory::{self, CveStatus, Patch, Recipe}; use compliance_core::models::{ CveAlert, CveSource, SbomEntry, VexAssessment, VexJustification, VexStatus, }; @@ -240,3 +243,136 @@ async fn an_alert_from_before_keeps_its_purl_after_the_component_is_gone() { pool.drop_tenant(tenant).await.ok(); } + +/// A Yocto recipe's CVE_STATUS and `CVE:` patch become the alerts' VEX +/// statements on every scan, reach the exports, are withdrawn when the recipe +/// stops saying so, and never replace a person's statement. +#[tokio::test] +async fn a_recipe_states_vex_each_scan_but_never_over_a_person() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "vexyocto_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP vex_lifecycle: no MongoDB reachable at {uri}"); + return; + }; + let tenant = "vex-yocto"; + let Ok(db) = pool.for_tenant_id(tenant).await else { + eprintln!("SKIP vex_lifecycle: MongoDB at {uri} not usable"); + return; + }; + + // Arrange: busybox's recipe assesses one CVE and patches another; a + // person assessed a third one the recipe also names. + let mut recipe = Recipe { + file: "recipes-core/busybox/busybox_1.35.0.bb".into(), + pn: "busybox".into(), + bpn: "busybox".into(), + pv: Some("1.35.0".into()), + cve_status: vec![ + CveStatus { + cve: "CVE-2022-28391".into(), + status: "not-applicable-config".into(), + detail: "netstat is disabled".into(), + }, + CveStatus { + cve: "CVE-2022-48174".into(), + status: "ignored".into(), + detail: String::new(), + }, + ], + patches: vec![Patch { + file: "recipes-core/busybox/busybox/fix.patch".into(), + cves: vec!["CVE-2022-30065".into()], + }], + ..Recipe::default() + }; + let busybox = |id: &str| { + CveAlert::new( + id.into(), + TARGET.into(), + "busybox".into(), + "1.35.0".into(), + CveSource::Nvd, + ) + }; + let alerts: Vec = ["CVE-2022-28391", "CVE-2022-30065", "CVE-2022-48174"] + .into_iter() + .map(busybox) + .collect(); + for alert in &alerts { + upsert_reported(&db, alert).await.unwrap(); + } + let person = mongodb::bson::to_bson(&by_person(VexStatus::Affected)).unwrap(); + db.cve_alerts() + .update_one( + doc! { "cve_id": "CVE-2022-48174" }, + doc! { "$set": { "vex": person } }, + ) + .await + .unwrap(); + + // Act: the scan states what the recipe says. + let statements = yocto_inventory::vex_statements(std::slice::from_ref(&recipe), &alerts); + assert_eq!(statements.len(), 3); + assert_eq!( + apply_scan_statements(&db, TARGET, &statements) + .await + .unwrap(), + 2 + ); + + // Assert: not_affected and fixed by the scan; the person's stays. + let status = stored(&db, "CVE-2022-28391").await.vex.unwrap(); + assert_eq!( + (status.status, status.justification, status.by_scan), + ( + VexStatus::NotAffected, + Some(VexJustification::VulnerableCodeNotPresent), + true + ) + ); + let patched = stored(&db, "CVE-2022-30065").await.vex.unwrap(); + assert_eq!(patched.status, VexStatus::Fixed); + let kept = stored(&db, "CVE-2022-48174").await.vex.unwrap(); + assert_eq!((kept.status, kept.by_scan), (VexStatus::Affected, false)); + + // The exports carry the recipe's reason. + let current = vec![stored(&db, "CVE-2022-28391").await]; + let input = vex_docs::VexInput { + subject: "pump", + author: "ws", + tooling: "Prüfwerk test", + alerts: ¤t, + sbom: &[], + now: chrono::Utc::now(), + }; + let openvex = vex_docs::openvex(&input).to_string(); + assert!(openvex.contains("not_affected"), "{openvex}"); + assert!(openvex.contains("netstat is disabled"), "{openvex}"); + + // The next scan: the recipe no longer assesses CVE-2022-28391, so its + // statement is withdrawn; the patch still fixes CVE-2022-30065. + recipe.cve_status.remove(0); + for alert in &alerts { + upsert_reported(&db, alert).await.unwrap(); + } + let statements = yocto_inventory::vex_statements(std::slice::from_ref(&recipe), &alerts); + apply_scan_statements(&db, TARGET, &statements) + .await + .unwrap(); + assert!(stored(&db, "CVE-2022-28391").await.vex.is_none()); + assert_eq!( + stored(&db, "CVE-2022-30065").await.vex.map(|v| v.status), + Some(VexStatus::Fixed) + ); + assert_eq!( + stored(&db, "CVE-2022-48174").await.vex.map(|v| v.status), + Some(VexStatus::Affected) + ); + + pool.drop_tenant(tenant).await.ok(); +} diff --git a/compliance-core/src/csaf_docs.rs b/compliance-core/src/csaf_docs.rs index 01fea0e..05e7fd1 100644 --- a/compliance-core/src/csaf_docs.rs +++ b/compliance-core/src/csaf_docs.rs @@ -236,7 +236,17 @@ fn vulnerability( "product_ids": [product], })); } - VexStatus::UnderInvestigation | VexStatus::Fixed => {} + // Why it is under investigation or fixed (a Yocto recipe's + // CVE_STATUS or patch), as the impact on these products. + VexStatus::UnderInvestigation | VexStatus::Fixed => { + if let Some(text) = vex.impact_statement.as_deref() { + threats.push(serde_json::json!({ + "category": "impact", + "details": text, + "product_ids": [product], + })); + } + } } } for (field, list) in [ @@ -325,4 +335,48 @@ mod tests { "https://example.invalid/example-pumps" ); } + + #[test] + fn a_scan_note_on_an_open_or_fixed_status_reaches_every_export() { + use crate::models::{CveAlert, CveSource, VexAssessment}; + let mut alert = CveAlert::new( + "CVE-2022-48174".into(), + "t".into(), + "busybox".into(), + "1.35.0".into(), + CveSource::Nvd, + ); + let note = "Yocto CVE_STATUS \"disputed\" in recipes-core/busybox/busybox_1.35.0.bb"; + alert.vex = Some(VexAssessment { + status: VexStatus::UnderInvestigation, + justification: None, + impact_statement: Some(note.into()), + action_statement: None, + by: "pruefwerk-scan".into(), + by_name: None, + at: Utc::now(), + by_scan: true, + }); + let alerts = [alert]; + let input = VexInput { + subject: "pump", + author: "ws", + tooling: "test", + alerts: &alerts, + sbom: &[], + now: Utc::now(), + }; + + let openvex = crate::vex_docs::openvex(&input); + let statement = &openvex["statements"][0]; + assert_eq!(statement["status"], "under_investigation"); + assert_eq!(statement["status_notes"], note); + assert!( + statement.get("impact_statement").is_none(), + "only for not_affected" + ); + + let csaf = csaf_vex(&input, "https://example.invalid/ws", "en"); + assert_eq!(csaf["vulnerabilities"][0]["threats"][0]["details"], note); + } } diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index af95301..974082e 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -65,6 +65,7 @@ pub use project::{Project, ProjectKind}; pub use repository::ScanTrigger; pub use sbom::{ ComponentHash, SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef, + YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, }; pub use scan::{ RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage, diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index b7470ff..5a1b868 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -23,6 +23,16 @@ impl VulnRef { } } +/// The `package_manager` of a component read from a Yocto/OpenEmbedded recipe +/// in a layer tree, without a build. +pub const YOCTO_RECIPE_MANAGER: &str = "yocto-recipe"; + +/// Where a [`YOCTO_RECIPE_MANAGER`] component comes from, as the SBOM view, +/// the exports and the evidence say it. Layer overrides, PACKAGECONFIG and +/// what the image installs are not resolved, so the inventory lists more than +/// an image contains. +pub const YOCTO_RECIPE_SOURCE: &str = "Yocto recipe inventory (not the image SBOM)"; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SbomEntry { #[serde(rename = "_id", skip_serializing_if = "Option::is_none")] @@ -58,6 +68,10 @@ pub struct SbomEntry { /// TR-03183-2's component creator; #508). A URL only, never a person. #[serde(default, skip_serializing_if = "Option::is_none")] pub manufacturer_url: Option, + /// The CPE 2.3 name NVD knows the component by, where it has no purl an + /// advisory database could look up (a Yocto recipe's CVE_PRODUCT). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpe: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -90,6 +104,7 @@ impl SbomEntry { hashes: Vec::new(), download_url: None, manufacturer_url: None, + cpe: None, created_at: now, updated_at: now, } diff --git a/compliance-core/src/purl.rs b/compliance-core/src/purl.rs index dd683cb..441b724 100644 --- a/compliance-core/src/purl.rs +++ b/compliance-core/src/purl.rs @@ -64,6 +64,19 @@ impl Purl { } } +/// `text` percent-encoded for a purl component or qualifier value: every byte +/// but the unreserved ones (`A-Z a-z 0-9 . - _ ~`) as `%XX`. +pub fn encode(text: &str) -> String { + text.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} + /// `text` with its `%XX` escapes decoded; an invalid escape is kept as is. fn decode(text: &str) -> String { let bytes = text.as_bytes(); @@ -92,6 +105,17 @@ fn decode(text: &str) -> String { mod tests { use super::*; + #[test] + fn an_encoded_value_parses_back_to_itself() { + let url = "https://busybox.net/downloads/busybox-1.35.0.tar.bz2"; + let purl = format!("pkg:generic/busybox@1.35.0?download_url={}", encode(url)); + assert!(!encode(url).contains(['/', ':'])); + assert_eq!( + Purl::parse(&purl).and_then(|p| p.qualifier("download_url").map(String::from)), + Some(url.to_string()) + ); + } + #[test] fn the_parts_are_read_and_decoded() { let p = Purl::parse("pkg:npm/%40angular/core@16.2.0").unwrap(); diff --git a/compliance-core/src/sbom_docs.rs b/compliance-core/src/sbom_docs.rs index 45a1f1b..d13fadc 100644 --- a/compliance-core/src/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -8,7 +8,9 @@ //! packages, a dependency graph whose completeness is stated, and licences as //! the suppliers declare them. -use crate::models::{advisory_source, is_cve, ComponentHash, SbomEntry}; +use crate::models::{ + advisory_source, is_cve, ComponentHash, SbomEntry, YOCTO_RECIPE_MANAGER, YOCTO_RECIPE_SOURCE, +}; use crate::purl::Purl; use crate::spdx_license; @@ -24,16 +26,7 @@ pub fn component_ref(entry: &SbomEntry) -> String { /// The identifier of the product (the target) the SBOM and the VEX describe: /// `pkg:generic/`, the name percent-encoded as a purl requires. pub fn product_ref(subject: &str) -> String { - let encoded: String = subject - .bytes() - .map(|b| match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => { - (b as char).to_string() - } - _ => format!("%{b:02X}"), - }) - .collect(); - format!("pkg:generic/{encoded}") + format!("pkg:generic/{}", crate::purl::encode(subject)) } /// A license as CycloneDX writes it: an SPDX id, an SPDX expression @@ -92,6 +85,16 @@ fn bsi_properties(purl: &Purl) -> Option { ])) } +/// The property that says where a component comes from when its source +/// limits what it proves: a Yocto recipe is in the layer tree, not +/// necessarily in the image. +const SOURCE_PROPERTY: &str = "pruefwerk:component:source"; + +/// 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) +} + /// 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() { @@ -139,6 +142,16 @@ pub fn cdx_components(entries: &[SbomEntry]) -> Vec { } } } + 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 }); + match comp["properties"].as_array_mut() { + Some(properties) => properties.push(property), + None => comp["properties"] = serde_json::json!([property]), + } + } if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) { comp["licenses"] = license_choice(license); } @@ -357,6 +370,16 @@ pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { if let (Some(raw), None) = (raw, &license) { package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}")); } + if let (Some(cpe), Some(refs)) = (&e.cpe, package["externalRefs"].as_array_mut()) { + refs.push(serde_json::json!({ + "referenceCategory": "SECURITY", + "referenceType": "cpe23Type", + "referenceLocator": cpe, + })); + } + if let Some(source) = source_note(e) { + package["comment"] = serde_json::Value::String(source.to_string()); + } package }) .collect(); @@ -431,4 +454,33 @@ mod tests { assert_eq!(package(3)["licenseDeclared"], "MIT OR Apache-2.0"); assert!(package(3).get("licenseComments").is_none()); } + + #[test] + fn a_yocto_recipe_says_it_is_not_the_image_sbom_in_both_formats() { + let mut recipe = SbomEntry::new( + "t".into(), + "busybox".into(), + "1.35.0".into(), + YOCTO_RECIPE_MANAGER.into(), + ); + recipe.purl = Some("pkg:generic/busybox@1.35.0".into()); + recipe.cpe = Some("cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*".into()); + let other = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into()); + let entries = [recipe, other]; + + let cdx = cyclonedx(&entries, "t"); + let component = &cdx["components"][0]; + assert_eq!(component["cpe"], "cpe:2.3:a:*:busybox:1.35.0:*:*:*:*:*:*:*"); + assert_eq!( + component["properties"], + serde_json::json!([{ "name": SOURCE_PROPERTY, "value": YOCTO_RECIPE_SOURCE }]) + ); + assert!(cdx["components"][1].get("properties").is_none()); + + let spdx = spdx(&entries, "t"); + let package = &spdx["packages"][0]; + assert_eq!(package["comment"], YOCTO_RECIPE_SOURCE); + assert_eq!(package["externalRefs"][1]["referenceType"], "cpe23Type"); + assert!(spdx["packages"][1].get("comment").is_none()); + } } diff --git a/compliance-core/src/scan_matrix.rs b/compliance-core/src/scan_matrix.rs index 2297e57..674f3f6 100644 --- a/compliance-core/src/scan_matrix.rs +++ b/compliance-core/src/scan_matrix.rs @@ -39,8 +39,7 @@ pub const YOCTO_BUILD_PLANNED: &str = /// The recipe inventory of a Yocto layer tree (SBOM and CVEs from its BitBake /// recipes): `Some(reason)` while no stage runs it, `None` once one does. -const RECIPE_INVENTORY: Option<&str> = - Some("the recipe inventory (SBOM and CVEs from the BitBake recipes) is planned"); +const RECIPE_INVENTORY: Option<&str> = None; /// Recipe lint (oelint-adv and our own rules) over a Yocto layer tree, likewise. const RECIPE_LINT: Option<&str> = None; @@ -715,20 +714,14 @@ mod tests { } #[test] - fn a_yocto_layer_tree_runs_recipe_lint_and_lists_the_planned_inventory() { + fn a_yocto_layer_tree_runs_its_recipe_inventory_and_lint() { let t = target_with( TargetType::EmbeddedLinuxYocto, vec![Artifact::git_repo("https://git/meta-pump", "main")], ); let opts = applicable_scans(&t); let inventory = option(&opts, ScanType::RecipeInventory).expect("listed"); - assert!( - !inventory.default_on, - "the inventory must not be pre-selected yet" - ); - // The layer tree is there, so the run records the stage as not done - // instead of passing over it. - assert_eq!(inventory.unavailable_with_artifact(), RECIPE_INVENTORY); + assert!(inventory.default_on && inventory.unavailable.is_none()); // Recipe lint runs over the layers. let lint = option(&opts, ScanType::RecipeLint).expect("listed"); assert!(lint.default_on && lint.unavailable.is_none() && lint.blocked_reason.is_none()); diff --git a/compliance-core/src/vex_docs.rs b/compliance-core/src/vex_docs.rs index 209ea90..42fc192 100644 --- a/compliance-core/src/vex_docs.rs +++ b/compliance-core/src/vex_docs.rs @@ -174,8 +174,15 @@ pub fn openvex(input: &VexInput<'_>) -> serde_json::Value { if let Some(j) = vex.justification { statement["justification"] = serde_json::json!(j); } + // OpenVEX's impact statement belongs to `not_affected`; the + // reason of another status (a scan's note) is its status note. if let Some(text) = vex.impact_statement.as_deref() { - statement["impact_statement"] = serde_json::json!(text); + let field = if status == VexStatus::NotAffected { + "impact_statement" + } else { + "status_notes" + }; + statement[field] = serde_json::json!(text); } if let Some(text) = vex.action_statement.as_deref() { statement["action_statement"] = serde_json::json!(text); diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 93b8de6..f475403 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4447,6 +4447,7 @@ tbody tr:last-child td { .cra-violated { background: var(--danger); } .cra-open { background: var(--warning); } +.cra-partial { background: var(--info); } .cra-clear { background: var(--success); } .cra-process { background: color-mix(in srgb, var(--accent) 28%, var(--bg-elevated)); } diff --git a/compliance-dashboard/src/components/cra_bar.rs b/compliance-dashboard/src/components/cra_bar.rs index 0fc561c..534d919 100644 --- a/compliance-dashboard/src/components/cra_bar.rs +++ b/compliance-dashboard/src/components/cra_bar.rs @@ -9,10 +9,11 @@ use crate::infrastructure::evidence::CraCounts; /// The states in reading order: what needs work first, process evidence last. /// Each is (label, CSS modifier, count). -fn segments(counts: &CraCounts) -> [(Text, &'static str, u32); 4] { +fn segments(counts: &CraCounts) -> [(Text, &'static str, u32); 5] { [ (tx::NOT_SATISFIED, "violated", counts.not_satisfied), (tx::NOT_ASSESSED, "open", counts.not_assessed), + (tx::PARTIAL, "partial", counts.partial), (tx::NO_VIOLATION, "clear", counts.no_violation_found), (tx::NOT_CODE_CHECKABLE, "process", counts.not_code_checkable), ] diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 60fc065..986fc5c 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -2064,6 +2064,15 @@ pub mod sbom { de: "Paketquelle", en: "Manager", }; + /// The source of a component read from a Yocto recipe (its badge). + pub const YOCTO_RECIPE: Text = Text { + de: "Yocto-Rezept", + 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.", + }; pub const LICENSE: Text = Text { de: "Lizenz", en: "License", @@ -2614,6 +2623,16 @@ pub mod compliance { de: "Nicht bewertet", en: "Not assessed", }; + /// A control assessed on part of what it covers (a Yocto recipe + /// inventory instead of the image's SBOM). + pub const PARTIAL: Text = Text { + de: "Teilweise bewertet", + en: "Partly assessed", + }; + pub const RECIPE_INVENTORY_ONLY: Text = Text { + de: "Nur das Yocto-Rezeptinventar, nicht die SBOM des Images: geprüft sind die Rezepte im Layer-Baum, nicht was das Image enthält. Vollständig erst mit der SBOM aus dem Build.", + en: "Recipe inventory only, not the image SBOM: the recipes in the layer tree were checked, not what the image contains. Complete only with the SBOM from the build.", + }; pub const DEPENDENCIES_UNRESOLVED: Text = Text { de: "Die Abhängigkeiten dieser Manifeste wurden nicht aufgelöst (kein Lockfile, \ oder eines, das kein Werkzeug liest), die Stückliste ist also unvollständig:", @@ -2789,6 +2808,7 @@ pub mod compliance { ), "languages_unknown" => LANGUAGES_UNKNOWN.get(lang).to_string(), "no_components" => NO_COMPONENTS.get(lang).to_string(), + "recipe_inventory_only" => RECIPE_INVENTORY_ONLY.get(lang).to_string(), "dependencies_unresolved" => format!( "{} {}", DEPENDENCIES_UNRESOLVED.get(lang), @@ -2902,6 +2922,11 @@ pub mod compliance { }); assert!(not_assessed_reason(&unresolved, Lang::En) .is_some_and(|text| text.ends_with("android/app/build.gradle, ios/Podfile"))); + assert!(not_assessed_reason( + &serde_json::json!({ "kind": "recipe_inventory_only" }), + Lang::En + ) + .is_some_and(|text| text.starts_with("Recipe inventory only, not the image SBOM"))); assert_eq!( not_assessed_reason(&serde_json::Value::Null, Lang::En), None diff --git a/compliance-dashboard/src/infrastructure/evidence.rs b/compliance-dashboard/src/infrastructure/evidence.rs index 20d8d3d..39d048c 100644 --- a/compliance-dashboard/src/infrastructure/evidence.rs +++ b/compliance-dashboard/src/infrastructure/evidence.rs @@ -41,6 +41,10 @@ pub struct CraCounts { pub not_satisfied: u32, /// Not assessed: no rule for the scanned code, or a tool did not finish. pub not_assessed: u32, + /// Partly assessed: a Yocto target's components are its recipe + /// inventory, not the image's SBOM. + #[serde(default)] + pub partial: u32, /// Checked in the code, and nothing found. pub no_violation_found: u32, /// A design or process requirement, evidenced outside the code. @@ -129,9 +133,11 @@ mod tests { Some(CraCounts { not_satisfied: 3, not_assessed: 5, + partial: 0, no_violation_found: 13, not_code_checkable: 19, - }) + }), + "a summary from before the partial state reads as none partial" ); let skipped: ComplianceSummaryRow = serde_json::from_value(serde_json::json!({ "target_id": "65f1", "counts": null })) diff --git a/compliance-dashboard/src/pages/compliance.rs b/compliance-dashboard/src/pages/compliance.rs index 9e57828..83ebe7c 100644 --- a/compliance-dashboard/src/pages/compliance.rs +++ b/compliance-dashboard/src/pages/compliance.rs @@ -16,9 +16,10 @@ use crate::infrastructure::evidence::{fetch_compliance, CraCounts}; /// The label and badge of each control state, in the order the page lists /// them: violated first, requirements evidenced outside the code last. -const STATES: [(&str, Text, &str); 4] = [ +const STATES: [(&str, Text, &str); 5] = [ ("not_satisfied", tx::NOT_SATISFIED, "badge badge-critical"), ("not_assessed", tx::NOT_ASSESSED, "badge badge-medium"), + ("partial", tx::PARTIAL, "badge badge-info"), ( "no_violation_found", tx::NO_VIOLATION, @@ -102,7 +103,7 @@ pub fn CompliancePage(id: String) -> Element { // Violated first; what the code check cleared, then what is // evidenced outside the code, last and folded. - for (state, label, badge) in STATES.into_iter().take(3) { + for (state, label, badge) in STATES.into_iter().take(STATES.len() - 1) { { let group = in_state(state); // One reason for the whole group is said once, not per row. @@ -270,14 +271,15 @@ mod tests { #[test] fn violated_requirements_lead_and_process_ones_close() { - // The page lists the first three states as open groups and folds the - // last one; this order is what it relies on. + // The page lists every state but the last as an open group and folds + // the last one; this order is what it relies on. let order: Vec<&str> = STATES.iter().map(|(state, _, _)| *state).collect(); assert_eq!( order, [ "not_satisfied", "not_assessed", + "partial", "no_violation_found", "not_code_checkable" ] diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index fc96029..2c39ce6 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -1,3 +1,4 @@ +use compliance_core::models::YOCTO_RECIPE_MANAGER; use dioxus::prelude::*; use crate::components::page_header::PageHeader; @@ -303,7 +304,17 @@ pub fn SbomPage(target: String) -> Element { style: "font-family: var(--font-mono, monospace); font-size: 13px;", "{version_label(&entry, lang)}" } - td { "{entry.package_manager}" } + td { + if entry.package_manager == YOCTO_RECIPE_MANAGER { + span { + class: "badge badge-info", + title: "{tx::YOCTO_RECIPE_HINT.get(lang)}", + {tx::YOCTO_RECIPE.get(lang)} + } + } else { + "{entry.package_manager}" + } + } td { span { class: "sbom-license-badge {license_class}", "{entry.license.as_deref().unwrap_or(\"-\")}" diff --git a/docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc b/docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc new file mode 100644 index 0000000..06bb56d Binary files /dev/null and b/docker/__pycache__/pruefwerk_yocto_recipes.cpython-314.pyc differ diff --git a/docker/pruefwerk_yocto_recipes.py b/docker/pruefwerk_yocto_recipes.py new file mode 100644 index 0000000..245253e --- /dev/null +++ b/docker/pruefwerk_yocto_recipes.py @@ -0,0 +1,299 @@ +"""Read the recipes of a Yocto/OpenEmbedded layer tree as JSON, without a build. + +Prüfwerk runs this with `python3 -I pruefwerk_yocto_recipes.py ` and turns +the output into SBOM components and VEX statements (see +compliance-agent/src/pipeline/yocto_inventory.rs). The recipes are parsed with +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. + +Output: {"recipes": [...], "errors": [{"file", "error"}]}, sorted by file. +""" + +import glob +import json +import os +import re +import sys + +import regex +from oelint_parser import cls_stash +from oelint_parser.cls_item import FlagAssignment, Item, Variable +from oelint_parser.cls_stash import Stash +from oelint_parser.parser import INLINE_BLOCK + +# Directories never walked: version control, and the build output a tree may +# carry next to its layers. +SKIPPED_DIRS = {".git", ".hg", ".svn", "build", "tmp", "sstate-cache", "downloads"} + +# How much of a patch is read for its CVE: tags; the header comes first. +PATCH_HEADER_BYTES = 64 * 1024 + +CVE_ID = re.compile(r"CVE-\d{4}-\d{4,}") +CVE_TAG = re.compile(r"^CVE:\s*(.*)$", re.MULTILINE) + + +def inside(path: str, tree: str) -> bool: + """Whether `path`, symlinks resolved, lies within `tree`.""" + real = os.path.realpath(path) + return real == tree or real.startswith(tree + os.sep) + + +def confine(tree: str) -> None: + """Keep the parser inside `tree`. A recipe is the customer's input: an + `include /proc/1/environ` or `${@oe.utils.read_file(...)}` must not bring + another file's content into a value Prüfwerk stores. Includes outside the + tree are treated as missing, and read_file is never evaluated.""" + find = Stash.FindLocalOrLayer + + def find_inside(self: Stash, name: str, localdir: str) -> str: + found = find(self, name, localdir) + return found if found and inside(found, tree) else "" + + Stash.FindLocalOrLayer = find_inside + # A pattern that never matches: ExpandTerm then leaves the call as text. + 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.""" + layers: list[str] = [] + recipes: list[str] = [] + appends: 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: + layers.append(os.path.dirname(root)) + for name in files: + path = os.path.join(root, name) + if not inside(path, tree): + continue + if name.endswith(".bb"): + recipes.append(path) + elif name.endswith(".bbappend"): + appends.append(path) + return sorted(layers), sorted(recipes), sorted(appends) + + +def appends_for(recipe: str, appends: list[str]) -> list[str]: + """The bbappends that apply to `recipe` (`%` matches any version suffix).""" + stem = os.path.basename(recipe)[: -len(".bb")] + matching = [] + for append in appends: + pattern = re.escape(os.path.basename(append)[: -len(".bbappend")]) + pattern = pattern.replace(re.escape("%"), ".*") + if re.fullmatch(pattern, stem): + matching.append(append) + return matching + + +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-") + + +def assignments(stash: Stash, recipe: str, name: str) -> list: + """Every assignment of `name` in the recipe, its includes and appends.""" + return sorted( + stash.GetItemsFor( + filename=recipe, + classifier=Variable.CLASSIFIER, + attribute=Variable.ATTR_VAR, + attributeValue=name, + ), + key=lambda i: i.Line, + ) + + +def raw(stash: Stash, item: Variable) -> str: + """An assignment's value with its inline Python (`${@...}`) put back as + written: the parser swaps it for a placeholder, and it is never run.""" + if INLINE_BLOCK in item.VarValueStripped: + return stash._ReverseInlineBlock(item) + return item.VarValueStripped + + +def value(stash: Stash, recipe: str, name: str) -> str | None: + """The expanded value of `name` as BitBake would combine its assignments: + `=`, `?=`, `+=`, `.=` in order, then `:append`, `:prepend` and `:remove`. + Overrides (`:class-target`, a machine) are not resolved: every override's + append counts, so a value may list more than one configuration uses.""" + items = assignments(stash, recipe, name) + if not items: + return None + current: str | None = None + for item in items: + if item.SubItems: + continue + text = raw(stash, item) + op = item.VarOp.strip() + if op in ("=", ":="): + current = text + elif op in ("?=", "??="): + current = text if current is None else current + elif op == "+=": + current = f"{current or ''} {text}" + elif op == "=+": + current = f"{text} {current or ''}" + elif op == ".=": + current = f"{current or ''}{text}" + elif op == "=.": + current = f"{text}{current or ''}" + for item in items: + if "append" in item.SubItems: + current = f"{current or ''}{raw(stash, item)}" + elif "prepend" in item.SubItems: + current = f"{raw(stash, item)}{current or ''}" + for item in items: + if "remove" in item.SubItems and current is not None: + for word in item.VarValueStripped.split(): + current = " ".join(w for w in current.split() if w != word) + if current is None: + return None + return stash.ExpandTerm(recipe, current).strip() + + +def words(stash: Stash, recipe: str, name: str) -> list[str]: + """The value of `name` split into words.""" + return Item.safe_linesplit(value(stash, recipe, name) or "") + + +def flags(stash: Stash, recipe: str, name: str) -> dict[str, str]: + """The expanded flags of `name` (`CVE_STATUS[CVE-...]`), the last one winning.""" + items = stash.GetItemsFor( + filename=recipe, + classifier=FlagAssignment.CLASSIFIER, + attribute=FlagAssignment.ATTR_NAME, + attributeValue=name, + ) + found: dict[str, str] = {} + for item in sorted(items, key=lambda i: i.Line): + found[item.Flag] = stash.ExpandTerm(recipe, item.ValueStripped).strip() + return found + + +def status_entry(cve: str, value: str) -> dict[str, str]: + """A CVE_STATUS value `reason: detail` as its parts.""" + reason, _, detail = value.partition(":") + return {"cve": cve, "status": reason.strip(), "detail": detail.strip()} + + +def cve_statuses(stash: Stash, recipe: str) -> list[dict]: + """CVE_STATUS flags, CVE_STATUS_GROUPS and the older CVE_CHECK_IGNORE.""" + statuses = {cve: status_entry(cve, v) for cve, v in flags(stash, recipe, "CVE_STATUS").items()} + for group in words(stash, recipe, "CVE_STATUS_GROUPS"): + status = flags(stash, recipe, group).get("status") + if status is None: + continue + for cve in words(stash, recipe, group): + statuses.setdefault(cve, status_entry(cve, status)) + for cve in words(stash, recipe, "CVE_CHECK_IGNORE"): + statuses.setdefault(cve, {"cve": cve, "status": "ignored", "detail": "CVE_CHECK_IGNORE"}) + return [statuses[cve] for cve in sorted(statuses) if CVE_ID.fullmatch(cve)] + + +def find_local_file(name: str, origins: list[str], tree: str) -> str | None: + """Where a `file://` entry lives: next to the recipe or one of its appends, + directly or in one subdirectory (`files/`, `${BPN}/`, `${BP}/`).""" + for origin in origins: + base = os.path.dirname(origin) + candidates = [os.path.join(base, name)] + candidates += sorted(glob.glob(os.path.join(glob.escape(base), "*", glob.escape(name)))) + for candidate in candidates: + if os.path.isfile(candidate) and inside(candidate, tree): + return candidate + return None + + +def patch_cves(path: str | None, name: str) -> list[str]: + """The CVEs a patch fixes: its `CVE:` tags and the ids in its file name, + as OpenEmbedded's cve-check reads them.""" + cves = set(CVE_ID.findall(os.path.basename(name))) + if path is not None: + with open(path, "rb") as patch: + header = patch.read(PATCH_HEADER_BYTES).decode("utf-8", errors="replace") + for tag in CVE_TAG.findall(header): + cves.update(CVE_ID.findall(tag)) + return sorted(cves) + + +def sources(origins: list[str], tree: str, src_uri: list[str]) -> tuple[str | None, list[dict]]: + """The first upstream URL of SRC_URI and the patches it applies.""" + upstream = None + patches = [] + for entry in src_uri: + url, *options = entry.split(";") + if not url.startswith("file://"): + upstream = upstream or entry + continue + if "apply=no" in options: + continue + name = url[len("file://"):] + if not name.endswith((".patch", ".diff")) and "apply=yes" not in options: + continue + path = find_local_file(name, origins, tree) + patches.append({ + "file": os.path.relpath(path, tree) if path else name, + "cves": patch_cves(path, name), + }) + 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]: + stash.AddFile(path) + stash.Finalize() + if stash.IsImage(recipe) or stash.IsPackageGroup(recipe): + return None + 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 { + "file": os.path.relpath(recipe, tree), + "appends": [os.path.relpath(a, tree) for a in appends], + "pn": pn, + "bpn": stash.GuessBaseRecipeName(recipe), + "pv": pv, + "srcrev": value(stash, recipe, "SRCREV") or None, + "src_uri": upstream, + "license": value(stash, recipe, "LICENSE") or None, + "cve_product": words(stash, recipe, "CVE_PRODUCT"), + "cve_version": value(stash, recipe, "CVE_VERSION") or None, + "cve_status": cve_statuses(stash, recipe), + "patches": patches, + } + + +def main(tree: str) -> int: + tree = os.path.realpath(tree) + confine(tree) + layers, recipe_files, appends = walk(tree) + recipes = [] + errors = [] + for recipe in recipe_files: + 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) + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.stderr.write("usage: pruefwerk_yocto_recipes.py \n") + sys.exit(2) + sys.exit(main(sys.argv[1])) diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 28b0ee5..29b851f 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -49,6 +49,9 @@ Prüfwerk builds the SBOM during each scan: PlatformIO, Arduino, embedded Rust). - **CODESYS projects** -- the referenced libraries and the runtime version from a `.projectarchive`; see [SPS / PLC (CODESYS)](/guide/plc). +- **Yocto / OpenEmbedded layers** -- the recipes of a layer tree, read without + a build; see [Embedded Linux / Yocto](/guide/yocto#recipe-inventory). They + appear with the package source **Yocto-Rezept**. - **Unity projects** -- the editor version (from `ProjectSettings/ProjectVersion.txt`) and the packages pinned in @@ -262,7 +265,10 @@ A scan keeps the status current: when a complete CVE check no longer finds an alert (the component was removed or updated past the fix), it is marked resolved, and one nobody assessed, or assessed as affected, becomes `fixed`. A `not_affected` or `fixed` someone stated is never changed by a scan. If the -vulnerability comes back, the scan's `fixed` is withdrawn. +vulnerability comes back, the scan's `fixed` is withdrawn. A Yocto recipe's +`CVE_STATUS` and `CVE:` patches are stated by the scan too (see +[Embedded Linux / Yocto](/guide/yocto#recipe-inventory)), likewise never over a +person's statement. The statements are exported per target as **OpenVEX 0.2.0** and as **CycloneDX 1.6 VEX** (the SBOM with each vulnerability's analysis), both diff --git a/docs/guide/yocto.md b/docs/guide/yocto.md index 41177c9..b10b03f 100644 --- a/docs/guide/yocto.md +++ b/docs/guide/yocto.md @@ -37,7 +37,7 @@ searched. | SBOM from lockfiles (Syft) | runs, but a layer has no lockfiles, so it is usually empty | | 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 | in progress (tier 1), listed under **Nicht ausgeführt** until it lands | +| Recipe inventory | runs: SBOM components and NVD CVEs from the recipes, `CVE_STATUS` and `CVE:` patches as VEX; see [Recipe inventory](#recipe-inventory) | | 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 | @@ -91,6 +91,67 @@ used security, virtualisation and BSP layers, recognised by their `BBFILE_COLLECTIONS`) are not linted: their findings are upstream's. The run names them under **Nicht ausgeführt** as "Upstream-Layer". +## Recipe inventory + +A tree detected as a Yocto layer tree (see [Detection](#detection)), and any +Yocto target, gets a recipe inventory. Each recipe is parsed +with [oelint-parser](https://github.com/priv-kweihmann/oelint-parser) together +with its `.bbappend` files; nothing in it is executed and nothing is built. +Image recipes, package groups and tools built only for the build host +(`-native`, `nativesdk-`, `-cross`) are not components and are left out. + +| Component field | From the recipe | +|---|---| +| Name | the base recipe name (BPN) | +| Version | `PV`, else the version in the file name (`busybox_1.35.0.bb`); a git suffix is dropped (`1.0+git${SRCPV}` is `1.0`); with no version at all (`PV = "git"`), the `SRCREV` commit | +| Package URL | `pkg:github//@` for a source on GitHub, else `pkg:generic/@` with the `download_url` (a tarball) or `vcs_url` (a git repository at its `SRCREV`) | +| CPE | `cpe:2.3:a::::…` from `CVE_PRODUCT` (`product` or `vendor:product`) and `CVE_VERSION`, else from the name and version | +| License | `LICENSE`, with Yocto's `&` and `\|` written as `AND` and `OR` | + +**This is not the image's SBOM**, and the CRA view says so: the requirements +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 +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 +line naming the recipe and its `.bbappend` files. + +**CVEs.** The recipes are matched in NVD by CPE, every product of +`CVE_PRODUCT` (or the recipe name, as Yocto's cve-check does) against +`CVE_VERSION` (or the version). A recipe with only local `file://` sources and +no `CVE_PRODUCT` is the product's own code and is not looked up. A recipe +without a release version, a failed lookup, and recipes the scan's NVD time +budget (10 minutes) did not reach are listed under **CVE-Abgleich +unvollständig**. The requests are paced to NVD's rate limit: 50 per 30 seconds +with the deployment's NVD API key, 5 without; an answer from the last 6 hours +is reused, so the next scan gets further. The daily CVE re-check covers OSV +only and does not yet re-match recipes in NVD; a scan does. + +**What the recipe says about a CVE becomes its VEX statement**, made by the +scan, with the recipe (or patch) and its text as the impact statement, so it is +in the OpenVEX, CycloneDX VEX and CSAF exports (see +[SBOM & Licenses](/guide/sbom#vex-the-status-of-each-vulnerability)): + +| In the recipe | VEX statement | +|---|---| +| a patch in `SRC_URI` with a `CVE:` tag (or the CVE id in its file name) | `fixed` | +| `CVE_STATUS` `backported-patch`, `cpe-stable-backport`, `fixed-version` | `fixed` | +| `CVE_STATUS` `cpe-incorrect` | `not_affected`, `component_not_present` | +| `CVE_STATUS` `not-applicable-platform`, `not-applicable-config` | `not_affected`, `vulnerable_code_not_present` | +| `CVE_STATUS` `upstream-wontfix`, `disputed`, `ignored` (and the older `CVE_CHECK_IGNORE`) | `under_investigation` (CycloneDX `in_triage`), the reason as the status note: setting a CVE aside says nothing on whether the product is affected | +| `CVE_STATUS` `unpatched`, `vulnerable-investigation` | none: the alert stays to be assessed | + +In the OpenVEX export the note of an `under_investigation` or `fixed` +statement is its `status_notes`, in CSAF an `impact` threat, in CycloneDX the +analysis `detail`. `CVE_STATUS_GROUPS` count like single `CVE_STATUS` flags. The scan states them +again on every scan and withdraws one the recipe no longer makes; a statement +a person made is never replaced. + ## What is planned | Tier | Input | Analysis | diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index a5d824c..f8755ea 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -2,10 +2,15 @@ "scan_status": "completed", "skipped_stages": [ "firmware_sbom", - "malware", - "recipe_inventory" + "malware" + ], + "sbom": [ + "yocto-recipe:busybox@1.35.0", + "yocto-recipe:libmodbus@3.1.6", + "yocto-recipe:pump-ctl@1.0", + "yocto-recipe:pump-fw@1.0", + "yocto-recipe:pump-web@2.1" ], - "sbom": [], "findings": [ "oelint-adv:oelint.task.network pump-web_2.1.bb:8", "oelint-adv:oelint.var.badimagefeature.allow-empty-password pump-image.bb:7", @@ -17,5 +22,10 @@ "yocto-config:yocto-src-uri-http pump-web_2.1.bb:6", "yocto-config:yocto-sshd-root-login sshd_config:3" ], - "cves": [] + "cves": [ + "CVE-2022-0367", + "CVE-2022-28391", + "CVE-2022-30065", + "CVE-2022-48174" + ] } diff --git a/fixtures/nightly/firmware/README.md b/fixtures/nightly/firmware/README.md index b2970f9..fd7c95b 100644 --- a/fixtures/nightly/firmware/README.md +++ b/fixtures/nightly/firmware/README.md @@ -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 is recorded as not run 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) yet | `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. diff --git a/fixtures/nightly/firmware/yocto-layer/conf/layer.conf b/fixtures/nightly/firmware/yocto-layer/conf/layer.conf index 61347d1..47c75a0 100644 --- a/fixtures/nightly/firmware/yocto-layer/conf/layer.conf +++ b/fixtures/nightly/firmware/yocto-layer/conf/layer.conf @@ -1,7 +1,7 @@ -# Nightly fixture (#313): a minimal Yocto layer. Yocto builds are not analysed -# yet, so the scan must record that instead of completing silently. +# Nightly fixture (#313): a minimal Yocto layer. Its recipes are read as an +# inventory (no build): versions, upstream sources, CVE_STATUS and CVE patches. BBPATH .= ":${LAYERDIR}" -BBFILES += "${LAYERDIR}/recipes-*/*/*.bb" +BBFILES += "${LAYERDIR}/recipes-*/*/*.bb ${LAYERDIR}/recipes-*/*/*.bbappend" BBFILE_COLLECTIONS += "pruefwerk-fixture" BBFILE_PATTERN_pruefwerk-fixture = "^${LAYERDIR}/" LAYERSERIES_COMPAT_pruefwerk-fixture = "scarthgap" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/libmodbus/libmodbus_3.1.6.bb b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/libmodbus/libmodbus_3.1.6.bb new file mode 100644 index 0000000..ad6676a --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-connectivity/libmodbus/libmodbus_3.1.6.bb @@ -0,0 +1,14 @@ +# Nightly fixture: a library fetched from GitHub at a pinned commit, named in +# NVD as vendor:product. +SUMMARY = "A Modbus library" +HOMEPAGE = "https://libmodbus.org" +LICENSE = "LGPL-2.1-or-later" +LIC_FILES_CHKSUM = "file://COPYING.LESSER;md5=4fbd65380cdd255951079008b364516c" + +SRC_URI = "git://github.com/stephane/libmodbus;protocol=https;branch=master" +SRCREV = "e0fac20f30c11b10c4d00ebe9e2d4be3d8c1a6dd" +S = "${WORKDIR}/git" + +CVE_PRODUCT = "libmodbus:libmodbus" + +inherit autotools pkgconfig diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/0001-awk-fix-use-after-free-CVE-2022-30065.patch b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/0001-awk-fix-use-after-free-CVE-2022-30065.patch new file mode 100644 index 0000000..1e5c9a7 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/0001-awk-fix-use-after-free-CVE-2022-30065.patch @@ -0,0 +1,18 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Nightly Fixture +Subject: [PATCH] awk: fix use after free (CVE-2022-30065) + +Backported from upstream for the nightly fixture; the hunk is a stand-in. + +Upstream-Status: Backport +CVE: CVE-2022-30065 +Signed-off-by: Nightly Fixture +--- + editors/awk.c | 1 + + 1 file changed, 1 insertion(+) + +--- a/editors/awk.c ++++ b/editors/awk.c +@@ -1,1 +1,2 @@ + /* awk */ ++/* fixed */ diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/defconfig b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/defconfig new file mode 100644 index 0000000..1eb641b --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox/defconfig @@ -0,0 +1,2 @@ +# CONFIG_NETSTAT is not set +CONFIG_AWK=y diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_%.bbappend b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_%.bbappend new file mode 100644 index 0000000..6d0eec7 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_%.bbappend @@ -0,0 +1,4 @@ +# Nightly fixture: CVEs assessed as a group, the way a distro layer does it. +CVE_STATUS_GROUPS += "CVE_STATUS_BUSYBOX_APPLETS" +CVE_STATUS_BUSYBOX_APPLETS = "CVE-2025-46394 CVE-2025-60876" +CVE_STATUS_BUSYBOX_APPLETS[status] = "not-applicable-config: the tar and wget applets are disabled" diff --git a/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_1.35.0.bb b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_1.35.0.bb new file mode 100644 index 0000000..e665397 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/recipes-core/busybox/busybox_1.35.0.bb @@ -0,0 +1,14 @@ +# Nightly fixture: an old BusyBox with known CVEs in NVD. One of them is +# assessed in CVE_STATUS, another is fixed by a backported patch (CVE: tag). +SUMMARY = "Tiny versions of many common UNIX utilities in a single small executable" +HOMEPAGE = "https://www.busybox.net" +LICENSE = "GPL-2.0-only & bzip2-1.0.4" +LIC_FILES_CHKSUM = "file://LICENSE;md5=de10de48642ab74318e893a61105afbb" + +SRC_URI = "https://busybox.net/downloads/busybox-${PV}.tar.bz2 \ + file://0001-awk-fix-use-after-free-CVE-2022-30065.patch \ + file://defconfig \ + " +SRC_URI[sha256sum] = "faeeb244c35a348a334f4a59e44626ee870fb07b6884d68c10ae8bc19f83a694" + +CVE_STATUS[CVE-2022-28391] = "not-applicable-config: netstat is not enabled in our defconfig" diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index 2c0bd76..a8b98d6 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -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 firmware SBOM and the recipe inventory are recorded as skipped with their reasons until those stages land, never completing as if there were no components.", + "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.", "artifacts": [ { "kind": "source_archive",