feat(vex): CSAF 2.0 VEX advisory draft (#498, 3/4) #510
No files matched your search
@@ -8,6 +8,7 @@ use axum::Json;
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
use serde::Deserialize;
|
||||
|
||||
use compliance_core::csaf_docs;
|
||||
use compliance_core::models::{CveAlert, SbomEntry, VexAssessment, VexJustification, VexStatus};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
use compliance_core::vex_docs::{self, VexInput};
|
||||
@@ -110,24 +111,24 @@ pub struct VexExportQuery {
|
||||
pub format: Option<String>,
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx — the target's VEX
|
||||
/// statements as a document to download.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn export_vex(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<VexExportQuery>,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
/// What a VEX document of a target is built from: its name, its CVE alerts
|
||||
/// and its SBOM.
|
||||
struct VexSource {
|
||||
name: String,
|
||||
alerts: Vec<CveAlert>,
|
||||
sbom: Vec<SbomEntry>,
|
||||
}
|
||||
|
||||
/// Load the [`VexSource`] of target `id`.
|
||||
async fn load_source(db: &crate::database::Database, id: &str) -> Result<VexSource, StatusCode> {
|
||||
let oid = ObjectId::parse_str(id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let by_target = doc! { "repo_id": &id };
|
||||
let by_target = doc! { "repo_id": id };
|
||||
let components = db
|
||||
.sbom_entries()
|
||||
.count_documents(by_target.clone())
|
||||
@@ -151,32 +152,25 @@ pub async fn export_vex(
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
|
||||
)
|
||||
.await;
|
||||
let tooling = format!("Prüfwerk {}", super::platform::BUILD_VERSION);
|
||||
let author = if tenant.0.tenant_slug.is_empty() {
|
||||
Ok(VexSource {
|
||||
name: target.name,
|
||||
alerts,
|
||||
sbom,
|
||||
})
|
||||
}
|
||||
|
||||
/// The workspace's name, the author of its VEX statements.
|
||||
fn author(tenant: &TenantCtx) -> String {
|
||||
if tenant.0.tenant_slug.is_empty() {
|
||||
tenant.0.tenant_id.clone()
|
||||
} else {
|
||||
tenant.0.tenant_slug.clone()
|
||||
};
|
||||
let input = VexInput {
|
||||
subject: &target.name,
|
||||
author: &author,
|
||||
tooling: &tooling,
|
||||
alerts: &alerts,
|
||||
sbom: &sbom,
|
||||
now: chrono::Utc::now(),
|
||||
};
|
||||
let cyclonedx = query.format.as_deref() == Some("cyclonedx");
|
||||
let body = if cyclonedx {
|
||||
vex_docs::cyclonedx_vex(&input)
|
||||
} else {
|
||||
vex_docs::openvex(&input)
|
||||
};
|
||||
let json =
|
||||
serde_json::to_string_pretty(&body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let filename = format!(
|
||||
"vex-{id}-{}.json",
|
||||
if cyclonedx { "cyclonedx" } else { "openvex" }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `body` as a JSON file named `filename` to download.
|
||||
fn download(body: &serde_json::Value, filename: &str) -> Result<impl IntoResponse, StatusCode> {
|
||||
let json = serde_json::to_string_pretty(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("attachment"));
|
||||
Ok((
|
||||
@@ -190,3 +184,125 @@ pub async fn export_vex(
|
||||
json,
|
||||
))
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx — the target's VEX
|
||||
/// statements as a document to download.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn export_vex(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<VexExportQuery>,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let source = load_source(&db, &id).await?;
|
||||
let tooling = format!("Prüfwerk {}", super::platform::BUILD_VERSION);
|
||||
let author = author(&tenant);
|
||||
let input = VexInput {
|
||||
subject: &source.name,
|
||||
author: &author,
|
||||
tooling: &tooling,
|
||||
alerts: &source.alerts,
|
||||
sbom: &source.sbom,
|
||||
now: chrono::Utc::now(),
|
||||
};
|
||||
let cyclonedx = query.format.as_deref() == Some("cyclonedx");
|
||||
let body = if cyclonedx {
|
||||
vex_docs::cyclonedx_vex(&input)
|
||||
} else {
|
||||
vex_docs::openvex(&input)
|
||||
};
|
||||
let filename = format!(
|
||||
"vex-{id}-{}.json",
|
||||
if cyclonedx { "cyclonedx" } else { "openvex" }
|
||||
);
|
||||
download(&body, &filename)
|
||||
}
|
||||
|
||||
/// The query of [`export_csaf`].
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CsafExportQuery {
|
||||
/// The publisher's URL (`https://example.com`); without one the draft
|
||||
/// carries a placeholder to replace before release.
|
||||
#[serde(default)]
|
||||
pub namespace: Option<String>,
|
||||
/// `de` (default) or `en`: the language the statements are written in.
|
||||
#[serde(default)]
|
||||
pub lang: Option<String>,
|
||||
}
|
||||
|
||||
/// The publisher namespace of a CSAF draft: `given` when it is an http(s)
|
||||
/// URL, the placeholder for `author` without one.
|
||||
fn publisher_namespace(given: Option<&str>, author: &str) -> Result<String, StatusCode> {
|
||||
match given.map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(url)
|
||||
if reqwest::Url::parse(url).is_ok_and(|u| matches!(u.scheme(), "http" | "https")) =>
|
||||
{
|
||||
Ok(url.to_string())
|
||||
}
|
||||
Some(_) => Err(StatusCode::BAD_REQUEST),
|
||||
None => Ok(csaf_docs::placeholder_namespace(author)),
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/targets/{id}/csaf?namespace=<url>&lang=de|en — the target's VEX
|
||||
/// statements as a CSAF 2.0 VEX advisory, always a draft. 400 for a
|
||||
/// namespace that is not an http(s) URL.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn export_csaf(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(query): Query<CsafExportQuery>,
|
||||
) -> Result<impl IntoResponse, StatusCode> {
|
||||
let author = author(&tenant);
|
||||
let namespace = publisher_namespace(query.namespace.as_deref(), &author)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let source = load_source(&db, &id).await?;
|
||||
let tooling = format!("Prüfwerk {}", super::platform::BUILD_VERSION);
|
||||
let input = VexInput {
|
||||
subject: &source.name,
|
||||
author: &author,
|
||||
tooling: &tooling,
|
||||
alerts: &source.alerts,
|
||||
sbom: &source.sbom,
|
||||
now: chrono::Utc::now(),
|
||||
};
|
||||
let lang = if query.lang.as_deref() == Some("en") {
|
||||
"en"
|
||||
} else {
|
||||
"de"
|
||||
};
|
||||
let body = csaf_docs::csaf_vex(&input, &namespace, lang);
|
||||
let filename = csaf_docs::filename(&csaf_docs::tracking_id(&source.name, input.now));
|
||||
download(&body, &filename)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_publisher_namespace_is_a_web_url_or_the_placeholder() {
|
||||
assert_eq!(
|
||||
publisher_namespace(Some(" https://pumps.example.com "), "pumps"),
|
||||
Ok("https://pumps.example.com".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
publisher_namespace(None, "pumps"),
|
||||
Ok("https://example.invalid/pumps".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
publisher_namespace(Some(""), "pumps"),
|
||||
Ok("https://example.invalid/pumps".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
publisher_namespace(Some("javascript:alert(1)"), "pumps"),
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
);
|
||||
assert_eq!(
|
||||
publisher_namespace(Some("pumps.example.com"), "pumps"),
|
||||
Err(StatusCode::BAD_REQUEST)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,7 @@ pub fn build_router() -> Router {
|
||||
get(handlers::vex::list_target_cves),
|
||||
)
|
||||
.route("/api/v1/targets/{id}/vex", get(handlers::vex::export_vex))
|
||||
.route("/api/v1/targets/{id}/csaf", get(handlers::vex::export_csaf))
|
||||
.route("/api/v1/cves/{id}/vex", patch(handlers::vex::set_cve_vex))
|
||||
.route(
|
||||
"/api/v1/targets/{id}/evidence-pack",
|
||||
|
||||
@@ -17,7 +17,7 @@ use sha2::{Digest, Sha256};
|
||||
|
||||
use compliance_core::models::oscal_assessment::assess;
|
||||
use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun, SkipCode};
|
||||
use compliance_core::{sbom_docs, vex_docs};
|
||||
use compliance_core::{csaf_docs, sbom_docs, vex_docs};
|
||||
|
||||
use crate::error::AgentError;
|
||||
|
||||
@@ -103,6 +103,14 @@ pub fn build_pack(
|
||||
("cve-alerts.json", json(&inputs.cves)?),
|
||||
("vex.openvex.json", json(&vex_docs::openvex(&vex))?),
|
||||
("vex.cdx.json", json(&vex_docs::cyclonedx_vex(&vex))?),
|
||||
(
|
||||
"csaf-vex.json",
|
||||
json(&csaf_docs::csaf_vex(
|
||||
&vex,
|
||||
&csaf_docs::placeholder_namespace(vex.author),
|
||||
"de",
|
||||
))?,
|
||||
),
|
||||
("cra-compliance.json", json(&compliance_of(inputs))?),
|
||||
];
|
||||
// The SBOM's quality score of the last scan (sbomqs, #496), when it was
|
||||
@@ -350,6 +358,7 @@ mod tests {
|
||||
names,
|
||||
[
|
||||
"cra-compliance.json",
|
||||
"csaf-vex.json",
|
||||
"cve-alerts.json",
|
||||
"findings.csv",
|
||||
"findings.json",
|
||||
|
||||
@@ -8,6 +8,8 @@ CycloneDX `license.id` may carry.
|
||||
| File | Source | Licence |
|
||||
|---|---|---|
|
||||
| `bom-1.6.schema.json`, `spdx.schema.json`, `jsf-0.82.schema.json` | CycloneDX specification, tag 1.6 (`github.com/CycloneDX/specification/schema/`) | Apache-2.0 |
|
||||
| `csaf_json_schema.json` | CSAF 2.0 (OASIS), as vendored by gocsaf/csaf v3.6.0 (`csaf/schema/`) | Apache-2.0 (gocsaf) |
|
||||
| `cvss-v2.0.json`, `cvss-v3.0.json`, `cvss-v3.1.json` | FIRST CVSS schemas, as vendored by gocsaf/csaf v3.6.0 | BSD-3-Clause |
|
||||
| `openvex-0.2.0.schema.json` | OpenVEX specification (`github.com/openvex/spec`, `openvex_json_schema.json`) | CC0-1.0 |
|
||||
|
||||
Unchanged copies; update them only by copying the upstream file again.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"license": [
|
||||
"Copyright (c) 2017, FIRST.ORG, INC.",
|
||||
"All rights reserved.",
|
||||
"",
|
||||
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ",
|
||||
"following conditions are met:",
|
||||
"1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following ",
|
||||
" disclaimer.",
|
||||
"2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ",
|
||||
" following disclaimer in the documentation and/or other materials provided with the distribution.",
|
||||
"3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote ",
|
||||
" products derived from this software without specific prior written permission.",
|
||||
"",
|
||||
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, ",
|
||||
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ",
|
||||
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ",
|
||||
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ",
|
||||
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ",
|
||||
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ",
|
||||
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
],
|
||||
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "JSON Schema for Common Vulnerability Scoring System version 2.0",
|
||||
"id": "https://www.first.org/cvss/cvss-v2.0.json?20170531",
|
||||
"type": "object",
|
||||
"definitions": {
|
||||
"accessVectorType": {
|
||||
"type": "string",
|
||||
"enum": [ "NETWORK", "ADJACENT_NETWORK", "LOCAL" ]
|
||||
},
|
||||
"accessComplexityType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "MEDIUM", "LOW" ]
|
||||
},
|
||||
"authenticationType": {
|
||||
"type": "string",
|
||||
"enum": [ "MULTIPLE", "SINGLE", "NONE" ]
|
||||
},
|
||||
"ciaType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "PARTIAL", "COMPLETE" ]
|
||||
},
|
||||
"exploitabilityType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNPROVEN", "PROOF_OF_CONCEPT", "FUNCTIONAL", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"remediationLevelType": {
|
||||
"type": "string",
|
||||
"enum": [ "OFFICIAL_FIX", "TEMPORARY_FIX", "WORKAROUND", "UNAVAILABLE", "NOT_DEFINED" ]
|
||||
},
|
||||
"reportConfidenceType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNCONFIRMED", "UNCORROBORATED", "CONFIRMED", "NOT_DEFINED" ]
|
||||
},
|
||||
"collateralDamagePotentialType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "LOW_MEDIUM", "MEDIUM_HIGH", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"targetDistributionType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "MEDIUM", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"ciaRequirementType": {
|
||||
"type": "string",
|
||||
"enum": [ "LOW", "MEDIUM", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"scoreType": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "CVSS Version",
|
||||
"type": "string",
|
||||
"enum": [ "2.0" ]
|
||||
},
|
||||
"vectorString": {
|
||||
"type": "string",
|
||||
"pattern": "^((AV:[NAL]|AC:[LMH]|Au:[MSN]|[CIA]:[NPC]|E:(U|POC|F|H|ND)|RL:(OF|TF|W|U|ND)|RC:(UC|UR|C|ND)|CDP:(N|L|LM|MH|H|ND)|TD:(N|L|M|H|ND)|[CIA]R:(L|M|H|ND))/)*(AV:[NAL]|AC:[LMH]|Au:[MSN]|[CIA]:[NPC]|E:(U|POC|F|H|ND)|RL:(OF|TF|W|U|ND)|RC:(UC|UR|C|ND)|CDP:(N|L|LM|MH|H|ND)|TD:(N|L|M|H|ND)|[CIA]R:(L|M|H|ND))$"
|
||||
},
|
||||
"accessVector": { "$ref": "#/definitions/accessVectorType" },
|
||||
"accessComplexity": { "$ref": "#/definitions/accessComplexityType" },
|
||||
"authentication": { "$ref": "#/definitions/authenticationType" },
|
||||
"confidentialityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"integrityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"availabilityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"baseScore": { "$ref": "#/definitions/scoreType" },
|
||||
"exploitability": { "$ref": "#/definitions/exploitabilityType" },
|
||||
"remediationLevel": { "$ref": "#/definitions/remediationLevelType" },
|
||||
"reportConfidence": { "$ref": "#/definitions/reportConfidenceType" },
|
||||
"temporalScore": { "$ref": "#/definitions/scoreType" },
|
||||
"collateralDamagePotential": { "$ref": "#/definitions/collateralDamagePotentialType" },
|
||||
"targetDistribution": { "$ref": "#/definitions/targetDistributionType" },
|
||||
"confidentialityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"integrityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"availabilityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"environmentalScore": { "$ref": "#/definitions/scoreType" }
|
||||
},
|
||||
"required": [ "version", "vectorString", "baseScore" ]
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
{
|
||||
"license": [
|
||||
"Copyright (c) 2017, FIRST.ORG, INC.",
|
||||
"All rights reserved.",
|
||||
"",
|
||||
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ",
|
||||
"following conditions are met:",
|
||||
"1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following ",
|
||||
" disclaimer.",
|
||||
"2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ",
|
||||
" following disclaimer in the documentation and/or other materials provided with the distribution.",
|
||||
"3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote ",
|
||||
" products derived from this software without specific prior written permission.",
|
||||
"",
|
||||
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, ",
|
||||
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ",
|
||||
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ",
|
||||
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ",
|
||||
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ",
|
||||
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ",
|
||||
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
],
|
||||
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "JSON Schema for Common Vulnerability Scoring System version 3.0",
|
||||
"id": "https://www.first.org/cvss/cvss-v3.0.json?20170531",
|
||||
"type": "object",
|
||||
"definitions": {
|
||||
"attackVectorType": {
|
||||
"type": "string",
|
||||
"enum": [ "NETWORK", "ADJACENT_NETWORK", "LOCAL", "PHYSICAL" ]
|
||||
},
|
||||
"modifiedAttackVectorType": {
|
||||
"type": "string",
|
||||
"enum": [ "NETWORK", "ADJACENT_NETWORK", "LOCAL", "PHYSICAL", "NOT_DEFINED" ]
|
||||
},
|
||||
"attackComplexityType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW" ]
|
||||
},
|
||||
"modifiedAttackComplexityType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NOT_DEFINED" ]
|
||||
},
|
||||
"privilegesRequiredType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NONE" ]
|
||||
},
|
||||
"modifiedPrivilegesRequiredType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NONE", "NOT_DEFINED" ]
|
||||
},
|
||||
"userInteractionType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "REQUIRED" ]
|
||||
},
|
||||
"modifiedUserInteractionType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "REQUIRED", "NOT_DEFINED" ]
|
||||
},
|
||||
"scopeType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNCHANGED", "CHANGED" ]
|
||||
},
|
||||
"modifiedScopeType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNCHANGED", "CHANGED", "NOT_DEFINED" ]
|
||||
},
|
||||
"ciaType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "HIGH" ]
|
||||
},
|
||||
"modifiedCiaType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"exploitCodeMaturityType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNPROVEN", "PROOF_OF_CONCEPT", "FUNCTIONAL", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"remediationLevelType": {
|
||||
"type": "string",
|
||||
"enum": [ "OFFICIAL_FIX", "TEMPORARY_FIX", "WORKAROUND", "UNAVAILABLE", "NOT_DEFINED" ]
|
||||
},
|
||||
"confidenceType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNKNOWN", "REASONABLE", "CONFIRMED", "NOT_DEFINED" ]
|
||||
},
|
||||
"ciaRequirementType": {
|
||||
"type": "string",
|
||||
"enum": [ "LOW", "MEDIUM", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"scoreType": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"severityType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "MEDIUM", "HIGH", "CRITICAL" ]
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "CVSS Version",
|
||||
"type": "string",
|
||||
"enum": [ "3.0" ]
|
||||
},
|
||||
"vectorString": {
|
||||
"type": "string",
|
||||
"pattern": "^CVSS:3[.]0/((AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])/)*(AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])$"
|
||||
},
|
||||
"attackVector": { "$ref": "#/definitions/attackVectorType" },
|
||||
"attackComplexity": { "$ref": "#/definitions/attackComplexityType" },
|
||||
"privilegesRequired": { "$ref": "#/definitions/privilegesRequiredType" },
|
||||
"userInteraction": { "$ref": "#/definitions/userInteractionType" },
|
||||
"scope": { "$ref": "#/definitions/scopeType" },
|
||||
"confidentialityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"integrityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"availabilityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"baseScore": { "$ref": "#/definitions/scoreType" },
|
||||
"baseSeverity": { "$ref": "#/definitions/severityType" },
|
||||
"exploitCodeMaturity": { "$ref": "#/definitions/exploitCodeMaturityType" },
|
||||
"remediationLevel": { "$ref": "#/definitions/remediationLevelType" },
|
||||
"reportConfidence": { "$ref": "#/definitions/confidenceType" },
|
||||
"temporalScore": { "$ref": "#/definitions/scoreType" },
|
||||
"temporalSeverity": { "$ref": "#/definitions/severityType" },
|
||||
"confidentialityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"integrityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"availabilityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"modifiedAttackVector": { "$ref": "#/definitions/modifiedAttackVectorType" },
|
||||
"modifiedAttackComplexity": { "$ref": "#/definitions/modifiedAttackComplexityType" },
|
||||
"modifiedPrivilegesRequired": { "$ref": "#/definitions/modifiedPrivilegesRequiredType" },
|
||||
"modifiedUserInteraction": { "$ref": "#/definitions/modifiedUserInteractionType" },
|
||||
"modifiedScope": { "$ref": "#/definitions/modifiedScopeType" },
|
||||
"modifiedConfidentialityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"modifiedIntegrityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"modifiedAvailabilityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"environmentalScore": { "$ref": "#/definitions/scoreType" },
|
||||
"environmentalSeverity": { "$ref": "#/definitions/severityType" }
|
||||
},
|
||||
"required": [ "version", "vectorString", "baseScore", "baseSeverity" ]
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
{
|
||||
"license": [
|
||||
"Copyright (c) 2021, FIRST.ORG, INC.",
|
||||
"All rights reserved.",
|
||||
"",
|
||||
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ",
|
||||
"following conditions are met:",
|
||||
"1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following ",
|
||||
" disclaimer.",
|
||||
"2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ",
|
||||
" following disclaimer in the documentation and/or other materials provided with the distribution.",
|
||||
"3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote ",
|
||||
" products derived from this software without specific prior written permission.",
|
||||
"",
|
||||
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, ",
|
||||
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ",
|
||||
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ",
|
||||
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ",
|
||||
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ",
|
||||
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ",
|
||||
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
],
|
||||
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "JSON Schema for Common Vulnerability Scoring System version 3.1",
|
||||
"$id": "https://www.first.org/cvss/cvss-v3.1.json?20211103",
|
||||
"type": "object",
|
||||
"definitions": {
|
||||
"attackVectorType": {
|
||||
"type": "string",
|
||||
"enum": [ "NETWORK", "ADJACENT_NETWORK", "LOCAL", "PHYSICAL" ]
|
||||
},
|
||||
"modifiedAttackVectorType": {
|
||||
"type": "string",
|
||||
"enum": [ "NETWORK", "ADJACENT_NETWORK", "LOCAL", "PHYSICAL", "NOT_DEFINED" ]
|
||||
},
|
||||
"attackComplexityType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW" ]
|
||||
},
|
||||
"modifiedAttackComplexityType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NOT_DEFINED" ]
|
||||
},
|
||||
"privilegesRequiredType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NONE" ]
|
||||
},
|
||||
"modifiedPrivilegesRequiredType": {
|
||||
"type": "string",
|
||||
"enum": [ "HIGH", "LOW", "NONE", "NOT_DEFINED" ]
|
||||
},
|
||||
"userInteractionType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "REQUIRED" ]
|
||||
},
|
||||
"modifiedUserInteractionType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "REQUIRED", "NOT_DEFINED" ]
|
||||
},
|
||||
"scopeType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNCHANGED", "CHANGED" ]
|
||||
},
|
||||
"modifiedScopeType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNCHANGED", "CHANGED", "NOT_DEFINED" ]
|
||||
},
|
||||
"ciaType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "HIGH" ]
|
||||
},
|
||||
"modifiedCiaType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"exploitCodeMaturityType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNPROVEN", "PROOF_OF_CONCEPT", "FUNCTIONAL", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"remediationLevelType": {
|
||||
"type": "string",
|
||||
"enum": [ "OFFICIAL_FIX", "TEMPORARY_FIX", "WORKAROUND", "UNAVAILABLE", "NOT_DEFINED" ]
|
||||
},
|
||||
"confidenceType": {
|
||||
"type": "string",
|
||||
"enum": [ "UNKNOWN", "REASONABLE", "CONFIRMED", "NOT_DEFINED" ]
|
||||
},
|
||||
"ciaRequirementType": {
|
||||
"type": "string",
|
||||
"enum": [ "LOW", "MEDIUM", "HIGH", "NOT_DEFINED" ]
|
||||
},
|
||||
"scoreType": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 10
|
||||
},
|
||||
"severityType": {
|
||||
"type": "string",
|
||||
"enum": [ "NONE", "LOW", "MEDIUM", "HIGH", "CRITICAL" ]
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "CVSS Version",
|
||||
"type": "string",
|
||||
"enum": [ "3.1" ]
|
||||
},
|
||||
"vectorString": {
|
||||
"type": "string",
|
||||
"pattern": "^CVSS:3[.]1/((AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])/)*(AV:[NALP]|AC:[LH]|PR:[NLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])$"
|
||||
},
|
||||
"attackVector": { "$ref": "#/definitions/attackVectorType" },
|
||||
"attackComplexity": { "$ref": "#/definitions/attackComplexityType" },
|
||||
"privilegesRequired": { "$ref": "#/definitions/privilegesRequiredType" },
|
||||
"userInteraction": { "$ref": "#/definitions/userInteractionType" },
|
||||
"scope": { "$ref": "#/definitions/scopeType" },
|
||||
"confidentialityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"integrityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"availabilityImpact": { "$ref": "#/definitions/ciaType" },
|
||||
"baseScore": { "$ref": "#/definitions/scoreType" },
|
||||
"baseSeverity": { "$ref": "#/definitions/severityType" },
|
||||
"exploitCodeMaturity": { "$ref": "#/definitions/exploitCodeMaturityType" },
|
||||
"remediationLevel": { "$ref": "#/definitions/remediationLevelType" },
|
||||
"reportConfidence": { "$ref": "#/definitions/confidenceType" },
|
||||
"temporalScore": { "$ref": "#/definitions/scoreType" },
|
||||
"temporalSeverity": { "$ref": "#/definitions/severityType" },
|
||||
"confidentialityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"integrityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"availabilityRequirement": { "$ref": "#/definitions/ciaRequirementType" },
|
||||
"modifiedAttackVector": { "$ref": "#/definitions/modifiedAttackVectorType" },
|
||||
"modifiedAttackComplexity": { "$ref": "#/definitions/modifiedAttackComplexityType" },
|
||||
"modifiedPrivilegesRequired": { "$ref": "#/definitions/modifiedPrivilegesRequiredType" },
|
||||
"modifiedUserInteraction": { "$ref": "#/definitions/modifiedUserInteractionType" },
|
||||
"modifiedScope": { "$ref": "#/definitions/modifiedScopeType" },
|
||||
"modifiedConfidentialityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"modifiedIntegrityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"modifiedAvailabilityImpact": { "$ref": "#/definitions/modifiedCiaType" },
|
||||
"environmentalScore": { "$ref": "#/definitions/scoreType" },
|
||||
"environmentalSeverity": { "$ref": "#/definitions/severityType" }
|
||||
},
|
||||
"required": [ "version", "vectorString", "baseScore", "baseSeverity" ]
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! A CSAF 2.0 VEX advisory for a target (#498): the same statements as the
|
||||
//! OpenVEX and CycloneDX VEX documents ([`crate::vex_docs`]) in the format
|
||||
//! CERTs and the CRA's vulnerability reporting use. Always a draft: the
|
||||
//! manufacturer checks the publisher and the statements before releasing it.
|
||||
//!
|
||||
//! The product tree has the target as product and every affected component
|
||||
//! as `default_component_of` it; the statuses name the component in the
|
||||
//! product. A `not_affected` carries its justification as a flag (CSAF's flag
|
||||
//! labels are OpenVEX's justifications) and its impact statement as a threat;
|
||||
//! an `affected` its action statement as a remediation.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::models::{CveAlert, VexStatus};
|
||||
use crate::sbom_docs::product_ref;
|
||||
use crate::vex_docs::{component_id, rfc3339, status_of, VexInput};
|
||||
|
||||
/// The note every draft carries.
|
||||
pub const DRAFT_NOTE: &str = "Draft, not published: check publisher and statements before release.";
|
||||
|
||||
/// The product id of the target in the product tree.
|
||||
const PRODUCT_ID: &str = "PRODUCT";
|
||||
|
||||
/// The tracking id of the advisory for `subject` on `at`
|
||||
/// (`pruefwerk-vex-pump-remote-20261006`): lowercase letters, digits and
|
||||
/// dashes, so the file name CSAF derives from it is the id itself.
|
||||
pub fn tracking_id(subject: &str, at: DateTime<Utc>) -> String {
|
||||
let mut slug = String::with_capacity(subject.len());
|
||||
for c in subject.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
slug.push(c.to_ascii_lowercase());
|
||||
} else if !slug.ends_with('-') {
|
||||
slug.push('-');
|
||||
}
|
||||
}
|
||||
format!(
|
||||
"pruefwerk-vex-{}-{}",
|
||||
slug.trim_matches('-'),
|
||||
at.format("%Y%m%d")
|
||||
)
|
||||
}
|
||||
|
||||
/// The publisher namespace of a draft whose publisher gave none: a URL that
|
||||
/// cannot resolve (`example.invalid`), so it is plainly to be replaced before
|
||||
/// release.
|
||||
pub fn placeholder_namespace(publisher: &str) -> String {
|
||||
let slug: String = publisher
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
c.to_ascii_lowercase()
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
format!("https://example.invalid/{}", slug.trim_matches('-'))
|
||||
}
|
||||
|
||||
/// The file name of an advisory with `tracking_id`, as CSAF 2.0 §5.1 derives
|
||||
/// it.
|
||||
pub fn filename(tracking_id: &str) -> String {
|
||||
let name: String = tracking_id
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '+' || c == '-' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
format!("{name}.json")
|
||||
}
|
||||
|
||||
/// Whether `id` is a CVE id, which CSAF keeps in its own field.
|
||||
fn is_cve(id: &str) -> bool {
|
||||
id.strip_prefix("CVE-")
|
||||
.and_then(|rest| rest.split_once('-'))
|
||||
.is_some_and(|(year, number)| {
|
||||
year.len() == 4
|
||||
&& number.len() >= 4
|
||||
&& year
|
||||
.bytes()
|
||||
.chain(number.bytes())
|
||||
.all(|b| b.is_ascii_digit())
|
||||
})
|
||||
}
|
||||
|
||||
/// The id CSAF lists a vulnerability under: the alert's CVE, or the CVE
|
||||
/// among its aliases, else its own id. Alerts with the same key are one
|
||||
/// vulnerability (CSAF forbids listing a CVE twice).
|
||||
fn vulnerability_key(alert: &CveAlert) -> &str {
|
||||
if is_cve(&alert.cve_id) {
|
||||
return &alert.cve_id;
|
||||
}
|
||||
alert
|
||||
.aliases
|
||||
.iter()
|
||||
.find(|a| is_cve(a))
|
||||
.map_or(alert.cve_id.as_str(), String::as_str)
|
||||
}
|
||||
|
||||
/// The system a non-CVE id belongs to (`GHSA-…` is GitHub's advisory
|
||||
/// database).
|
||||
fn id_system(id: &str) -> &str {
|
||||
id.split_once('-').map_or("OSV", |(prefix, _)| prefix)
|
||||
}
|
||||
|
||||
/// The components the alerts are about, each once: `(id, name, purl)`.
|
||||
fn components(input: &VexInput<'_>) -> Vec<(String, String, String)> {
|
||||
let mut out: Vec<(String, String, String)> = Vec::new();
|
||||
for alert in input.alerts {
|
||||
let purl = component_id(alert, input.sbom);
|
||||
if out.iter().all(|(.., p)| *p != purl) {
|
||||
let name = format!("{} {}", alert.affected_package, alert.affected_version);
|
||||
out.push((format!("C{}", out.len() + 1), name, purl));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The product id of a component in the product.
|
||||
fn in_product(component: &str) -> String {
|
||||
format!("{component}-IN-{PRODUCT_ID}")
|
||||
}
|
||||
|
||||
/// The product tree: the target, its components, and each component as
|
||||
/// part of the target.
|
||||
fn product_tree(
|
||||
input: &VexInput<'_>,
|
||||
components: &[(String, String, String)],
|
||||
) -> serde_json::Value {
|
||||
let mut names = vec![serde_json::json!({
|
||||
"name": input.subject,
|
||||
"product_id": PRODUCT_ID,
|
||||
"product_identification_helper": { "purl": product_ref(input.subject) },
|
||||
})];
|
||||
let mut relationships = Vec::with_capacity(components.len());
|
||||
for (id, name, purl) in components {
|
||||
let mut product = serde_json::json!({ "name": name, "product_id": id });
|
||||
if purl.starts_with("pkg:") {
|
||||
product["product_identification_helper"] = serde_json::json!({ "purl": purl });
|
||||
}
|
||||
names.push(product);
|
||||
relationships.push(serde_json::json!({
|
||||
"category": "default_component_of",
|
||||
"product_reference": id,
|
||||
"relates_to_product_reference": PRODUCT_ID,
|
||||
"full_product_name": {
|
||||
"name": format!("{name} in {}", input.subject),
|
||||
"product_id": in_product(id),
|
||||
},
|
||||
}));
|
||||
}
|
||||
serde_json::json!({ "full_product_names": names, "relationships": relationships })
|
||||
}
|
||||
|
||||
/// The CSAF `product_status` key of a VEX status.
|
||||
fn status_key(status: VexStatus) -> &'static str {
|
||||
match status {
|
||||
VexStatus::UnderInvestigation => "under_investigation",
|
||||
VexStatus::Affected => "known_affected",
|
||||
VexStatus::NotAffected => "known_not_affected",
|
||||
VexStatus::Fixed => "fixed",
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `product` onto the list under `key` of the object `parent[field]`,
|
||||
/// creating both on first use.
|
||||
fn push_product(parent: &mut serde_json::Value, field: &str, key: &str, product: &str) {
|
||||
let list = &mut parent[field][key];
|
||||
match list.as_array_mut() {
|
||||
Some(list) => list.push(serde_json::json!(product)),
|
||||
None => *list = serde_json::json!([product]),
|
||||
}
|
||||
}
|
||||
|
||||
/// One vulnerability of the advisory, from all alerts listed under `key`.
|
||||
fn vulnerability(
|
||||
key: &str,
|
||||
alerts: &[&CveAlert],
|
||||
components: &[(String, String, String)],
|
||||
input: &VexInput<'_>,
|
||||
) -> serde_json::Value {
|
||||
let mut v = serde_json::json!({ "product_status": {} });
|
||||
if is_cve(key) {
|
||||
v["cve"] = serde_json::json!(key);
|
||||
}
|
||||
let mut ids: Vec<&str> = Vec::new();
|
||||
for alert in alerts {
|
||||
for id in std::iter::once(&alert.cve_id).chain(&alert.aliases) {
|
||||
if !is_cve(id) && !ids.contains(&id.as_str()) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
v["ids"] = ids
|
||||
.iter()
|
||||
.map(|id| serde_json::json!({ "system_name": id_system(id), "text": id }))
|
||||
.collect();
|
||||
}
|
||||
// The VEX profile requires notes on every vulnerability; without an
|
||||
// advisory summary they say what is affected.
|
||||
let text = alerts
|
||||
.iter()
|
||||
.find_map(|a| a.summary.clone())
|
||||
.unwrap_or_else(|| {
|
||||
let packages: Vec<String> = alerts
|
||||
.iter()
|
||||
.map(|a| format!("{} {}", a.affected_package, a.affected_version))
|
||||
.collect();
|
||||
format!("{key} in {}.", packages.join(", "))
|
||||
});
|
||||
v["notes"] = serde_json::json!([{ "category": "description", "text": text }]);
|
||||
let (mut flags, mut threats, mut remediations) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for alert in alerts {
|
||||
let purl = component_id(alert, input.sbom);
|
||||
let Some((id, ..)) = components.iter().find(|(.., p)| *p == purl) else {
|
||||
continue;
|
||||
};
|
||||
let product = in_product(id);
|
||||
let status = status_of(alert);
|
||||
let listed = v["product_status"][status_key(status)]
|
||||
.as_array()
|
||||
.is_some_and(|l| l.iter().any(|p| p == product.as_str()));
|
||||
if listed {
|
||||
continue;
|
||||
}
|
||||
push_product(&mut v, "product_status", status_key(status), &product);
|
||||
let Some(vex) = &alert.vex else { continue };
|
||||
match status {
|
||||
VexStatus::NotAffected => {
|
||||
if let Some(justification) = vex.justification {
|
||||
flags.push(serde_json::json!({
|
||||
"label": justification,
|
||||
"product_ids": [product],
|
||||
}));
|
||||
}
|
||||
if let Some(text) = vex.impact_statement.as_deref() {
|
||||
threats.push(serde_json::json!({
|
||||
"category": "impact",
|
||||
"details": text,
|
||||
"product_ids": [product],
|
||||
}));
|
||||
}
|
||||
}
|
||||
VexStatus::Affected => {
|
||||
let category = if alert.fixed_versions.is_empty() {
|
||||
"mitigation"
|
||||
} else {
|
||||
"vendor_fix"
|
||||
};
|
||||
let details = vex.action_statement.clone().unwrap_or_else(|| {
|
||||
format!(
|
||||
"Update {} to {}.",
|
||||
alert.affected_package,
|
||||
alert.fixed_versions.join(" or ")
|
||||
)
|
||||
});
|
||||
remediations.push(serde_json::json!({
|
||||
"category": category,
|
||||
"details": details,
|
||||
"product_ids": [product],
|
||||
}));
|
||||
}
|
||||
VexStatus::UnderInvestigation | VexStatus::Fixed => {}
|
||||
}
|
||||
}
|
||||
for (field, list) in [
|
||||
("flags", flags),
|
||||
("threats", threats),
|
||||
("remediations", remediations),
|
||||
] {
|
||||
if !list.is_empty() {
|
||||
v[field] = serde_json::Value::Array(list);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// A CSAF 2.0 VEX advisory (draft) for `input`, published by `input.author`
|
||||
/// under `namespace` (the publisher's URL), in language `lang` (`de`, `en`:
|
||||
/// the language its statements were written in). Marked TLP:AMBER until the
|
||||
/// manufacturer has reviewed it for publication.
|
||||
pub fn csaf_vex(input: &VexInput<'_>, namespace: &str, lang: &str) -> serde_json::Value {
|
||||
let now = rfc3339(input.now);
|
||||
let components = components(input);
|
||||
let mut keys: Vec<&str> = Vec::new();
|
||||
for alert in input.alerts {
|
||||
let key = vulnerability_key(alert);
|
||||
if !keys.contains(&key) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
let vulnerabilities: Vec<serde_json::Value> = keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let alerts: Vec<&CveAlert> = input
|
||||
.alerts
|
||||
.iter()
|
||||
.filter(|a| vulnerability_key(a) == *key)
|
||||
.collect();
|
||||
vulnerability(key, &alerts, &components, input)
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"document": {
|
||||
"category": "csaf_vex",
|
||||
"csaf_version": "2.0",
|
||||
"lang": lang,
|
||||
"distribution": { "tlp": { "label": "AMBER" } },
|
||||
"title": format!("VEX for {} (draft)", input.subject),
|
||||
"publisher": {
|
||||
"category": "vendor",
|
||||
"name": input.author,
|
||||
"namespace": namespace,
|
||||
},
|
||||
"notes": [{ "category": "general", "title": "Draft", "text": DRAFT_NOTE }],
|
||||
"tracking": {
|
||||
"id": tracking_id(input.subject, input.now),
|
||||
"status": "draft",
|
||||
"version": "1",
|
||||
"revision_history": [{
|
||||
"date": now,
|
||||
"number": "1",
|
||||
"summary": "Draft generated by Prüfwerk.",
|
||||
}],
|
||||
"initial_release_date": now,
|
||||
"current_release_date": now,
|
||||
"generator": { "engine": { "name": input.tooling }, "date": now },
|
||||
},
|
||||
},
|
||||
"product_tree": product_tree(input, &components),
|
||||
"vulnerabilities": vulnerabilities,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ids_and_file_names_follow_csaf() {
|
||||
let at = DateTime::parse_from_rfc3339("2026-10-06T12:00:00Z")
|
||||
.map(|d| d.with_timezone(&Utc))
|
||||
.unwrap_or_default();
|
||||
let id = tracking_id("Pump Remote / HMI", at);
|
||||
assert_eq!(id, "pruefwerk-vex-pump-remote-hmi-20261006");
|
||||
assert_eq!(filename(&id), "pruefwerk-vex-pump-remote-hmi-20261006.json");
|
||||
assert_eq!(filename("ACME_SA:2026/01"), "acme_sa_2026_01.json");
|
||||
assert!(is_cve("CVE-2021-44228"));
|
||||
assert!(!is_cve("GHSA-jfh8-c2jp-5v3q"));
|
||||
assert!(!is_cve("CVE-21-1"));
|
||||
assert_eq!(id_system("GHSA-jfh8-c2jp-5v3q"), "GHSA");
|
||||
assert_eq!(
|
||||
placeholder_namespace("example-pumps"),
|
||||
"https://example.invalid/example-pumps"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod config;
|
||||
pub mod control_check;
|
||||
pub mod csaf_docs;
|
||||
pub mod db;
|
||||
pub mod error;
|
||||
pub mod exec_policy;
|
||||
|
||||
@@ -53,7 +53,7 @@ fn entry_of<'a>(alert: &CveAlert, sbom: &'a [SbomEntry]) -> Option<&'a SbomEntry
|
||||
|
||||
/// The identifier of the component an alert is about: the SBOM's `bom-ref`
|
||||
/// (its purl), or a generic purl of the package and version.
|
||||
fn component_id(alert: &CveAlert, sbom: &[SbomEntry]) -> String {
|
||||
pub(crate) fn component_id(alert: &CveAlert, sbom: &[SbomEntry]) -> String {
|
||||
entry_of(alert, sbom).map_or_else(
|
||||
|| {
|
||||
let mut name = product_ref(&alert.affected_package);
|
||||
@@ -65,7 +65,7 @@ fn component_id(alert: &CveAlert, sbom: &[SbomEntry]) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
fn rfc3339(at: DateTime<Utc>) -> String {
|
||||
pub(crate) fn rfc3339(at: DateTime<Utc>) -> String {
|
||||
at.to_rfc3339_opts(SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// Validate a CSAF 2.0 document with BSI's csaf-validator-lib (MIT): the
|
||||
// schema, the mandatory (6.1.x) and the optional (6.2.x) tests. Run from the
|
||||
// directory the library is installed in; prints the result as JSON.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { register } from 'node:module'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
// js-cvss 0.4.4, which the library imports, ships ES modules whose relative
|
||||
// imports have no `.js`; Node needs it, so a resolve hook adds it.
|
||||
register(
|
||||
'data:text/javascript,' +
|
||||
encodeURIComponent(`export async function resolve(specifier, context, next) {
|
||||
try {
|
||||
return await next(specifier, context)
|
||||
} catch (e) {
|
||||
if (e.code !== 'ERR_MODULE_NOT_FOUND' || !specifier.startsWith('.')) throw e
|
||||
return next(specifier + '.js', context)
|
||||
}
|
||||
}`),
|
||||
)
|
||||
|
||||
// By file: the package's export map does not list every module.
|
||||
const lib = (name) =>
|
||||
import(pathToFileURL(join(process.cwd(), 'node_modules/@secvisogram/csaf-validator-lib', name)).href)
|
||||
const { default: validateStrict } = await lib('validateStrict.js')
|
||||
const schema = await lib('schemaTests.js')
|
||||
const mandatory = await lib('mandatoryTests.js')
|
||||
const optional = await lib('optionalTests.js')
|
||||
|
||||
const doc = JSON.parse(readFileSync(process.argv[2], 'utf8'))
|
||||
const result = await validateStrict(
|
||||
[schema.csaf_2_0_strict, ...Object.values(mandatory), ...Object.values(optional)],
|
||||
doc,
|
||||
)
|
||||
// One result per test; each error and warning is printed with its test.
|
||||
const found = (kind) =>
|
||||
result.tests.flatMap((t) =>
|
||||
(t[kind] ?? []).map((e) => ({ test: t.name, message: e.message, path: e.instancePath })),
|
||||
)
|
||||
console.log(
|
||||
JSON.stringify({ isValid: result.isValid, errors: found('errors'), warnings: found('warnings') }),
|
||||
)
|
||||
@@ -1,9 +1,11 @@
|
||||
//! The SBOM and VEX documents Prüfwerk writes against the official schemas
|
||||
//! vendored in `schemas/` (#498, #508): CycloneDX 1.6 and OpenVEX 0.2.0.
|
||||
//! vendored in `schemas/` (#498, #508): CycloneDX 1.6, OpenVEX 0.2.0 and CSAF
|
||||
//! 2.0.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use chrono::Utc;
|
||||
use compliance_core::csaf_docs;
|
||||
use compliance_core::models::{
|
||||
CveAlert, CveSource, SbomEntry, VexAssessment, VexJustification, VexStatus, VulnRef,
|
||||
};
|
||||
@@ -37,6 +39,22 @@ fn cyclonedx_errors(doc: &serde_json::Value) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The errors of `doc` against CSAF 2.0 (with the CVSS schemas it refers to).
|
||||
fn csaf_errors(doc: &serde_json::Value) -> Vec<String> {
|
||||
let mut options = jsonschema::options();
|
||||
for version in ["2.0", "3.0", "3.1"] {
|
||||
options = options.with_resource(
|
||||
format!("https://www.first.org/cvss/cvss-v{version}.json"),
|
||||
jsonschema::Resource::from_contents(schema(&format!("cvss-v{version}.json"))).unwrap(),
|
||||
);
|
||||
}
|
||||
let validator = options.build(&schema("csaf_json_schema.json")).unwrap();
|
||||
validator
|
||||
.iter_errors(doc)
|
||||
.map(|e| format!("{} at {}", e, e.instance_path))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn openvex_errors(doc: &serde_json::Value) -> Vec<String> {
|
||||
let validator = jsonschema::validator_for(&schema("openvex-0.2.0.schema.json")).unwrap();
|
||||
validator
|
||||
@@ -254,3 +272,128 @@ fn the_vex_documents_are_valid_against_their_schemas() {
|
||||
"update"
|
||||
);
|
||||
}
|
||||
|
||||
fn vex_input<'a>(alerts: &'a [CveAlert], sbom: &'a [SbomEntry]) -> VexInput<'a> {
|
||||
VexInput {
|
||||
subject: "Pump Remote",
|
||||
author: "Example Pumps GmbH",
|
||||
tooling: "Prüfwerk test",
|
||||
alerts,
|
||||
sbom,
|
||||
now: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The alerts plus a GitHub advisory for the same CVE as the log4j alert,
|
||||
/// found in a second component: one vulnerability in CSAF.
|
||||
fn csaf_alerts() -> Vec<CveAlert> {
|
||||
let mut alerts = alerts();
|
||||
let mut ghsa = alert("GHSA-jfh8-c2jp-5v3q", "log4j-api", "2.14.1");
|
||||
ghsa.aliases = vec!["CVE-2021-44228".into()];
|
||||
ghsa.summary = Some("Remote code injection in Log4j".into());
|
||||
alerts.push(ghsa);
|
||||
alerts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_csaf_advisory_is_valid_and_carries_the_statements() {
|
||||
let (sbom, alerts) = (sbom(), csaf_alerts());
|
||||
let doc = csaf_docs::csaf_vex(
|
||||
&vex_input(&alerts, &sbom),
|
||||
"https://example.invalid/pumps",
|
||||
"de",
|
||||
);
|
||||
assert_eq!(csaf_errors(&doc), Vec::<String>::new());
|
||||
assert_eq!(doc["document"]["category"], "csaf_vex");
|
||||
assert_eq!(doc["document"]["tracking"]["status"], "draft");
|
||||
assert_eq!(doc["document"]["distribution"]["tlp"]["label"], "AMBER");
|
||||
assert_eq!(doc["document"]["lang"], "de");
|
||||
assert_eq!(doc["document"]["notes"][0]["text"], csaf_docs::DRAFT_NOTE);
|
||||
let vulns = doc["vulnerabilities"].as_array().unwrap();
|
||||
// Log4Shell once, though two alerts name it.
|
||||
assert_eq!(vulns.len(), 4);
|
||||
let log4shell = &vulns[0];
|
||||
assert_eq!(log4shell["cve"], "CVE-2021-44228");
|
||||
assert_eq!(log4shell["ids"][0]["system_name"], "GHSA");
|
||||
let affected = log4shell["product_status"]["known_affected"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert_eq!(affected.len(), 1);
|
||||
assert_eq!(
|
||||
log4shell["product_status"]["under_investigation"][0],
|
||||
"C5-IN-PRODUCT"
|
||||
);
|
||||
assert_eq!(log4shell["remediations"][0]["category"], "vendor_fix");
|
||||
assert_eq!(log4shell["remediations"][0]["product_ids"][0], affected[0]);
|
||||
let lodash = &vulns[1];
|
||||
assert_eq!(
|
||||
lodash["flags"][0]["label"],
|
||||
"vulnerable_code_not_in_execute_path"
|
||||
);
|
||||
assert_eq!(lodash["threats"][0]["category"], "impact");
|
||||
assert!(vulns[2]["product_status"]["fixed"].is_array());
|
||||
// Every status names a component in the product.
|
||||
let relationships = doc["product_tree"]["relationships"].as_array().unwrap();
|
||||
assert_eq!(relationships.len(), 5);
|
||||
assert_eq!(relationships[0]["relates_to_product_reference"], "PRODUCT");
|
||||
// A broken document fails the check.
|
||||
let mut no_publisher = doc.clone();
|
||||
no_publisher["document"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("publisher");
|
||||
assert!(!csaf_errors(&no_publisher).is_empty());
|
||||
}
|
||||
|
||||
/// The advisory checked by the CSAF validators themselves, when installed:
|
||||
/// gocsaf's `csaf_validator` (Apache-2.0; `CSAF_VALIDATOR`, the schema and
|
||||
/// file name) and BSI's csaf-validator-lib (MIT; `CSAF_VALIDATOR_LIB`, the
|
||||
/// directory it is installed in, run by `tests/csaf/validate.mjs`: the
|
||||
/// mandatory and optional tests). `cargo test -p compliance-core --test
|
||||
/// vex_schemas -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "needs the CSAF validators"]
|
||||
fn the_csaf_advisory_passes_the_csaf_validators() {
|
||||
let (sbom, alerts) = (sbom(), csaf_alerts());
|
||||
let doc = csaf_docs::csaf_vex(
|
||||
&vex_input(&alerts, &sbom),
|
||||
"https://example.invalid/pumps",
|
||||
"de",
|
||||
);
|
||||
let dir = std::env::temp_dir().join(format!("csaf-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let id = doc["document"]["tracking"]["id"].as_str().unwrap();
|
||||
let path = dir.join(csaf_docs::filename(id));
|
||||
std::fs::write(&path, serde_json::to_vec_pretty(&doc).unwrap()).unwrap();
|
||||
let mut ran = false;
|
||||
if let Ok(validator) = std::env::var("CSAF_VALIDATOR") {
|
||||
let out = std::process::Command::new(validator)
|
||||
.arg(&path)
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
println!("csaf_validator: {text}");
|
||||
// Exit 4: no remote validator configured; anything else is a failure.
|
||||
assert!(matches!(out.status.code(), Some(0 | 4)), "{text}");
|
||||
ran = true;
|
||||
}
|
||||
if let Ok(lib) = std::env::var("CSAF_VALIDATOR_LIB") {
|
||||
let script =
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/csaf/validate.mjs");
|
||||
let out = std::process::Command::new("node")
|
||||
.arg(script)
|
||||
.arg(&path)
|
||||
.env("NODE_PATH", format!("{lib}/node_modules"))
|
||||
.current_dir(&lib)
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
println!("csaf-validator-lib: {text}");
|
||||
let result: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(result["errors"], serde_json::json!([]), "{text}");
|
||||
assert_eq!(result["isValid"], true);
|
||||
ran = true;
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(ran, "set CSAF_VALIDATOR and/or CSAF_VALIDATOR_LIB");
|
||||
}
|
||||
@@ -5005,6 +5005,26 @@ tbody tr:last-child td {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.vex-csaf {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.vex-csaf label {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
flex: 1 1 260px;
|
||||
font-size: 12.5px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.vex-csaf p {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.vex-table code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! On a target: its known vulnerabilities with their VEX status, an editor to
|
||||
//! state whether the product is affected, and the OpenVEX and CycloneDX VEX
|
||||
//! downloads (#498). Read-only roles see the statements but not the editor.
|
||||
//! state whether the product is affected, the OpenVEX and CycloneDX VEX
|
||||
//! downloads and the CSAF 2.0 draft (#498). Read-only roles see the
|
||||
//! statements but not the editor.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::BsDownload;
|
||||
@@ -15,7 +16,8 @@ use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::i18n::texts::{common, vex as tx};
|
||||
use crate::i18n::{use_lang, Lang, Text};
|
||||
use crate::infrastructure::vex::{
|
||||
fetch_target_cves, fetch_vex_export, save_cve_vex, VexFormat, VexStatementDto,
|
||||
csaf_filename, fetch_csaf_export, fetch_target_cves, fetch_vex_export, save_cve_vex, VexFormat,
|
||||
VexStatementDto,
|
||||
};
|
||||
|
||||
/// Every status, in the order the editor offers them.
|
||||
@@ -121,6 +123,7 @@ pub fn VexPanel(target_id: String) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
CsafExport { target_id: target_id.clone() }
|
||||
match &*alerts.read() {
|
||||
None => rsx! { div { class: "loading", {common::LOADING.get(lang)} } },
|
||||
Some(None) => rsx! { p { class: "target-muted", {tx::LOAD_FAILED.get(lang)} } },
|
||||
@@ -223,6 +226,49 @@ fn VexExportButton(target_id: String, format: VexFormat) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
/// The CSAF draft download: the publisher's web address, and the button.
|
||||
#[component]
|
||||
fn CsafExport(target_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
let mut namespace = use_signal(String::new);
|
||||
let mut busy = use_signal(|| false);
|
||||
rsx! {
|
||||
div { class: "vex-csaf",
|
||||
label {
|
||||
{tx::CSAF_NAMESPACE.get(lang)}
|
||||
input {
|
||||
r#type: "url",
|
||||
placeholder: "https://",
|
||||
value: "{namespace}",
|
||||
oninput: move |e| namespace.set(e.value()),
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-secondary btn-sm",
|
||||
disabled: busy(),
|
||||
onclick: move |_| {
|
||||
let id = target_id.clone();
|
||||
busy.set(true);
|
||||
spawn(async move {
|
||||
match fetch_csaf_export(id, namespace(), lang.code().to_string()).await {
|
||||
Ok(advisory) => crate::infrastructure::download::save_json(
|
||||
&advisory,
|
||||
&csaf_filename(&advisory),
|
||||
),
|
||||
Err(e) => toasts.push(ToastType::Error, format!("{}: {e}", tx::EXPORT_FAILED.get(lang))),
|
||||
}
|
||||
busy.set(false);
|
||||
});
|
||||
},
|
||||
Icon { icon: BsDownload, width: 14, height: 14 }
|
||||
{tx::EXPORT_CSAF.get(lang)}
|
||||
}
|
||||
p { class: "target-muted", {tx::CSAF_HINT.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement editor for one alert, starting from its current statement.
|
||||
/// `on_close` gets whether a statement was saved.
|
||||
#[component]
|
||||
|
||||
@@ -2282,6 +2282,21 @@ pub mod vex {
|
||||
de: "CycloneDX VEX herunterladen",
|
||||
en: "Download CycloneDX VEX",
|
||||
};
|
||||
pub const EXPORT_CSAF: Text = Text {
|
||||
de: "CSAF-Entwurf herunterladen",
|
||||
en: "Download CSAF draft",
|
||||
};
|
||||
pub const CSAF_NAMESPACE: Text = Text {
|
||||
de: "Web-Adresse des Herausgebers (für CSAF)",
|
||||
en: "Publisher web address (for CSAF)",
|
||||
};
|
||||
pub const CSAF_HINT: Text = Text {
|
||||
de: "Der CSAF-Entwurf ist als TLP:AMBER markiert. Prüfen Sie Herausgeber und \
|
||||
Aussagen, bevor Sie ihn veröffentlichen. Ohne Web-Adresse enthält er einen \
|
||||
Platzhalter.",
|
||||
en: "The CSAF draft is marked TLP:AMBER. Check the publisher and the statements \
|
||||
before you publish it. Without a web address it holds a placeholder.",
|
||||
};
|
||||
pub const EXPORT_FAILED: Text = Text {
|
||||
de: "Der VEX-Export ist fehlgeschlagen",
|
||||
en: "The VEX export failed",
|
||||
|
||||
@@ -107,6 +107,40 @@ pub async fn fetch_vex_export(
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// The CSAF 2.0 VEX advisory (a draft) of target `target_id`, as text to
|
||||
/// save. `namespace` is the publisher's web address (empty: a placeholder),
|
||||
/// `lang` the UI language the statements were written in.
|
||||
#[server]
|
||||
pub async fn fetch_csaf_export(
|
||||
target_id: String,
|
||||
namespace: String,
|
||||
lang: String,
|
||||
) -> Result<String, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/targets/{target_id}/csaf"))
|
||||
.await?
|
||||
.query(&[("namespace", namespace.trim()), ("lang", lang.as_str())])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::ok_response(resp)
|
||||
.await?
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
}
|
||||
|
||||
/// The file name of a CSAF advisory, from its tracking id (CSAF 2.0 §5.1).
|
||||
pub fn csaf_filename(advisory: &str) -> String {
|
||||
serde_json::from_str::<serde_json::Value>(advisory)
|
||||
.ok()
|
||||
.and_then(|doc| {
|
||||
doc["document"]["tracking"]["id"]
|
||||
.as_str()
|
||||
.map(compliance_core::csaf_docs::filename)
|
||||
})
|
||||
.unwrap_or_else(|| "csaf-vex.json".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -119,6 +153,13 @@ mod tests {
|
||||
assert_eq!(VexFormat::OpenVex.filename("65f0"), "vex-65f0.openvex.json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_csaf_file_is_named_after_its_tracking_id() {
|
||||
let advisory = r#"{"document":{"tracking":{"id":"pruefwerk-vex-pumps-20261006"}}}"#;
|
||||
assert_eq!(csaf_filename(advisory), "pruefwerk-vex-pumps-20261006.json");
|
||||
assert_eq!(csaf_filename("not json"), "csaf-vex.json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_leaves_out_what_is_not_given() {
|
||||
let dto = VexStatementDto {
|
||||
|
||||
+4
-1
@@ -270,7 +270,10 @@ differently:
|
||||
API: `GET /api/v1/targets/{id}/cves` lists the alerts with their statements,
|
||||
`PATCH /api/v1/cves/{id}/vex` sets one
|
||||
(`{"status": "not_affected", "justification": "…", "impact_statement": "…"}`),
|
||||
`GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx` downloads the document.
|
||||
`GET /api/v1/targets/{id}/vex?format=openvex|cyclonedx` downloads the document,
|
||||
`GET /api/v1/targets/{id}/csaf?namespace=<publisher URL>&lang=de|en` the same
|
||||
statements as a CSAF 2.0 VEX advisory (a TLP:AMBER draft; see
|
||||
[Assessing vulnerabilities](./vex-en.md#csaf-draft)).
|
||||
|
||||
## SBOM quality
|
||||
|
||||
|
||||
@@ -54,3 +54,26 @@ the vulnerability comes back, the scan withdraws its "Fixed".
|
||||
statements as OpenVEX 0.2.0 and CycloneDX 1.6. Both files are also in the
|
||||
evidence pack (`vex.openvex.json`, `vex.cdx.json`). Formats, how the terms map
|
||||
and the API: see [SBOM](./sbom.md#vex-the-status-of-each-vulnerability).
|
||||
|
||||
## CSAF draft
|
||||
|
||||
**Download CSAF draft** saves the same statements as a CSAF 2.0 VEX advisory
|
||||
(`csaf_vex`), the format manufacturers and CERTs publish vulnerabilities in.
|
||||
The draft
|
||||
|
||||
- names the target as the product and each affected component as part of it
|
||||
(with its purl);
|
||||
- carries every statement: "Affected" with your action statement as the
|
||||
remediation, "Not affected" with its justification and statement, "Under
|
||||
investigation" and "Fixed";
|
||||
- is marked as a draft (`draft`) and **TLP:AMBER**, with the note "Draft, not
|
||||
published: check publisher and statements before release.";
|
||||
- is tagged with the UI's language (`lang`).
|
||||
|
||||
The publisher is your workspace. Enter your company's web address before
|
||||
downloading (CSAF requires one); without it the document holds the
|
||||
placeholder `https://example.invalid/<workspace>`. Before publishing, check
|
||||
the publisher and the statements and set the TLP label to **WHITE** (public;
|
||||
"CLEAR" in TLP 2.0) or **GREEN**. The draft passes the CSAF schema and the
|
||||
standard's mandatory tests. It is also in the evidence pack
|
||||
(`csaf-vex.json`, with the placeholder).
|
||||
@@ -57,3 +57,27 @@ Aussagen des Prüfobjekts als OpenVEX 0.2.0 bzw. CycloneDX 1.6. Beide Dateien
|
||||
liegen auch im Nachweispaket (`vex.openvex.json`, `vex.cdx.json`). Formate,
|
||||
Zuordnung der Begriffe und API: siehe
|
||||
[Stückliste (SBOM)](./sbom.md#vex-the-status-of-each-vulnerability).
|
||||
|
||||
## CSAF-Entwurf
|
||||
|
||||
**CSAF-Entwurf herunterladen** speichert dieselben Aussagen als CSAF 2.0
|
||||
VEX-Advisory (`csaf_vex`), dem Format, in dem Hersteller und CERTs
|
||||
Schwachstellen veröffentlichen. Der Entwurf
|
||||
|
||||
- nennt das Prüfobjekt als Produkt und jede betroffene Komponente als Teil
|
||||
davon (mit purl);
|
||||
- übernimmt jede Aussage: „Betroffen“ mit Ihrer Handlungsanweisung als
|
||||
Abhilfe, „Nicht betroffen“ mit Begründung und Freitext, „In Prüfung“ und
|
||||
„Behoben“;
|
||||
- ist als Entwurf (`draft`) und **TLP:AMBER** markiert und trägt den Hinweis
|
||||
„Draft, not published: check publisher and statements before release.“;
|
||||
- ist in der Sprache der Oberfläche ausgezeichnet (`lang`).
|
||||
|
||||
Herausgeber ist Ihr Arbeitsbereich. Tragen Sie vor dem Herunterladen die
|
||||
Web-Adresse Ihres Unternehmens ein (CSAF verlangt sie); ohne sie steht ein
|
||||
Platzhalter `https://example.invalid/<Arbeitsbereich>` im Dokument. Vor der
|
||||
Veröffentlichung prüfen Sie Herausgeber und Aussagen und setzen die
|
||||
TLP-Kennzeichnung auf **WHITE** (öffentlich, in TLP 2.0 „CLEAR“) oder
|
||||
**GREEN**. Der Entwurf besteht das CSAF-Schema und die Pflichttests des
|
||||
CSAF-Standards. Er liegt auch im Nachweispaket (`csaf-vex.json`, mit
|
||||
Platzhalter).
|
||||
@@ -27,6 +27,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #494 | DevSkim: .NET SAST without a build (C#, VB.NET, .config) |
|
||||
| #498 (2/4) | VEX editor and downloads on the target page |
|
||||
| #508 (A) | CycloneDX 1.6 SBOM with BSI TR-03183-2 properties |
|
||||
| #498 (3/4) | CSAF 2.0 VEX advisory draft |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -578,6 +579,34 @@ check 19) and one with a Python project.
|
||||
- **[visible]** SBOM downloads and evidence packs are CycloneDX 1.6 with the
|
||||
new fields, and the SBOM quality score rises on the next rescan.
|
||||
|
||||
### 28. #498 part 3: CSAF 2.0 VEX draft
|
||||
|
||||
Use the target of check 26, with statements of every status.
|
||||
|
||||
- **Do:** on the target page, **Schwachstellen und VEX**: leave the web
|
||||
address empty, **CSAF-Entwurf herunterladen**. **Expect:** a file
|
||||
`pruefwerk-vex-<target>-<date>.json`, with:
|
||||
- `document.category` `csaf_vex`, `tracking.status` `draft`, TLP `AMBER`,
|
||||
`lang` `de`, the draft note;
|
||||
- `publisher.namespace` `https://example.invalid/<workspace>`;
|
||||
- the target as product and each component `default_component_of` it;
|
||||
- each statement under its status: "Betroffen" in `known_affected` with a
|
||||
remediation (`vendor_fix` when a fixed version is known), "Nicht
|
||||
betroffen" in `known_not_affected` with its flag and/or impact threat;
|
||||
- one vulnerability per CVE, even when a GHSA alert names the same CVE.
|
||||
- **Do:** enter `https://example.com`, switch to English, download again.
|
||||
**Expect:** that namespace and `lang` `en`. Enter `example.com` (no
|
||||
scheme). **Expect:** an error toast (400).
|
||||
- **Do:** validate the file (e.g. the BSI CSAF validator at
|
||||
`https://secvisogram.github.io/` or gocsaf `csaf_validator`). **Expect:**
|
||||
no errors; warnings only for the optional tests (key order, missing
|
||||
canonical URL, CVSS score).
|
||||
- **Do:** download the evidence pack. **Expect:** `csaf-vex.json` with the
|
||||
placeholder namespace.
|
||||
- **Docs:** `/guide/vex` and `/guide/vex-en` have a CSAF section.
|
||||
- **[visible]** a new download and web-address field in the VEX card; the
|
||||
evidence pack gains `csaf-vex.json`.
|
||||
|
||||
## After the pass
|
||||
|
||||
- The nightly job on `main` is green with the new mobile targets.
|
||||
|
||||
Reference in new issue
Block a user