fix(sbom): .NET assemblies from DLL metadata mapped to NuGet ids (#460)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 10m42s

Syft names a DLL without a .deps.json by its version resource: product
name and file version. As a purl that is no NuGet package, so OSV
matched nothing: pkg:nuget/DotNetZip%20Library@1.9.1.5 has no advisory,
pkg:nuget/DotNetZip@1.9.1.5 has GHSA-7378-6268-4278.

Syft's dotnet-portable-executable-entry components are now mapped, in
this order:

- a DLL inside packages/<Id>.<Version>/ is that package
- a curated alias table, by assembly name (file name) and then product
  name (DotNetZip Library -> DotNetZip, Json.NET -> Newtonsoft.Json,
  Apache log4net -> log4net, Xceed Toolkit for WPF ->
  Extended.Wpf.Toolkit, empira MigraDoc -> PDFsharp-MigraDoc), with how
  the package's file versions relate to its versions (Newtonsoft.Json:
  first three parts; EntityFramework: unrelated, so the DLL only
  confirms a manifest entry)
- the assembly name, when it is a valid NuGet id and not one of the
  tree's own projects (project name or <AssemblyName>), whose names are
  not sent to OSV or nuget.org
- otherwise no purl, and the scan records the assembly as not matched
  against OSV

Alias before file name: DotNetZip ships Ionic.Zip.dll, and Ionic.Zip is
a different package. Versions go through nuget_license's
normalise_version (4.1.0.0 -> 4.1.0, +build dropped); a non-zero fourth
part stays (1.9.1.5 is a real NuGet version).

One package found in several DLLs, or in a DLL and a manifest, is one
entry: SbomEntry gains `evidence` (the manifests and DLLs it was read
from), and merge_nuget compares normalised versions and merges the
evidence instead of dropping it. Native pe-binary components are left
as they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
Sharang ParnerkarandClaude Opus 5.5 committed 2026-10-06 00:23:10 +02:00
1 parent 34688fa322
commit 8571b660a2
9 files changed
+801 -46

No files matched your search

+17 -1
View File
@@ -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 {
+37 -18
View File
@@ -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<ScanOutput, CoreError> {
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<SbomEntry>,
/// 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<String>,
/// The .NET assemblies read from DLL metadata that no NuGet package was
/// found for (`<product> <file version>`, #460): in the SBOM without a
/// purl, so not matched against advisories, which the caller records.
pub unmapped_assemblies: Vec<String>,
}
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<SbomEntry>, Option<String>) {
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,
}
}
}
+70 -22
View File
@@ -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<String>,
/// The declared range, when it is not an exact version.
requirement: Option<String>,
/// 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<SbomEntry> {
let mut packages: Vec<Package> = Vec::new();
let central = central_versions(root);
let from = |found: Vec<Package>, 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(), &central));
packages.extend(from(
read_package_references(entry.path(), &central),
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<SbomEntry> = 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<SbomEntry> {
.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<SbomEntry>, nuget: Vec<SbomEntry>) {
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<Package> {
id: id.to_string(),
version,
requirement,
source: String::new(),
})
}
@@ -355,7 +395,13 @@ fn restored_packages(root: &Path) -> Vec<Package> {
.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<Package> {
/// 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<Package> {
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<Package> {
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<Package> {
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())
@@ -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/<Id>.<Version>/…`)
//! 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<SbomEntry>,
/// The assemblies no NuGet package was found for (`<product> <version>`),
/// in the SBOM without a purl.
pub unmapped: Vec<String>,
}
/// 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<SyftPackage>,
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<String> = 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<String>) -> 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::<Vec<_>>().join(".")
}
/// The assembly names the tree builds itself, lower-cased: every project
/// file's name and `<AssemblyName>`.
fn own_assemblies(root: &Path) -> HashSet<String> {
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<String> = 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<SyftPackage> {
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<SbomEntry>, Vec<String>) {
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<String> {
let mut out: Vec<String> = 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#"<packages>
<package id="log4net" version="3.3.2" />
<package id="EntityFramework" version="6.4.4" />
</packages>"#,
),
(
"Hmi/Hmi.csproj",
r#"<Project><ItemGroup><PackageReference Include="HelixToolkit.Wpf" Version="2.20.0" /></ItemGroup></Project>"#,
),
]);
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",
"<Project><PropertyGroup><AssemblyName>PlantControl</AssemblyName></PropertyGroup></Project>",
)]);
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");
}
}
@@ -231,7 +231,7 @@ fn lookup_key(entry: &SbomEntry) -> Option<PackageKey> {
}
/// 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<String> {
pub(super) fn normalise_version(raw: &str) -> Option<String> {
let raw = raw.split('+').next().unwrap_or(raw).trim();
let (numeric, pre) = match raw.split_once('-') {
Some((n, p)) => (n, Some(p)),
+65 -3
View File
@@ -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<Vec<String>>,
}
#[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> {
pub(super) async fn run_syft(
repo_path: &Path,
repo_id: &str,
) -> Result<Vec<SyftPackage>, 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<Vec<Sbom
});
}
let cdx: CycloneDxBom = serde_json::from_slice(&output.stdout)?;
Ok(parse_cyclonedx(&output.stdout, repo_id)?)
}
/// The components of Syft's CycloneDX JSON output.
pub(super) fn parse_cyclonedx(
json: &[u8],
repo_id: &str,
) -> Result<Vec<SyftPackage>, 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<Vec<Sbom
// dependencies (the actions it uses are catalogued separately, with purls).
.filter(|c| c.component_type.as_deref() != Some("file"))
.map(|c| {
let assembly_paths = c.is_dotnet_assembly().then(|| c.locations());
let package_manager = c
.purl
.as_deref()
@@ -57,7 +84,10 @@ pub(super) async fn run_syft(repo_path: &Path, repo_id: &str) -> Result<Vec<Sbom
);
entry.purl = c.purl.map(canonical_purl);
entry.license = c.licenses.and_then(|ls| extract_license(&ls));
entry
SyftPackage {
entry,
assembly_paths,
}
})
.collect();
@@ -78,6 +108,38 @@ struct CdxComponent {
component_type: Option<String>,
purl: Option<String>,
licenses: Option<Vec<CdxLicenseWrapper>>,
#[serde(default)]
properties: Vec<CdxProperty>,
}
#[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:<n>:path`),
/// without the leading `/` it gives them.
fn locations(&self) -> Vec<String> {
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)]
+7
View File
@@ -25,6 +25,12 @@ pub struct SbomEntry {
pub license: Option<String>,
pub purl: Option<String>,
pub known_vulnerabilities: Vec<VulnRef>,
/// 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<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub created_at: DateTime<Utc>,
#[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,
}
+14
View File
@@ -32,6 +32,20 @@ Every package with an exact version gets the purl `pkg:nuget/<Id>@<Version>`
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/<Id>.<Version>/` 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 `<AssemblyName>`) 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/<Id>.<Version>/`): `<license type="expression">` as an SPDX
expression, `<license type="file">` as `LicenseRef-file`, an older
+14
View File
@@ -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/<Id>.<Version>/` 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 `<AssemblyName>`) 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/<Id>.<Version>/`): `<license
type="expression">` als SPDX-Ausdruck, `<license type="file">` als