diff --git a/Dockerfile.agent b/Dockerfile.agent index 04e7971..377b8cf 100644 --- a/Dockerfile.agent +++ b/Dockerfile.agent @@ -7,6 +7,10 @@ ARG SYFT_VERSION=1.52.0 ARG SYFT_SHA256=caeedb81fb0491615f1ebd1761e4145d41ee86dd2cc7bf80669f9f5ad9d6133d ARG GITLEAKS_VERSION=8.21.2 ARG GITLEAKS_SHA256=5bc41815076e6ed6ef8fbecc9d9b75bcae31f39029ceb55da08086315316e3ba +# SBOM quality score (Interlynk, Apache-2.0), #496. The checksum is the one +# in the release's checksums.txt. +ARG SBOMQS_VERSION=2.1.2 +ARG SBOMQS_SHA256=451c800019c81059f86eac2c1344c57572b3436e7e0ffeaa076459d195a39ab8 ARG SEMGREP_VERSION=1.177.0 ARG RUFF_VERSION=0.16.8 # mobsfscan pins an older semgrep; it is installed without its dependencies so @@ -48,6 +52,8 @@ ARG SYFT_VERSION ARG SYFT_SHA256 ARG GITLEAKS_VERSION ARG GITLEAKS_SHA256 +ARG SBOMQS_VERSION +ARG SBOMQS_SHA256 ARG SEMGREP_VERSION ARG RUFF_VERSION ARG MOBSFSCAN_VERSION @@ -80,6 +86,12 @@ RUN curl -sSfL -o /tmp/gitleaks.tar.gz \ && tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks \ && rm /tmp/gitleaks.tar.gz +RUN curl -sSfL -o /tmp/sbomqs.tar.gz \ + "https://github.com/interlynk-io/sbomqs/releases/download/v${SBOMQS_VERSION}/sbomqs_${SBOMQS_VERSION}_Linux_x86_64.tar.gz" \ + && echo "${SBOMQS_SHA256} /tmp/sbomqs.tar.gz" | sha256sum -c - \ + && tar -xzf /tmp/sbomqs.tar.gz -C /usr/local/bin sbomqs \ + && rm /tmp/sbomqs.tar.gz + RUN pip3 install --break-system-packages --no-cache-dir \ "semgrep==${SEMGREP_VERSION}" "ruff==${RUFF_VERSION}" @@ -94,10 +106,10 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \ COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py RUN mkdir -p /opt/pruefwerk \ - && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s"}\n' \ + && printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s"}\n' \ "${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \ "${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \ - "${MOBSFSCAN_VERSION}" \ + "${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" \ > /opt/pruefwerk/tool-versions.json # The agent runs unprivileged. It writes only to its home (tool caches), the diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index 4c8ff18..4dcb922 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -197,6 +197,41 @@ pub async fn export_sbom( )) } +/// The target whose SBOM quality is asked for. +#[derive(serde::Deserialize)] +pub struct SbomQualityParams { + pub repo_id: String, +} + +/// GET /api/v1/sbom/quality?repo_id= — the target's SBOM quality score +/// (sbomqs against BSI TR-03183-2 and NTIA, #496) from its newest scan that +/// scored one, with that scan's id and end; `data: null` when none did. +#[tracing::instrument(skip_all, fields(repo_id = %params.repo_id))] +pub async fn sbom_quality( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(params): Query, +) -> Result, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + let run = db + .scan_runs() + .find_one(doc! { "repo_id": ¶ms.repo_id, "sbom_quality": { "$exists": true } }) + .sort(doc! { "started_at": -1 }) + .await + .map_err(|e| { + tracing::warn!("SBOM quality: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Json(match run { + Some(run) => serde_json::json!({ + "data": run.sbom_quality, + "scan_run_id": run.id.map(|id| id.to_hex()), + "completed_at": run.completed_at, + }), + None => serde_json::json!({ "data": null }), + })) +} + #[tracing::instrument(skip_all)] pub async fn license_summary( Extension(agent): AgentExt, diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index 6d1c886..8782c62 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -136,6 +136,7 @@ pub fn build_router() -> Router { .route("/api/v1/sbom/filters", get(handlers::sbom_filters)) .route("/api/v1/sbom/export", get(handlers::export_sbom)) .route("/api/v1/sbom/licenses", get(handlers::license_summary)) + .route("/api/v1/sbom/quality", get(handlers::sbom_quality)) .route("/api/v1/sbom/diff", get(handlers::sbom_diff)) .route("/api/v1/issues", get(handlers::list_issues)) .route("/api/v1/scan-runs", get(handlers::list_scan_runs)) diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index d176f58..ac1d33b 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -106,8 +106,15 @@ pub struct ControlStatus { #[serde(skip_serializing_if = "Option::is_none")] pub evidence_type: Option, pub findings: Vec, + /// The SBOM's quality score (sbomqs, #496), on the SBOM requirement + /// only: supporting evidence, it does not change `state`. + #[serde(skip_serializing_if = "Option::is_none")] + pub sbom_quality: Option, } +/// The CRA requirement the SBOM quality score supports. +pub const SBOM_CONTROL: &str = "cra-ai-23"; + /// Whether a finding still counts against its controls: a false positive, a /// wrong CRA mapping and a resolved finding do not; an accepted risk still /// does. @@ -222,6 +229,7 @@ pub fn control_statuses( severity: None, evidence_type: None, findings: against, + sbom_quality: None, } }) .collect() diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index c921de9..901f191 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -85,7 +85,7 @@ pub fn build_pack( sbom: &inputs.sbom, now: at, }; - let files: Vec<(&str, Vec)> = vec![ + let mut files: Vec<(&str, Vec)> = vec![ ( "oscal-assessment-results.json", json(&assess(&inputs.findings, at))?, @@ -105,6 +105,11 @@ pub fn build_pack( ("vex.cdx.json", json(&vex_docs::cyclonedx_vex(&vex))?), ("cra-compliance.json", json(&compliance_of(inputs))?), ]; + // The SBOM's quality score of the last scan (sbomqs, #496), when it was + // scored. + if let Some(quality) = sbom_quality(inputs) { + files.push(("sbom-quality.json", json(quality)?)); + } let listed: Vec = files .iter() .map(|(name, bytes)| ManifestFile { @@ -212,6 +217,14 @@ pub fn sbom_coverage(inputs: &EvidenceInputs) -> compliance::SbomCoverage { } } +/// The SBOM quality score of the target's last scan, if it was scored. +pub fn sbom_quality(inputs: &EvidenceInputs) -> Option<&compliance_core::models::SbomQuality> { + inputs + .last_run + .as_ref() + .and_then(|run| run.sbom_quality.as_ref()) +} + /// The target's state against every CRA Annex I control. pub fn compliance_of(inputs: &EvidenceInputs) -> Vec { control_map::ControlMap::cra() @@ -223,8 +236,12 @@ pub fn compliance_of(inputs: &EvidenceInputs) -> Vec &failed_tools(inputs), &sbom_coverage(inputs), ); - // The catalog's own ratings, next to our state. + // The catalog's own ratings, next to our state; the SBOM's + // quality score next to the SBOM requirement. for status in &mut statuses { + if status.control == compliance::SBOM_CONTROL { + status.sbom_quality = sbom_quality(inputs).cloned(); + } if let Some(control) = inputs.catalog.get(&status.control) { status.severity = control.severity.as_ref().map(ToString::to_string); status.evidence_type = control.evidence_type.clone(); @@ -374,6 +391,50 @@ mod tests { ); } + #[test] + fn the_sbom_quality_score_is_supporting_evidence_for_the_sbom_requirement() { + let mut inputs = inputs(); + let without = compliance_of(&inputs); + let mut run = ScanRun::new("t1".into(), compliance_core::models::ScanTrigger::Manual); + run.sbom_quality = Some(compliance_core::models::SbomQuality { + tool: "sbomqs".into(), + tool_version: "v2.1.2".into(), + spec: "cyclonedx 1.5".into(), + components: 1, + profiles: vec![compliance_core::models::SbomQualityProfile { + id: "bsi-v2.1".into(), + name: "BSI TR-03183-2 v2.1".into(), + score: 0.9, + grade: "F".into(), + failed: vec![], + }], + }); + inputs.last_run = Some(run); + let with = compliance_of(&inputs); + let sbom = with + .iter() + .find(|c| c.control == compliance::SBOM_CONTROL) + .expect("cra-ai-23 in the map"); + assert_eq!( + sbom.sbom_quality + .as_ref() + .map(|q| q.profiles[0].grade.as_str()), + Some("F") + ); + // It changes no state and sits on no other requirement. + for (a, b) in without.iter().zip(&with) { + assert_eq!(a.state, b.state, "{}", a.control); + if b.control != compliance::SBOM_CONTROL { + assert!(b.sbom_quality.is_none()); + } + } + let (_, listed) = build_pack(&inputs, Utc::now()).expect("pack"); + assert!(listed.iter().any(|f| f.name == "sbom-quality.json")); + // Without a score, no file. + let (_, listed) = build_pack(&super::tests::inputs(), Utc::now()).expect("pack"); + assert!(listed.iter().all(|f| f.name != "sbom-quality.json")); + } + #[test] fn csv_cells_are_quoted_and_formulas_defused() { let csv = findings_csv(&inputs().findings); diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 66d8a09..e2860bf 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -33,6 +33,7 @@ mod pr_review; mod public_http; pub mod repo_view; pub mod sbom; +pub mod sbom_quality; pub mod semgrep; pub mod source_text; pub mod tool_cmd; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 3e6d077..e79639f 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -890,16 +890,25 @@ impl PipelineOrchestrator { .await; match &result { Ok(count) => { + let mut completed = doc! { + "status": "completed", + "current_phase": "completed", + "new_findings_count": *count as i64, + "completed_at": mongodb::bson::DateTime::now(), + }; + // The SBOM as it now stands, scored against BSI TR-03183-2 + // and NTIA (#496): evidence for cra-ai-23, not findings. + if let Some(quality) = self.score_sbom(target_id, &target.name, &scan_run_id).await + { + if let Ok(quality) = mongodb::bson::to_bson(&quality) { + completed.insert("sbom_quality", quality); + } + } self.db .scan_runs() .update_one( doc! { "_id": &insert.inserted_id }, - doc! { "$set": { - "status": "completed", - "current_phase": "completed", - "new_findings_count": *count as i64, - "completed_at": mongodb::bson::DateTime::now(), - } }, + doc! { "$set": completed }, ) .await?; // Refresh the target's cached findings count. The shared pipeline diff --git a/compliance-agent/src/pipeline/sbom_quality.rs b/compliance-agent/src/pipeline/sbom_quality.rs new file mode 100644 index 0000000..59c2e1e --- /dev/null +++ b/compliance-agent/src/pipeline/sbom_quality.rs @@ -0,0 +1,286 @@ +//! The quality of a target's SBOM, scored by sbomqs (#496). +//! +//! The CycloneDX document Prüfwerk exports for a target (the same bytes as +//! the evidence pack's `sbom.cdx.json`) is scored against BSI TR-03183-2 v2.1 +//! and the NTIA minimum elements (2021). The score and the checks the SBOM +//! does not meet are stored on the scan run, shown on the SBOM page and put +//! into the CRA evidence as supporting evidence for the SBOM requirement +//! (cra-ai-23). It raises no findings. +//! +//! sbomqs (Interlynk, Apache-2.0) is a Go binary pinned in the agent image. +//! It runs offline: the component analysis that would call Interlynk's API is +//! opt-in and never turned on here, and the tool gets no API key. + +use std::time::Duration; + +use compliance_core::models::{SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile}; + +use crate::pipeline::tool_cmd; + +/// The profiles asked for, by their explicit names. In sbomqs 2.1.2 the short +/// names float: `bsi` is the newest BSI version and `ntia` the CISA 2026 +/// minimum elements, so they are not used. +pub(crate) const PROFILES: [&str; 2] = ["bsi-v2.1", "ntia-2021"]; + +/// Longest sbomqs may take for one document. +const TIMEOUT: Duration = Duration::from_secs(120); + +/// The skipped-stage id when the SBOM could not be scored. +pub const SBOM_QUALITY_STAGE: &str = "sbom_quality"; + +/// Why an SBOM was not scored. +#[derive(Debug)] +pub(crate) enum ScoreError { + /// sbomqs is not installed (a development machine). + NotInstalled, + /// It ran but did not give a score; the details are for the log. + Failed(String), +} + +impl std::fmt::Display for ScoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotInstalled => write!(f, "sbomqs is not installed"), + Self::Failed(e) => write!(f, "sbomqs failed: {e}"), + } + } +} + +/// Score the CycloneDX document of `entries` (named after `subject`). +/// +/// # Errors +/// +/// [`ScoreError::NotInstalled`] without sbomqs, [`ScoreError::Failed`] when it +/// fails, times out or its output cannot be read. +pub(crate) async fn score(entries: &[SbomEntry], subject: &str) -> Result { + let doc = compliance_core::sbom_docs::cyclonedx(entries, subject); + let bytes = serde_json::to_vec_pretty(&doc).map_err(|e| ScoreError::Failed(e.to_string()))?; + let dir = std::env::temp_dir().join(format!("sbomqs-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).map_err(|e| ScoreError::Failed(e.to_string()))?; + let path = dir.join("sbom.cdx.json"); + let result = async { + std::fs::write(&path, &bytes).map_err(|e| ScoreError::Failed(e.to_string()))?; + let mut cmd = tool_cmd::tool("sbomqs", &[]); + cmd.arg("score") + .arg("--json") + .arg("--profile") + .arg(PROFILES.join(",")) + .arg(&path); + let output = tool_cmd::run_bounded_for(&mut cmd, "sbomqs", TIMEOUT) + .await + .map_err(|e| match e.kind() { + std::io::ErrorKind::NotFound => ScoreError::NotInstalled, + _ => ScoreError::Failed(e.to_string()), + })?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(ScoreError::Failed(format!( + "exit {}: {}", + output.status, + stderr.chars().take(300).collect::() + ))); + } + parse(&output.stdout).map_err(ScoreError::Failed) + } + .await; + let _ = std::fs::remove_dir_all(&dir); + result +} + +/// The score in sbomqs's `score --json` output for one document. +fn parse(stdout: &[u8]) -> Result { + let out: serde_json::Value = + serde_json::from_slice(stdout).map_err(|e| format!("output is not JSON: {e}"))?; + let file = out["files"] + .as_array() + .and_then(|f| f.first()) + .ok_or("no scored document in the output")?; + let text = |v: &serde_json::Value| v.as_str().unwrap_or_default().to_string(); + let profiles: Vec = file["profiles"] + .as_array() + .ok_or("no profiles in the output")? + .iter() + .enumerate() + .map(|(i, p)| SbomQualityProfile { + id: profile_id(&text(&p["profile"]), i), + name: text(&p["profile"]), + score: p["score"].as_f64().unwrap_or_default(), + grade: text(&p["grade"]), + failed: p["features"] + .as_array() + .into_iter() + .flatten() + .filter(|f| !f["ignored"].as_bool().unwrap_or(false)) + .filter(|f| f["score"].as_f64().unwrap_or_default() < 10.0) + .map(|f| SbomQualityCheck { + key: text(&f["key"]), + description: text(&f["description"]), + score: f["score"].as_f64().unwrap_or_default(), + required: f["required"].as_bool().unwrap_or(false), + }) + .collect(), + }) + .collect(); + if profiles.is_empty() { + return Err("no profile was scored".into()); + } + Ok(SbomQuality { + tool: "sbomqs".into(), + tool_version: text(&out["creation_info"]["version"]), + spec: format!("{} {}", text(&file["spec"]), text(&file["spec_version"])) + .trim() + .to_string(), + components: file["num_components"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .unwrap_or_default(), + profiles, + }) +} + +/// Which of [`PROFILES`] the profile named `name` (at `index`) is. +fn profile_id(name: &str, index: usize) -> String { + let name = name.to_ascii_lowercase(); + if name.starts_with("bsi") { + PROFILES[0].to_string() + } else if name.starts_with("ntia") { + PROFILES[1].to_string() + } else { + PROFILES + .get(index) + .copied() + .unwrap_or("unknown") + .to_string() + } +} + +impl crate::pipeline::orchestrator::PipelineOrchestrator { + /// Score the SBOM of target `target_id` (named `subject`) as it stands at + /// the end of a scan run. `None` when it has no components or could not + /// be scored; the latter is recorded as a skipped stage of the run. + pub(crate) async fn score_sbom( + &self, + target_id: &str, + subject: &str, + scan_run_id: &str, + ) -> Option { + use compliance_core::models::{SkipCode, SkippedStage}; + use futures_util::TryStreamExt; + use mongodb::bson::doc; + + let filter = doc! { "repo_id": target_id }; + let count = self + .db + .sbom_entries() + .count_documents(filter.clone()) + .await + .ok()?; + if count == 0 || count > crate::api::handlers::sbom::MAX_EXPORT_COMPONENTS { + return None; + } + let entries: Vec = match self.db.sbom_entries().find(filter).await { + Ok(cursor) => cursor.try_collect().await.ok()?, + Err(e) => { + tracing::warn!(target_id, "SBOM not scored: {e}"); + return None; + } + }; + match score(&entries, subject).await { + Ok(quality) => { + tracing::info!( + target_id, + scores = ?quality.profiles.iter().map(|p| (p.id.as_str(), p.score)).collect::>(), + "SBOM quality (sbomqs)" + ); + Some(quality) + } + Err(e) => { + tracing::warn!(target_id, "SBOM not scored: {e}"); + let reason = match e { + ScoreError::NotInstalled => "sbomqs is not installed", + ScoreError::Failed(_) => "sbomqs did not complete", + }; + self.skip_stage( + scan_run_id, + SkippedStage::new(SBOM_QUALITY_STAGE, SkipCode::ToolFailed, reason) + .about("sbomqs"), + ) + .await; + None + } + } + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + const OUTPUT: &str = include_str!("../../tests/fixtures/sbomqs/score.json"); + + #[test] + fn the_output_gives_both_profiles_and_their_failed_checks() { + let q = parse(OUTPUT.as_bytes()).unwrap(); + assert_eq!(q.tool, "sbomqs"); + assert_eq!(q.tool_version, "v2.1.2"); + assert_eq!(q.spec, "cyclonedx 1.5"); + assert_eq!(q.components, 3); + let ids: Vec<&str> = q.profiles.iter().map(|p| p.id.as_str()).collect(); + assert_eq!(ids, ["bsi-v2.1", "ntia-2021"]); + let bsi = &q.profiles[0]; + assert_eq!(bsi.name, "BSI TR-03183-2 v2.1"); + assert_eq!(bsi.grade, "F"); + assert!((bsi.score - 0.926).abs() < 0.001); + // A met check is not listed, an ignored one neither. + assert!(bsi.failed.iter().all(|c| c.key != "comp_name")); + assert!(bsi.failed.iter().all(|c| c.key != "comp_source_hash")); + let version = bsi + .failed + .iter() + .find(|c| c.key == "sbom_spec_version") + .unwrap(); + assert!(version.required); + assert_eq!( + version.description, + "CycloneDX 1.5 does not meet minimum version 1.6" + ); + assert!(bsi + .failed + .iter() + .any(|c| c.key == "sbom_uri" && !c.required)); + let ntia = &q.profiles[1]; + assert_eq!(ntia.name, "NTIA Minimum Elements (2021)"); + // Partly met checks are listed with their score. + let version = ntia + .failed + .iter() + .find(|c| c.key == "comp_version") + .unwrap(); + assert!((version.score - 6.667).abs() < 0.001); + } + + #[test] + fn output_that_is_not_a_score_is_an_error() { + assert!(parse(b"not json").is_err()); + assert!(parse(br#"{"files": []}"#).is_err()); + assert!(parse(br#"{"files": [{"profiles": []}]}"#).is_err()); + } + + #[tokio::test] + async fn without_sbomqs_the_score_says_so() { + // The test environment has no sbomqs on PATH unless a developer + // installed it; then it must score the document. + let entries = vec![SbomEntry::new( + "t".into(), + "okhttp".into(), + "3.12.0".into(), + "maven".into(), + )]; + match score(&entries, "t").await { + Err(ScoreError::NotInstalled) => {} + Ok(q) => assert_eq!(q.profiles.len(), 2), + Err(e) => panic!("{e}"), + } + } +} diff --git a/compliance-agent/tests/fixtures/sbomqs/score.json b/compliance-agent/tests/fixtures/sbomqs/score.json new file mode 100644 index 0000000..23473dd --- /dev/null +++ b/compliance-agent/tests/fixtures/sbomqs/score.json @@ -0,0 +1,242 @@ +{ + "run_id": "00000000-0000-0000-0000-000000000000", + "timestamp": "2026-10-06T10:16:12Z", + "creation_info": { + "name": "sbomqs", + "version": "v2.1.2", + "sbomqs_engine_version": "8", + "vendor": "Interlynk (support@interlynk.io)" + }, + "files": [ + { + "sbom_quality_score": 1.8915343915343912, + "grade": "F", + "num_components": 3, + "file_name": "sbom.cdx.json", + "spec": "cyclonedx", + "spec_version": "1.5", + "file_format": "json", + "creation_time": "", + "comprehenssive": null, + "profiles": [ + { + "profile": "BSI TR-03183-2 v2.1", + "score": 0.9259259259259258, + "grade": "F", + "message": "BSI TR-03183-2 v2.1.0 Profile", + "features": [ + { + "key": "sbom_spec_version", + "score": 0, + "description": "CycloneDX 1.5 does not meet minimum version 1.6", + "ignored": false, + "required": true + }, + { + "key": "sbom_creator", + "score": 0, + "description": "SBOM creator is missing", + "ignored": false, + "required": true + }, + { + "key": "sbom_timestamp", + "score": 0, + "description": "SBOM creation timestamp is missing", + "ignored": false, + "required": true + }, + { + "key": "comp_creator", + "score": 0, + "description": "creator information missing for all components", + "ignored": false, + "required": true + }, + { + "key": "comp_name", + "score": 10, + "description": "component name declared for all components", + "ignored": false, + "required": true + }, + { + "key": "comp_version", + "score": 0, + "description": "component version missing for 1 out of 3 components", + "ignored": false, + "required": true + }, + { + "key": "comp_filename", + "score": 0, + "description": "no components declare filename", + "ignored": false, + "required": true + }, + { + "key": "comp_depth", + "score": 0, + "description": "Primary component is missing.", + "ignored": false, + "required": true + }, + { + "key": "comp_distribution_license", + "score": 0, + "description": "no components declare distribution licence (concluded)", + "ignored": false, + "required": true + }, + { + "key": "comp_deployable_hash", + "score": 0, + "description": "no components declare deployable component hash", + "ignored": false, + "required": true + }, + { + "key": "comp_executable_prop", + "score": 0, + "description": "no components declare executable property", + "ignored": false, + "required": true + }, + { + "key": "comp_archive_prop", + "score": 0, + "description": "no components declare archive property", + "ignored": false, + "required": true + }, + { + "key": "comp_structured_prop", + "score": 0, + "description": "no components declare structured property", + "ignored": false, + "required": true + }, + { + "key": "sbom_uri", + "score": 0, + "description": "SBOM-URI is missing", + "ignored": false, + "required": false, + "additional": true + }, + { + "key": "comp_source_code_url", + "score": 0, + "description": "no components declare source code URI", + "ignored": false, + "required": false, + "additional": true + }, + { + "key": "comp_download_url", + "score": 0, + "description": "no components declare deployable form URI", + "ignored": false, + "required": false, + "additional": true + }, + { + "key": "comp_other_identifiers", + "score": 3.333333333333333, + "description": "1/3 components declare unique identifiers (CPE/SWID/purl)", + "ignored": false, + "required": false, + "additional": true + }, + { + "key": "comp_original_licenses", + "score": 3.333333333333333, + "description": "1/3 components declare original licence (declared)", + "ignored": false, + "required": false, + "additional": true + }, + { + "key": "comp_effective_license", + "score": 0, + "description": "no components declare effective licence", + "ignored": false, + "required": false + }, + { + "key": "comp_source_hash", + "score": 0, + "description": "no components declare source code hash", + "ignored": true, + "required": false + }, + { + "key": "comp_security_txt_url", + "score": 0, + "description": "no components declare security.txt URL", + "ignored": false, + "required": false + } + ] + }, + { + "profile": "NTIA Minimum Elements (2021)", + "score": 2.8571428571428568, + "grade": "F", + "message": "NTIA Minimum Elements (2021) Profile", + "features": [ + { + "key": "comp_supplier", + "score": 0, + "description": "supplier or manufacturer information missing for all 3 components", + "ignored": false, + "required": true + }, + { + "key": "comp_name", + "score": 10, + "description": "name declared for all components", + "ignored": false, + "required": true + }, + { + "key": "comp_version", + "score": 6.666666666666666, + "description": "version declared for 2 of 3 components", + "ignored": false, + "required": true + }, + { + "key": "comp_uniq_id", + "score": 3.333333333333333, + "description": "unique identifier declared for 1 of 3 components (PURL)", + "ignored": false, + "required": true + }, + { + "key": "sbom_relationships", + "score": 0, + "description": "define primary component", + "ignored": false, + "required": true + }, + { + "key": "sbom_authors", + "score": 0, + "description": "SBOM author information missing", + "ignored": false, + "required": true + }, + { + "key": "sbom_timestamp", + "score": 0, + "description": "SBOM creation timestamp missing", + "ignored": false, + "required": true + } + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 31dcbfe..9eed8ca 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -59,7 +59,7 @@ pub use pentest::{ }; pub use project::{Project, ProjectKind}; pub use repository::ScanTrigger; -pub use sbom::{SbomEntry, VulnRef}; +pub use sbom::{SbomEntry, SbomQuality, SbomQualityCheck, SbomQualityProfile, VulnRef}; pub use scan::{ RunErrorCode, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode, SkippedStage, }; diff --git a/compliance-core/src/models/sbom.rs b/compliance-core/src/models/sbom.rs index a39f683..b869b70 100644 --- a/compliance-core/src/models/sbom.rs +++ b/compliance-core/src/models/sbom.rs @@ -59,3 +59,48 @@ impl SbomEntry { } } } + +/// How well a scan's SBOM meets the SBOM standards (#496), as sbomqs scores +/// the CycloneDX document Prüfwerk exports for the target. Supporting evidence +/// for the CRA SBOM requirement (cra-ai-23), not a source of findings. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct SbomQuality { + /// The scoring tool (`sbomqs`). + pub tool: String, + /// Its version (`v2.1.2`). + pub tool_version: String, + /// The format scored (`cyclonedx 1.5`). + pub spec: String, + /// Components the document lists, as the tool counted them. + pub components: u32, + /// One score per profile, in the order they were asked for. + pub profiles: Vec, +} + +/// One profile's score. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct SbomQualityProfile { + /// The profile as Prüfwerk asks for it (`bsi-v2.1`, `ntia-2021`). + pub id: String, + /// Its name as the tool reports it (`BSI TR-03183-2 v2.1`). + pub name: String, + /// 0 to 10. + pub score: f64, + /// The tool's grade (`A` to `F`). + pub grade: String, + /// The profile's checks the SBOM does not fully meet. + pub failed: Vec, +} + +/// One check of a profile that the SBOM does not fully meet. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct SbomQualityCheck { + /// The tool's key (`comp_supplier`). + pub key: String, + /// What the tool found (`supplier missing for all 3 components`). + pub description: String, + /// 0 to 10. + pub score: f64, + /// Whether the profile requires it (otherwise it is additional). + pub required: bool, +} diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 2367b93..c61d350 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -165,6 +165,10 @@ pub struct ScanRun { /// in runs from before it was recorded. #[serde(default)] pub planned_phases: Vec, + /// How well the target's SBOM meets the BSI TR-03183-2 and NTIA profiles + /// at the end of this run (sbomqs, #496); `None` when it was not scored. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sbom_quality: Option, } /// Why a stage was skipped, stable for the dashboard to word in the reader's @@ -305,6 +309,7 @@ impl ScanRun { skipped_stages: Vec::new(), languages: Vec::new(), planned_phases: Vec::new(), + sbom_quality: None, } } } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 5eaaff2..4e83b29 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -2771,6 +2771,58 @@ tbody tr:last-child td { color: inherit; } +.sbom-quality { + margin-bottom: 16px; +} + +.sbom-quality-head { + margin: 0 0 4px; + font-size: 15px; +} + +.sbom-quality-hint, +.sbom-quality-meta { + margin: 0 0 8px; + font-size: 12px; + color: var(--text-secondary); +} + +.sbom-quality-profile summary { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 0; + cursor: pointer; +} + +.sbom-quality-name { + font-weight: 500; +} + +.sbom-quality-score { + font-variant-numeric: tabular-nums; + color: var(--text-secondary); +} + +.sbom-quality-sub { + margin: 4px 0; + font-size: 12px; + color: var(--text-tertiary); +} + +.sbom-quality-checks { + margin: 0 0 8px; + padding-left: 18px; + font-size: 13px; +} + +.sbom-quality-req { + margin: 0 6px; + font-size: 11px; + color: var(--text-tertiary); + text-transform: uppercase; +} + .sbom-vuln-link { font-size: 12px; color: var(--accent); diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index eced9db..e1f22fc 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1976,6 +1976,34 @@ pub mod sbom { de: "EPSS-Daten: FIRST.org, Exploit Prediction Scoring System", en: "EPSS data: FIRST.org, Exploit Prediction Scoring System", }; + pub const QUALITY_TITLE: Text = Text { + de: "SBOM-Qualität", + en: "SBOM quality", + }; + pub const QUALITY_HINT: Text = Text { + de: "Bewertung der exportierten CycloneDX-SBOM durch sbomqs. Ergänzender Nachweis zur CRA-Anforderung cra-ai-23 (SBOM), kein Befund.", + en: "How sbomqs rates the exported CycloneDX SBOM. Supporting evidence for the CRA requirement cra-ai-23 (SBOM), not a finding.", + }; + pub const QUALITY_NONE: Text = Text { + de: "Noch nicht bewertet: Die nächste Prüfung bewertet die SBOM.", + en: "Not scored yet: the next scan scores the SBOM.", + }; + pub const QUALITY_FAILED_CHECKS: Text = Text { + de: "Nicht erfüllte Prüfpunkte", + en: "Checks not met", + }; + pub const QUALITY_REQUIRED: Text = Text { + de: "Pflicht", + en: "required", + }; + pub const QUALITY_ADDITIONAL: Text = Text { + de: "zusätzlich", + en: "additional", + }; + pub const QUALITY_SCORED_AT: Text = Text { + de: "Bewertet", + en: "Scored", + }; pub const LOAD_FAILED: Text = Text { de: "Die SBOM konnte nicht geladen werden.", en: "Failed to load SBOM.", @@ -2303,6 +2331,10 @@ pub mod compliance { de: "Eigenschaft des Designs oder Prozesses; wird im BreakPilot-Compliance-Prozess nachgewiesen.", en: "A design or process property; evidenced in the BreakPilot compliance process.", }; + pub const SBOM_QUALITY: Text = Text { + de: "Ergänzender Nachweis, SBOM-Qualität (sbomqs)", + en: "Supporting evidence, SBOM quality (sbomqs)", + }; pub const NOT_ASSESSED_HINT: Text = Text { de: "Noch keine abgeschlossene Prüfung. Nach der ersten Prüfung steht hier das Ergebnis.", en: "No scan has completed yet. The result appears after the first scan.", diff --git a/compliance-dashboard/src/infrastructure/sbom.rs b/compliance-dashboard/src/infrastructure/sbom.rs index e2918a3..1084414 100644 --- a/compliance-dashboard/src/infrastructure/sbom.rs +++ b/compliance-dashboard/src/infrastructure/sbom.rs @@ -203,6 +203,28 @@ pub async fn fetch_sbom_export(repo_id: String, format: String) -> Result, + /// RFC 3339. + #[serde(default)] + pub completed_at: Option, +} + +/// The SBOM quality score of target `repo_id` (`GET /api/v1/sbom/quality`). +#[server] +pub async fn fetch_sbom_quality(repo_id: String) -> Result { + let resp = super::agent_client::agent_get("/api/v1/sbom/quality") + .await? + .query(&[("repo_id", repo_id)]) + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::json_or_error(resp).await +} + #[server] pub async fn fetch_license_summary( repo_id: Option, diff --git a/compliance-dashboard/src/pages/compliance.rs b/compliance-dashboard/src/pages/compliance.rs index 1aeaa31..9e57828 100644 --- a/compliance-dashboard/src/pages/compliance.rs +++ b/compliance-dashboard/src/pages/compliance.rs @@ -180,6 +180,7 @@ fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Elem .as_str() .and_then(tx::evidence_type) .map(|t| t.get(lang)); + let quality = sbom_quality_line(&control["sbom_quality"]); rsx! { li { class: "cra-control", div { class: "cra-control-head", @@ -198,6 +199,11 @@ fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Elem if let Some(note) = note { p { class: "cra-control-reason", "{note}" } } + if !quality.is_empty() { + p { class: "cra-control-reason cra-control-quality", + "{tx::SBOM_QUALITY.get(lang)}: {quality}" + } + } if !findings.is_empty() { ul { class: "cra-control-findings", for f in findings { @@ -225,10 +231,43 @@ fn ControlRow(control: serde_json::Value, lang: Lang, show_reason: bool) -> Elem } } +/// The SBOM quality score on the SBOM requirement, one profile after the +/// other (`BSI TR-03183-2 v2.1 0.9/10 (F) · NTIA Minimum Elements (2021) +/// 2.9/10 (F)`); empty without one. +fn sbom_quality_line(quality: &serde_json::Value) -> String { + quality["profiles"] + .as_array() + .into_iter() + .flatten() + .map(|p| { + format!( + "{} {:.1}/10 ({})", + p["name"].as_str().unwrap_or_default(), + p["score"].as_f64().unwrap_or_default(), + p["grade"].as_str().unwrap_or_default() + ) + }) + .collect::>() + .join(" · ") +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_sbom_quality_reads_as_one_line() { + let q = serde_json::json!({ "profiles": [ + { "name": "BSI TR-03183-2 v2.1", "score": 0.926, "grade": "F" }, + { "name": "NTIA Minimum Elements (2021)", "score": 2.857, "grade": "F" }, + ]}); + assert_eq!( + sbom_quality_line(&q), + "BSI TR-03183-2 v2.1 0.9/10 (F) · NTIA Minimum Elements (2021) 2.9/10 (F)" + ); + assert_eq!(sbom_quality_line(&serde_json::Value::Null), ""); + } + #[test] fn violated_requirements_lead_and_process_ones_close() { // The page lists the first three states as open groups and folds the diff --git a/compliance-dashboard/src/pages/sbom.rs b/compliance-dashboard/src/pages/sbom.rs index 2df4488..3f22f6a 100644 --- a/compliance-dashboard/src/pages/sbom.rs +++ b/compliance-dashboard/src/pages/sbom.rs @@ -65,6 +65,17 @@ pub fn SbomPage() -> Element { } }); + // ── SBOM quality of the selected target (#496) ── + let sbom_quality = use_resource(move || { + let repo = repo_filter(); + async move { + if repo.is_empty() { + return None; + } + fetch_sbom_quality(repo).await.ok() + } + }); + // ── License summary ── let license_data = use_resource(move || { let repo = repo_filter(); @@ -243,6 +254,11 @@ pub fn SbomPage() -> Element { } } + // ── SBOM quality of the selected target (#496) ── + if let Some(Some(resp)) = &*sbom_quality.read() { + {sbom_quality_card(resp.clone(), lang)} + } + // ── SBOM table ── match &*sbom.read() { Some(Some(resp)) => { @@ -794,3 +810,58 @@ fn epss_label(epss: &EpssData) -> String { (epss.percentile * 100.0).floor() ) } + +/// The selected target's SBOM quality score: one line per profile, the checks +/// it does not meet folded under it. +fn sbom_quality_card(resp: SbomQualityResponse, lang: Lang) -> Element { + rsx! { + section { class: "card sbom-quality", + h3 { class: "sbom-quality-head", {tx::QUALITY_TITLE.get(lang)} } + p { class: "sbom-quality-hint", {tx::QUALITY_HINT.get(lang)} } + match resp.data { + None => rsx! { p { class: "sbom-quality-hint", {tx::QUALITY_NONE.get(lang)} } }, + Some(q) => rsx! { + for profile in q.profiles { + details { class: "sbom-quality-profile", + summary { + span { class: "badge {grade_class(&profile.grade)}", "{profile.grade}" } + span { class: "sbom-quality-name", "{profile.name}" } + span { class: "sbom-quality-score", "{profile.score:.1} / 10" } + } + if !profile.failed.is_empty() { + p { class: "sbom-quality-sub", {tx::QUALITY_FAILED_CHECKS.get(lang)} } + ul { class: "sbom-quality-checks", + for check in profile.failed { + li { + code { "{check.key}" } + span { class: "sbom-quality-req", + if check.required { {tx::QUALITY_REQUIRED.get(lang)} } else { {tx::QUALITY_ADDITIONAL.get(lang)} } + } + " {check.description}" + } + } + } + } + } + } + p { class: "sbom-quality-meta", + "{q.tool} {q.tool_version} · {q.spec}" + if let Some(at) = resp.completed_at.as_deref() { + " · {tx::QUALITY_SCORED_AT.get(lang)} {at.get(..10).unwrap_or(at)}" + } + } + }, + } + } + } +} + +/// The badge class of an sbomqs grade. +fn grade_class(grade: &str) -> &'static str { + match grade { + "A" => "badge-low", + "B" | "C" => "badge-medium", + "D" => "badge-high", + _ => "badge-critical", + } +} diff --git a/docs/guide/repositories.md b/docs/guide/repositories.md index 298735e..a68e06c 100644 --- a/docs/guide/repositories.md +++ b/docs/guide/repositories.md @@ -179,7 +179,8 @@ its name, type and artifacts, and the buttons: - **Prüfung starten** (Run scan) -- starts a scan now. - **Nachweispaket herunterladen** (Download evidence pack) -- a ZIP with the OSCAL assessment (CRA Annex I), the SBOM (CycloneDX, SPDX), the findings - (JSON, CSV), the CVE alerts and a manifest with SHA-256 checksums. + (JSON, CSV), the CVE alerts, the SBOM's quality score (`sbom-quality.json`, + once a scan has scored it) and a manifest with SHA-256 checksums. - **Bearbeiten** (Edit) -- see below. - **Löschen** (Delete) -- see below. diff --git a/docs/guide/sbom.md b/docs/guide/sbom.md index fe8bc23..7c09c19 100644 --- a/docs/guide/sbom.md +++ b/docs/guide/sbom.md @@ -249,6 +249,29 @@ API: `GET /api/v1/targets/{id}/cves` lists the alerts with their statements, (`{"status": "not_affected", "justification": "…", "impact_statement": "…"}`), `GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx` downloads the document. +## SBOM quality + +When a target is selected on the **Pakete** tab, **SBOM-Qualität** (SBOM +quality) shows how the exported CycloneDX document meets two standards, as +[sbomqs](https://github.com/interlynk-io/sbomqs) scores it at the end of each +scan: + +- **BSI TR-03183-2 v2.1** -- the German technical guideline for SBOMs under + the CRA +- **NTIA Minimum Elements (2021)** + +Each line has sbomqs's grade (A to F) and score out of 10. Open it for the +checks the SBOM does not fully meet, marked **Pflicht** (required) or +**zusätzlich** (additional), with what sbomqs found. The score is supporting +evidence for the CRA requirement **cra-ai-23** (SBOM): it is shown there on +the target's CRA page and is in the evidence pack as `sbom-quality.json`, but +it raises no findings and does not change the requirement's state. + +The score rates the document, not the software. Today's export is CycloneDX +1.5 without suppliers, hashes or the TR's component properties, so BSI +TR-03183-2, which asks for CycloneDX 1.6 and those fields, grades it low; the +failed checks list what the export would need. + ## Compare Tab **Vergleich** compares the SBOMs of two targets, for example two firmware diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 9804427..bfb5bcf 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -135,6 +135,12 @@ vulnerabilities. Syft output feeds into both the SBOM feature and the vulnerability scanning pipeline. +## sbomqs -- SBOM Quality + +[sbomqs](https://github.com/interlynk-io/sbomqs) (Interlynk, Apache-2.0; pinned with its checksum in the agent image) scores the CycloneDX document Prüfwerk exports for a target, the same bytes as the evidence pack's `sbom.cdx.json`, at the end of every completed scan (`pipeline/sbom_quality.rs`). Two profiles, by their explicit names: `bsi-v2.1` (BSI TR-03183-2 v2.1) and `ntia-2021` (NTIA minimum elements). In sbomqs 2.1.2 the short names float (`bsi` is the newest BSI version, `ntia` the CISA 2026 elements), so they are not used. + +The score per profile, its grade and the checks not fully met are stored on the scan run (`sbom_quality`), shown on the SBOM page, attached to the CRA requirement cra-ai-23 as supporting evidence and written to the evidence pack (`sbom-quality.json`). They raise no findings. sbomqs runs offline: its component analysis, which would call Interlynk's API, is opt-in and never turned on, and the tool starts with an empty environment like every other tool. A scan without sbomqs (a development machine) records the skipped stage `sbom_quality`. + ## Embedded Library Versions Libraries copied into a firmware tree have no manifest Syft could read. diff --git a/docs/release/staging-test-plan-after-v0.4.5.md b/docs/release/staging-test-plan-after-v0.4.5.md index e2a10fa..3ccbfc7 100644 --- a/docs/release/staging-test-plan-after-v0.4.5.md +++ b/docs/release/staging-test-plan-after-v0.4.5.md @@ -475,6 +475,27 @@ alerts (e.g. the log4j/gson target of check 19). In managed repositories new High findings go through LLM triage and open tracker issues on that first rescan (#451). +### 24. #496 SBOM quality score (sbomqs) + +- **Do:** after the deploy, `docker exec` into the agent and run + `sbomqs version` and `cat /opt/pruefwerk/tool-versions.json`; then scan any + target with components (e.g. `fixtures/nightly/js-npm-lock-v3`). +- **Expect:** `v2.1.2`, and `"sbomqs":"2.1.2"` in the tool versions. On + **SBOM**, with the target selected, **SBOM-Qualität** lists + "BSI TR-03183-2 v2.1" and "NTIA Minimum Elements (2021)" with a grade and + score each; opening one lists the failed checks (e.g. `sbom_spec_version`, + "CycloneDX 1.5 does not meet minimum version 1.6"). The target's CRA page + shows the same scores on **cra-ai-23**, whose state is unchanged. The + evidence pack has `sbom-quality.json`, listed in `manifest.json`. No new + findings. +- **Log:** `SBOM quality (sbomqs)` with the scores per profile. No outbound + connection from sbomqs. +- **Switch:** none; without the binary the run records the skipped stage + `sbom_quality` ("sbomqs is not installed"). +- **[visible]** SBOM-Qualität card on the SBOM page, the score on cra-ai-23, + `sbom-quality.json` in the evidence pack. Expect a low BSI grade until the + export carries CycloneDX 1.6 and the TR's fields. + ## After the pass - The nightly job on `main` is green with the new mobile targets.