feat(mobile): legacy Android and Unity builds flagged, not resolved; Android found everywhere (#466)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Dashboard (push) Successful in 5m0s
CI / Deploy Agent (push) Successful in 6m27s

This commit was merged in pull request #466.
This commit is contained in:
sharang committed 2026-10-05 21:17:52 +00:00
1 parent 0da96110c3
commit 04b4f32807
24 files changed
+836 -28

No files matched your search

+50 -4
View File
@@ -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", "<manifest/>"),
("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",
"<manifest/>",
),
("Game/Assembly-CSharp.csproj", "<Project/>"),
("Phone/src/test/AndroidManifest.xml", "<manifest/>"),
],
);
})
.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| {
+2 -1
View File
@@ -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,
}
}
@@ -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<ScanOutput, CoreError> {
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<Hit> {
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<Hit> {
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<u32> {
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<Hit> {
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::<u32>().ok()),
parts.next().and_then(|m| m.parse::<u32>().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<String> {
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", "<manifest/>"),
(
"Mobile App/default.properties",
"# generated\nsplit.density=false\ntarget=android-8\n",
),
("Tablet App/AndroidManifest.xml", "<manifest/>"),
(
"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", "<manifest/>"),
("app/build.gradle", "android { compileSdk 34 }"),
// An ADT layout that has moved to Gradle keeps its properties.
("legacy/AndroidManifest.xml", "<manifest/>"),
("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);
}
}
+5 -4
View File
@@ -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
@@ -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(
+1
View File
@@ -1,3 +1,4 @@
pub mod build_lifecycle;
pub mod code_review;
pub mod cppcheck;
pub mod cve;
+28 -11
View File
@@ -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;
}
+49 -5
View File
@@ -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<ScanOutput, CoreError> {
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<SbomEntry>, Option<String>) {
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<UnlockedEcosystem> {
});
}
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
}
+2 -2
View File
@@ -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<Vec<SbomEntry>, 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<Sbom
.await
.map_err(|_| CoreError::Scanner {
scanner: "syft".to_string(),
source: "timed out after 5 minutes".into(),
source: "timed out after 10 minutes".into(),
})?
.map_err(|e| CoreError::Scanner {
scanner: "syft".to_string(),
+203
View File
@@ -0,0 +1,203 @@
//! Components of Unity projects.
//!
//! A Unity project is recognised by `ProjectSettings/ProjectVersion.txt`. The
//! editor version written there is itself a component of the shipped app
//! (Unity's runtime is built into it), and an outdated one matters for the CRA.
//! The Unity packages the project uses are read from `Packages/packages-lock.json`
//! (exact versions, with what they pull in) or else `Packages/manifest.json`.
//! A project without `Packages/` has packages nobody can list; that is an
//! end-of-life build, reported by [`crate::pipeline::build_lifecycle`].
//!
//! No advisory database covers Unity or its packages, so these components are
//! listed as not matched for CVEs (see [`crate::pipeline::cve`]).
use std::path::{Path, PathBuf};
use compliance_core::models::SbomEntry;
use super::mobile::{MAX_DEPTH, SKIPPED_DIRS};
/// The package manager name of every Unity component.
pub(crate) const UNITY_MANAGER: &str = "unity";
/// The name of the component standing for the editor (and runtime) version.
const EDITOR_COMPONENT: &str = "Unity Editor";
/// The Unity projects under `root`: the directories holding
/// `ProjectSettings/ProjectVersion.txt`.
fn unity_projects(root: &Path) -> Vec<PathBuf> {
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<String> {
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<Vec<(String, String)>> {
let dir = project.join("Packages");
let read = |name: &str| -> Option<serde_json::Value> {
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<SbomEntry> {
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<String> {
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());
}
}
+8
View File
@@ -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",
+29
View File
@@ -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,
+14
View File
@@ -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.
@@ -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"
]
}
@@ -0,0 +1 @@
<Project ToolsVersion="4.0"><PropertyGroup><TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion></PropertyGroup></Project>
@@ -0,0 +1,3 @@
using UnityEngine;
public class PumpGauge : MonoBehaviour { }
@@ -0,0 +1,2 @@
m_EditorVersion: 2019.2.4f1
m_EditorVersionWithRevision: 2019.2.4f1 (c63b2af89a85)
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.pump.phone">
<uses-sdk android:minSdkVersion="8" />
<application android:label="Pump">
<activity android:name=".Main" />
</application>
</manifest>
@@ -0,0 +1,3 @@
# Automatically generated by Android Tools.
split.density=false
target=android-8
@@ -0,0 +1,7 @@
package com.example.pump;
import android.app.Activity;
/** Shows the pump's status. */
public class Main extends Activity {
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.pump.tablet">
<uses-sdk android:minSdkVersion="11" />
<application android:label="Pump">
<activity android:name=".Main" />
</application>
</manifest>
@@ -0,0 +1 @@
target=android-11
@@ -0,0 +1,7 @@
package com.example.pump;
import android.app.Activity;
/** Shows the pump's status. */
public class Main extends Activity {
}
+20
View File
@@ -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
}
}
]
}