From 5a71bc2ea220cdda42332e7e95618e412bbb83e8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:09:48 +0200 Subject: [PATCH] feat(mobile): legacy Android and Unity builds flagged, not resolved; Android found everywhere The first pilot scan of an Android + Unity repository on prod showed: the two Android apps were not recognised, Unity was typed as a desktop app, and the SBOM was empty without saying why. - Classification: every AndroidManifest.xml outside test folders is an Android module: Gradle's src/main, an Eclipse/ADT project's root, a Unity project's Assets/Plugins/Android. #449 counted only src/main and the repository root, so the ADT apps (and with #458 the target type) were missed. - build-lifecycle (new, like dotnet-lifecycle; CWE-1104, medium): - legacy-build-system-no-sbom for an ADT project (properties file, no Gradle) and a Unity project without Packages/manifest.json; the remedy is migrating the build. Bound to cra-ai-23. - android-sdk-end-of-support for target=android-N below 29. - unity-editor-end-of-support, judged conservatively (before 2021, and the 2021-2023 tech streams). Both bound to cra-ai-22. Such builds are not resolved (decided: flag, do not support); they also record a skipped sbom_dependencies stage, so the SBOM requirements read "Nicht bewertet" instead of clean. - Unity SBOM: the editor version, and for modern projects the packages in Packages/packages-lock.json (else manifest.json); listed as not matched for CVEs (no advisory database covers Unity). - A syft failure is no longer silent: a skipped `sbom` stage (tool syft), so the SBOM requirements are not assessed; syft gets 10 minutes. Nightly fixture mobile-legacy-adt-unity in the pilot's shape. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/classify/language.rs | 54 ++- compliance-agent/src/evidence/compliance.rs | 3 +- .../src/pipeline/build_lifecycle.rs | 367 ++++++++++++++++++ compliance-agent/src/pipeline/cve.rs | 9 +- .../src/pipeline/dotnet/config.rs | 2 +- compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/pipeline/orchestrator.rs | 39 +- compliance-agent/src/pipeline/sbom/mod.rs | 54 ++- compliance-agent/src/pipeline/sbom/syft.rs | 4 +- compliance-agent/src/pipeline/sbom/unity.rs | 203 ++++++++++ compliance-dashboard/src/i18n/texts.rs | 8 + control-map/data/cra_control_map.json | 29 ++ docs/guide/sbom.md | 14 + .../baselines/mobile-legacy-adt-unity.json | 19 + .../Pump Game/Assembly-CSharp.csproj | 1 + .../Pump Game/Assets/Scripts/PumpGauge.cs | 3 + .../ProjectSettings/ProjectVersion.txt | 2 + .../Pump Phone/AndroidManifest.xml | 7 + .../Pump Phone/default.properties | 3 + .../Pump Phone/src/com/example/pump/Main.java | 7 + .../Pump Tablet/AndroidManifest.xml | 7 + .../Pump Tablet/project.properties | 1 + .../src/com/example/pump/Main.java | 7 + fixtures/nightly/targets.json | 20 + 24 files changed, 836 insertions(+), 28 deletions(-) create mode 100644 compliance-agent/src/pipeline/build_lifecycle.rs create mode 100644 compliance-agent/src/pipeline/sbom/unity.rs create mode 100644 fixtures/nightly/baselines/mobile-legacy-adt-unity.json create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assembly-CSharp.csproj create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assets/Scripts/PumpGauge.cs create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Game/ProjectSettings/ProjectVersion.txt create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/AndroidManifest.xml create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/default.properties create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/src/com/example/pump/Main.java create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/AndroidManifest.xml create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/project.properties create mode 100644 fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/src/com/example/pump/Main.java diff --git a/compliance-agent/src/classify/language.rs b/compliance-agent/src/classify/language.rs index 13c6541..0f5921b 100644 --- a/compliance-agent/src/classify/language.rs +++ b/compliance-agent/src/classify/language.rs @@ -210,10 +210,12 @@ fn dotnet_confidence(count: usize, projects: usize) -> f32 { fn mobile_shape(root: &Path, m: &Markers) -> MobileShape { let mut shape = MobileShape::default(); for manifest in m.located_ending("androidmanifest.xml") { - // Only an app or library module's main manifest, not one under a - // test or Unity plugin folder. - let lower = manifest.to_lowercase(); - if lower.ends_with("src/main/androidmanifest.xml") || lower == "androidmanifest.xml" { + // Every Android manifest names Android code: a Gradle module's + // `src/main/`, an Eclipse (ADT) project's root, a Unity project's + // `Assets/Plugins/Android/`. Only test manifests say nothing about + // the product. + let lower = format!("/{}", manifest.to_lowercase()); + if !lower.contains("/androidtest/") && !lower.contains("/test/") { shape.android_modules.push(manifest.clone()); } } @@ -658,6 +660,50 @@ mod tests { assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp)); } + #[tokio::test] + async fn an_eclipse_adt_project_and_a_unity_plugin_manifest_are_android() { + // The shape of a real pilot repository: an old ADT app (manifest at + // the project root, no Gradle) beside a Unity project whose only + // Android trace is its plugin manifest; Unity's generated C# + // projects alongside. + let v = classify_tree(|root| { + write_all( + root, + &[ + ("Phone/AndroidManifest.xml", ""), + ("Phone/project.properties", "target=android-11"), + ("Phone/src/com/example/Main.java", "class Main {}"), + ( + "Game/ProjectSettings/ProjectVersion.txt", + "m_EditorVersion: 2019.4.1f1", + ), + ( + "Game/Assets/Plugins/Android/AndroidManifest.xml", + "", + ), + ("Game/Assembly-CSharp.csproj", ""), + ("Phone/src/test/AndroidManifest.xml", ""), + ], + ); + }) + .await; + assert_eq!(top(&v), TargetType::AndroidApp); + let modules: Vec<&str> = v + .iter() + .flat_map(|x| &x.facts) + .filter(|f| f.key == "android_module") + .map(|f| f.value.as_str()) + .collect(); + assert_eq!( + modules, + [ + "Game/Assets/Plugins/Android/AndroidManifest.xml", + "Phone/AndroidManifest.xml" + ] + ); + assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp)); + } + #[tokio::test] async fn a_unity_project_with_android_plugins_is_an_android_app() { let v = classify_tree(|root| { diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index 5230eba..d176f58 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -62,7 +62,7 @@ pub enum SbomCoverage { } /// The tools that check a target's components rather than its code. -const COMPONENT_TOOLS: [&str; 3] = ["syft", "osv", "dotnet-lifecycle"]; +const COMPONENT_TOOLS: [&str; 4] = ["syft", "osv", "dotnet-lifecycle", "build-lifecycle"]; /// The tool a skipped stage of a scan run stands for, when that stage is one /// a control's binding relies on. @@ -72,6 +72,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> { "sast_c_cpp" => Some("cppcheck"), "sast_mobile" => Some("mobsfscan"), "cve_lookup" => Some("osv"), + "sbom" => Some("syft"), _ => None, } } diff --git a/compliance-agent/src/pipeline/build_lifecycle.rs b/compliance-agent/src/pipeline/build_lifecycle.rs new file mode 100644 index 0000000..4cd5975 --- /dev/null +++ b/compliance-agent/src/pipeline/build_lifecycle.rs @@ -0,0 +1,367 @@ +//! Build systems and platforms past their end of life, as findings. +//! +//! Prüfwerk does not read the dependencies of end-of-life build systems: an +//! Eclipse/ADT Android project (`default.properties` or `project.properties` +//! beside the manifest, no Gradle) or a Unity project without +//! `Packages/manifest.json` has no machine-readable list of what it ships, so +//! no complete SBOM and no CVE monitoring are possible. That is the finding, +//! and modernising the build is the remedy. The platform such a project builds +//! for is a finding of its own when it no longer gets security updates (an +//! old Android API level, an old Unity editor). + +use std::path::Path; + +use compliance_core::models::{ScanType, Severity}; +use compliance_core::traits::{ScanOutput, Scanner}; +use compliance_core::CoreError; + +use crate::pipeline::dotnet::config::{into_finding, Hit}; + +/// The scanner name of these findings. +pub const SCANNER: &str = "build-lifecycle"; + +/// Below this Android API level (Android 10) no Android release receives +/// security updates any more. +const OLDEST_PATCHED_ANDROID_API: u32 = 29; + +/// How deep projects are looked for. +const MAX_DEPTH: usize = 8; + +/// Directories never searched: build output, dependencies, tool caches. +const SKIPPED_DIRS: &[&str] = &[ + ".git", + ".gradle", + "build", + "bin", + "gen", + "node_modules", + "Library", + "Temp", + "Pods", +]; + +/// The checks over a tree. +#[derive(Debug, Default)] +pub struct BuildLifecycleScanner; + +impl Scanner for BuildLifecycleScanner { + fn name(&self) -> &str { + SCANNER + } + + fn scan_type(&self) -> ScanType { + ScanType::Sbom + } + + #[tracing::instrument(skip_all)] + async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result { + let root = repo_path.to_path_buf(); + let hits = tokio::task::spawn_blocking(move || check_tree(&root)) + .await + .map_err(|e| CoreError::Scanner { + scanner: SCANNER.to_string(), + source: Box::new(e), + })?; + Ok(ScanOutput { + findings: hits + .into_iter() + .map(|hit| into_finding(repo_path, repo_id, hit)) + .collect(), + sbom_entries: Vec::new(), + }) + } +} + +/// Every check over the tree under `root`. +pub(crate) fn check_tree(root: &Path) -> Vec { + let mut hits = Vec::new(); + let files = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(MAX_DEPTH) + .sort_by_file_name() + .into_iter() + .filter_entry(|e| { + !(e.file_type().is_dir() + && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()); + for entry in files { + let Some(dir) = entry.path().parent() else { + continue; + }; + match entry.file_name().to_string_lossy().as_ref() { + "AndroidManifest.xml" => hits.extend(check_adt_project(root, dir)), + "ProjectVersion.txt" if dir.file_name().is_some_and(|n| n == "ProjectSettings") => { + if let Some(project) = dir.parent() { + hits.extend(check_unity_project(root, project)); + } + } + _ => {} + } + } + hits +} + +/// `path` relative to `root`, `/`-separated. +fn relative(root: &Path, path: &Path) -> String { + path.strip_prefix(root) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/") +} + +/// An Eclipse/ADT Android project in `dir`: its properties file names the +/// target API, and no Gradle build lists its dependencies. +fn check_adt_project(root: &Path, dir: &Path) -> Vec { + let gradle = ["build.gradle", "build.gradle.kts"] + .iter() + .any(|f| dir.join(f).is_file()); + let Some(properties) = ["project.properties", "default.properties"] + .iter() + .map(|f| dir.join(f)) + .find(|p| p.is_file()) + else { + return Vec::new(); + }; + if gradle { + return Vec::new(); + } + let path = relative(root, &properties); + let text = std::fs::read_to_string(&properties).unwrap_or_default(); + let target = text + .lines() + .enumerate() + .find(|(_, l)| l.trim_start().starts_with("target=")); + let line = target.map_or(1, |(i, _)| u32::try_from(i + 1).unwrap_or(1)); + let mut hits = vec![Hit { + scanner: SCANNER, + scan_type: ScanType::Sbom, + rule_id: "legacy-build-system-no-sbom", + title: "Legacy build system: the SBOM cannot be determined".to_string(), + description: format!( + "{} is an Eclipse/ADT Android project (no Gradle build). Its dependencies are not \ + declared in any machine-readable form, so no complete SBOM and no CVE monitoring \ + are possible for it.", + relative(root, dir) + ), + remediation: "Migrate the project to Gradle with the Android Gradle Plugin (Android \ + Studio imports ADT projects), declare its libraries as Gradle \ + dependencies and commit a gradle.lockfile.", + severity: Severity::Medium, + cwe: "CWE-1104", + path: path.clone(), + line: Some(line), + }]; + if let Some(api) = target.and_then(|(_, l)| android_api(l)) { + if api < OLDEST_PATCHED_ANDROID_API { + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sbom, + rule_id: "android-sdk-end-of-support", + title: format!("Android API {api} receives no security updates"), + description: format!( + "{} builds against Android API {api}. Android releases below API \ + {OLDEST_PATCHED_ANDROID_API} (Android 10) receive no security updates, \ + so the platform the app is built for stays vulnerable.", + relative(root, dir) + ), + remediation: "Raise the target and minimum API level to a supported Android \ + release (after migrating the build to Gradle) and test on it.", + severity: Severity::Medium, + cwe: "CWE-1104", + path, + line: Some(line), + }); + } + } + hits +} + +/// The API level a `target=` line names: `target=android-11`, or +/// `target=Google Inc.:Google APIs:8`. +fn android_api(line: &str) -> Option { + let value = line.trim().strip_prefix("target=")?.trim(); + value + .rsplit(['-', ':']) + .next() + .and_then(|n| n.trim().parse().ok()) +} + +/// A Unity project at `project`: without `Packages/manifest.json` its packages +/// are not declared; an editor version out of support is a finding of its own. +fn check_unity_project(root: &Path, project: &Path) -> Vec { + let version_file = project.join("ProjectSettings/ProjectVersion.txt"); + let path = relative(root, &version_file); + let version = std::fs::read_to_string(&version_file) + .unwrap_or_default() + .lines() + .find_map(|l| { + l.trim() + .strip_prefix("m_EditorVersion:") + .map(|v| v.trim().to_string()) + }) + .unwrap_or_default(); + let mut hits = Vec::new(); + if !project.join("Packages/manifest.json").is_file() { + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sbom, + rule_id: "legacy-build-system-no-sbom", + title: "Legacy build system: the SBOM cannot be determined".to_string(), + description: format!( + "{} is a Unity project without Packages/manifest.json. The Unity packages and \ + plug-ins it ships are not declared in any machine-readable form, so no \ + complete SBOM and no CVE monitoring are possible for it.", + relative(root, project) + ), + remediation: "Move the project to a current Unity LTS release with the Unity \ + Package Manager, and commit its Packages/ folder (manifest.json \ + and packages-lock.json).", + severity: Severity::Medium, + cwe: "CWE-1104", + path: path.clone(), + line: Some(1), + }); + } + if unity_out_of_support(&version) { + hits.push(Hit { + scanner: SCANNER, + scan_type: ScanType::Sbom, + rule_id: "unity-editor-end-of-support", + title: format!("Unity {version} receives no security updates"), + description: format!( + "{} is built with Unity {version}, a release Unity no longer supports. The \ + Unity runtime is part of the shipped app, and security fixes are only \ + published for supported releases.", + relative(root, project) + ), + remediation: "Upgrade the project to a supported Unity LTS release.", + severity: Severity::Medium, + cwe: "CWE-1104", + path, + line: Some(1), + }); + } + hits +} + +/// Whether a Unity editor version is certainly out of support: every release +/// before 2021, and the tech-stream releases of 2021 to 2023 (only the LTS +/// release of a year, `.3`, was supported beyond the next one). Later LTS +/// releases are not judged here. +fn unity_out_of_support(version: &str) -> bool { + let mut parts = version.split('.'); + let (Some(year), Some(minor)) = ( + parts.next().and_then(|y| y.parse::().ok()), + parts.next().and_then(|m| m.parse::().ok()), + ) else { + return false; + }; + match year { + 2000..=2020 => true, + 2021..=2023 => minor != 3, + _ => false, + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + /// A scratch tree holding `files`, removed on drop. + struct Tree(std::path::PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-buildlc-{}", uuid::Uuid::new_v4())); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + fn hits(t: &Tree) -> Vec { + check_tree(&t.0) + .into_iter() + .map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0))) + .collect() + } + + #[test] + fn the_pilot_shape_gives_legacy_build_and_lifecycle_findings() { + let t = tree(&[ + ("Mobile App/AndroidManifest.xml", ""), + ( + "Mobile App/default.properties", + "# generated\nsplit.density=false\ntarget=android-8\n", + ), + ("Tablet App/AndroidManifest.xml", ""), + ( + "Tablet App/project.properties", + "target=Google Inc.:Google APIs:11\n", + ), + ( + "Unity/ProjectSettings/ProjectVersion.txt", + "m_EditorVersion: 2019.2.4f1\n", + ), + ]); + assert_eq!( + hits(&t), + [ + "legacy-build-system-no-sbom Mobile App/default.properties:3", + "android-sdk-end-of-support Mobile App/default.properties:3", + "legacy-build-system-no-sbom Tablet App/project.properties:1", + "android-sdk-end-of-support Tablet App/project.properties:1", + "legacy-build-system-no-sbom Unity/ProjectSettings/ProjectVersion.txt:1", + "unity-editor-end-of-support Unity/ProjectSettings/ProjectVersion.txt:1", + ] + ); + } + + #[test] + fn modern_builds_give_nothing() { + let t = tree(&[ + ("app/src/main/AndroidManifest.xml", ""), + ("app/build.gradle", "android { compileSdk 34 }"), + // An ADT layout that has moved to Gradle keeps its properties. + ("legacy/AndroidManifest.xml", ""), + ("legacy/project.properties", "target=android-34"), + ( + "legacy/build.gradle", + "apply plugin: 'com.android.application'", + ), + ( + "game/ProjectSettings/ProjectVersion.txt", + "m_EditorVersion: 6000.0.23f1\n", + ), + ("game/Packages/manifest.json", "{\"dependencies\":{}}"), + ]); + assert!(hits(&t).is_empty(), "{:?}", hits(&t)); + } + + #[test] + fn unity_support_is_judged_conservatively() { + assert!(unity_out_of_support("2019.2.4f1")); + assert!(unity_out_of_support("2020.3.48f1")); + assert!(unity_out_of_support("2021.2.19f1")); + assert!(unity_out_of_support("2023.1.20f1")); + assert!(!unity_out_of_support("2022.3.50f1")); + assert!(!unity_out_of_support("6000.0.23f1")); + assert!(!unity_out_of_support("garbage")); + } + + #[test] + fn android_targets_are_read_in_both_forms() { + assert_eq!(android_api("target=android-8"), Some(8)); + assert_eq!(android_api("target=Google Inc.:Google APIs:11"), Some(11)); + assert_eq!(android_api("target=android-L"), None); + } +} diff --git a/compliance-agent/src/pipeline/cve.rs b/compliance-agent/src/pipeline/cve.rs index 3a395b8..fedb45a 100644 --- a/compliance-agent/src/pipeline/cve.rs +++ b/compliance-agent/src/pipeline/cve.rs @@ -501,10 +501,11 @@ const PURL_TYPES_WITHOUT_OSV: &[&str] = &["pkg:cocoapods/"]; /// Whether `entry` belongs to a package manager OSV has no advisories for. fn without_osv_advisories(entry: &SbomEntry) -> bool { - entry - .purl - .as_deref() - .is_some_and(|purl| PURL_TYPES_WITHOUT_OSV.iter().any(|t| purl.starts_with(t))) + entry.package_manager == crate::pipeline::sbom::unity::UNITY_MANAGER + || entry + .purl + .as_deref() + .is_some_and(|purl| PURL_TYPES_WITHOUT_OSV.iter().any(|t| purl.starts_with(t))) } /// The CODESYS runtime component (name + version) from an SBOM, if present. The diff --git a/compliance-agent/src/pipeline/dotnet/config.rs b/compliance-agent/src/pipeline/dotnet/config.rs index 5ac8ab0..847031e 100644 --- a/compliance-agent/src/pipeline/dotnet/config.rs +++ b/compliance-agent/src/pipeline/dotnet/config.rs @@ -91,7 +91,7 @@ impl Scanner for DotnetConfigScanner { } /// A [`Hit`] as a finding of `repo_id`. -fn into_finding(repo_path: &Path, repo_id: &str, hit: Hit) -> Finding { +pub(crate) fn into_finding(repo_path: &Path, repo_id: &str, hit: Hit) -> Finding { let line = hit.line.unwrap_or(0).to_string(); let fingerprint = dedup::compute_fingerprint(&[repo_id, hit.rule_id, &hit.path, &line]); let mut finding = Finding::new( diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index c77b841..dbfdc11 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -1,3 +1,4 @@ +pub mod build_lifecycle; pub mod code_review; pub mod cppcheck; pub mod cve; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index e2df54e..98bc14e 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -285,20 +285,27 @@ impl PipelineOrchestrator { tracing::info!("[{repo_id}] Stage 2: SBOM Generation"); self.update_phase(scan_run_id, ScanPhase::SbomGeneration) .await; - let mut sbom_entries = match async { + let (mut sbom_entries, syft_failure) = async { let sbom_scanner = SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env)); - sbom_scanner.scan(&repo_path, &repo_id).await + sbom_scanner.generate(&repo_path, &repo_id).await } .instrument(tracing::info_span!("stage_sbom_generation")) - .await - { - Ok(output) => output.sbom_entries, - Err(e) => { - tracing::warn!("[{repo_id}] SBOM generation failed: {e}"); - Vec::new() - } - }; + .await; + // Syft reads the lockfiles and archives: without it the SBOM is short + // of most components, and the SBOM requirements are not assessed. + if let Some(reason) = syft_failure { + self.skip_stage( + scan_run_id, + SkippedStage::new( + "sbom", + SkipCode::ToolFailed, + format!("syft did not complete: {reason}"), + ) + .about("syft"), + ) + .await; + } // A manifest with no lockfile pins no versions, and generating one runs // the project's own code, which this deployment may not. Syft reports @@ -458,6 +465,16 @@ impl PipelineOrchestrator { } Err(e) => tracing::warn!("[{repo_id}] .NET configuration scan failed: {e}"), } + // End-of-life build systems and platforms (ADT, Unity + // without UPM, old Android API levels and Unity editors). + let build = crate::pipeline::build_lifecycle::BuildLifecycleScanner; + match build.scan(&repo_path, &repo_id).await { + Ok(output) => { + completed.push(crate::pipeline::build_lifecycle::SCANNER.to_string()); + findings.extend(output.findings); + } + Err(e) => tracing::warn!("[{repo_id}] build lifecycle check failed: {e}"), + } (findings, completed) } .instrument(tracing::info_span!("stage_pattern_scanning")) @@ -1731,7 +1748,7 @@ impl PipelineOrchestrator { scan_run_id, &format!("OSV: {}", component_list(unchecked)), "these components were not matched against OSV, which has no advisories \ - for their package manager (CocoaPods) or refused the request", + for their package manager (CocoaPods, Unity) or refused the request", ) .await; } diff --git a/compliance-agent/src/pipeline/sbom/mod.rs b/compliance-agent/src/pipeline/sbom/mod.rs index 451e80e..1880c13 100644 --- a/compliance-agent/src/pipeline/sbom/mod.rs +++ b/compliance-agent/src/pipeline/sbom/mod.rs @@ -7,6 +7,7 @@ pub(crate) use nuget::is_restored_package; #[cfg(test)] pub(crate) use nuget::nuget_components; mod syft; +pub(crate) mod unity; use std::path::Path; @@ -37,7 +38,27 @@ impl Scanner for SbomScanner { #[tracing::instrument(skip_all)] async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result { + let (entries, _syft_failure) = self.generate(repo_path, repo_id).await; + Ok(ScanOutput { + findings: Vec::new(), + sbom_entries: entries, + }) + } +} + +impl SbomScanner { + /// The SBOM of `repo_path`, and why Syft did not complete if it did not: + /// then the SBOM is short of everything Syft reads (lockfiles, archives), + /// which the caller records rather than showing an SBOM that looks + /// complete. + #[tracing::instrument(skip_all)] + pub async fn generate( + &self, + repo_path: &Path, + repo_id: &str, + ) -> (Vec, Option) { let mut entries = Vec::new(); + let mut syft_failure = None; // Generate missing lock files so Syft can resolve the full dependency tree generate_lockfiles(repo_path, self.exec).await; @@ -45,7 +66,10 @@ impl Scanner for SbomScanner { // Run syft for SBOM generation match syft::run_syft(repo_path, repo_id).await { Ok(syft_entries) => entries.extend(syft_entries), - Err(e) => tracing::warn!("syft failed: {e}"), + Err(e) => { + tracing::warn!("syft failed: {e}"); + syft_failure = Some(e.to_string()); + } } // A Gradle build without a lockfile gives Syft nothing; its build files @@ -62,6 +86,15 @@ impl Scanner for SbomScanner { } } + // Unity projects: the editor version and the packages `Packages/` pins. + let tree = repo_path.to_path_buf(); + let target = repo_id.to_string(); + entries.extend( + tokio::task::spawn_blocking(move || unity::unity_components(&tree, &target)) + .await + .unwrap_or_default(), + ); + // NuGet packages from packages.config, project files and restored // package folders, which Syft does not read (#445). nuget::merge_nuget(&mut entries, nuget::nuget_components(repo_path, repo_id)); @@ -75,10 +108,7 @@ impl Scanner for SbomScanner { Err(e) => tracing::warn!("cargo-audit skipped: {e}"), } - Ok(ScanOutput { - findings: Vec::new(), - sbom_entries: entries, - }) + (entries, syft_failure) } } @@ -161,6 +191,20 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec { }); } out.extend(mobile::unlocked_mobile_ecosystems(repo_path)); + // End-of-life build systems declare nothing readable (see + // `build_lifecycle`, which reports them as findings too). + out.extend( + crate::pipeline::build_lifecycle::check_tree(repo_path) + .into_iter() + .filter(|hit| hit.rule_id == "legacy-build-system-no-sbom") + .map(|hit| UnlockedEcosystem { + manifest: hit.path, + problem: "belongs to a legacy build system (Eclipse/ADT, or Unity without \ + Packages/manifest.json) whose dependencies cannot be read", + remedy: "migrate the build (Gradle with the Android Gradle Plugin, or a \ + current Unity LTS with the Package Manager)", + }), + ); out.extend(nuget::unresolved_projects(repo_path)); out } diff --git a/compliance-agent/src/pipeline/sbom/syft.rs b/compliance-agent/src/pipeline/sbom/syft.rs index 661a036..f6f1f07 100644 --- a/compliance-agent/src/pipeline/sbom/syft.rs +++ b/compliance-agent/src/pipeline/sbom/syft.rs @@ -6,7 +6,7 @@ use compliance_core::CoreError; #[tracing::instrument(skip_all, fields(repo_id = %repo_id))] pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result, CoreError> { let output = tokio::time::timeout( - std::time::Duration::from_secs(300), + std::time::Duration::from_secs(600), crate::pipeline::tool_cmd::tool("syft", &["SYFT_CACHE_DIR"]) .arg(repo_path) .args(["-o", "cyclonedx-json"]) @@ -19,7 +19,7 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result Vec { + walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(MAX_DEPTH) + .sort_by_file_name() + .into_iter() + .filter_entry(|e| { + !(e.file_type().is_dir() + && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file() && e.file_name() == "ProjectVersion.txt") + .filter_map(|e| { + let settings = e.path().parent()?; + (settings.file_name()? == "ProjectSettings") + .then(|| settings.parent().map(Path::to_path_buf)) + .flatten() + }) + .collect() +} + +/// The editor version `ProjectVersion.txt` names (`m_EditorVersion: 2019.2.4f1`). +fn editor_version(project: &Path) -> Option { + let text = std::fs::read_to_string(project.join("ProjectSettings/ProjectVersion.txt")).ok()?; + text.lines() + .find_map(|line| line.trim().strip_prefix("m_EditorVersion:")) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) +} + +/// The packages a project's `Packages/` folder pins: from +/// `packages-lock.json` the registry and git packages (not Unity's built-in +/// modules or the project's own embedded and local packages), else from +/// `manifest.json` those with an exact version. `None` without either file. +fn packages(project: &Path) -> Option> { + let dir = project.join("Packages"); + let read = |name: &str| -> Option { + serde_json::from_str(&std::fs::read_to_string(dir.join(name)).ok()?).ok() + }; + if let Some(lock) = read("packages-lock.json") { + let deps = lock["dependencies"].as_object()?; + return Some( + deps.iter() + .filter(|(_, p)| matches!(p["source"].as_str(), Some("registry" | "git"))) + .filter_map(|(name, p)| Some((name.clone(), p["version"].as_str()?.to_string()))) + .collect(), + ); + } + let manifest = read("manifest.json")?; + let deps = manifest["dependencies"].as_object()?; + Some( + deps.iter() + .filter(|(name, _)| !name.starts_with("com.unity.modules.")) + .filter_map(|(name, v)| Some((name.clone(), v.as_str()?.to_string()))) + .filter(|(_, v)| v.chars().next().is_some_and(|c| c.is_ascii_digit())) + .collect(), + ) +} + +/// The Unity components under `root`: each project's editor version and the +/// packages its `Packages/` folder pins. +/// +/// # Arguments +/// +/// * `root` - the checked-out or unpacked source tree +/// * `repo_id` - the target the entries belong to +pub(crate) fn unity_components(root: &Path, repo_id: &str) -> Vec { + let mut out = Vec::new(); + for project in unity_projects(root) { + if let Some(version) = editor_version(&project) { + out.push(SbomEntry::new( + repo_id.to_string(), + EDITOR_COMPONENT.to_string(), + version, + UNITY_MANAGER.to_string(), + )); + } + for (name, version) in packages(&project).unwrap_or_default() { + out.push(SbomEntry::new( + repo_id.to_string(), + name, + version, + UNITY_MANAGER.to_string(), + )); + } + } + out.sort_by(|a, b| (&a.name, &a.version).cmp(&(&b.name, &b.version))); + out.dedup_by(|a, b| a.name == b.name && a.version == b.version); + out +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + /// A scratch tree holding `files`, removed on drop. + struct Tree(PathBuf); + impl Drop for Tree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn tree(files: &[(&str, &str)]) -> Tree { + let dir = std::env::temp_dir().join(format!("cs-unity-{}", uuid::Uuid::new_v4())); + for (path, content) in files { + let full = dir.join(path); + std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); + std::fs::write(full, content).expect("write"); + } + Tree(dir) + } + + fn components(t: &Tree) -> Vec { + unity_components(&t.0, "t") + .into_iter() + .map(|e| format!("{}@{}", e.name, e.version)) + .collect() + } + + const VERSION: &str = + "m_EditorVersion: 2019.2.4f1\nm_EditorVersionWithRevision: 2019.2.4f1 (c63b2af89a85)\n"; + + #[test] + fn a_unity_project_without_packages_lists_its_editor() { + let t = tree(&[("GT Unity/ProjectSettings/ProjectVersion.txt", VERSION)]); + assert_eq!(components(&t), ["Unity Editor@2019.2.4f1"]); + } + + #[test] + fn the_lock_lists_registry_and_git_packages_only() { + let lock = r#"{ "dependencies": { + "com.unity.textmeshpro": { "version": "2.0.1", "depth": 0, "source": "registry" }, + "com.unity.modules.ui": { "version": "1.0.0", "depth": 0, "source": "builtin" }, + "com.example.own": { "version": "file:own", "depth": 0, "source": "embedded" }, + "com.vendor.sdk": { "version": "https://git.example/sdk.git#1.4.0", "depth": 0, "source": "git" } + } }"#; + let t = tree(&[ + ("ProjectSettings/ProjectVersion.txt", VERSION), + ("Packages/packages-lock.json", lock), + ("Packages/manifest.json", "{}"), + ]); + assert_eq!( + components(&t), + [ + "Unity Editor@2019.2.4f1", + "com.unity.textmeshpro@2.0.1", + "com.vendor.sdk@https://git.example/sdk.git#1.4.0", + ] + ); + } + + #[test] + fn without_a_lock_the_manifest_gives_exact_versions() { + let manifest = r#"{ "dependencies": { + "com.unity.analytics": "3.3.2", + "com.unity.modules.audio": "1.0.0", + "com.example.local": "file:../local" + } }"#; + let t = tree(&[ + ("ProjectSettings/ProjectVersion.txt", VERSION), + ("Packages/manifest.json", manifest), + ]); + assert_eq!( + components(&t), + ["Unity Editor@2019.2.4f1", "com.unity.analytics@3.3.2"] + ); + } + + #[test] + fn a_tree_without_unity_has_nothing() { + let t = tree(&[("src/main.c", "int main;")]); + assert!(components(&t).is_empty()); + } +} diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index e161c62..4071a4f 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -435,6 +435,10 @@ pub mod scans { de: "Herstellercode (HAL, CMSIS, Drittanbieter)", en: "Vendor code (HAL, CMSIS, third party)", }, + "sbom" => Text { + de: "Stückliste (Syft)", + en: "SBOM (Syft)", + }, "sbom_dependencies" => Text { de: "Abhängigkeiten (SBOM)", en: "Dependencies (SBOM)", @@ -1726,6 +1730,10 @@ pub mod findings { de: ".NET-Version ohne Support", en: ".NET version out of support", }, + "build-lifecycle" => Text { + de: "Build-System und Plattform", + en: "Build system and platform", + }, "gdpr-patterns" => Text { de: "Datenschutz-Muster", en: "Privacy patterns", diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index d1f317b..a93df3f 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -729,6 +729,21 @@ "dotnet-framework-end-of-support" ], "check": "Components must still receive security updates; a project targeting a .NET or .NET Framework version past Microsoft's end of support violates it." + }, + { + "tool": "build-lifecycle", + "scan_type": "sbom", + "languages": [ + "java", + "kotlin", + "csharp" + ], + "cwe": [], + "rules": [ + "android-sdk-end-of-support", + "unity-editor-end-of-support" + ], + "check": "The platform a product is built for must still receive security updates; an Android API level or a Unity editor release out of support violates it." } ], "note": null, @@ -744,6 +759,20 @@ "languages": [], "cwe": [], "rules": [] + }, + { + "tool": "build-lifecycle", + "scan_type": "sbom", + "languages": [ + "java", + "kotlin", + "csharp" + ], + "cwe": [], + "rules": [ + "legacy-build-system-no-sbom" + ], + "check": "The product's components must be declared in a machine-readable form an SBOM can be built from; a build system that declares none (Eclipse/ADT, Unity without its package manifest) violates it." } ], "note": null, diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index 0e0de9e..75b0582 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -46,6 +46,20 @@ Prüfwerk builds the SBOM during each scan: - **CODESYS projects** -- the referenced libraries and the runtime version from a `.projectarchive`; see [SPS / PLC (CODESYS)](/guide/plc). +- **Unity projects** -- the editor version (from + `ProjectSettings/ProjectVersion.txt`) and the packages pinned in + `Packages/packages-lock.json` (or `Packages/manifest.json`). No advisory + database covers Unity, so they are listed under **CVE-Abgleich unvollständig**. + +**End-of-life build systems are not resolved.** An Eclipse/ADT Android project +(`default.properties` or `project.properties` beside the manifest, no Gradle) +or a Unity project without `Packages/manifest.json` declares its dependencies +nowhere readable. Prüfwerk reports it as a finding (**Legacy build system: the +SBOM cannot be determined**, with the migration as the remedy) and lists it +under **Nicht ausgeführt**, so the SBOM requirements are **Nicht bewertet** +rather than clean. An Android API level below 29 or a Unity release out of +support is a finding of its own. + Firmware images, container images and app packages are not unpacked yet; their components come from the source code. diff --git a/fixtures/nightly/baselines/mobile-legacy-adt-unity.json b/fixtures/nightly/baselines/mobile-legacy-adt-unity.json new file mode 100644 index 0000000..b6ab1b5 --- /dev/null +++ b/fixtures/nightly/baselines/mobile-legacy-adt-unity.json @@ -0,0 +1,19 @@ +{ + "scan_status": "completed", + "skipped_stages": [ + "cve_lookup", + "sbom_dependencies" + ], + "sbom": [ + "unity:Unity Editor@2019.2.4f1" + ], + "findings": [ + "mobsfscan:android_manifest_insecure_minsdk_error AndroidManifest.xml:3", + "mobsfscan:android_manifest_missing_explicit_allow_backup AndroidManifest.xml:1" + ], + "cves": [ + "android-sdk-end-of-support", + "legacy-build-system-no-sbom", + "unity-editor-end-of-support" + ] +} diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assembly-CSharp.csproj b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assembly-CSharp.csproj new file mode 100644 index 0000000..23acdc4 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assembly-CSharp.csproj @@ -0,0 +1 @@ +v4.7.1 diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assets/Scripts/PumpGauge.cs b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assets/Scripts/PumpGauge.cs new file mode 100644 index 0000000..3203be6 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/Assets/Scripts/PumpGauge.cs @@ -0,0 +1,3 @@ +using UnityEngine; + +public class PumpGauge : MonoBehaviour { } diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/ProjectSettings/ProjectVersion.txt b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/ProjectSettings/ProjectVersion.txt new file mode 100644 index 0000000..dbb1604 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Game/ProjectSettings/ProjectVersion.txt @@ -0,0 +1,2 @@ +m_EditorVersion: 2019.2.4f1 +m_EditorVersionWithRevision: 2019.2.4f1 (c63b2af89a85) diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/AndroidManifest.xml b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/AndroidManifest.xml new file mode 100644 index 0000000..8239d64 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/default.properties b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/default.properties new file mode 100644 index 0000000..c34445d --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/default.properties @@ -0,0 +1,3 @@ +# Automatically generated by Android Tools. +split.density=false +target=android-8 diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/src/com/example/pump/Main.java b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/src/com/example/pump/Main.java new file mode 100644 index 0000000..8069872 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Phone/src/com/example/pump/Main.java @@ -0,0 +1,7 @@ +package com.example.pump; + +import android.app.Activity; + +/** Shows the pump's status. */ +public class Main extends Activity { +} diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/AndroidManifest.xml b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/AndroidManifest.xml new file mode 100644 index 0000000..bec5b97 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/project.properties b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/project.properties new file mode 100644 index 0000000..c4a5b63 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/project.properties @@ -0,0 +1 @@ +target=android-11 diff --git a/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/src/com/example/pump/Main.java b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/src/com/example/pump/Main.java new file mode 100644 index 0000000..8069872 --- /dev/null +++ b/fixtures/nightly/mobile/legacy-adt-unity/Pump Tablet/src/com/example/pump/Main.java @@ -0,0 +1,7 @@ +package com.example.pump; + +import android.app.Activity; + +/** Shows the pump's status. */ +public class Main extends Activity { +} diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index 41f4456..cd99ded 100644 --- a/fixtures/nightly/targets.json +++ b/fixtures/nightly/targets.json @@ -724,6 +724,26 @@ "expect": { "min_sbom_components": 4 } + }, + { + "key": "mobile-legacy-adt-unity", + "name": "Legacy Android (Eclipse/ADT) and Unity 2019", + "target_type": "android_app", + "description": "Uploaded as a source archive. The shape of a real pilot repository: two Eclipse/ADT Android apps (manifest at the project root, default.properties / project.properties with target=android-8 and android-11, no Gradle) beside a Unity 2019.2 project without Packages/. Prüfwerk does not resolve such builds: each must give a legacy-build-system finding, the old API levels and the Unity editor end-of-support findings, the Unity editor as an SBOM component, and a recorded sbom_dependencies skip so the SBOM does not read as complete.", + "artifacts": [ + { + "kind": "source_archive", + "upload": "fixtures/nightly/mobile/legacy-adt-unity" + } + ], + "expect": { + "sast_rule_ids": [ + "legacy-build-system-no-sbom", + "android-sdk-end-of-support", + "unity-editor-end-of-support" + ], + "min_sbom_components": 1 + } } ] }