435 lines
18 KiB
Rust
435 lines
18 KiB
Rust
//! SBOM documents in the two exchange formats: CycloneDX 1.6 and SPDX 2.3.
|
|
//! Shared by the agent's SBOM export and evidence pack and by the MCP server,
|
|
//! so all of them say the same. The CycloneDX parts are shared with the VEX
|
|
//! documents (see [`crate::vex_docs`]), which refer to the same `bom-ref`s.
|
|
//!
|
|
//! The CycloneDX document follows BSI TR-03183-2 v2.1 (#508) as far as
|
|
//! Prüfwerk knows the data: the `bsi:component:*` properties of the registry
|
|
//! packages, a dependency graph whose completeness is stated, and licences as
|
|
//! the suppliers declare them.
|
|
|
|
use crate::models::{advisory_source, is_cve, ComponentHash, SbomEntry};
|
|
use crate::purl::Purl;
|
|
use crate::spdx_license;
|
|
|
|
/// The `bom-ref` of a component, which a VEX statement refers to: its purl,
|
|
/// or `<package manager>:<name>@<version>` without one.
|
|
pub fn component_ref(entry: &SbomEntry) -> String {
|
|
entry
|
|
.purl
|
|
.clone()
|
|
.unwrap_or_else(|| format!("{}:{}@{}", entry.package_manager, entry.name, entry.version))
|
|
}
|
|
|
|
/// The identifier of the product (the target) the SBOM and the VEX describe:
|
|
/// `pkg:generic/<name>`, the name percent-encoded as a purl requires.
|
|
pub fn product_ref(subject: &str) -> String {
|
|
let encoded: String = subject
|
|
.bytes()
|
|
.map(|b| match b {
|
|
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'-' | b'_' | b'~' => {
|
|
(b as char).to_string()
|
|
}
|
|
_ => format!("%{b:02X}"),
|
|
})
|
|
.collect();
|
|
format!("pkg:generic/{encoded}")
|
|
}
|
|
|
|
/// A license as CycloneDX writes it: an SPDX id, an SPDX expression
|
|
/// (`MIT OR Apache-2.0`), or a named license. A name or URL of a license
|
|
/// SPDX lists becomes its id ([`spdx_license::normalise`], BSI TR-03183-2).
|
|
/// It is the license the supplier declares (registry or lockfile metadata):
|
|
/// Prüfwerk has not concluded it.
|
|
fn license_choice(license: &str) -> serde_json::Value {
|
|
let license = spdx_license::normalise(license);
|
|
if spdx_license::canonical_id(&license) == Some(&*license) {
|
|
serde_json::json!([{ "license": { "id": license, "acknowledgement": "declared" } }])
|
|
} else if spdx_license::has_operator(&license) {
|
|
serde_json::json!([{ "expression": license, "acknowledgement": "declared" }])
|
|
} else {
|
|
serde_json::json!([{ "license": { "name": license, "acknowledgement": "declared" } }])
|
|
}
|
|
}
|
|
|
|
/// The file a registry package is distributed as (`log4j-core-2.14.1.jar`),
|
|
/// where its purl determines it. `None` for a package type whose file the
|
|
/// purl does not name (PyPI wheel or sdist, Go modules) and without a version.
|
|
fn package_filename(purl: &Purl) -> Option<String> {
|
|
let version = purl.version.as_deref()?;
|
|
let name = &purl.name;
|
|
Some(match purl.ty.as_str() {
|
|
// The registry tarball is named after the unscoped name.
|
|
"npm" => format!("{name}-{version}.tgz"),
|
|
"maven" => {
|
|
let extension = purl.qualifier("type").unwrap_or("jar");
|
|
match purl.qualifier("classifier") {
|
|
Some(classifier) => format!("{name}-{version}-{classifier}.{extension}"),
|
|
None => format!("{name}-{version}.{extension}"),
|
|
}
|
|
}
|
|
"nuget" => format!("{}.{}.nupkg", name.to_lowercase(), version.to_lowercase()),
|
|
"cargo" => format!("{name}-{version}.crate"),
|
|
"gem" => match purl.qualifier("platform") {
|
|
Some(platform) => format!("{name}-{version}-{platform}.gem"),
|
|
None => format!("{name}-{version}.gem"),
|
|
},
|
|
"hex" => format!("{name}-{version}.tar"),
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
/// The `bsi:component:*` properties of a registry package: its file, and that
|
|
/// it is a package archive. A package archive is described like the TR's rpm
|
|
/// example (Table 7): not executable itself, an archive, structured.
|
|
fn bsi_properties(purl: &Purl) -> Option<serde_json::Value> {
|
|
let filename = package_filename(purl)?;
|
|
Some(serde_json::json!([
|
|
{ "name": "bsi:component:filename", "value": filename },
|
|
{ "name": "bsi:component:executable", "value": "non-executable" },
|
|
{ "name": "bsi:component:archive", "value": "archive" },
|
|
{ "name": "bsi:component:structured", "value": "structured" },
|
|
]))
|
|
}
|
|
|
|
/// A CycloneDX severity from an advisory's (`HIGH`, `MODERATE`, `critical`).
|
|
pub fn cdx_severity(severity: &str) -> &'static str {
|
|
match severity.trim().to_ascii_lowercase().as_str() {
|
|
"critical" => "critical",
|
|
"high" => "high",
|
|
"medium" | "moderate" => "medium",
|
|
"low" => "low",
|
|
"info" | "informational" => "info",
|
|
"none" => "none",
|
|
_ => "unknown",
|
|
}
|
|
}
|
|
|
|
/// Hashes as CycloneDX writes them.
|
|
fn cdx_hashes(hashes: &[ComponentHash]) -> serde_json::Value {
|
|
hashes
|
|
.iter()
|
|
.map(|h| serde_json::json!({ "alg": h.alg, "content": h.content }))
|
|
.collect()
|
|
}
|
|
|
|
/// The components of a CycloneDX document, each with its `bom-ref`.
|
|
pub fn cdx_components(entries: &[SbomEntry]) -> Vec<serde_json::Value> {
|
|
let mut seen = std::collections::HashSet::new();
|
|
entries
|
|
.iter()
|
|
.filter(|e| seen.insert(component_ref(e)))
|
|
.map(|e| {
|
|
let mut comp = serde_json::json!({
|
|
"type": "library",
|
|
"bom-ref": component_ref(e),
|
|
"name": e.name,
|
|
"version": e.version,
|
|
});
|
|
if let Some(purl) = &e.purl {
|
|
comp["purl"] = serde_json::Value::String(purl.clone());
|
|
if let Some(parsed) = Purl::parse(purl) {
|
|
// CycloneDX's group is the namespace (a Maven group id,
|
|
// an npm scope), not the package manager.
|
|
if let Some(namespace) = &parsed.namespace {
|
|
comp["group"] = serde_json::Value::String(namespace.clone());
|
|
}
|
|
if let Some(properties) = bsi_properties(&parsed) {
|
|
comp["properties"] = properties;
|
|
}
|
|
}
|
|
}
|
|
if let Some(license) = e.license.as_deref().filter(|l| !l.trim().is_empty()) {
|
|
comp["licenses"] = license_choice(license);
|
|
}
|
|
if let Some(url) = &e.manufacturer_url {
|
|
comp["manufacturer"] = serde_json::json!({ "url": [url] });
|
|
}
|
|
if !e.hashes.is_empty() {
|
|
let hashes = cdx_hashes(&e.hashes);
|
|
// The file and where it is downloaded from: the TR's hash of
|
|
// the deployable component and its URI (#508).
|
|
if let Some(url) = &e.download_url {
|
|
comp["externalReferences"] = serde_json::json!([{
|
|
"type": "distribution",
|
|
"url": url,
|
|
"hashes": hashes,
|
|
}]);
|
|
}
|
|
comp["hashes"] = hashes;
|
|
}
|
|
comp
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Who creates Prüfwerk's SBOM documents, as BSI TR-03183-2 asks for the
|
|
/// "creator of the SBOM": its name and email address (`metadata.manufacturer`).
|
|
const CREATOR_NAME: &str = "BreakPilot GmbH";
|
|
const CREATOR_EMAIL: &str = "kontakt@breakpilot.com";
|
|
|
|
/// The product's version: when its SBOM data was last compiled, as an
|
|
/// RFC 3339 date-time. A target has no version of its own, and BSI
|
|
/// TR-03183-2 names the modification date for a component without one.
|
|
fn product_version(entries: &[SbomEntry]) -> Option<String> {
|
|
entries
|
|
.iter()
|
|
.map(|e| e.updated_at)
|
|
.max()
|
|
.map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
|
|
}
|
|
|
|
/// The frame of a CycloneDX 1.6 document about `subject`, whose components
|
|
/// are `entries`: a fresh serial number, the creator and the product as
|
|
/// `metadata.component`.
|
|
pub fn cdx_frame(subject: &str, entries: &[SbomEntry]) -> serde_json::Value {
|
|
let mut doc = serde_json::json!({
|
|
"bomFormat": "CycloneDX",
|
|
"specVersion": "1.6",
|
|
"serialNumber": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
|
|
"version": 1,
|
|
"metadata": {
|
|
"timestamp": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
|
"tools": { "components": [{ "type": "application", "name": "Prüfwerk" }] },
|
|
"manufacturer": {
|
|
"name": CREATOR_NAME,
|
|
"contact": [{ "email": CREATOR_EMAIL }],
|
|
},
|
|
"component": {
|
|
"type": "application",
|
|
"bom-ref": product_ref(subject),
|
|
"purl": product_ref(subject),
|
|
"name": subject,
|
|
}
|
|
},
|
|
});
|
|
if let Some(version) = product_version(entries) {
|
|
doc["metadata"]["component"]["version"] = serde_json::Value::String(version);
|
|
}
|
|
doc
|
|
}
|
|
|
|
/// The dependency graph of a document whose product contains `components`,
|
|
/// and its completeness. The SBOM is flat: the product depends on every
|
|
/// component, directly or through another one, and which of them depend on
|
|
/// which is not known. So every component gets an empty entry, as CycloneDX
|
|
/// asks for one without dependencies, and the graph is stated `incomplete`.
|
|
fn cdx_dependencies(doc: &mut serde_json::Value, components: &[serde_json::Value]) {
|
|
let product = doc["metadata"]["component"]["bom-ref"].clone();
|
|
let refs: Vec<serde_json::Value> = components.iter().map(|c| c["bom-ref"].clone()).collect();
|
|
let mut dependencies = Vec::with_capacity(refs.len() + 1);
|
|
dependencies.push(serde_json::json!({ "ref": product, "dependsOn": refs }));
|
|
dependencies.extend(refs.iter().map(|r| serde_json::json!({ "ref": r })));
|
|
doc["dependencies"] = serde_json::Value::Array(dependencies);
|
|
doc["compositions"] = serde_json::json!([{
|
|
"aggregate": "incomplete",
|
|
"dependencies": [product],
|
|
}]);
|
|
}
|
|
|
|
/// The identification of a CycloneDX vulnerability known as `primary` and
|
|
/// `others`: `id` and `source` of the primary id (NVD for a CVE, else
|
|
/// `source`, the scanner that found it), the other ids as `references` to
|
|
/// their databases.
|
|
pub fn cdx_vulnerability(primary: &str, others: &[&str], source: &str) -> serde_json::Value {
|
|
let mut v = if is_cve(primary) {
|
|
let (name, url) = advisory_source(primary);
|
|
serde_json::json!({ "id": primary, "source": { "name": name, "url": url } })
|
|
} else {
|
|
serde_json::json!({ "id": primary, "source": { "name": source } })
|
|
};
|
|
if !others.is_empty() {
|
|
v["references"] = others
|
|
.iter()
|
|
.map(|id| {
|
|
let (name, url) = advisory_source(id);
|
|
serde_json::json!({ "id": id, "source": { "name": name, "url": url } })
|
|
})
|
|
.collect();
|
|
}
|
|
v
|
|
}
|
|
|
|
/// One vulnerability of a CycloneDX SBOM: its primary id, its other ids,
|
|
/// the source and severity it was first found with, and the components it
|
|
/// affects.
|
|
struct SbomVulnerability<'a> {
|
|
id: &'a str,
|
|
others: Vec<&'a str>,
|
|
source: &'a str,
|
|
severity: Option<&'a str>,
|
|
affects: Vec<String>,
|
|
}
|
|
|
|
/// A CycloneDX 1.6 document for `entries`, named after `subject`. The known
|
|
/// vulnerabilities of the components are listed at the top level, each
|
|
/// naming the components it affects by `bom-ref` (CycloneDX keeps them out of
|
|
/// the components). A vulnerability is listed under its CVE when one is
|
|
/// known, with its GitHub advisory as a reference.
|
|
pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|
let mut doc = cdx_frame(subject, entries);
|
|
let components = cdx_components(entries);
|
|
cdx_dependencies(&mut doc, &components);
|
|
doc["components"] = serde_json::Value::Array(components);
|
|
// One vulnerability per CVE (or advisory without one), affecting every
|
|
// component it was found in, by whichever scanner and id.
|
|
let mut vulns: Vec<SbomVulnerability<'_>> = Vec::new();
|
|
for e in entries {
|
|
for v in &e.known_vulnerabilities {
|
|
let id = v.cve();
|
|
let i = match vulns.iter().position(|known| known.id == id) {
|
|
Some(i) => i,
|
|
None => {
|
|
vulns.push(SbomVulnerability {
|
|
id,
|
|
others: Vec::new(),
|
|
source: &v.source,
|
|
severity: None,
|
|
affects: Vec::new(),
|
|
});
|
|
vulns.len() - 1
|
|
}
|
|
};
|
|
let known = &mut vulns[i];
|
|
for other in std::iter::once(&v.id).chain(&v.aliases) {
|
|
if other != id && !known.others.contains(&other.as_str()) {
|
|
known.others.push(other);
|
|
}
|
|
}
|
|
known.severity = known.severity.or(v.severity.as_deref());
|
|
let reference = component_ref(e);
|
|
if !known.affects.contains(&reference) {
|
|
known.affects.push(reference);
|
|
}
|
|
}
|
|
}
|
|
if !vulns.is_empty() {
|
|
doc["vulnerabilities"] = vulns
|
|
.into_iter()
|
|
.map(|known| {
|
|
let mut v = cdx_vulnerability(known.id, &known.others, known.source);
|
|
v["affects"] = known
|
|
.affects
|
|
.into_iter()
|
|
.map(|r| serde_json::json!({ "ref": r }))
|
|
.collect();
|
|
if let Some(severity) = known.severity {
|
|
v["ratings"] = serde_json::json!([{ "severity": cdx_severity(severity) }]);
|
|
}
|
|
v
|
|
})
|
|
.collect();
|
|
}
|
|
doc
|
|
}
|
|
|
|
/// An SPDX 2.3 document for `entries`, named after `subject`.
|
|
pub fn spdx(entries: &[SbomEntry], subject: &str) -> serde_json::Value {
|
|
let packages: Vec<serde_json::Value> = entries
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(i, e)| {
|
|
// The license is what the supplier declares; nothing is
|
|
// concluded without a license review of our own. SPDX takes only
|
|
// an expression of listed ids; another license is NOASSERTION,
|
|
// its text kept as a comment.
|
|
let raw = e
|
|
.license
|
|
.as_deref()
|
|
.map(str::trim)
|
|
.filter(|l| !l.is_empty());
|
|
let license = raw
|
|
.map(spdx_license::normalise)
|
|
.filter(|l| spdx_license::is_spdx_expression(l));
|
|
let mut package = serde_json::json!({
|
|
"SPDXID": format!("SPDXRef-Package-{i}"),
|
|
"name": e.name,
|
|
"versionInfo": e.version,
|
|
"downloadLocation": "NOASSERTION",
|
|
"licenseConcluded": "NOASSERTION",
|
|
"licenseDeclared": license.as_deref().unwrap_or("NOASSERTION"),
|
|
"externalRefs": e.purl.as_ref().map(|p| vec![serde_json::json!({
|
|
"referenceCategory": "PACKAGE-MANAGER",
|
|
"referenceType": "purl",
|
|
"referenceLocator": p,
|
|
})]).unwrap_or_default(),
|
|
});
|
|
if let (Some(raw), None) = (raw, &license) {
|
|
package["licenseComments"] = serde_json::Value::String(format!("Declared: {raw}"));
|
|
}
|
|
package
|
|
})
|
|
.collect();
|
|
|
|
serde_json::json!({
|
|
"spdxVersion": "SPDX-2.3",
|
|
"dataLicense": "CC0-1.0",
|
|
"SPDXID": "SPDXRef-DOCUMENT",
|
|
"name": format!("sbom-{subject}"),
|
|
"documentNamespace": format!("https://compliance-scanner/sbom/{subject}"),
|
|
"packages": packages,
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn both_formats_list_every_component() {
|
|
let mut e = SbomEntry::new("t".into(), "lwIP".into(), "2.1.2".into(), "embedded".into());
|
|
e.license = Some("BSD-3-Clause".into());
|
|
let cdx = cyclonedx(std::slice::from_ref(&e), "t");
|
|
assert_eq!(cdx["bomFormat"], "CycloneDX");
|
|
assert_eq!(
|
|
cdx["components"][0]["licenses"][0]["license"]["id"],
|
|
"BSD-3-Clause"
|
|
);
|
|
let spdx = spdx(&[e], "t");
|
|
assert_eq!(spdx["spdxVersion"], "SPDX-2.3");
|
|
assert_eq!(spdx["packages"][0]["versionInfo"], "2.1.2");
|
|
}
|
|
|
|
#[test]
|
|
fn known_license_names_are_exported_as_spdx_ids() {
|
|
let entries: Vec<SbomEntry> = [
|
|
"The Apache Software License, Version 2.0",
|
|
"https://opensource.org/licenses/MIT",
|
|
"Custom Pump License",
|
|
"MIT OR Apache-2.0",
|
|
]
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(i, license)| {
|
|
let mut e = SbomEntry::new("t".into(), format!("c{i}"), "1".into(), "maven".into());
|
|
e.license = Some(license.into());
|
|
e
|
|
})
|
|
.collect();
|
|
|
|
let cdx = cyclonedx(&entries, "t");
|
|
let licenses = |i: usize| &cdx["components"][i]["licenses"][0];
|
|
assert_eq!(licenses(0)["license"]["id"], "Apache-2.0");
|
|
assert!(licenses(0)["license"].get("name").is_none());
|
|
assert_eq!(licenses(1)["license"]["id"], "MIT");
|
|
assert_eq!(licenses(2)["license"]["name"], "Custom Pump License");
|
|
assert!(licenses(2)["license"].get("id").is_none());
|
|
assert_eq!(licenses(3)["expression"], "MIT OR Apache-2.0");
|
|
|
|
let spdx = spdx(&entries, "t");
|
|
let package = |i: usize| &spdx["packages"][i];
|
|
for i in 0..4 {
|
|
assert_eq!(package(i)["licenseConcluded"], "NOASSERTION");
|
|
}
|
|
assert_eq!(package(0)["licenseDeclared"], "Apache-2.0");
|
|
assert_eq!(package(1)["licenseDeclared"], "MIT");
|
|
assert_eq!(package(2)["licenseDeclared"], "NOASSERTION");
|
|
assert_eq!(
|
|
package(2)["licenseComments"],
|
|
"Declared: Custom Pump License"
|
|
);
|
|
assert_eq!(package(3)["licenseDeclared"], "MIT OR Apache-2.0");
|
|
assert!(package(3).get("licenseComments").is_none());
|
|
}
|
|
}
|