diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 2e4a27e..62607d5 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -294,7 +294,7 @@ impl PipelineOrchestrator { tracing::info!("[{repo_id}] Stage 2: SBOM Generation"); self.update_phase(scan_run_id, ScanPhase::SbomGeneration) .await; - let (mut sbom_entries, syft_failure) = async { + let generated = async { let sbom_scanner = SbomScanner::new(compliance_core::ExecPolicy::from_env(self.config.app_env)) .with_nuget_registry(NugetRegistry::from_env( @@ -305,6 +305,9 @@ impl PipelineOrchestrator { } .instrument(tracing::info_span!("stage_sbom_generation")) .await; + let mut sbom_entries = generated.entries; + let syft_failure = generated.syft_failure; + let unmapped_assemblies = generated.unmapped_assemblies; // 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 { @@ -372,6 +375,19 @@ impl PipelineOrchestrator { // Whether every component was matched: only then is a CVE missing // from this scan known to be gone (and its issue closed). let mut cve_complete = true; + // .NET assemblies read from DLL metadata that no NuGet package is + // known for have no purl (#460): OSV was not asked about them. + if !unmapped_assemblies.is_empty() { + cve_complete = false; + self.record_cve_gap( + scan_run_id, + &format!("NuGet: {}", component_list(&unmapped_assemblies)), + "these .NET assemblies were read from DLL metadata (product name and \ + file version), and no NuGet package is known for them, so they were \ + not matched against OSV", + ) + .await; + } let mut cve_alerts = match tokio::time::timeout( std::time::Duration::from_secs(600), async { diff --git a/compliance-agent/src/pipeline/sbom/mod.rs b/compliance-agent/src/pipeline/sbom/mod.rs index 5f6103b..4f6dc9a 100644 --- a/compliance-agent/src/pipeline/sbom/mod.rs +++ b/compliance-agent/src/pipeline/sbom/mod.rs @@ -2,6 +2,7 @@ mod cargo_audit; mod gradle; mod mobile; mod nuget; +mod nuget_assembly; mod nuget_license; pub(crate) use nuget::is_restored_package; @@ -52,25 +53,32 @@ 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; + let generated = self.generate(repo_path, repo_id).await; Ok(ScanOutput { findings: Vec::new(), - sbom_entries: entries, + sbom_entries: generated.entries, }) } } +/// What [`SbomScanner::generate`] found. +pub struct GeneratedSbom { + pub entries: Vec, + /// 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. + pub syft_failure: Option, + /// The .NET assemblies read from DLL metadata that no NuGet package was + /// found for (` `, #460): in the SBOM without a + /// purl, so not matched against advisories, which the caller records. + pub unmapped_assemblies: Vec, +} + 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. + /// The SBOM of `repo_path`; see [`GeneratedSbom`] for what it reports + /// besides. #[tracing::instrument(skip_all)] - pub async fn generate( - &self, - repo_path: &Path, - repo_id: &str, - ) -> (Vec, Option) { + pub async fn generate(&self, repo_path: &Path, repo_id: &str) -> GeneratedSbom { let mut entries = Vec::new(); let mut syft_failure = None; @@ -78,13 +86,22 @@ impl SbomScanner { generate_lockfiles(repo_path, self.exec).await; // Run syft for SBOM generation - match syft::run_syft(repo_path, repo_id).await { - Ok(syft_entries) => entries.extend(syft_entries), + let syft_packages = match syft::run_syft(repo_path, repo_id).await { + Ok(packages) => packages, Err(e) => { tracing::warn!("syft failed: {e}"); syft_failure = Some(e.to_string()); + Vec::new() } - } + }; + + // NuGet packages from packages.config, project files and restored + // package folders, which Syft does not read (#445), and the .NET + // assemblies Syft read from DLL metadata as NuGet packages (#460). + let mut nuget_manifest = nuget::nuget_components(repo_path, repo_id); + let resolved = + nuget_assembly::resolve_assemblies(repo_path, syft_packages, &mut nuget_manifest); + entries.extend(resolved.entries); // A Gradle build without a lockfile gives Syft nothing; its build files // still name the direct dependencies. @@ -109,9 +126,7 @@ impl SbomScanner { .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)); + nuget::merge_nuget(&mut entries, nuget_manifest); // Their licenses: from the restored packages' .nuspec, then nuget.org. nuget_license::enrich_nuget_licenses(repo_path, &mut entries, self.nuget_registry.as_ref()) .await; @@ -125,7 +140,11 @@ impl SbomScanner { Err(e) => tracing::warn!("cargo-audit skipped: {e}"), } - (entries, syft_failure) + GeneratedSbom { + entries, + syft_failure, + unmapped_assemblies: resolved.unmapped, + } } } diff --git a/compliance-agent/src/pipeline/sbom/nuget.rs b/compliance-agent/src/pipeline/sbom/nuget.rs index f1d68e8..cbb5e39 100644 --- a/compliance-agent/src/pipeline/sbom/nuget.rs +++ b/compliance-agent/src/pipeline/sbom/nuget.rs @@ -17,7 +17,7 @@ //! assets file beside it has unknown transitive dependencies: //! [`unresolved_projects`] reports it, so the SBOM does not look complete. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::path::{Path, PathBuf}; use compliance_core::models::SbomEntry; @@ -36,6 +36,8 @@ struct Package { version: Option, /// The declared range, when it is not an exact version. requirement: Option, + /// The file or folder it was read from, relative to the tree's root. + source: String, } /// Every NuGet package the tree under `root` names, as SBOM entries with a @@ -45,35 +47,48 @@ struct Package { pub(crate) fn nuget_components(root: &Path, repo_id: &str) -> Vec { let mut packages: Vec = Vec::new(); let central = central_versions(root); + let from = |found: Vec, path: &Path| { + let source = relative(root, path); + found.into_iter().map(move |p| Package { + source: source.clone(), + ..p + }) + }; for entry in walk_sources(root) { let name = entry.file_name().to_string_lossy(); let lower = name.to_ascii_lowercase(); if lower == "packages.config" { - packages.extend(read_packages_config(entry.path())); + packages.extend(from(read_packages_config(entry.path()), entry.path())); } else if lower == "packages.lock.json" { - packages.extend(read_lock_file(entry.path())); + packages.extend(from(read_lock_file(entry.path()), entry.path())); } else if is_project_file(&name) { - packages.extend(read_package_references(entry.path(), ¢ral)); + packages.extend(from( + read_package_references(entry.path(), ¢ral), + entry.path(), + )); // `obj/` is skipped by the walk; the assets file in it is read here. if let Some(dir) = entry.path().parent() { - packages.extend(read_assets_file(&dir.join("obj/project.assets.json"))); + let assets = dir.join("obj/project.assets.json"); + packages.extend(from(read_assets_file(&assets), &assets)); } } } packages.extend(restored_packages(root)); - let mut seen: HashSet<(String, String)> = HashSet::new(); - let mut out = Vec::new(); + let mut index: HashMap<(String, String), usize> = HashMap::new(); + let mut out: Vec = Vec::new(); for p in packages { let key = ( p.id.to_ascii_lowercase(), p.version - .clone() + .as_deref() + .map(version_key) .or_else(|| p.requirement.clone()) .unwrap_or_default() .to_ascii_lowercase(), ); - if !seen.insert(key) { + if let Some(&i) = index.get(&key) { + add_evidence(&mut out[i], p.source); continue; } let mut entry = SbomEntry::new( @@ -87,23 +102,47 @@ pub(crate) fn nuget_components(root: &Path, repo_id: &str) -> Vec { .as_ref() .map(|v| format!("pkg:nuget/{}@{}", p.id, v)); entry.version_requirement = p.requirement; + add_evidence(&mut entry, p.source); + index.insert(key, out.len()); out.push(entry); } out } +/// A version as two NuGet sources compare it: `2.20.0.0`, `2.20.0` and +/// `2.20.0+build` are the same package version. +pub(super) fn version_key(version: &str) -> String { + super::nuget_license::normalise_version(version) + .unwrap_or_else(|| version.trim().to_ascii_lowercase()) +} + +/// Record `source` as evidence of `entry`, once. +pub(super) fn add_evidence(entry: &mut SbomEntry, source: String) { + if !source.is_empty() && !entry.evidence.contains(&source) { + entry.evidence.push(source); + } +} + /// Add the [`nuget_components`] not already in `entries` (Syft reads -/// `packages.lock.json` too). Matched by name and version, case-insensitively, -/// as NuGet ids are. +/// `packages.lock.json` too, and DLLs, see [`super::nuget_assembly`]). +/// Matched by id, case-insensitively as NuGet ids are, and by version as +/// NuGet compares it (`2.20.0.0` is `2.20.0`); a duplicate adds its evidence +/// to the entry already there. pub(crate) fn merge_nuget(entries: &mut Vec, nuget: Vec) { for n in nuget { - let known = entries.iter().any(|e| { + let known = entries.iter_mut().find(|e| { e.package_manager == NUGET && e.name.eq_ignore_ascii_case(&n.name) - && e.version.eq_ignore_ascii_case(&n.version) + && version_key(&e.version) == version_key(&n.version) + && e.version_requirement == n.version_requirement }); - if !known { - entries.push(n); + match known { + Some(e) => { + for source in n.evidence { + add_evidence(e, source); + } + } + None => entries.push(n), } } } @@ -164,6 +203,7 @@ fn package(id: &str, declared: &str) -> Option { id: id.to_string(), version, requirement, + source: String::new(), }) } @@ -355,7 +395,13 @@ fn restored_packages(root: &Path) -> Vec { .filter_map(Result::ok) .filter(|c| c.file_type().is_ok_and(|t| t.is_dir())) .filter(|c| is_restored_package(&c.path())) - .filter_map(|c| split_package_folder(&c.file_name().to_string_lossy())) + .filter_map(|c| { + let p = split_folder(&c.file_name().to_string_lossy())?; + Some(Package { + source: format!("{}/", relative(root, &c.path())), + ..p + }) + }) .collect(); if !found.is_empty() { found.sort_by(|a, b| a.id.cmp(&b.id)); @@ -372,7 +418,7 @@ fn restored_packages(root: &Path) -> Vec { /// version in its folder name. pub(crate) fn is_restored_package(dir: &Path) -> bool { dir.file_name() - .is_some_and(|n| split_package_folder(&n.to_string_lossy()).is_some()) + .is_some_and(|n| split_folder(&n.to_string_lossy()).is_some()) && holds_package_content(dir) } @@ -391,7 +437,11 @@ fn holds_package_content(dir: &Path) -> bool { /// `Newtonsoft.Json.12.0.1` as id `Newtonsoft.Json` and version `12.0.1`: /// the version is the shortest dotted tail that is one. -fn split_package_folder(name: &str) -> Option { +pub(super) fn split_package_folder(name: &str) -> Option<(String, String)> { + split_folder(name).map(|p| (p.id, p.version.unwrap_or_default())) +} + +fn split_folder(name: &str) -> Option { name.match_indices('.').find_map(|(i, _)| { let (id, rest) = (&name[..i], &name[i + 1..]); let numeric = rest.split(['-', '+']).next().unwrap_or(rest); @@ -404,6 +454,7 @@ fn split_package_folder(name: &str) -> Option { id: id.to_string(), version: Some(rest.to_string()), requirement: None, + source: String::new(), }) }) } @@ -558,10 +609,7 @@ mod tests { #[test] fn package_folder_names_split_at_the_version() { - let split = |n: &str| { - let p = split_package_folder(n).unwrap(); - (p.id, p.version.unwrap()) - }; + let split = |n: &str| split_package_folder(n).unwrap(); assert_eq!( split("Microsoft.AspNet.Mvc.5.2.7"), ("Microsoft.AspNet.Mvc".into(), "5.2.7".into()) diff --git a/compliance-agent/src/pipeline/sbom/nuget_assembly.rs b/compliance-agent/src/pipeline/sbom/nuget_assembly.rs new file mode 100644 index 0000000..ef2e19c --- /dev/null +++ b/compliance-agent/src/pipeline/sbom/nuget_assembly.rs @@ -0,0 +1,575 @@ +//! .NET assemblies Syft read from DLL metadata, as NuGet packages (#460). +//! +//! For a DLL without a `.deps.json`, Syft names the package after the DLL's +//! version resource: its product name and file version (`DotNetZip Library` +//! `1.9.1.5`, `Json.NET` `13.0.1.25517`, `Helix Toolkit` +//! `2.20.0+0.Branch…`). As a purl that is no NuGet package, and OSV matches +//! nothing: `pkg:nuget/DotNetZip%20Library@1.9.1.5` has no advisory, +//! `pkg:nuget/DotNetZip@1.9.1.5` has one. +//! +//! Each such assembly is mapped to a NuGet id and version, in this order: +//! +//! 1. a DLL inside a restored package folder (`packages/./…`) +//! is that package; +//! 2. the curated [`ALIASES`], by assembly name (the file name) and then by +//! product name, with how that package's file versions relate to its +//! package versions; +//! 3. the assembly name, when it is a valid NuGet id and not the name of a +//! project in the tree (the tree's own build output is no dependency, and +//! its name is not sent to OSV or nuget.org); +//! 4. otherwise the assembly stays in the SBOM without a purl, so it is not +//! matched against advisories, and is reported as unmapped. +//! +//! Versions are normalised as NuGet files them (`4.1.0.0` → `4.1.0`, build +//! metadata dropped); a fourth part that is not `0` stays (`1.9.1.5` is a +//! real NuGet version). The same package found in several DLLs, or in a DLL +//! and a manifest, becomes one entry that keeps every place as evidence. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +use compliance_core::models::SbomEntry; + +use super::nuget::{add_evidence, split_package_folder, version_key}; +use super::nuget_license::{is_package_id, normalise_version}; +use super::syft::SyftPackage; +use crate::pipeline::dotnet::{is_project_file, parse_xml, read_text, walk_sources}; + +const NUGET: &str = "nuget"; + +/// How the file versions of a package's DLLs relate to its package versions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum VersionRule { + /// The file version is the package version (`4.1.0.0` is `4.1.0`). + Package, + /// The first three parts are the package version; the fourth counts + /// builds (`13.0.1.25517` is `13.0.1`). + ThreeParts, + /// The file version does not encode the package version (Entity + /// Framework's `6.400.420.21404` is 6.4.4): the DLL only confirms a + /// package a manifest names. + Unrelated, +} + +/// Product or assembly names that are not the NuGet id of their package, +/// and packages whose file versions are not their package versions. Matched +/// case-insensitively, by assembly name (file name) first, then by product +/// name. Public packages only. +const ALIASES: &[(&str, &str, VersionRule)] = &[ + ("DotNetZip Library", "DotNetZip", VersionRule::Package), + ("Json.NET", "Newtonsoft.Json", VersionRule::ThreeParts), + ( + "Newtonsoft.Json", + "Newtonsoft.Json", + VersionRule::ThreeParts, + ), + ("Apache log4net", "log4net", VersionRule::Package), + ( + "Xceed Toolkit for WPF", + "Extended.Wpf.Toolkit", + VersionRule::Package, + ), + ( + "Xceed.Wpf.Toolkit", + "Extended.Wpf.Toolkit", + VersionRule::Package, + ), + ("empira MigraDoc", "PDFsharp-MigraDoc", VersionRule::Package), + ("EntityFramework", "EntityFramework", VersionRule::Unrelated), + ( + "EntityFramework.SqlServer", + "EntityFramework", + VersionRule::Unrelated, + ), +]; + +/// What an assembly read from DLL metadata is. +#[derive(Debug, PartialEq, Eq)] +enum Mapping { + /// The NuGet package `id` at `version`. + Package { id: String, version: String }, + /// The NuGet package `id`, at the version a manifest names. + Confirms { id: String }, + /// Built from a project in the tree. + Own, + /// No NuGet package known. + Unmapped, +} + +/// The SBOM entries of Syft's components, with every .NET assembly read +/// from DLL metadata mapped to its NuGet package (see the module docs). +pub(super) struct Resolved { + pub entries: Vec, + /// The assemblies no NuGet package was found for (` `), + /// in the SBOM without a purl. + pub unmapped: Vec, +} + +/// Map the assemblies among `packages` to NuGet packages. `manifest` holds +/// the NuGet packages the tree's manifests name: an assembly that only +/// confirms one of them adds its evidence there. +pub(super) fn resolve_assemblies( + root: &Path, + packages: Vec, + manifest: &mut [SbomEntry], +) -> Resolved { + let own = own_assemblies(root); + let mut entries = Vec::new(); + let mut unmapped = Vec::new(); + // Index into `entries` of each assembly-derived entry, by id and version. + let mut index: HashMap<(String, String), usize> = HashMap::new(); + for SyftPackage { + mut entry, + assembly_paths, + } in packages + { + let Some(paths) = assembly_paths else { + entries.push(entry); + continue; + }; + let evidence: Vec = paths + .iter() + .map(|p| format!("{p} (DLL metadata: {} {})", entry.name, entry.version)) + .collect(); + match map_assembly(&paths, &entry.name, &entry.version, &own) { + Mapping::Package { id, version } => { + entry.purl = Some(format!("pkg:nuget/{id}@{version}")); + entry.name = id; + entry.version = version; + entry.package_manager = NUGET.to_string(); + } + Mapping::Confirms { id } => { + let mut confirmed = manifest + .iter_mut() + .filter(|m| m.name.eq_ignore_ascii_case(&id) && m.purl.is_some()) + .peekable(); + if confirmed.peek().is_some() { + for m in confirmed { + for e in &evidence { + add_evidence(m, e.clone()); + } + } + continue; + } + entry.purl = None; + unmapped.push(format!("{} {}", entry.name, entry.version)); + } + Mapping::Own => entry.purl = None, + Mapping::Unmapped => { + entry.purl = None; + unmapped.push(format!("{} {}", entry.name, entry.version)); + } + } + let key = (entry.name.to_ascii_lowercase(), version_key(&entry.version)); + if let Some(&i) = index.get(&key) { + if let Some(kept) = entries.get_mut(i) { + for e in evidence { + add_evidence(kept, e); + } + } + continue; + } + for e in evidence { + add_evidence(&mut entry, e); + } + index.insert(key, entries.len()); + entries.push(entry); + } + let mut seen = HashSet::new(); + unmapped.retain(|u| seen.insert(u.to_ascii_lowercase())); + Resolved { entries, unmapped } +} + +/// The NuGet package of an assembly Syft named `product` at `version`, read +/// from the DLLs at `paths`. +fn map_assembly(paths: &[String], product: &str, version: &str, own: &HashSet) -> Mapping { + if let Some((id, version)) = paths.iter().find_map(|p| restored_folder(p)) { + return Mapping::Package { id, version }; + } + let Some(name) = paths.first().map(|p| assembly_name(p)) else { + return Mapping::Unmapped; + }; + if let Some(&(_, id, rule)) = alias(&name).or_else(|| alias(product)) { + let version = match rule { + VersionRule::Package => normalise_version(version), + VersionRule::ThreeParts => normalise_version(&three_parts(version)), + VersionRule::Unrelated => { + return Mapping::Confirms { id: id.to_string() }; + } + }; + return match version { + Some(version) => Mapping::Package { + id: id.to_string(), + version, + }, + None => Mapping::Unmapped, + }; + } + if own.contains(&name.to_ascii_lowercase()) { + return Mapping::Own; + } + match normalise_version(version) { + Some(version) if is_package_id(&name) => Mapping::Package { id: name, version }, + _ => Mapping::Unmapped, + } +} + +fn alias(name: &str) -> Option<&'static (&'static str, &'static str, VersionRule)> { + ALIASES + .iter() + .find(|(key, _, _)| key.eq_ignore_ascii_case(name)) +} + +/// The id and version of the restored package folder `path` lies in +/// (`packages/DotNetZip.1.9.1.8/lib/net20/Ionic.Zip.dll`). +fn restored_folder(path: &str) -> Option<(String, String)> { + let parts: Vec<&str> = path.split(['/', '\\']).collect(); + parts.windows(2).find_map(|w| { + w[0].eq_ignore_ascii_case("packages") + .then(|| split_package_folder(w[1])) + .flatten() + }) +} + +/// The assembly name of a DLL: its file name without the extension, and +/// without `.resources` for a satellite assembly. +fn assembly_name(path: &str) -> String { + let file = path.rsplit(['/', '\\']).next().unwrap_or(path); + let lower = file.to_ascii_lowercase(); + let stem = [".dll", ".exe"] + .iter() + .find(|ext| lower.ends_with(*ext)) + .map_or(file, |ext| &file[..file.len() - ext.len()]); + let lower = stem.to_ascii_lowercase(); + lower + .strip_suffix(".resources") + .map_or(stem, |s| &stem[..s.len()]) + .to_string() +} + +/// The first three parts of a version, build metadata dropped. +fn three_parts(version: &str) -> String { + let version = version.split('+').next().unwrap_or(version); + version.split('.').take(3).collect::>().join(".") +} + +/// The assembly names the tree builds itself, lower-cased: every project +/// file's name and ``. +fn own_assemblies(root: &Path) -> HashSet { + let mut out = HashSet::new(); + for entry in walk_sources(root) { + let file = entry.file_name().to_string_lossy().to_string(); + if !is_project_file(&file) { + continue; + } + if let Some((stem, _)) = file.rsplit_once('.') { + out.insert(stem.to_ascii_lowercase()); + } + let Some(text) = read_text(entry.path()) else { + continue; + }; + let Some(doc) = parse_xml(&text) else { + continue; + }; + out.extend( + doc.descendants() + .filter(|n| n.is_element() && n.tag_name().name() == "AssemblyName") + .filter_map(|n| n.text()) + .map(str::trim) + .filter(|n| !n.is_empty() && !n.contains("$(")) + .map(str::to_ascii_lowercase), + ); + } + out +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::pipeline::sbom::nuget::{merge_nuget, nuget_components}; + use crate::pipeline::sbom::syft::parse_cyclonedx; + + 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-nuget-asm-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).expect("mkdir"); + 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) + } + + /// A component as Syft's CycloneDX output has a .NET assembly it read + /// from DLL metadata. + fn dll(name: &str, version: &str, paths: &[&str]) -> String { + let locations: Vec = paths + .iter() + .enumerate() + .map(|(i, p)| format!(r#"{{"name":"syft:location:{i}:path","value":"/{p}"}}"#)) + .collect(); + format!( + r#"{{"type":"library","name":"{name}","version":"{version}", + "purl":"pkg:nuget/{}@{version}", + "properties":[ + {{"name":"syft:package:foundBy","value":"dotnet-portable-executable-cataloger"}}, + {{"name":"syft:package:metadataType","value":"dotnet-portable-executable-entry"}}, + {}]}}"#, + name.replace(' ', "%20"), + locations.join(",") + ) + } + + fn syft(components: &[String]) -> Vec { + let json = format!(r#"{{"components":[{}]}}"#, components.join(",")); + parse_cyclonedx(json.as_bytes(), "r").expect("cyclonedx") + } + + /// The SBOM as `SbomScanner::generate` builds it from Syft's output and + /// the tree's manifests. + fn sbom(root: &Path, components: &[String]) -> (Vec, Vec) { + let mut manifest = nuget_components(root, "r"); + let resolved = resolve_assemblies(root, syft(components), &mut manifest); + let mut entries = resolved.entries; + merge_nuget(&mut entries, manifest); + (entries, resolved.unmapped) + } + + fn purls(entries: &[SbomEntry]) -> Vec { + let mut out: Vec = entries.iter().filter_map(|e| e.purl.clone()).collect(); + out.sort(); + out + } + + #[test] + fn dotnetzip_from_dll_metadata_is_the_nuget_package() { + // DotNetZip ships Ionic.Zip.dll, product name "DotNetZip Library". + let t = tree(&[]); + let (entries, unmapped) = sbom( + &t.0, + &[dll("DotNetZip Library", "1.9.1.5", &["lib/Ionic.Zip.dll"])], + ); + assert_eq!(purls(&entries), ["pkg:nuget/DotNetZip@1.9.1.5"]); + assert_eq!(entries[0].name, "DotNetZip"); + assert_eq!(entries[0].version, "1.9.1.5"); + assert_eq!( + entries[0].evidence, + ["lib/Ionic.Zip.dll (DLL metadata: DotNetZip Library 1.9.1.5)"] + ); + assert!(unmapped.is_empty()); + } + + #[test] + fn product_names_and_file_versions_become_ids_and_package_versions() { + let t = tree(&[]); + let (entries, unmapped) = sbom( + &t.0, + &[ + dll("Json.NET", "13.0.1.25517", &["bin/Newtonsoft.Json.dll"]), + dll("Apache log4net", "3.3.2.0", &["bin/log4net.dll"]), + dll( + "Helix Toolkit", + "2.20.0+0.Branch.origin-master.Sha.0123abc", + &["bin/HelixToolkit.Wpf.dll"], + ), + dll( + "Xceed Toolkit for WPF", + "4.1.0.0", + &["bin/Xceed.Wpf.Toolkit.dll"], + ), + dll( + "empira MigraDoc", + "1.50.5147.0", + &[ + "bin/MigraDoc.Rendering.dll", + "bin/de/MigraDoc.Rendering.resources.dll", + ], + ), + dll( + "empira MigraDoc", + "1.50.5147.0", + &["bin/MigraDoc.DocumentObjectModel.dll"], + ), + ], + ); + assert_eq!( + purls(&entries), + [ + "pkg:nuget/Extended.Wpf.Toolkit@4.1.0", + "pkg:nuget/HelixToolkit.Wpf@2.20.0", + "pkg:nuget/Newtonsoft.Json@13.0.1", + "pkg:nuget/PDFsharp-MigraDoc@1.50.5147", + "pkg:nuget/log4net@3.3.2", + ] + ); + // The two MigraDoc DLLs are one package, with both as evidence. + let migradoc = entries + .iter() + .find(|e| e.name == "PDFsharp-MigraDoc") + .unwrap(); + assert_eq!(migradoc.evidence.len(), 3); + assert!(unmapped.is_empty()); + } + + #[test] + fn a_dll_and_a_manifest_of_one_package_are_one_entry() { + let t = tree(&[ + ( + "Hmi/packages.config", + r#" + + + "#, + ), + ( + "Hmi/Hmi.csproj", + r#""#, + ), + ]); + let (entries, unmapped) = sbom( + &t.0, + &[ + dll("Apache log4net", "3.3.2.0", &["Hmi/bin/log4net.dll"]), + dll( + "Helix Toolkit", + "2.20.0+0.Branch.origin-master", + &["Hmi/bin/HelixToolkit.Wpf.dll"], + ), + // Entity Framework's file version is not its package version. + dll( + "Microsoft Entity Framework", + "6.400.420.21404", + &["Hmi/bin/EntityFramework.dll"], + ), + ], + ); + assert_eq!( + purls(&entries), + [ + "pkg:nuget/EntityFramework@6.4.4", + "pkg:nuget/HelixToolkit.Wpf@2.20.0", + "pkg:nuget/log4net@3.3.2", + ] + ); + assert_eq!(entries.len(), 3); + let log4net = entries.iter().find(|e| e.name == "log4net").unwrap(); + assert_eq!( + log4net.evidence, + [ + "Hmi/bin/log4net.dll (DLL metadata: Apache log4net 3.3.2.0)", + "Hmi/packages.config", + ] + ); + let ef = entries + .iter() + .find(|e| e.name == "EntityFramework") + .unwrap(); + assert_eq!( + ef.evidence, + [ + "Hmi/packages.config", + "Hmi/bin/EntityFramework.dll (DLL metadata: Microsoft Entity Framework 6.400.420.21404)", + ] + ); + assert!(unmapped.is_empty()); + } + + #[test] + fn a_dll_in_a_restored_package_folder_is_that_package() { + let t = tree(&[("packages/DotNetZip.1.9.1.8/lib/net20/Ionic.Zip.dll", "")]); + let (entries, _) = sbom( + &t.0, + &[dll( + "DotNetZip Library", + "1.9.1.5", + &["packages/DotNetZip.1.9.1.8/lib/net20/Ionic.Zip.dll"], + )], + ); + assert_eq!(purls(&entries), ["pkg:nuget/DotNetZip@1.9.1.8"]); + assert_eq!(entries[0].evidence.len(), 2); + } + + #[test] + fn own_assemblies_and_unknown_products_get_no_purl() { + let t = tree(&[( + "src/Plant.Hmi/Plant.Hmi.csproj", + "PlantControl", + )]); + let (entries, unmapped) = sbom( + &t.0, + &[ + dll( + "Plant HMI", + "1.0.0.0", + &["src/Plant.Hmi/bin/PlantControl.exe"], + ), + dll("Plant HMI", "1.0.0.0", &["src/Plant.Hmi/bin/Plant.Hmi.dll"]), + // Neither an alias nor a valid id, nor a version. + dll("Some Vendor Lib", "1.0.0.0", &["lib/Some Vendor Lib.dll"]), + dll("Odd", "build-7", &["lib/Odd.dll"]), + // Entity Framework without a manifest naming its version. + dll( + "Microsoft Entity Framework", + "6.400.420.21404", + &["lib/EntityFramework.dll"], + ), + ], + ); + assert!(purls(&entries).is_empty(), "{:?}", purls(&entries)); + assert_eq!( + unmapped, + [ + "Some Vendor Lib 1.0.0.0", + "Odd build-7", + "Microsoft Entity Framework 6.400.420.21404", + ] + ); + } + + #[test] + fn other_components_pass_unchanged() { + let t = tree(&[]); + let json = br#"{"components":[ + {"type":"library","name":"lodash","version":"4.17.21","purl":"pkg:npm/lodash@4.17.21"}, + {"type":"application","name":"Some C Runtime","version":"14.44.35211.0", + "properties":[{"name":"syft:package:metadataType","value":"pe-binary"}, + {"name":"syft:location:0:path","value":"/msvcp140.dll"}]} + ]}"#; + let resolved = resolve_assemblies(&t.0, parse_cyclonedx(json, "r").unwrap(), &mut []); + let names: Vec<(&str, Option<&str>, &str)> = resolved + .entries + .iter() + .map(|e| { + ( + e.name.as_str(), + e.purl.as_deref(), + e.package_manager.as_str(), + ) + }) + .collect(); + assert_eq!( + names, + [ + ("lodash", Some("pkg:npm/lodash@4.17.21"), "npm"), + ("Some C Runtime", None, "unknown"), + ] + ); + assert!(resolved.unmapped.is_empty()); + } + + #[test] + fn assembly_names() { + assert_eq!(assembly_name("bin/Ionic.Zip.dll"), "Ionic.Zip"); + assert_eq!(assembly_name("bin\\de\\PdfSharp.resources.DLL"), "PdfSharp"); + assert_eq!(assembly_name("Tool.exe"), "Tool"); + assert_eq!(three_parts("13.0.1.25517"), "13.0.1"); + assert_eq!(three_parts("2.5.1+Branch.x"), "2.5.1"); + } +} diff --git a/compliance-agent/src/pipeline/sbom/nuget_license.rs b/compliance-agent/src/pipeline/sbom/nuget_license.rs index 16ebd13..9ebd564 100644 --- a/compliance-agent/src/pipeline/sbom/nuget_license.rs +++ b/compliance-agent/src/pipeline/sbom/nuget_license.rs @@ -231,7 +231,7 @@ fn lookup_key(entry: &SbomEntry) -> Option { } /// Whether `id` is a valid NuGet package id: letters, digits, `.`, `_`, `-`. -fn is_package_id(id: &str) -> bool { +pub(super) fn is_package_id(id: &str) -> bool { !id.is_empty() && id.len() <= 100 && id @@ -243,7 +243,7 @@ fn is_package_id(id: &str) -> bool { /// dropped, at least three parts, and a fourth part only when it is not `0` /// (`2.0` → `2.0.0`, `6.2.0.0` → `6.2.0`, `1.0.0-Beta` → `1.0.0-beta`). /// `None` for something that is not a version. -fn normalise_version(raw: &str) -> Option { +pub(super) fn normalise_version(raw: &str) -> Option { let raw = raw.split('+').next().unwrap_or(raw).trim(); let (numeric, pre) = match raw.split_once('-') { Some((n, p)) => (n, Some(p)), diff --git a/compliance-agent/src/pipeline/sbom/syft.rs b/compliance-agent/src/pipeline/sbom/syft.rs index f6f1f07..3d00af7 100644 --- a/compliance-agent/src/pipeline/sbom/syft.rs +++ b/compliance-agent/src/pipeline/sbom/syft.rs @@ -3,8 +3,26 @@ use std::path::Path; use compliance_core::models::SbomEntry; use compliance_core::CoreError; +/// Syft's metadata type for a .NET assembly it read from a DLL's or EXE's +/// version resource (product name, file version) rather than from a +/// manifest (#460). +const DOTNET_ASSEMBLY: &str = "dotnet-portable-executable-entry"; + +/// One component Syft reported. +pub(super) struct SyftPackage { + pub entry: SbomEntry, + /// For a .NET assembly read from DLL metadata ([`DOTNET_ASSEMBLY`]): the + /// files it was read from, relative to the scanned tree. Its name and + /// version are the DLL's product name and file version, not yet a NuGet + /// id and package version (see `nuget_assembly`). + pub assembly_paths: Option>, +} + #[tracing::instrument(skip_all, fields(repo_id = %repo_id))] -pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result, CoreError> { +pub(super) async fn run_syft( + repo_path: &Path, + repo_id: &str, +) -> Result, CoreError> { let output = tokio::time::timeout( std::time::Duration::from_secs(600), crate::pipeline::tool_cmd::tool("syft", &["SYFT_CACHE_DIR"]) @@ -34,7 +52,15 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result Result, serde_json::Error> { + let cdx: CycloneDxBom = serde_json::from_slice(json)?; let entries = cdx .components .unwrap_or_default() @@ -44,6 +70,7 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result Result, purl: Option, licenses: Option>, + #[serde(default)] + properties: Vec, +} + +#[derive(serde::Deserialize)] +struct CdxProperty { + name: String, + #[serde(default)] + value: String, +} + +impl CdxComponent { + fn property(&self, name: &str) -> Option<&str> { + self.properties + .iter() + .find(|p| p.name == name) + .map(|p| p.value.as_str()) + } + + fn is_dotnet_assembly(&self) -> bool { + self.property("syft:package:metadataType") == Some(DOTNET_ASSEMBLY) + } + + /// The files Syft read the component from (`syft:location::path`), + /// without the leading `/` it gives them. + fn locations(&self) -> Vec { + self.properties + .iter() + .filter(|p| p.name.starts_with("syft:location:") && p.name.ends_with(":path")) + .map(|p| p.value.trim_start_matches('/').to_string()) + .collect() + } } #[derive(serde::Deserialize)] diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index e3ceb41..0396f23 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -25,6 +25,12 @@ pub struct SbomEntry { pub license: Option, pub purl: Option, pub known_vulnerabilities: Vec, + /// Where the component was found, when more than its name tells: the + /// manifests and DLLs one NuGet package was read from (`Hmi/packages.config`, + /// `lib/Ionic.Zip.dll (DLL metadata: DotNetZip Library 1.9.1.5)`). Kept when + /// duplicates of one package are merged. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub evidence: Vec, #[serde(with = "super::serde_helpers::bson_datetime")] pub created_at: DateTime, #[serde(with = "super::serde_helpers::bson_datetime")] @@ -44,6 +50,7 @@ impl SbomEntry { license: None, purl: None, known_vulnerabilities: Vec::new(), + evidence: Vec::new(), created_at: now, updated_at: now, } diff --git a/docs/guide/dotnet-en.md b/docs/guide/dotnet-en.md index a026c56..49fa090 100644 --- a/docs/guide/dotnet-en.md +++ b/docs/guide/dotnet-en.md @@ -32,6 +32,20 @@ Every package with an exact version gets the purl `pkg:nuget/@` and is matched against OSV (ecosystem NuGet). A version range (`7.*`, `[1.0,2.0)`) is listed without a purl, with the range as its requirement. +**Packages from DLLs.** Syft also reads DLLs (in `bin/`, `lib/`, committed +anywhere) and names them by their version resource: product name and file +version (`DotNetZip Library 1.9.1.5`, `Json.NET 13.0.1.25517`). Those are +mapped to the NuGet package: a DLL inside `packages/./` is that +package; known product and assembly names map through a curated table +(`DotNetZip Library` → `DotNetZip`, `Json.NET` → `Newtonsoft.Json`, …); +otherwise the assembly name (file name) is the id. Versions are normalised as +NuGet files them (`4.1.0.0` → `4.1.0`, `+build` metadata dropped). The DLLs +of the tree's own projects (project name or ``) get no purl. A +DLL that cannot be mapped stays in the SBOM without a purl and is listed in +the scan as not matched against OSV. One package found in several places +(manifest and DLL, several DLLs) is one SBOM entry, with every place as +evidence. + **Licenses of NuGet packages.** First from the `.nuspec` of a restored package (`packages/./`): `` as an SPDX expression, `` as `LicenseRef-file`, an older diff --git a/docs/guide/dotnet.md b/docs/guide/dotnet.md index 94c9ce3..00bcc1f 100644 --- a/docs/guide/dotnet.md +++ b/docs/guide/dotnet.md @@ -33,6 +33,20 @@ wird gegen OSV (Ökosystem NuGet) abgeglichen. Ein Versionsbereich (`7.*`, `[1.0,2.0)`) steht ohne purl in der Stückliste, mit dem Bereich als Anforderung. +**Pakete aus DLLs.** Syft liest auch DLLs (in `bin/`, `lib/`, irgendwo +eingecheckt) und benennt sie nach ihrer Versionsressource: Produktname und +Dateiversion (`DotNetZip Library 1.9.1.5`, `Json.NET 13.0.1.25517`). Diese +werden dem NuGet-Paket zugeordnet: eine DLL in `packages/./` ist +dieses Paket; bekannte Produkt- und Assembly-Namen über eine gepflegte Tabelle +(`DotNetZip Library` → `DotNetZip`, `Json.NET` → `Newtonsoft.Json`, …); sonst +ist der Assembly-Name (Dateiname) die Id. Versionen werden normalisiert, wie +NuGet sie führt (`4.1.0.0` → `4.1.0`, `+build`-Metadaten entfallen). DLLs der +eigenen Projekte (Projektname oder ``) erhalten keine purl. Eine +DLL ohne Zuordnung bleibt ohne purl in der Stückliste und wird im Scan als +nicht gegen OSV abgeglichen ausgewiesen. Ein Paket, das an mehreren Stellen +vorkommt (Manifest und DLL, mehrere DLLs), ist ein Eintrag mit allen +Fundstellen als Nachweis. + **Lizenzen der NuGet-Pakete.** Zuerst aus der `.nuspec` eines wiederhergestellten Pakets (`packages/./`): `` als SPDX-Ausdruck, `` als