Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
249ef873c5 |
No files matched your search
@@ -17,7 +17,7 @@ use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
|||||||
use compliance_core::csaf_ingest::Advisory;
|
use compliance_core::csaf_ingest::Advisory;
|
||||||
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
use compliance_core::device_check::{DeviceCheck, DeviceLookup};
|
||||||
use compliance_core::models::plc_device::normalised_order_number;
|
use compliance_core::models::plc_device::normalised_order_number;
|
||||||
use compliance_core::models::{PlcDevice, TargetDevice};
|
use compliance_core::models::PlcDevice;
|
||||||
use compliance_core::tenant_ctx::TenantCtx;
|
use compliance_core::tenant_ctx::TenantCtx;
|
||||||
|
|
||||||
/// The provider whose advisories name devices by order number.
|
/// The provider whose advisories name devices by order number.
|
||||||
@@ -44,14 +44,10 @@ async fn advisories_naming(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Each of `devices` against `advisories`.
|
/// Each of `devices` against `advisories`.
|
||||||
/// An exported device keeps the export it comes from (#1090, #1097).
|
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||||
fn checks(devices: Vec<TargetDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
|
||||||
devices
|
devices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|d| DeviceCheck {
|
.map(|device| DeviceCheck::new(device, advisories))
|
||||||
exported_in: d.exported_in,
|
|
||||||
..DeviceCheck::new(d.device, advisories)
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,13 +81,10 @@ pub async fn list_devices(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
.ok_or(StatusCode::NOT_FOUND)?;
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
// Entered and exported alike (#1090, #1097): a TIA export's devices are
|
let mut order_numbers: Vec<String> = target
|
||||||
// listed under their names in the project, saying which export they are
|
.devices
|
||||||
// from, so a client edits only the entered ones.
|
|
||||||
let target_devices = target.target_devices();
|
|
||||||
let mut order_numbers: Vec<String> = target_devices
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|d| d.device.order_number.clone())
|
.map(|d| d.order_number.clone())
|
||||||
.collect();
|
.collect();
|
||||||
order_numbers.sort();
|
order_numbers.sort();
|
||||||
order_numbers.dedup();
|
order_numbers.dedup();
|
||||||
@@ -100,7 +93,7 @@ pub async fn list_devices(
|
|||||||
} else {
|
} else {
|
||||||
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
||||||
};
|
};
|
||||||
let devices = checks(target_devices, &advisories);
|
let devices = checks(target.devices, &advisories);
|
||||||
Ok(Json(ApiResponse {
|
Ok(Json(ApiResponse {
|
||||||
total: Some(devices.len() as u64),
|
total: Some(devices.len() as u64),
|
||||||
data: devices,
|
data: devices,
|
||||||
@@ -205,15 +198,9 @@ mod tests {
|
|||||||
assert_eq!(advisories.len(), 1);
|
assert_eq!(advisories.len(), 1);
|
||||||
let devices = checks(
|
let devices = checks(
|
||||||
vec![
|
vec![
|
||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None)
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
||||||
.unwrap()
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
.into(),
|
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None)
|
|
||||||
.unwrap()
|
|
||||||
.into(),
|
|
||||||
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None)
|
|
||||||
.unwrap()
|
|
||||||
.into(),
|
|
||||||
],
|
],
|
||||||
&advisories,
|
&advisories,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -968,10 +968,7 @@ pub struct UploadArtifactForm {
|
|||||||
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
|
/// (a supplier's CycloneDX or SPDX 2 SBOM of a bought-in component).
|
||||||
#[schema(example = "source_archive")]
|
#[schema(example = "source_archive")]
|
||||||
kind: String,
|
kind: String,
|
||||||
/// The PLC project's format, for a PLC project: `plcopen_xml`,
|
/// The PLC project's format, for a PLC project.
|
||||||
/// `structured_text`, `project_archive` or `tia_export` (a TIA
|
|
||||||
/// connector's export, whose manifest is read on upload).
|
|
||||||
#[schema(example = "tia_export")]
|
|
||||||
plc_format: Option<String>,
|
plc_format: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1001,7 +998,7 @@ pub struct UploadArtifactForm {
|
|||||||
(status = 400, description = "Not an id, or a missing or unknown field"),
|
(status = 400, description = "Not an id, or a missing or unknown field"),
|
||||||
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
(status = 413, description = "The file is too large (a supplier SBOM: over 20 MiB)"),
|
||||||
(status = 415, description = "An archive format that cannot be unpacked"),
|
(status = 415, description = "An archive format that cannot be unpacked"),
|
||||||
(status = 422, description = "A supplier SBOM or TIA export that cannot be read; `error` says why, `code` names it"),
|
(status = 422, description = "A supplier SBOM that cannot be read; `error` says why"),
|
||||||
(status = 401, description = "No valid bearer token"),
|
(status = 401, description = "No valid bearer token"),
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
@@ -1087,15 +1084,13 @@ pub(super) struct AttachedUpload {
|
|||||||
/// refused when it cannot be, its summary is kept with it, and it replaces the
|
/// refused when it cannot be, its summary is kept with it, and it replaces the
|
||||||
/// target's previous one. Any other archive is checked for a format that can
|
/// target's previous one. Any other archive is checked for a format that can
|
||||||
/// be unpacked and for encryption. The file is deleted unless the artifact
|
/// be unpacked and for encryption. The file is deleted unless the artifact
|
||||||
/// references it. A TIA export's manifest is read (#1090), its devices are
|
/// references it.
|
||||||
/// kept with it, and it replaces the target's previous export.
|
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
|
/// 400 for a kind that is not uploaded as a file, 415 for an archive that
|
||||||
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
|
/// cannot be unpacked, the supplier SBOM's refusal ([`SupplierSbomSummary::of`]),
|
||||||
/// 422 with its code for a TIA export that cannot be read, 500 when the
|
/// 500 when the file or the database fails.
|
||||||
/// file or the database fails.
|
|
||||||
pub(super) async fn attach_upload(
|
pub(super) async fn attach_upload(
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
target: &OnboardedTarget,
|
target: &OnboardedTarget,
|
||||||
@@ -1128,22 +1123,6 @@ pub(super) async fn attach_upload(
|
|||||||
let read = SupplierSbomSummary::of(read)?;
|
let read = SupplierSbomSummary::of(read)?;
|
||||||
artifact.detected.extend(read.facts());
|
artifact.detected.extend(read.facts());
|
||||||
summary = Some(read);
|
summary = Some(read);
|
||||||
} else if is_tia_export(&artifact) {
|
|
||||||
// A connector's export (#1090): its manifest is read now, so a bad
|
|
||||||
// one is refused while the connector can still say so.
|
|
||||||
let path = upload.path.clone();
|
|
||||||
let manifest =
|
|
||||||
tokio::task::spawn_blocking(move || crate::pipeline::plc::tia::read_manifest(&path))
|
|
||||||
.await
|
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
|
||||||
.map_err(|e| UploadRefusal {
|
|
||||||
status: StatusCode::UNPROCESSABLE_ENTITY,
|
|
||||||
reason: Some((e.to_string(), e.code())),
|
|
||||||
})?;
|
|
||||||
artifact.detected.extend(tia_facts(&manifest));
|
|
||||||
if let Some(plc) = artifact.plc.as_mut() {
|
|
||||||
plc.devices = manifest.devices().matched;
|
|
||||||
}
|
|
||||||
} else if kind != ArtifactKind::FirmwareImage {
|
} else if kind != ArtifactKind::FirmwareImage {
|
||||||
match archive_check(upload.path.clone()).await? {
|
match archive_check(upload.path.clone()).await? {
|
||||||
// 7z and rar are never unpacked: say so now, not after a scan.
|
// 7z and rar are never unpacked: say so now, not after a scan.
|
||||||
@@ -1169,23 +1148,7 @@ pub(super) async fn attach_upload(
|
|||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
upload.keep();
|
upload.keep();
|
||||||
if kind == ArtifactKind::SupplierSbom {
|
if kind == ArtifactKind::SupplierSbom {
|
||||||
replace_earlier(
|
replace_supplier_sboms(db, oid, &artifact_id, &target.artifacts).await;
|
||||||
db,
|
|
||||||
oid,
|
|
||||||
&artifact_id,
|
|
||||||
&target.artifacts,
|
|
||||||
Replaced::SupplierSbom,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
} else if is_tia_export(&artifact) {
|
|
||||||
replace_earlier(
|
|
||||||
db,
|
|
||||||
oid,
|
|
||||||
&artifact_id,
|
|
||||||
&target.artifacts,
|
|
||||||
Replaced::TiaExport,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(AttachedUpload {
|
Ok(AttachedUpload {
|
||||||
@@ -1194,82 +1157,35 @@ pub(super) async fn attach_upload(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether `artifact` is a TIA connector's export (#1090).
|
/// Remove the target's supplier SBOMs other than the one just uploaded
|
||||||
fn is_tia_export(artifact: &compliance_core::models::Artifact) -> bool {
|
/// (`kept`): a new version replaces the one before it (#1025), so a scan never
|
||||||
artifact.kind == ArtifactKind::PlcProject
|
/// reads two versions as one. Their files go too, once nothing references
|
||||||
&& artifact.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport)
|
/// them. Best-effort, after the new one is stored: if this fails, the next
|
||||||
}
|
/// scan reads both versions, and nothing is lost.
|
||||||
|
async fn replace_supplier_sboms(
|
||||||
/// What a TIA export's manifest says, as the artifact's facts.
|
|
||||||
fn tia_facts(manifest: &compliance_core::models::TiaManifest) -> [DetectedFact; 4] {
|
|
||||||
[
|
|
||||||
DetectedFact::new("tia_version", manifest.tia_version.as_str(), "upload"),
|
|
||||||
DetectedFact::new("tia_project", manifest.project.name.as_str(), "upload"),
|
|
||||||
DetectedFact::new("tia_devices", manifest.devices.len().to_string(), "upload"),
|
|
||||||
DetectedFact::new("tia_blocks", manifest.blocks.len().to_string(), "upload"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The kinds of upload a new one replaces.
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
enum Replaced {
|
|
||||||
/// A supplier's SBOM: a new version replaces the one before it (#1025).
|
|
||||||
SupplierSbom,
|
|
||||||
/// A TIA export: a new export of the project replaces the last (#1090).
|
|
||||||
TiaExport,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Replaced {
|
|
||||||
/// The artifacts of this kind, as a Mongo filter.
|
|
||||||
fn filter(self) -> mongodb::bson::Document {
|
|
||||||
match self {
|
|
||||||
Self::SupplierSbom => doc! { "kind": "supplier_sbom" },
|
|
||||||
Self::TiaExport => doc! { "kind": "plc_project", "plc.format": "tia_export" },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `artifact` is of this kind.
|
|
||||||
fn matches(self, artifact: &compliance_core::models::Artifact) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::SupplierSbom => artifact.kind == ArtifactKind::SupplierSbom,
|
|
||||||
Self::TiaExport => is_tia_export(artifact),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove the target's uploads of kind `what` other than the one just
|
|
||||||
/// uploaded (`kept`), so a scan never reads two versions as one: a new
|
|
||||||
/// supplier SBOM replaces the one before it (#1025), a new TIA export the
|
|
||||||
/// last (#1090). Their files go too, once nothing references them.
|
|
||||||
/// Best-effort, after the new one is stored: if this fails, the next scan
|
|
||||||
/// reads both, and nothing is lost.
|
|
||||||
async fn replace_earlier(
|
|
||||||
db: &crate::database::Database,
|
db: &crate::database::Database,
|
||||||
target: ObjectId,
|
target: ObjectId,
|
||||||
kept: &str,
|
kept: &str,
|
||||||
before: &[compliance_core::models::Artifact],
|
before: &[compliance_core::models::Artifact],
|
||||||
what: Replaced,
|
|
||||||
) {
|
) {
|
||||||
let mut earlier = what.filter();
|
|
||||||
earlier.insert("id", doc! { "$ne": kept });
|
|
||||||
let pulled = db
|
let pulled = db
|
||||||
.onboarded_targets()
|
.onboarded_targets()
|
||||||
.update_one(
|
.update_one(
|
||||||
doc! { "_id": target },
|
doc! { "_id": target },
|
||||||
doc! { "$pull": { "artifacts": earlier } },
|
doc! { "$pull": { "artifacts": { "kind": "supplier_sbom", "id": { "$ne": kept } } } },
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
if let Err(e) = pulled {
|
if let Err(e) = pulled {
|
||||||
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload not removed");
|
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM not removed");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for old in before
|
for old in before
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|a| what.matches(a) && a.id != kept)
|
.filter(|a| a.kind == ArtifactKind::SupplierSbom && a.id != kept)
|
||||||
.filter_map(|a| a.stored_path.as_deref())
|
.filter_map(|a| a.stored_path.as_deref())
|
||||||
{
|
{
|
||||||
if let Err(e) = std::fs::remove_file(old) {
|
if let Err(e) = std::fs::remove_file(old) {
|
||||||
tracing::warn!(target_id = %target, ?what, error = %e, "replaced upload's file left");
|
tracing::warn!(target_id = %target, error = %e, "replaced supplier SBOM file left");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,12 +75,6 @@ pub const KEY_SCOPES: &[(Method, &str, &str)] = &[
|
|||||||
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
(Method::GET, "/api/v1/licenses/policy", SBOM_READ),
|
||||||
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
(Method::GET, "/api/v1/scan-runs", SCANS_READ),
|
||||||
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/targets/{id}/scan", SCANS_RUN),
|
||||||
// A TIA connector uploads its export (#1090) and starts a scan.
|
|
||||||
(
|
|
||||||
Method::POST,
|
|
||||||
"/api/v1/targets/{id}/artifacts/upload",
|
|
||||||
UPLOADS_WRITE,
|
|
||||||
),
|
|
||||||
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
(Method::POST, "/api/v1/dast/targets/{id}/scan", SCANS_RUN),
|
||||||
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/targets/{id}/enisa", ENISA_READ),
|
||||||
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
(Method::GET, "/api/v1/cves/{id}/enisa", ENISA_READ),
|
||||||
@@ -91,7 +85,6 @@ const FINDINGS_WRITE: &str = "pruefwerk:findings.write";
|
|||||||
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
const SBOM_READ: &str = "pruefwerk:sbom.read";
|
||||||
const SCANS_READ: &str = "pruefwerk:scans.read";
|
const SCANS_READ: &str = "pruefwerk:scans.read";
|
||||||
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
const SCANS_RUN: &str = "pruefwerk:scans.run";
|
||||||
const UPLOADS_WRITE: &str = "pruefwerk:uploads.write";
|
|
||||||
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
const ENISA_READ: &str = "pruefwerk:enisa.read";
|
||||||
|
|
||||||
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
/// What a legacy key (issued before scopes, no scopes of its own) may do:
|
||||||
|
|||||||
@@ -341,7 +341,6 @@ const ALL_SCOPES: &[&str] = &[
|
|||||||
"pruefwerk:sbom.read",
|
"pruefwerk:sbom.read",
|
||||||
"pruefwerk:scans.read",
|
"pruefwerk:scans.read",
|
||||||
"pruefwerk:scans.run",
|
"pruefwerk:scans.run",
|
||||||
"pruefwerk:uploads.write",
|
|
||||||
"pruefwerk:enisa.read",
|
"pruefwerk:enisa.read",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -125,7 +125,6 @@ pub async fn require_entitlement(
|
|||||||
// carry no tenant context here): the registry also says whether this
|
// carry no tenant context here): the registry also says whether this
|
||||||
// member is blocked in the tenant.
|
// member is blocked in the tenant.
|
||||||
let user = Some(ctx.user_id.as_str()).filter(|u| !u.is_empty());
|
let user = Some(ctx.user_id.as_str()).filter(|u| !u.is_empty());
|
||||||
let open = open_when_not_entitled(&request);
|
|
||||||
match registry.check_entitlement(&ctx.tenant_id, None, user).await {
|
match registry.check_entitlement(&ctx.tenant_id, None, user).await {
|
||||||
Ok(check) if check.allowed => {
|
Ok(check) if check.allowed => {
|
||||||
let mut ctx = ctx;
|
let mut ctx = ctx;
|
||||||
@@ -138,15 +137,6 @@ pub async fn require_entitlement(
|
|||||||
request.extensions_mut().insert(ctx);
|
request.extensions_mut().insert(ctx);
|
||||||
next.run(request).await
|
next.run(request).await
|
||||||
}
|
}
|
||||||
// The registry knows the workspace but refuses it (expired, blocked):
|
|
||||||
// its branding is still read, so the screen that says so keeps the
|
|
||||||
// workspace's frame and logo. Read-only, and nothing else.
|
|
||||||
Ok(_) if open => {
|
|
||||||
let mut ctx = ctx;
|
|
||||||
ctx.status = TenantStatus::Restricted;
|
|
||||||
request.extensions_mut().insert(ctx);
|
|
||||||
next.run(request).await
|
|
||||||
}
|
|
||||||
Ok(check) if check.member_blocked() => (
|
Ok(check) if check.member_blocked() => (
|
||||||
StatusCode::FORBIDDEN,
|
StatusCode::FORBIDDEN,
|
||||||
Json(serde_json::json!({
|
Json(serde_json::json!({
|
||||||
@@ -176,17 +166,6 @@ pub async fn require_entitlement(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The routes a workspace the registry refuses still reads: its branding
|
|
||||||
/// (#1087), so a lockout screen keeps its frame and logo. GET only; the
|
|
||||||
/// acknowledgement and everything else stay refused.
|
|
||||||
const OPEN_WHEN_NOT_ENTITLED: [&str; 2] = ["/api/v1/branding", "/api/v1/branding/logo"];
|
|
||||||
|
|
||||||
/// Whether `request` reads one of [`OPEN_WHEN_NOT_ENTITLED`].
|
|
||||||
fn open_when_not_entitled(request: &Request) -> bool {
|
|
||||||
request.method() == axum::http::Method::GET
|
|
||||||
&& OPEN_WHEN_NOT_ENTITLED.contains(&request.uri().path())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 503 when the registry cannot answer: access is never widened on doubt.
|
/// 503 when the registry cannot answer: access is never widened on doubt.
|
||||||
fn entitlement_unavailable() -> Response {
|
fn entitlement_unavailable() -> Response {
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -526,7 +526,7 @@ mod tests {
|
|||||||
|
|
||||||
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
fn device(order_number: &str, firmware: &str) -> SbomEntry {
|
||||||
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
let device = compliance_core::models::PlcDevice::new(order_number, firmware, None).unwrap();
|
||||||
crate::pipeline::sbom::devices::entries(&[device.into()], "t").remove(0)
|
crate::pipeline::sbom::devices::entries(&[device], "t").remove(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1930,10 +1930,9 @@ impl PipelineOrchestrator {
|
|||||||
// Siemens' advisories as with a project.
|
// Siemens' advisories as with a project.
|
||||||
// Also when the last one was removed, so its components and
|
// Also when the last one was removed, so its components and
|
||||||
// alerts go with it.
|
// alerts go with it.
|
||||||
let target_devices = target.target_devices();
|
if target.target_type == TargetType::PlcSps || !target.devices.is_empty() {
|
||||||
if target.target_type == TargetType::PlcSps || !target_devices.is_empty() {
|
|
||||||
let devices =
|
let devices =
|
||||||
crate::pipeline::sbom::devices::entries(&target_devices, &target_id);
|
crate::pipeline::sbom::devices::entries(&target.devices, &target_id);
|
||||||
if let Err(e) = self
|
if let Err(e) = self
|
||||||
.persist_control_app_sbom(target, &target_id, scan_run_id, devices)
|
.persist_control_app_sbom(target, &target_id, scan_run_id, devices)
|
||||||
.await
|
.await
|
||||||
@@ -2008,12 +2007,6 @@ impl PipelineOrchestrator {
|
|||||||
// first, as in a code scan (#820, #825).
|
// first, as in a code scan (#820, #825).
|
||||||
let mut left_out = LeftOut::default();
|
let mut left_out = LeftOut::default();
|
||||||
for a in &sources {
|
for a in &sources {
|
||||||
// A TIA export's block code is not read yet (#1093): the run says
|
|
||||||
// what it holds instead of finding nothing in it.
|
|
||||||
if a.plc.as_ref().map(|p| p.format) == Some(PlcFormat::TiaExport) {
|
|
||||||
self.note_tia_export(scan_run_id, a).await;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
let Some(path) = ingest_set.get(&a.id).and_then(|ia| ia.working_path.clone()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -2159,7 +2152,7 @@ impl PipelineOrchestrator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
all_sbom.extend(crate::pipeline::sbom::devices::entries(
|
all_sbom.extend(crate::pipeline::sbom::devices::entries(
|
||||||
&target.target_devices(),
|
&target.devices,
|
||||||
target_id,
|
target_id,
|
||||||
));
|
));
|
||||||
if !all_sbom.is_empty() {
|
if !all_sbom.is_empty() {
|
||||||
@@ -2173,82 +2166,6 @@ impl PipelineOrchestrator {
|
|||||||
Ok(new_count)
|
Ok(new_count)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a TIA export holds that this run does not analyse (#1090): its
|
|
||||||
/// blocks' code (until #1093), its know-how-protected blocks, and the
|
|
||||||
/// devices it names that cannot be matched against advisories. Its
|
|
||||||
/// matchable devices are in the SBOM through
|
|
||||||
/// [`compliance_core::models::OnboardedTarget::target_devices`].
|
|
||||||
async fn note_tia_export(&self, scan_run_id: &str, export: &Artifact) {
|
|
||||||
let name = export
|
|
||||||
.display_name
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| export.source_ref.clone());
|
|
||||||
let read = export
|
|
||||||
.stored_path
|
|
||||||
.as_deref()
|
|
||||||
.ok_or(compliance_core::models::TiaBundleError::NoManifest)
|
|
||||||
.and_then(|p| crate::pipeline::plc::tia::read_manifest(std::path::Path::new(p)));
|
|
||||||
let manifest = match read {
|
|
||||||
Ok(manifest) => manifest,
|
|
||||||
Err(e) => {
|
|
||||||
// Read at upload, so only a file lost since gets here.
|
|
||||||
tracing::warn!(scan_run_id, export = %name, error = %e, "TIA export not readable");
|
|
||||||
self.skip_stage(
|
|
||||||
scan_run_id,
|
|
||||||
SkippedStage::new(
|
|
||||||
"plc_tia_export",
|
|
||||||
SkipCode::ArtifactNotIngested,
|
|
||||||
format!("{name} could not be read: {e}"),
|
|
||||||
)
|
|
||||||
.about(name),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(blocks) = crate::pipeline::plc::tia::blocks_not_analysed(&manifest) {
|
|
||||||
self.skip_stage(
|
|
||||||
scan_run_id,
|
|
||||||
SkippedStage::new(
|
|
||||||
"plc_tia_blocks",
|
|
||||||
SkipCode::PlcBlocksNotAnalysed,
|
|
||||||
format!("the code of the blocks in {name} is not analysed yet: {blocks}"),
|
|
||||||
)
|
|
||||||
.about(blocks),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
let protected = component_list(&manifest.protected_blocks());
|
|
||||||
if !protected.is_empty() {
|
|
||||||
self.skip_stage(
|
|
||||||
scan_run_id,
|
|
||||||
SkippedStage::new(
|
|
||||||
"plc_protected_blocks",
|
|
||||||
SkipCode::ProtectedBlocks,
|
|
||||||
format!("know-how-protected blocks in {name} cannot be analysed: {protected}"),
|
|
||||||
)
|
|
||||||
.about(protected),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
let unmatched = component_list(&manifest.devices().unmatched);
|
|
||||||
if !unmatched.is_empty() {
|
|
||||||
self.skip_stage(
|
|
||||||
scan_run_id,
|
|
||||||
SkippedStage::new(
|
|
||||||
"plc_devices_unmatched",
|
|
||||||
SkipCode::DevicesUnmatched,
|
|
||||||
format!(
|
|
||||||
"devices in {name} without a Siemens order number or firmware are not \
|
|
||||||
matched against advisories: {unmatched}"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.about(unmatched),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Provision-and-test (#183): instantiate the target's control logic on an
|
/// Provision-and-test (#183): instantiate the target's control logic on an
|
||||||
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
/// ephemeral soft-PLC (OpenPLC), start it, probe the provisioned Modbus
|
||||||
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
/// endpoint, and tear the instance down. Used when a PLC/SPS target has the
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ pub mod parser;
|
|||||||
pub mod plcopen;
|
pub mod plcopen;
|
||||||
pub mod rules;
|
pub mod rules;
|
||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
pub(crate) mod tia;
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|||||||
@@ -1,152 +0,0 @@
|
|||||||
//! Reading a TIA export (#1090): the zip a TIA Portal connector uploads, with
|
|
||||||
//! its [`TiaManifest`] at the root. Only the manifest is read here; the block
|
|
||||||
//! exports beside it are unpacked by ingest like any PLC project.
|
|
||||||
|
|
||||||
use std::io::Read;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use compliance_core::models::tia_export::{MANIFEST_NAME, MAX_MANIFEST_BYTES};
|
|
||||||
use compliance_core::models::{TiaBundleError, TiaManifest};
|
|
||||||
|
|
||||||
/// Read the manifest of the TIA export at `bundle`.
|
|
||||||
///
|
|
||||||
/// The manifest is read up to [`MAX_MANIFEST_BYTES`], whatever size the zip
|
|
||||||
/// declares for it, so a forged entry cannot make this read more.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
///
|
|
||||||
/// [`TiaBundleError::NotZip`] when `bundle` is not a readable zip,
|
|
||||||
/// [`TiaBundleError::NoManifest`] without a `manifest.json` at its root, and
|
|
||||||
/// [`TiaManifest::parse`]'s refusals.
|
|
||||||
pub(crate) fn read_manifest(bundle: &Path) -> Result<TiaManifest, TiaBundleError> {
|
|
||||||
let file = std::fs::File::open(bundle).map_err(|_| TiaBundleError::NotZip)?;
|
|
||||||
let mut zip = zip::ZipArchive::new(file).map_err(|_| TiaBundleError::NotZip)?;
|
|
||||||
let entry = match zip.by_name(MANIFEST_NAME) {
|
|
||||||
Ok(entry) => entry,
|
|
||||||
Err(zip::result::ZipError::FileNotFound) => return Err(TiaBundleError::NoManifest),
|
|
||||||
Err(e) => return Err(TiaBundleError::ManifestInvalid(e.to_string())),
|
|
||||||
};
|
|
||||||
let mut json = Vec::new();
|
|
||||||
// One byte more than allowed, so an oversized manifest is told apart from
|
|
||||||
// one exactly at the limit.
|
|
||||||
entry
|
|
||||||
.take(MAX_MANIFEST_BYTES + 1)
|
|
||||||
.read_to_end(&mut json)
|
|
||||||
.map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))?;
|
|
||||||
TiaManifest::parse(&json)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The blocks of `manifest` whose code is analysed by no stage yet (all
|
|
||||||
/// readable ones, until #1093): how many, and in which languages, as a run
|
|
||||||
/// note's subject (`12 (FBD, LAD, SCL)`). `None` when there are none.
|
|
||||||
pub(crate) fn blocks_not_analysed(manifest: &TiaManifest) -> Option<String> {
|
|
||||||
let readable: Vec<_> = manifest.blocks.iter().filter(|b| !b.protected).collect();
|
|
||||||
if readable.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let languages: std::collections::BTreeSet<String> = readable
|
|
||||||
.iter()
|
|
||||||
.filter_map(|b| b.language.as_deref())
|
|
||||||
.map(str::to_ascii_uppercase)
|
|
||||||
.collect();
|
|
||||||
let languages = languages.into_iter().collect::<Vec<_>>().join(", ");
|
|
||||||
Some(if languages.is_empty() {
|
|
||||||
readable.len().to_string()
|
|
||||||
} else {
|
|
||||||
format!("{} ({languages})", readable.len())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
pub(crate) mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::io::Write;
|
|
||||||
|
|
||||||
/// A fresh directory for one test's files.
|
|
||||||
pub(crate) fn scratch() -> std::path::PathBuf {
|
|
||||||
let dir = std::env::temp_dir().join(format!("tia-{}", uuid::Uuid::new_v4()));
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A TIA export zip with `files` (name, content) in `dir`.
|
|
||||||
pub(crate) fn bundle(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
|
|
||||||
let path = dir.join("linie1.tia-export.zip");
|
|
||||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap());
|
|
||||||
for (name, content) in files {
|
|
||||||
zip.start_file(*name, zip::write::SimpleFileOptions::default())
|
|
||||||
.unwrap();
|
|
||||||
zip.write_all(content).unwrap();
|
|
||||||
}
|
|
||||||
zip.finish().unwrap();
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A manifest with one CPU, one GSD device and three blocks, one of them
|
|
||||||
/// protected.
|
|
||||||
pub(crate) const MANIFEST: &str = r#"{
|
|
||||||
"bundle_version": 1,
|
|
||||||
"tia_version": "V20",
|
|
||||||
"project": {"name": "Linie 1"},
|
|
||||||
"devices": [
|
|
||||||
{"name": "PLC_1", "role": "cpu",
|
|
||||||
"type_identifier": "OrderNumber:6ES7 511-1AK02-0AB0/V2.9"},
|
|
||||||
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"}
|
|
||||||
],
|
|
||||||
"blocks": [
|
|
||||||
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
|
||||||
"file": "blocks/PLC_1/Main.xml"},
|
|
||||||
{"device": "PLC_1", "name": "Pumpe", "kind": "fb", "language": "scl",
|
|
||||||
"file": "blocks/PLC_1/Pumpe.scl"},
|
|
||||||
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_manifest_is_read_from_the_root_of_the_zip() {
|
|
||||||
let dir = scratch();
|
|
||||||
let path = bundle(
|
|
||||||
&dir,
|
|
||||||
&[
|
|
||||||
("manifest.json", MANIFEST.as_bytes()),
|
|
||||||
("blocks/PLC_1/Main.xml", b"<Document/>"),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
let manifest = read_manifest(&path).unwrap();
|
|
||||||
assert_eq!(manifest.project.name, "Linie 1");
|
|
||||||
assert_eq!(
|
|
||||||
blocks_not_analysed(&manifest).as_deref(),
|
|
||||||
Some("2 (LAD, SCL)")
|
|
||||||
);
|
|
||||||
assert_eq!(manifest.protected_blocks(), ["PLC_1/FB_42"]);
|
|
||||||
std::fs::remove_dir_all(&dir).ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_bundle_that_is_not_one_is_refused_with_its_reason() {
|
|
||||||
let dir = scratch();
|
|
||||||
let not_zip = dir.join("x.zip");
|
|
||||||
std::fs::write(¬_zip, b"plain text").unwrap();
|
|
||||||
assert_eq!(read_manifest(¬_zip), Err(TiaBundleError::NotZip));
|
|
||||||
let nested = bundle(&dir, &[("export/manifest.json", MANIFEST.as_bytes())]);
|
|
||||||
assert_eq!(read_manifest(&nested), Err(TiaBundleError::NoManifest));
|
|
||||||
let huge = vec![b' '; MAX_MANIFEST_BYTES as usize + 10];
|
|
||||||
let oversized = bundle(&dir, &[("manifest.json", &huge)]);
|
|
||||||
assert_eq!(
|
|
||||||
read_manifest(&oversized),
|
|
||||||
Err(TiaBundleError::ManifestTooLarge)
|
|
||||||
);
|
|
||||||
std::fs::remove_dir_all(&dir).ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_protected_blocks_leave_nothing_unanalysed() {
|
|
||||||
let mut manifest = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
|
||||||
manifest.blocks.retain(|b| b.protected);
|
|
||||||
assert_eq!(blocks_not_analysed(&manifest), None);
|
|
||||||
manifest.blocks[0].protected = false;
|
|
||||||
manifest.blocks[0].language = None;
|
|
||||||
assert_eq!(blocks_not_analysed(&manifest).as_deref(), Some("1"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -65,9 +65,8 @@ pub struct RepoView {
|
|||||||
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
pub supplier_sboms: Vec<(std::path::PathBuf, String)>,
|
||||||
/// Who supplies the component, for one bought in (#1025).
|
/// Who supplies the component, for one bought in (#1025).
|
||||||
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
pub supplier: Option<compliance_core::models::SupplierComponent>,
|
||||||
/// The Siemens controllers the target runs on (SPS item 4a): entered,
|
/// The Siemens controllers the target runs on (SPS item 4a).
|
||||||
/// and declared by its TIA exports (#1090).
|
pub devices: Vec<compliance_core::models::PlcDevice>,
|
||||||
pub devices: Vec<compliance_core::models::TargetDevice>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RepoView {
|
impl RepoView {
|
||||||
@@ -105,7 +104,7 @@ impl RepoView {
|
|||||||
build_outputs: Vec::new(),
|
build_outputs: Vec::new(),
|
||||||
supplier_sboms: Vec::new(),
|
supplier_sboms: Vec::new(),
|
||||||
supplier: target.supplier.clone(),
|
supplier: target.supplier.clone(),
|
||||||
devices: target.target_devices(),
|
devices: target.devices.clone(),
|
||||||
};
|
};
|
||||||
if let Some(git) = &code.git {
|
if let Some(git) = &code.git {
|
||||||
view.default_branch = git.default_branch.clone();
|
view.default_branch = git.default_branch.clone();
|
||||||
|
|||||||
@@ -1,32 +1,23 @@
|
|||||||
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
|
//! The Siemens controllers a target runs on ([`PlcDevice`], SPS item 4a) as
|
||||||
//! SBOM entries: one per device, named and versioned as the customer
|
//! SBOM entries: one per device, named and versioned as the customer
|
||||||
//! entered it or a TIA export declares it (#1090), with the order number the
|
//! entered it, with the order number the vendor's CSAF advisories name it by
|
||||||
//! vendor's CSAF advisories name it by (matched in
|
//! (matched in [`crate::pipeline::csaf_match`]).
|
||||||
//! [`crate::pipeline::csaf_match`]).
|
|
||||||
|
|
||||||
use compliance_core::models::{SbomEntry, TargetDevice};
|
use compliance_core::models::{PlcDevice, SbomEntry};
|
||||||
|
|
||||||
/// The package manager of a device entry.
|
/// The package manager of a device entry.
|
||||||
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
|
pub(crate) const DEVICE_MANAGER: &str = "siemens-device";
|
||||||
|
|
||||||
/// The SBOM entries of target `repo_id`'s devices
|
/// The SBOM entries of target `repo_id`'s `devices`. A device is named by its
|
||||||
/// ([`compliance_core::models::OnboardedTarget::target_devices`]). A device
|
/// order number, so two devices of one type at one firmware are one entry;
|
||||||
/// is named by its order number, so two devices of one type at one firmware
|
/// its label, if any, is kept as evidence.
|
||||||
/// are one entry; where it is known from, and its label, are kept as
|
pub(crate) fn entries(devices: &[PlcDevice], repo_id: &str) -> Vec<SbomEntry> {
|
||||||
/// evidence.
|
|
||||||
pub(crate) fn entries(devices: &[TargetDevice], repo_id: &str) -> Vec<SbomEntry> {
|
|
||||||
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
|
let mut entries: Vec<SbomEntry> = Vec::with_capacity(devices.len());
|
||||||
for TargetDevice {
|
for device in devices {
|
||||||
device,
|
let evidence = device.label.as_deref().map_or_else(
|
||||||
exported_in,
|
|| "entered with the target".to_string(),
|
||||||
} in devices
|
|l| format!("entered as {l}"),
|
||||||
{
|
);
|
||||||
let evidence = match (exported_in, device.label.as_deref()) {
|
|
||||||
(Some(file), Some(label)) => format!("configured as {label} in the TIA export {file}"),
|
|
||||||
(Some(file), None) => format!("configured in the TIA export {file}"),
|
|
||||||
(None, Some(label)) => format!("entered as {label}"),
|
|
||||||
(None, None) => "entered with the target".to_string(),
|
|
||||||
};
|
|
||||||
if let Some(known) = entries
|
if let Some(known) = entries
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|e| e.name == device.order_number && e.version == device.firmware)
|
.find(|e| e.name == device.order_number && e.version == device.firmware)
|
||||||
@@ -53,7 +44,6 @@ pub(crate) fn entries(devices: &[TargetDevice], repo_id: &str) -> Vec<SbomEntry>
|
|||||||
#[allow(clippy::unwrap_used)]
|
#[allow(clippy::unwrap_used)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use compliance_core::models::PlcDevice;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn each_device_type_and_firmware_is_one_entry() {
|
fn each_device_type_and_firmware_is_one_entry() {
|
||||||
@@ -63,7 +53,6 @@ mod tests {
|
|||||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||||
];
|
];
|
||||||
|
|
||||||
let devices: Vec<TargetDevice> = devices.into_iter().map(TargetDevice::from).collect();
|
|
||||||
let entries = entries(&devices, "t");
|
let entries = entries(&devices, "t");
|
||||||
|
|
||||||
assert_eq!(entries.len(), 2);
|
assert_eq!(entries.len(), 2);
|
||||||
@@ -80,16 +69,4 @@ mod tests {
|
|||||||
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
|
assert_eq!(first.evidence, ["entered as Zelle 1", "entered as Zelle 2"]);
|
||||||
assert_eq!(entries[1].evidence, ["entered with the target"]);
|
assert_eq!(entries[1].evidence, ["entered with the target"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_exported_device_says_which_export_configures_it() {
|
|
||||||
let exported = TargetDevice {
|
|
||||||
device: PlcDevice::new("6ES7511-1AK02-0AB0", "2.9", Some("PLC_1")).unwrap(),
|
|
||||||
exported_in: Some("linie1.tia-export.zip".into()),
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
entries(&[exported], "t")[0].evidence,
|
|
||||||
["configured as PLC_1 in the TIA export linie1.tia-export.zip"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -606,113 +606,3 @@ async fn a_targets_supplier_is_set_checked_and_removed() {
|
|||||||
|
|
||||||
server.cleanup().await;
|
server.cleanup().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A TIA connector's export (#1090), read with TIA
|
|
||||||
/// `tia`, its CPU at firmware `firmware`.
|
|
||||||
fn tia_export(tia: &str, firmware: &str) -> Vec<u8> {
|
|
||||||
use std::io::Write;
|
|
||||||
let manifest = json!({
|
|
||||||
"bundle_version": 1,
|
|
||||||
"tia_version": tia,
|
|
||||||
"project": {"name": "Linie 1"},
|
|
||||||
"devices": [
|
|
||||||
{"name": "PLC_1", "role": "cpu",
|
|
||||||
"type_identifier": format!("OrderNumber:6ES7 511-1AK02-0AB0/V{firmware}")},
|
|
||||||
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"}
|
|
||||||
],
|
|
||||||
"blocks": [
|
|
||||||
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
|
||||||
"file": "blocks/PLC_1/Main.xml"},
|
|
||||||
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true}
|
|
||||||
]
|
|
||||||
});
|
|
||||||
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
|
||||||
let options = zip::write::SimpleFileOptions::default();
|
|
||||||
zip.start_file("manifest.json", options).unwrap();
|
|
||||||
zip.write_all(manifest.to_string().as_bytes()).unwrap();
|
|
||||||
zip.start_file("blocks/PLC_1/Main.xml", options).unwrap();
|
|
||||||
zip.write_all(b"<Document/>").unwrap();
|
|
||||||
zip.finish().unwrap().into_inner()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Upload `bytes` as a TIA export to target `id`.
|
|
||||||
async fn upload_tia_export(server: &TestServer, id: &str, bytes: Vec<u8>) -> reqwest::Response {
|
|
||||||
let form = reqwest::multipart::Form::new()
|
|
||||||
.text("kind", "plc_project")
|
|
||||||
.text("plc_format", "tia_export")
|
|
||||||
.part(
|
|
||||||
"file",
|
|
||||||
reqwest::multipart::Part::bytes(bytes).file_name("linie1.tia-export.zip"),
|
|
||||||
);
|
|
||||||
server
|
|
||||||
.client
|
|
||||||
.post(format!(
|
|
||||||
"{}/api/v1/targets/{id}/artifacts/upload",
|
|
||||||
server.base_url
|
|
||||||
))
|
|
||||||
.multipart(form)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_tia_export_brings_its_devices_and_replaces_the_last_one() {
|
|
||||||
let server = TestServer::start().await;
|
|
||||||
let resp = server
|
|
||||||
.post(
|
|
||||||
"/api/v1/targets",
|
|
||||||
&json!({ "name": "linie-1", "target_type": "plc_sps", "artifacts": [] }),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let body: serde_json::Value = resp.json().await.unwrap();
|
|
||||||
let id = body["data"]["_id"]["$oid"].as_str().unwrap().to_string();
|
|
||||||
|
|
||||||
// Not an export: refused with its code, and not kept.
|
|
||||||
let resp = upload_tia_export(&server, &id, b"plain text".to_vec()).await;
|
|
||||||
assert_eq!(resp.status(), 422);
|
|
||||||
let body: serde_json::Value = resp.json().await.unwrap();
|
|
||||||
assert_eq!(body["code"], "not_zip", "{body}");
|
|
||||||
assert!(stored_uploads(&id).is_empty());
|
|
||||||
|
|
||||||
let resp = upload_tia_export(&server, &id, tia_export("V20", "2.9")).await;
|
|
||||||
assert_eq!(resp.status(), 200);
|
|
||||||
let body: serde_json::Value = resp.json().await.unwrap();
|
|
||||||
let artifact = &body["data"]["artifacts"][0];
|
|
||||||
assert_eq!(artifact["plc"]["format"], "tia_export", "{body}");
|
|
||||||
// The CPU, by order number and configured firmware; not the GSD device.
|
|
||||||
assert_eq!(
|
|
||||||
artifact["plc"]["devices"],
|
|
||||||
json!([{"order_number": "6ES7511-1AK02-0AB0", "firmware": "2.9", "label": "PLC_1"}])
|
|
||||||
);
|
|
||||||
|
|
||||||
// The next export replaces it, file and all.
|
|
||||||
let resp = upload_tia_export(&server, &id, tia_export("V21", "3.1")).await;
|
|
||||||
assert_eq!(resp.status(), 200);
|
|
||||||
let body: serde_json::Value = resp.json().await.unwrap();
|
|
||||||
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
|
||||||
assert_eq!(artifacts.len(), 1, "{body}");
|
|
||||||
let facts = &artifacts[0]["detected"];
|
|
||||||
assert!(
|
|
||||||
facts
|
|
||||||
.as_array()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.any(|f| f["key"] == "tia_version" && f["value"] == "V21"),
|
|
||||||
"{body}"
|
|
||||||
);
|
|
||||||
assert_eq!(stored_uploads(&id).len(), 1);
|
|
||||||
|
|
||||||
// The Steuerungen page lists the exported CPU under its project name.
|
|
||||||
let resp = server.get(&format!("/api/v1/targets/{id}/devices")).await;
|
|
||||||
assert_eq!(resp.status(), 200);
|
|
||||||
let body: serde_json::Value = resp.json().await.unwrap();
|
|
||||||
let devices = body["data"].as_array().unwrap();
|
|
||||||
assert_eq!(devices.len(), 1, "{body}");
|
|
||||||
assert_eq!(devices[0]["label"], "PLC_1", "{body}");
|
|
||||||
// It says which export it comes from, so the page saves and edits only
|
|
||||||
// the devices entered with the target, never this one.
|
|
||||||
assert_eq!(devices[0]["exported_in"], "linie1.tia-export.zip", "{body}");
|
|
||||||
|
|
||||||
server.cleanup().await;
|
|
||||||
}
|
|
||||||
@@ -34,13 +34,9 @@ async fn fake_registry(seen: Seen) -> String {
|
|||||||
"/v1/internal/entitlements/check",
|
"/v1/internal/entitlements/check",
|
||||||
post(|State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
|
post(|State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
|
||||||
let blocked = body["user_id"].as_str() == Some("u-blocked");
|
let blocked = body["user_id"].as_str() == Some("u-blocked");
|
||||||
let expired = body["user_id"].as_str() == Some("u-expired");
|
|
||||||
seen.lock().unwrap().push(body);
|
seen.lock().unwrap().push(body);
|
||||||
Json(if blocked {
|
Json(if blocked {
|
||||||
serde_json::json!({ "allowed": false, "status": "active", "reason": "member_blocked" })
|
serde_json::json!({ "allowed": false, "status": "active", "reason": "member_blocked" })
|
||||||
} else if expired {
|
|
||||||
serde_json::json!({ "allowed": false, "status": "expired", "reason": "entitlement_expired",
|
|
||||||
"branding": { "color": "#0082c9" } })
|
|
||||||
} else {
|
} else {
|
||||||
serde_json::json!({ "allowed": true, "status": "active" })
|
serde_json::json!({ "allowed": true, "status": "active" })
|
||||||
})
|
})
|
||||||
@@ -88,17 +84,6 @@ async fn agent(registry: &str) -> Option<Arc<ComplianceAgent>> {
|
|||||||
|
|
||||||
/// GET /r as `ctx` through the entitlement middleware.
|
/// GET /r as `ctx` through the entitlement middleware.
|
||||||
async fn call(agent: Arc<ComplianceAgent>, ctx: TenantContext) -> (StatusCode, serde_json::Value) {
|
async fn call(agent: Arc<ComplianceAgent>, ctx: TenantContext) -> (StatusCode, serde_json::Value) {
|
||||||
call_at(agent, ctx, "GET", "/r").await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `method` `path` as `ctx` through the entitlement middleware; every route
|
|
||||||
/// answers "ok".
|
|
||||||
async fn call_at(
|
|
||||||
agent: Arc<ComplianceAgent>,
|
|
||||||
ctx: TenantContext,
|
|
||||||
method: &str,
|
|
||||||
path: &str,
|
|
||||||
) -> (StatusCode, serde_json::Value) {
|
|
||||||
let inject = move |mut req: Request, next: Next| {
|
let inject = move |mut req: Request, next: Next| {
|
||||||
let ctx = ctx.clone();
|
let ctx = ctx.clone();
|
||||||
async move {
|
async move {
|
||||||
@@ -108,19 +93,10 @@ async fn call_at(
|
|||||||
};
|
};
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/r", get(|| async { "ok" }))
|
.route("/r", get(|| async { "ok" }))
|
||||||
.route("/api/v1/branding", get(|| async { "ok" }))
|
|
||||||
.route("/api/v1/branding/logo", get(|| async { "ok" }))
|
|
||||||
.route("/api/v1/branding/ack", post(|| async { "ok" }))
|
|
||||||
.layer(from_fn_with_state(agent, require_entitlement))
|
.layer(from_fn_with_state(agent, require_entitlement))
|
||||||
.layer(from_fn(inject));
|
.layer(from_fn(inject));
|
||||||
let resp = app
|
let resp = app
|
||||||
.oneshot(
|
.oneshot(Request::builder().uri("/r").body(Body::empty()).unwrap())
|
||||||
Request::builder()
|
|
||||||
.method(method)
|
|
||||||
.uri(path)
|
|
||||||
.body(Body::empty())
|
|
||||||
.unwrap(),
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let status = resp.status();
|
let status = resp.status();
|
||||||
@@ -162,41 +138,6 @@ async fn a_blocked_member_is_refused_and_others_are_not() {
|
|||||||
assert_eq!(seen.lock().unwrap().len(), calls);
|
assert_eq!(seen.lock().unwrap().len(), calls);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_refused_workspace_still_reads_its_branding_and_nothing_else() {
|
|
||||||
let seen: Seen = Arc::default();
|
|
||||||
let base = fake_registry(seen).await;
|
|
||||||
let Some(agent) = agent(&base).await else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
// Its frame and logo, for the screen that says it is refused.
|
|
||||||
for path in ["/api/v1/branding", "/api/v1/branding/logo"] {
|
|
||||||
let (status, _) = call_at(agent.clone(), member("u-expired"), "GET", path).await;
|
|
||||||
assert_eq!(status, StatusCode::OK, "{path}");
|
|
||||||
}
|
|
||||||
// Everything else, the acknowledgement included, stays refused.
|
|
||||||
let (status, body) = call(agent.clone(), member("u-expired")).await;
|
|
||||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
||||||
assert_eq!(body["error"], "not_entitled");
|
|
||||||
let (status, _) = call_at(
|
|
||||||
agent.clone(),
|
|
||||||
member("u-expired"),
|
|
||||||
"POST",
|
|
||||||
"/api/v1/branding/ack",
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
|
||||||
// A blocked member sees the frame too, and nothing else.
|
|
||||||
let (status, _) = call_at(
|
|
||||||
agent.clone(),
|
|
||||||
member("u-blocked"),
|
|
||||||
"GET",
|
|
||||||
"/api/v1/branding",
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(status, StatusCode::OK);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn an_unreachable_registry_still_refuses_as_before() {
|
async fn an_unreachable_registry_still_refuses_as_before() {
|
||||||
// Not a block decision: the entitlement check itself fails closed when
|
// Not a block decision: the entitlement check itself fails closed when
|
||||||
|
|||||||
@@ -114,10 +114,6 @@ pub struct DeviceCheck {
|
|||||||
pub product: Option<DeviceName>,
|
pub product: Option<DeviceName>,
|
||||||
/// The advisories naming it: affecting it first, then by severity.
|
/// The advisories naming it: affecting it first, then by severity.
|
||||||
pub advisories: Vec<DeviceAdvisory>,
|
pub advisories: Vec<DeviceAdvisory>,
|
||||||
/// The TIA export that declares it (its file name, #1090/#1097); none for
|
|
||||||
/// a device entered with the target. Only an entered one is edited.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub exported_in: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DeviceCheck {
|
impl DeviceCheck {
|
||||||
@@ -151,7 +147,6 @@ impl DeviceCheck {
|
|||||||
device,
|
device,
|
||||||
product,
|
product,
|
||||||
advisories: rows,
|
advisories: rows,
|
||||||
exported_in: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ pub mod repository;
|
|||||||
pub mod sbom;
|
pub mod sbom;
|
||||||
pub mod scan;
|
pub mod scan;
|
||||||
pub(crate) mod serde_helpers;
|
pub(crate) mod serde_helpers;
|
||||||
pub mod tia_export;
|
|
||||||
pub mod vex;
|
pub mod vex;
|
||||||
pub mod webhook_delivery;
|
pub mod webhook_delivery;
|
||||||
pub mod werkbank;
|
pub mod werkbank;
|
||||||
@@ -73,8 +72,7 @@ pub use onboarding::{
|
|||||||
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
|
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
|
||||||
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
|
ComplianceFramework, ComplianceProfile, DetectedFact, ExternalRef, ExternalSystem,
|
||||||
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
|
GitArtifactConfig, IssueTrackerConfig, LastScan, OnboardedTarget, PlcArtifactConfig, PlcFormat,
|
||||||
SupplierComponent, TargetDevice, TargetScanConfig, TargetType, TargetTypeCandidate,
|
SupplierComponent, TargetScanConfig, TargetType, TargetTypeCandidate, WebArtifactConfig,
|
||||||
WebArtifactConfig,
|
|
||||||
};
|
};
|
||||||
pub use oscal::OscalDocument;
|
pub use oscal::OscalDocument;
|
||||||
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
|
pub use oscal_assessment::{assess, AssessmentResultsDoc, ControlLinker};
|
||||||
@@ -95,10 +93,6 @@ pub use scan::{
|
|||||||
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
RunErrorCode, RunNote, ScanPhase, ScanRun, ScanRunStatus, ScanStep, ScanType, SkipCode,
|
||||||
SkippedStage,
|
SkippedStage,
|
||||||
};
|
};
|
||||||
pub use tia_export::{
|
|
||||||
AccessLevel, CpuSecurity, ExportedDevices, Setting, TiaBlock, TiaBlockKind, TiaBundleError,
|
|
||||||
TiaConnector, TiaDevice, TiaDeviceRole, TiaManifest, TiaProject,
|
|
||||||
};
|
|
||||||
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
pub use vex::{SupplierVex, VexAssessment, VexError, VexJustification, VexStatus};
|
||||||
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
pub use webhook_delivery::{DeliveryResult, WebhookDelivery, DELIVERIES_SHOWN};
|
||||||
pub use werkbank::{
|
pub use werkbank::{
|
||||||
|
|||||||
@@ -218,10 +218,6 @@ pub enum PlcFormat {
|
|||||||
/// A CODESYS project archive (`.projectarchive` — a zip bundling the project
|
/// A CODESYS project archive (`.projectarchive` — a zip bundling the project
|
||||||
/// plus its referenced libraries and runtime; the source of the control-app SBOM).
|
/// plus its referenced libraries and runtime; the source of the control-app SBOM).
|
||||||
ProjectArchive,
|
ProjectArchive,
|
||||||
/// A Siemens TIA Portal project as a TIA connector exports it (#1090): a
|
|
||||||
/// zip with a manifest of devices, security settings and blocks
|
|
||||||
/// ([`super::TiaManifest`]) beside the block exports.
|
|
||||||
TiaExport,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
|
/// PLC-specific configuration for a [`ArtifactKind::PlcProject`] artifact.
|
||||||
@@ -229,30 +225,6 @@ pub enum PlcFormat {
|
|||||||
pub struct PlcArtifactConfig {
|
pub struct PlcArtifactConfig {
|
||||||
/// The project source format.
|
/// The project source format.
|
||||||
pub format: PlcFormat,
|
pub format: PlcFormat,
|
||||||
/// The Siemens devices a [`PlcFormat::TiaExport`] declares, read when it
|
|
||||||
/// was uploaded; matched against Siemens' advisories beside the devices
|
|
||||||
/// entered with the target ([`OnboardedTarget::target_devices`]).
|
|
||||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
||||||
pub devices: Vec<super::PlcDevice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A controller a target runs on and where it is known from.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct TargetDevice {
|
|
||||||
/// The device.
|
|
||||||
pub device: super::PlcDevice,
|
|
||||||
/// The TIA export that declares it (its file name); `None` for a device
|
|
||||||
/// entered with the target.
|
|
||||||
pub exported_in: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<super::PlcDevice> for TargetDevice {
|
|
||||||
fn from(device: super::PlcDevice) -> Self {
|
|
||||||
Self {
|
|
||||||
device,
|
|
||||||
exported_in: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single fact discovered about a target by ingest or classification
|
/// A single fact discovered about a target by ingest or classification
|
||||||
@@ -382,10 +354,7 @@ impl Artifact {
|
|||||||
/// A PLC-project artifact in the given format.
|
/// A PLC-project artifact in the given format.
|
||||||
pub fn plc_project(source_ref: impl Into<String>, format: PlcFormat) -> Self {
|
pub fn plc_project(source_ref: impl Into<String>, format: PlcFormat) -> Self {
|
||||||
let mut a = Self::bare(ArtifactKind::PlcProject, source_ref);
|
let mut a = Self::bare(ArtifactKind::PlcProject, source_ref);
|
||||||
a.plc = Some(PlcArtifactConfig {
|
a.plc = Some(PlcArtifactConfig { format });
|
||||||
format,
|
|
||||||
devices: Vec::new(),
|
|
||||||
});
|
|
||||||
a
|
a
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -812,40 +781,6 @@ impl OnboardedTarget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The controllers the target runs on: those entered with it, then those
|
|
||||||
/// its TIA exports declare (#1090). An exported device whose order number
|
|
||||||
/// an entered one already names is left out: the entered one says which
|
|
||||||
/// firmware is installed, the export only what was configured.
|
|
||||||
pub fn target_devices(&self) -> Vec<TargetDevice> {
|
|
||||||
let mut devices: Vec<TargetDevice> = self
|
|
||||||
.devices
|
|
||||||
.iter()
|
|
||||||
.cloned()
|
|
||||||
.map(TargetDevice::from)
|
|
||||||
.collect();
|
|
||||||
for artifact in &self.artifacts {
|
|
||||||
let Some(plc) = &artifact.plc else { continue };
|
|
||||||
let file = artifact
|
|
||||||
.display_name
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| artifact.source_ref.clone());
|
|
||||||
for device in &plc.devices {
|
|
||||||
if self
|
|
||||||
.devices
|
|
||||||
.iter()
|
|
||||||
.any(|entered| entered.order_number == device.order_number)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
devices.push(TargetDevice {
|
|
||||||
device: device.clone(),
|
|
||||||
exported_in: Some(file.clone()),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
devices
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first artifact of the given kind, if present.
|
/// The first artifact of the given kind, if present.
|
||||||
pub fn first_of(&self, kind: ArtifactKind) -> Option<&Artifact> {
|
pub fn first_of(&self, kind: ArtifactKind) -> Option<&Artifact> {
|
||||||
self.artifacts.iter().find(|a| a.kind == kind)
|
self.artifacts.iter().find(|a| a.kind == kind)
|
||||||
@@ -1049,33 +984,4 @@ mod tests {
|
|||||||
assert!(r.project_id.is_none());
|
assert!(r.project_id.is_none());
|
||||||
assert!(r.last_reconciled_at.is_none());
|
assert!(r.last_reconciled_at.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn exported_devices_join_the_entered_ones_unless_one_names_their_type() {
|
|
||||||
let device = |order: &str, firmware: &str, label: &str| {
|
|
||||||
super::super::PlcDevice::new(order, firmware, Some(label)).unwrap()
|
|
||||||
};
|
|
||||||
let mut target = OnboardedTarget::new("Linie 1".into(), TargetType::PlcSps);
|
|
||||||
target.devices = vec![device("6ES7511-1AK02-0AB0", "3.1.4", "Zelle 1")];
|
|
||||||
let mut export = Artifact::plc_project("linie1.tia-export.zip", PlcFormat::TiaExport);
|
|
||||||
export.display_name = Some("Linie 1 (TIA V20)".into());
|
|
||||||
if let Some(plc) = export.plc.as_mut() {
|
|
||||||
plc.devices = vec![
|
|
||||||
// Entered with an exact firmware: the export does not add it again.
|
|
||||||
device("6ES7511-1AK02-0AB0", "3.1", "PLC_1"),
|
|
||||||
device("6AV2124-0GC01-0AX0", "17.0", "HMI_1"),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
target.artifacts.push(export);
|
|
||||||
assert_eq!(
|
|
||||||
target.target_devices(),
|
|
||||||
[
|
|
||||||
TargetDevice::from(device("6ES7511-1AK02-0AB0", "3.1.4", "Zelle 1")),
|
|
||||||
TargetDevice {
|
|
||||||
device: device("6AV2124-0GC01-0AX0", "17.0", "HMI_1"),
|
|
||||||
exported_in: Some("Linie 1 (TIA V20)".into()),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -324,17 +324,6 @@ pub enum SkipCode {
|
|||||||
/// The month's quota is used up and the Prüftag limit the customer set
|
/// The month's quota is used up and the Prüftag limit the customer set
|
||||||
/// is reached, so this counted Prüfung did not run (t72).
|
/// is reached, so this counted Prüfung did not run (t72).
|
||||||
PrueftagCapReached,
|
PrueftagCapReached,
|
||||||
/// PLC blocks a project export holds whose code is not analysed yet
|
|
||||||
/// (TIA export blocks until #1093); `subject` says how many, in which
|
|
||||||
/// languages.
|
|
||||||
PlcBlocksNotAnalysed,
|
|
||||||
/// Know-how-protected PLC blocks, whose code cannot be read and so is
|
|
||||||
/// not analysed; `subject` lists them.
|
|
||||||
ProtectedBlocks,
|
|
||||||
/// Devices a project export names without a Siemens order number or a
|
|
||||||
/// firmware version, so they are not matched against advisories;
|
|
||||||
/// `subject` lists them.
|
|
||||||
DevicesUnmatched,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SkipCode {
|
impl SkipCode {
|
||||||
@@ -371,10 +360,7 @@ impl SkipCode {
|
|||||||
| Self::TooLargeToScan
|
| Self::TooLargeToScan
|
||||||
| Self::ReleaseUnknown
|
| Self::ReleaseUnknown
|
||||||
| Self::PrueftagLimitReached
|
| Self::PrueftagLimitReached
|
||||||
| Self::PrueftagCapReached
|
| Self::PrueftagCapReached => false,
|
||||||
| Self::PlcBlocksNotAnalysed
|
|
||||||
| Self::ProtectedBlocks
|
|
||||||
| Self::DevicesUnmatched => false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,509 +0,0 @@
|
|||||||
//! The export a TIA Portal connector uploads (#1090): one zip per export of
|
|
||||||
//! an engineering project, read only, with a `manifest.json` at its root.
|
|
||||||
//!
|
|
||||||
//! The manifest says what the project holds: its devices with their order
|
|
||||||
//! numbers and configured firmware (matched against Siemens' advisories like
|
|
||||||
//! a device entered by hand, [`PlcDevice`]), each CPU's security settings,
|
|
||||||
//! and its blocks, naming the know-how-protected ones that cannot be read.
|
|
||||||
//! Block code itself lies beside it under `blocks/` (SimaticML XML, SIMATIC SD
|
|
||||||
//! documents on V21, SCL sources).
|
|
||||||
//!
|
|
||||||
//! The contract is versioned by [`TiaManifest::bundle_version`]; fields this
|
|
||||||
//! version does not know are ignored, so a newer connector can add some
|
|
||||||
//! without breaking an older Prüfwerk. Nothing in it is a secret: a
|
|
||||||
//! connector never exports passwords or keys.
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use super::PlcDevice;
|
|
||||||
|
|
||||||
/// The manifest's file name, at the root of the zip.
|
|
||||||
pub const MANIFEST_NAME: &str = "manifest.json";
|
|
||||||
|
|
||||||
/// The largest manifest read, in bytes. A project with thousands of blocks
|
|
||||||
/// stays well below it.
|
|
||||||
pub const MAX_MANIFEST_BYTES: u64 = 4 << 20;
|
|
||||||
|
|
||||||
/// The bundle versions this Prüfwerk reads.
|
|
||||||
pub const BUNDLE_VERSIONS: std::ops::RangeInclusive<u32> = 1..=1;
|
|
||||||
|
|
||||||
/// The longest device name kept as a device's label; the rest is cut off.
|
|
||||||
const LABEL_MAX_CHARS: usize = 120;
|
|
||||||
|
|
||||||
/// The manifest of a TIA export.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct TiaManifest {
|
|
||||||
/// The contract version the connector wrote (see [`BUNDLE_VERSIONS`]).
|
|
||||||
pub bundle_version: u32,
|
|
||||||
/// The TIA Portal version the project was read with (`V20`, `V21`).
|
|
||||||
pub tia_version: String,
|
|
||||||
/// The engineering project.
|
|
||||||
pub project: TiaProject,
|
|
||||||
/// When the connector read the project (RFC 3339).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub exported_at: Option<String>,
|
|
||||||
/// The connector that wrote the bundle.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub connector: Option<TiaConnector>,
|
|
||||||
/// The project's devices: CPUs, HMIs, modules.
|
|
||||||
#[serde(default)]
|
|
||||||
pub devices: Vec<TiaDevice>,
|
|
||||||
/// The project's PLC blocks.
|
|
||||||
#[serde(default)]
|
|
||||||
pub blocks: Vec<TiaBlock>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The engineering project a bundle was read from.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct TiaProject {
|
|
||||||
/// The project's name in TIA Portal.
|
|
||||||
pub name: String,
|
|
||||||
/// When the project was last changed (RFC 3339), if TIA says.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub modified: Option<String>,
|
|
||||||
/// Whether the project is protected by user management (UMAC).
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub protected: Setting<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The connector that wrote a bundle.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct TiaConnector {
|
|
||||||
/// Its name.
|
|
||||||
pub name: String,
|
|
||||||
/// Its version.
|
|
||||||
pub version: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a device is in the project.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum TiaDeviceRole {
|
|
||||||
/// A PLC CPU.
|
|
||||||
Cpu,
|
|
||||||
/// An HMI panel or PC runtime.
|
|
||||||
Hmi,
|
|
||||||
/// An I/O, communication or other module.
|
|
||||||
Module,
|
|
||||||
/// Anything else, including roles a newer connector names.
|
|
||||||
#[serde(other)]
|
|
||||||
Other,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A device of the project.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct TiaDevice {
|
|
||||||
/// Its name in the project (`PLC_1`).
|
|
||||||
pub name: String,
|
|
||||||
/// What it is.
|
|
||||||
pub role: TiaDeviceRole,
|
|
||||||
/// TIA's type identifier (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`), from
|
|
||||||
/// which order number and firmware are taken when not given on their own.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub type_identifier: Option<String>,
|
|
||||||
/// The order number (MLFB).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub order_number: Option<String>,
|
|
||||||
/// The firmware version configured in the project (`V2.9`).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub firmware: Option<String>,
|
|
||||||
/// A CPU's protection and security settings.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub security: Option<CpuSecurity>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A setting as the connector read it: its value, or why it could not be
|
|
||||||
/// read (Openness throws for some settings, e.g. the access level of a CPU
|
|
||||||
/// without a password). Absent when the connector did not look.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
#[serde(bound(deserialize = "T: Deserialize<'de>"))]
|
|
||||||
pub struct Setting<T> {
|
|
||||||
/// The value read.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub value: Option<T>,
|
|
||||||
/// Why it could not be read.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub unreadable: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Default for Setting<T> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
value: None,
|
|
||||||
unreadable: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Setting<T> {
|
|
||||||
/// Whether the connector said nothing about it.
|
|
||||||
pub fn is_absent(&self) -> bool {
|
|
||||||
self.value.is_none() && self.unreadable.is_none()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A CPU's access level ("Protection & Security"), as Openness names it
|
|
||||||
/// (`PlcProtectionAccessLevel`).
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum AccessLevel {
|
|
||||||
/// Full access including fail-safe: no protection.
|
|
||||||
FullAccessIncludingFailsafe,
|
|
||||||
/// Full access: no protection.
|
|
||||||
FullAccess,
|
|
||||||
/// Read access without a password.
|
|
||||||
ReadAccess,
|
|
||||||
/// HMI access only without a password.
|
|
||||||
HmiAccess,
|
|
||||||
/// No access without a password.
|
|
||||||
NoAccess,
|
|
||||||
/// No level set.
|
|
||||||
None,
|
|
||||||
/// A level a newer TIA names.
|
|
||||||
#[serde(other)]
|
|
||||||
Other,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A CPU's protection and security settings as configured in the project
|
|
||||||
/// (not necessarily as on the running machine). Read by #1091's rules.
|
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct CpuSecurity {
|
|
||||||
/// The access level.
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub access_level: Setting<AccessLevel>,
|
|
||||||
/// "Permit access with PUT/GET communication from remote partner".
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub put_get: Setting<bool>,
|
|
||||||
/// Whether the web server is on.
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub web_server: Setting<bool>,
|
|
||||||
/// Whether the web server is reachable over HTTPS only.
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub web_server_https_only: Setting<bool>,
|
|
||||||
/// Whether the OPC UA server is on.
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub opc_ua_server: Setting<bool>,
|
|
||||||
/// The OPC UA server's security policies (`None`, `Basic256Sha256`, …).
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub opc_ua_security_policies: Setting<Vec<String>>,
|
|
||||||
/// "Only allow secure PG/PC and HMI communication".
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub secure_pg_hmi_only: Setting<bool>,
|
|
||||||
/// "Protect confidential PLC configuration data".
|
|
||||||
#[serde(default, skip_serializing_if = "Setting::is_absent")]
|
|
||||||
pub confidential_data_protected: Setting<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The kind of a PLC block.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum TiaBlockKind {
|
|
||||||
/// Organization block.
|
|
||||||
Ob,
|
|
||||||
/// Function block.
|
|
||||||
Fb,
|
|
||||||
/// Function.
|
|
||||||
Fc,
|
|
||||||
/// Data block.
|
|
||||||
Db,
|
|
||||||
/// PLC data type.
|
|
||||||
Udt,
|
|
||||||
/// Anything else.
|
|
||||||
#[serde(other)]
|
|
||||||
Other,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A PLC block of the project.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
||||||
pub struct TiaBlock {
|
|
||||||
/// The device whose program holds it (`PLC_1`).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub device: Option<String>,
|
|
||||||
/// Its name.
|
|
||||||
pub name: String,
|
|
||||||
/// Its kind.
|
|
||||||
pub kind: TiaBlockKind,
|
|
||||||
/// Its programming language as TIA names it (`SCL`, `LAD`, `FBD`, `GRAPH`).
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub language: Option<String>,
|
|
||||||
/// Where its export lies in the bundle (`blocks/PLC_1/Main.xml`); none
|
|
||||||
/// for a protected block.
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub file: Option<String>,
|
|
||||||
/// Whether it is know-how protected, so its code cannot be read.
|
|
||||||
#[serde(default)]
|
|
||||||
pub protected: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a bundle cannot be read.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
||||||
pub enum TiaBundleError {
|
|
||||||
/// Not a zip file.
|
|
||||||
#[error("not a zip file")]
|
|
||||||
NotZip,
|
|
||||||
/// No `manifest.json` at the root of the zip.
|
|
||||||
#[error("no manifest.json at the root of the zip")]
|
|
||||||
NoManifest,
|
|
||||||
/// The manifest is larger than [`MAX_MANIFEST_BYTES`].
|
|
||||||
#[error("manifest.json is larger than {} MiB", MAX_MANIFEST_BYTES >> 20)]
|
|
||||||
ManifestTooLarge,
|
|
||||||
/// The manifest is not the contract's JSON.
|
|
||||||
#[error("manifest.json is not a TIA export manifest: {0}")]
|
|
||||||
ManifestInvalid(String),
|
|
||||||
/// A bundle version this Prüfwerk does not read.
|
|
||||||
#[error("bundle version {0} is not supported (supported: {min}–{max})", min = BUNDLE_VERSIONS.start(), max = BUNDLE_VERSIONS.end())]
|
|
||||||
BundleVersion(u32),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TiaBundleError {
|
|
||||||
/// A stable name of the refusal, for a client to word in its own
|
|
||||||
/// language.
|
|
||||||
pub fn code(&self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::NotZip => "not_zip",
|
|
||||||
Self::NoManifest => "no_manifest",
|
|
||||||
Self::ManifestTooLarge => "manifest_too_large",
|
|
||||||
Self::ManifestInvalid(_) => "manifest_invalid",
|
|
||||||
Self::BundleVersion(_) => "bundle_version",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The devices of a manifest as advisories match them: those with a Siemens
|
|
||||||
/// order number and a firmware version, and the names of those without.
|
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
|
||||||
pub struct ExportedDevices {
|
|
||||||
/// Devices matched against Siemens' advisories, labelled with their
|
|
||||||
/// names in the project.
|
|
||||||
pub matched: Vec<PlcDevice>,
|
|
||||||
/// Names of the devices that cannot be matched: no Siemens order number,
|
|
||||||
/// or no firmware version.
|
|
||||||
pub unmatched: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TiaManifest {
|
|
||||||
/// Read a manifest from its JSON.
|
|
||||||
///
|
|
||||||
/// # Errors
|
|
||||||
///
|
|
||||||
/// [`TiaBundleError::ManifestTooLarge`] above [`MAX_MANIFEST_BYTES`],
|
|
||||||
/// [`TiaBundleError::ManifestInvalid`] when it is not the contract's
|
|
||||||
/// JSON, [`TiaBundleError::BundleVersion`] for a version outside
|
|
||||||
/// [`BUNDLE_VERSIONS`].
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use compliance_core::models::TiaManifest;
|
|
||||||
///
|
|
||||||
/// let m = TiaManifest::parse(br#"{"bundle_version": 1, "tia_version": "V20",
|
|
||||||
/// "project": {"name": "Linie 1"}}"#).unwrap();
|
|
||||||
/// assert_eq!(m.project.name, "Linie 1");
|
|
||||||
/// ```
|
|
||||||
pub fn parse(json: &[u8]) -> Result<Self, TiaBundleError> {
|
|
||||||
if json.len() as u64 > MAX_MANIFEST_BYTES {
|
|
||||||
return Err(TiaBundleError::ManifestTooLarge);
|
|
||||||
}
|
|
||||||
// The version first, so a newer contract is refused as such rather
|
|
||||||
// than as a manifest that does not parse.
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Version {
|
|
||||||
bundle_version: u32,
|
|
||||||
}
|
|
||||||
let version: Version = serde_json::from_slice(json)
|
|
||||||
.map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))?;
|
|
||||||
if !BUNDLE_VERSIONS.contains(&version.bundle_version) {
|
|
||||||
return Err(TiaBundleError::BundleVersion(version.bundle_version));
|
|
||||||
}
|
|
||||||
serde_json::from_slice(json).map_err(|e| TiaBundleError::ManifestInvalid(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The devices to match against Siemens' advisories, and those that
|
|
||||||
/// cannot be. Order number and firmware come from the device's own
|
|
||||||
/// fields, else from its type identifier.
|
|
||||||
pub fn devices(&self) -> ExportedDevices {
|
|
||||||
let mut out = ExportedDevices::default();
|
|
||||||
for device in &self.devices {
|
|
||||||
let (type_order, type_firmware) = device
|
|
||||||
.type_identifier
|
|
||||||
.as_deref()
|
|
||||||
.map(split_type_identifier)
|
|
||||||
.unwrap_or_default();
|
|
||||||
let order = device.order_number.as_deref().or(type_order);
|
|
||||||
let firmware = device.firmware.as_deref().or(type_firmware);
|
|
||||||
let label: String = device.name.trim().chars().take(LABEL_MAX_CHARS).collect();
|
|
||||||
let matched = match (order, firmware) {
|
|
||||||
(Some(order), Some(firmware)) => {
|
|
||||||
PlcDevice::new(order, firmware, Some(label.as_str())).ok()
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
match matched {
|
|
||||||
Some(d) => out.matched.push(d),
|
|
||||||
None => out.unmatched.push(label),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The names of the know-how-protected blocks, as `device/block` when
|
|
||||||
/// the device is named.
|
|
||||||
pub fn protected_blocks(&self) -> Vec<String> {
|
|
||||||
self.blocks
|
|
||||||
.iter()
|
|
||||||
.filter(|b| b.protected)
|
|
||||||
.map(|b| match &b.device {
|
|
||||||
Some(d) => format!("{d}/{}", b.name),
|
|
||||||
None => b.name.clone(),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Order number and firmware of a TIA type identifier
|
|
||||||
/// (`OrderNumber:6ES7 515-2UM01-0AB0/V2.9`). The firmware is the segment after
|
|
||||||
/// the order number when it is a version (`/V5.2.3/S120` has `V5.2.3`, a
|
|
||||||
/// catalog variant `//10002` none). A catalog order number with wildcards
|
|
||||||
/// (`6SL3040-1MA01-0Axx`) names no single article, so it is none. A GSD or
|
|
||||||
/// system identifier (`GSD:…`, `System:…`) has neither.
|
|
||||||
fn split_type_identifier(identifier: &str) -> (Option<&str>, Option<&str>) {
|
|
||||||
let Some(rest) = identifier.trim().strip_prefix("OrderNumber:") else {
|
|
||||||
return (None, None);
|
|
||||||
};
|
|
||||||
let mut segments = rest.split('/');
|
|
||||||
let order = segments
|
|
||||||
.next()
|
|
||||||
.map(str::trim)
|
|
||||||
.filter(|o| !o.is_empty() && !o.contains(['x', 'X']));
|
|
||||||
let firmware = segments
|
|
||||||
.next()
|
|
||||||
.map(str::trim)
|
|
||||||
.filter(|f| f.starts_with(['V', 'v']));
|
|
||||||
(order, firmware)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
const MANIFEST: &str = r#"{
|
|
||||||
"bundle_version": 1,
|
|
||||||
"tia_version": "V20",
|
|
||||||
"project": {"name": "Linie 1", "protected": {"value": false}},
|
|
||||||
"exported_at": "2026-12-01T10:00:00Z",
|
|
||||||
"connector": {"name": "Breakpilot TIA Connector", "version": "0.1.0"},
|
|
||||||
"devices": [
|
|
||||||
{"name": "PLC_1", "role": "cpu",
|
|
||||||
"type_identifier": "OrderNumber:6ES7 515-2UM01-0AB0/V2.9",
|
|
||||||
"security": {"access_level": {"unreadable": "no password set"},
|
|
||||||
"put_get": {"value": true}}},
|
|
||||||
{"name": "HMI_1", "role": "hmi", "order_number": "6AV2 124-0GC01-0AX0",
|
|
||||||
"firmware": "V17.0.0.0"},
|
|
||||||
{"name": "Drittgeraet", "role": "module", "type_identifier": "GSD:VENDOR.XML/DAP1"},
|
|
||||||
{"name": "Antrieb", "role": "drive", "order_number": "6SL3210-1KE11-8UF2"}
|
|
||||||
],
|
|
||||||
"blocks": [
|
|
||||||
{"device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
|
||||||
"file": "blocks/PLC_1/Main.xml"},
|
|
||||||
{"device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true},
|
|
||||||
{"name": "Rezept", "kind": "udt", "future_field": 1}
|
|
||||||
],
|
|
||||||
"future_section": {"anything": true}
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_manifest_is_read_and_unknown_fields_are_ignored() {
|
|
||||||
let m = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
|
||||||
assert_eq!(m.tia_version, "V20");
|
|
||||||
assert_eq!(m.project.protected.value, Some(false));
|
|
||||||
assert_eq!(m.devices[3].role, TiaDeviceRole::Other);
|
|
||||||
let security = m.devices[0].security.as_ref().unwrap();
|
|
||||||
assert_eq!(security.access_level.value, None);
|
|
||||||
assert_eq!(
|
|
||||||
security.access_level.unreadable.as_deref(),
|
|
||||||
Some("no password set")
|
|
||||||
);
|
|
||||||
assert_eq!(security.put_get.value, Some(true));
|
|
||||||
assert!(security.web_server.is_absent());
|
|
||||||
assert_eq!(m.blocks[2].kind, TiaBlockKind::Udt);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn devices_with_order_number_and_firmware_are_matched_the_rest_named() {
|
|
||||||
let devices = TiaManifest::parse(MANIFEST.as_bytes()).unwrap().devices();
|
|
||||||
assert_eq!(
|
|
||||||
devices.matched,
|
|
||||||
[
|
|
||||||
PlcDevice::new("6ES7515-2UM01-0AB0", "2.9", Some("PLC_1")).unwrap(),
|
|
||||||
PlcDevice::new("6AV2124-0GC01-0AX0", "17.0.0.0", Some("HMI_1")).unwrap(),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
// A GSD device has no order number; the drive no firmware.
|
|
||||||
assert_eq!(devices.unmatched, ["Drittgeraet", "Antrieb"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_type_identifier_yields_only_a_concrete_article_and_its_version() {
|
|
||||||
assert_eq!(
|
|
||||||
split_type_identifier("OrderNumber:6ES7 515-2UM01-0AB0/V2.9"),
|
|
||||||
(Some("6ES7 515-2UM01-0AB0"), Some("V2.9"))
|
|
||||||
);
|
|
||||||
// A family qualifier after the version.
|
|
||||||
assert_eq!(
|
|
||||||
split_type_identifier("OrderNumber:6SL3040-1MA01-0AA0/V5.2.3/S120"),
|
|
||||||
(Some("6SL3040-1MA01-0AA0"), Some("V5.2.3"))
|
|
||||||
);
|
|
||||||
// A catalog variant is no firmware; a wildcard is no article.
|
|
||||||
assert_eq!(
|
|
||||||
split_type_identifier("OrderNumber:6ES7 193-6BP00-0BA0//10002"),
|
|
||||||
(Some("6ES7 193-6BP00-0BA0"), None)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
split_type_identifier("OrderNumber:6SL3040-1MA01-0Axx/V5.2"),
|
|
||||||
(None, Some("V5.2"))
|
|
||||||
);
|
|
||||||
assert_eq!(split_type_identifier("System:Rack.S120"), (None, None));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn protected_blocks_are_named_with_their_device() {
|
|
||||||
let m = TiaManifest::parse(MANIFEST.as_bytes()).unwrap();
|
|
||||||
assert_eq!(m.protected_blocks(), ["PLC_1/FB_42"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_bad_manifest_is_refused_with_its_code() {
|
|
||||||
let code = |json: &str| TiaManifest::parse(json.as_bytes()).unwrap_err().code();
|
|
||||||
assert_eq!(code("not json"), "manifest_invalid");
|
|
||||||
assert_eq!(code(r#"{"tia_version": "V20"}"#), "manifest_invalid");
|
|
||||||
assert_eq!(
|
|
||||||
code(r#"{"bundle_version": 2, "tia_version": "V22", "project": {"name": "x"}}"#),
|
|
||||||
"bundle_version"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
code(r#"{"bundle_version": 1, "tia_version": "V20"}"#),
|
|
||||||
"manifest_invalid"
|
|
||||||
);
|
|
||||||
let huge = vec![b' '; MAX_MANIFEST_BYTES as usize + 1];
|
|
||||||
assert_eq!(
|
|
||||||
TiaManifest::parse(&huge).unwrap_err(),
|
|
||||||
TiaBundleError::ManifestTooLarge
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_long_device_name_is_cut_for_the_label() {
|
|
||||||
let json = format!(
|
|
||||||
r#"{{"bundle_version": 1, "tia_version": "V21", "project": {{"name": "p"}},
|
|
||||||
"devices": [{{"name": "{}", "role": "cpu",
|
|
||||||
"type_identifier": "OrderNumber:6ES7511-1AK02-0AB0/V3.1"}}]}}"#,
|
|
||||||
"x".repeat(500)
|
|
||||||
);
|
|
||||||
let devices = TiaManifest::parse(json.as_bytes()).unwrap().devices();
|
|
||||||
assert_eq!(
|
|
||||||
devices.matched[0].label.as_deref().map(str::len),
|
|
||||||
Some(LABEL_MAX_CHARS)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9919,7 +9919,6 @@ div.offer-option { flex-direction: column; align-items: flex-start; justify-cont
|
|||||||
.dev-detail-head { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; align-items: flex-start; }
|
.dev-detail-head { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; align-items: flex-start; }
|
||||||
.dev-detail-head > div:first-child { display: flex; flex-direction: column; gap: 4px; }
|
.dev-detail-head > div:first-child { display: flex; flex-direction: column; gap: 4px; }
|
||||||
.dev-detail-label { font-size: 14px; color: var(--text-tertiary); }
|
.dev-detail-label { font-size: 14px; color: var(--text-tertiary); }
|
||||||
.dev-detail-source { display: block; margin-top: 2px; }
|
|
||||||
.dev-detail-actions { display: flex; gap: 8px; }
|
.dev-detail-actions { display: flex; gap: 8px; }
|
||||||
.dev-detail-actions .btn { min-height: 44px; }
|
.dev-detail-actions .btn { min-height: 44px; }
|
||||||
.btn-danger-ghost { color: var(--danger); border-color: var(--danger-bg); }
|
.btn-danger-ghost { color: var(--danger); border-color: var(--danger-bg); }
|
||||||
|
|||||||
@@ -819,24 +819,6 @@ pub mod scans {
|
|||||||
(SkipCode::NativePlcProject, Lang::En) => format!(
|
(SkipCode::NativePlcProject, Lang::En) => format!(
|
||||||
"CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target."
|
"CODESYS project in its native format, control logic not analysed: {subject}. Export the POUs as PLCopen XML (Project → Export PLCopenXML) and add the export to the target."
|
||||||
),
|
),
|
||||||
(SkipCode::PlcBlocksNotAnalysed, Lang::De) => format!(
|
|
||||||
"Bausteine aus dem TIA-Export, Code noch nicht analysiert: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::PlcBlocksNotAnalysed, Lang::En) => format!(
|
|
||||||
"Blocks from the TIA export, code not analysed yet: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::ProtectedBlocks, Lang::De) => format!(
|
|
||||||
"Know-how-geschützte Bausteine, nicht analysierbar: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::ProtectedBlocks, Lang::En) => format!(
|
|
||||||
"Know-how-protected blocks, which cannot be analysed: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::DevicesUnmatched, Lang::De) => format!(
|
|
||||||
"Geräte ohne Siemens-Bestellnummer oder Firmware, nicht mit Advisories abgeglichen: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::DevicesUnmatched, Lang::En) => format!(
|
|
||||||
"Devices without a Siemens order number or firmware, not matched against advisories: {subject}"
|
|
||||||
),
|
|
||||||
(SkipCode::ToolFailed, Lang::De) => format!(
|
(SkipCode::ToolFailed, Lang::De) => format!(
|
||||||
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
|
"{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet."
|
||||||
),
|
),
|
||||||
@@ -9057,15 +9039,6 @@ pub mod devices {
|
|||||||
de: "Firmware",
|
de: "Firmware",
|
||||||
en: "Firmware",
|
en: "Firmware",
|
||||||
};
|
};
|
||||||
/// Where an exported device comes from, instead of its edit buttons: it
|
|
||||||
/// changes with the next export, not here.
|
|
||||||
pub fn exported_from(file: &str, lang: Lang) -> String {
|
|
||||||
match lang {
|
|
||||||
Lang::De => format!("Aus dem TIA-Export {file}; ändert sich mit dem nächsten Export."),
|
|
||||||
Lang::En => format!("From the TIA export {file}; changes with the next export."),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const CHANGE_FIRMWARE: Text = Text {
|
pub const CHANGE_FIRMWARE: Text = Text {
|
||||||
de: "Firmware ändern",
|
de: "Firmware ändern",
|
||||||
en: "Change firmware",
|
en: "Change firmware",
|
||||||
|
|||||||
@@ -104,14 +104,7 @@ pub fn TargetDevicesPage(id: String) -> Element {
|
|||||||
}
|
}
|
||||||
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
None => return rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||||
};
|
};
|
||||||
// The devices entered with the target: the only ones saved. Exported ones
|
let devices: Vec<PlcDevice> = listed.iter().map(|c| c.device.clone()).collect();
|
||||||
// (#1090, #1097) are listed after them and change with their export, so
|
|
||||||
// a selected entered device has the same index in both lists.
|
|
||||||
let devices: Vec<PlcDevice> = listed
|
|
||||||
.iter()
|
|
||||||
.filter(|c| c.exported_in.is_none())
|
|
||||||
.map(|c| c.device.clone())
|
|
||||||
.collect();
|
|
||||||
// A first device is added from the empty rail's form.
|
// A first device is added from the empty rail's form.
|
||||||
let show_form = can_write && (adding() || listed.is_empty());
|
let show_form = can_write && (adding() || listed.is_empty());
|
||||||
let chosen = (!show_form)
|
let chosen = (!show_form)
|
||||||
@@ -369,11 +362,8 @@ fn DeviceDetail(
|
|||||||
div {
|
div {
|
||||||
h2 { "{name}" }
|
h2 { "{name}" }
|
||||||
span { class: "dev-detail-label", "{label}" }
|
span { class: "dev-detail-label", "{label}" }
|
||||||
if let Some(file) = &check.exported_in {
|
|
||||||
span { class: "dev-detail-label dev-detail-source", {tx::exported_from(file, lang)} }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if can_write && check.exported_in.is_none() {
|
if can_write {
|
||||||
div { class: "dev-detail-actions",
|
div { class: "dev-detail-actions",
|
||||||
if !editing() {
|
if !editing() {
|
||||||
button {
|
button {
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ curl -H "Authorization: Bearer bp_…" https://pruefwerk.breakpilot.com/api/v1/f
|
|||||||
| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) |
|
| `pruefwerk:sbom.read` | Stückliste lesen und exportieren (`GET /api/v1/sbom`, `/sbom/filters`, `/sbom/export`, `/sbom/licenses`, `/sbom/quality`, `/sbom/diff`) |
|
||||||
| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) |
|
| `pruefwerk:scans.read` | Prüfläufe lesen (`GET /api/v1/scan-runs`) |
|
||||||
| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) |
|
| `pruefwerk:scans.run` | Eine Prüfung starten (`POST /api/v1/targets/{id}/scan`, `/dast/targets/{id}/scan`) |
|
||||||
| `pruefwerk:uploads.write` | Dateien zu Prüfobjekten hochladen (`POST /api/v1/targets/{id}/artifacts/upload`), etwa den Export des TIA-Connectors |
|
|
||||||
| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) |
|
| `pruefwerk:enisa.read` | ENISA-Meldeentwürfe lesen (`GET /api/v1/targets/{id}/enisa`, `/cves/{id}/enisa`) |
|
||||||
|
|
||||||
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
|
Alles andere ist mit einem Schlüssel nicht erreichbar, auch mit allen Scopes:
|
||||||
|
|||||||
@@ -244,89 +244,6 @@ The API takes `devices` on `POST /api/v1/targets` and `PATCH
|
|||||||
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
|
naming it, and `GET /api/v1/devices/lookup?order_number=` what the advisories
|
||||||
know of an order number.
|
know of an order number.
|
||||||
|
|
||||||
## Siemens TIA Portal projects (TIA export)
|
|
||||||
|
|
||||||
A TIA Portal project reaches Prüfwerk as a **TIA export**: a zip that a TIA
|
|
||||||
connector writes on the engineering PC, reading the project through TIA Portal
|
|
||||||
Openness and never changing it. It is uploaded to a PLC/SPS target as a PLC
|
|
||||||
project with the format `tia_export`, with an API key holding
|
|
||||||
`pruefwerk:uploads.write` ([API keys](./api-keys)):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -H "Authorization: Bearer bp_…" \
|
|
||||||
-F kind=plc_project -F plc_format=tia_export \
|
|
||||||
-F file=@linie1.tia-export.zip \
|
|
||||||
https://pruefwerk.breakpilot.com/api/v1/targets/<id>/artifacts/upload
|
|
||||||
```
|
|
||||||
|
|
||||||
Its manifest is read on upload: a file that is not an export is refused with
|
|
||||||
`422` and a `code` (`not_zip`, `no_manifest`, `manifest_too_large`,
|
|
||||||
`manifest_invalid`, `bundle_version`). A new export of a target replaces the
|
|
||||||
last one.
|
|
||||||
|
|
||||||
What the export brings today:
|
|
||||||
|
|
||||||
- **Devices**: each device with a Siemens order number and a firmware version
|
|
||||||
joins the target's controllers (above), named as in the project, and is
|
|
||||||
matched against Siemens' advisories like one entered by hand. A controller
|
|
||||||
entered by hand with the same order number wins: it says which firmware is
|
|
||||||
installed, the export only what was configured. Devices without either are
|
|
||||||
listed on the run as not matched.
|
|
||||||
- **Blocks**: their code is not analysed yet; the run says how many and in
|
|
||||||
which languages. Know-how-protected blocks are listed as not analysable,
|
|
||||||
never counted as clean.
|
|
||||||
- **Security settings** of each CPU: carried in the export, not checked yet.
|
|
||||||
|
|
||||||
### The export's contract
|
|
||||||
|
|
||||||
`manifest.json` at the root of the zip, at most 4 MiB; fields Prüfwerk does not
|
|
||||||
know are ignored. Nothing in it is a secret: a connector never exports
|
|
||||||
passwords or keys.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"bundle_version": 1,
|
|
||||||
"tia_version": "V20",
|
|
||||||
"project": { "name": "Linie 1", "modified": "2026-11-30T10:00:00Z",
|
|
||||||
"protected": { "value": true } },
|
|
||||||
"exported_at": "2026-12-01T09:00:00Z",
|
|
||||||
"connector": { "name": "Breakpilot TIA Connector", "version": "0.1.0" },
|
|
||||||
"devices": [
|
|
||||||
{ "name": "PLC_1", "role": "cpu",
|
|
||||||
"type_identifier": "OrderNumber:6ES7 515-2UM01-0AB0/V2.9",
|
|
||||||
"security": {
|
|
||||||
"access_level": { "unreadable": "no password set" },
|
|
||||||
"put_get": { "value": false },
|
|
||||||
"web_server": { "value": true },
|
|
||||||
"web_server_https_only": { "value": true },
|
|
||||||
"opc_ua_server": { "value": true },
|
|
||||||
"opc_ua_security_policies": { "value": ["Basic256Sha256"] },
|
|
||||||
"secure_pg_hmi_only": { "value": true },
|
|
||||||
"confidential_data_protected": { "value": true }
|
|
||||||
} },
|
|
||||||
{ "name": "HMI_1", "role": "hmi", "order_number": "6AV2 124-0GC01-0AX0",
|
|
||||||
"firmware": "V17.0.0.0" }
|
|
||||||
],
|
|
||||||
"blocks": [
|
|
||||||
{ "device": "PLC_1", "name": "Main", "kind": "ob", "language": "LAD",
|
|
||||||
"file": "blocks/PLC_1/Main.xml" },
|
|
||||||
{ "device": "PLC_1", "name": "FB_42", "kind": "fb", "protected": true }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Field | |
|
|
||||||
| --- | --- |
|
|
||||||
| `bundle_version` | `1` |
|
|
||||||
| `tia_version` | the TIA Portal version read with: `V20`, `V21` |
|
|
||||||
| `devices[].role` | `cpu`, `hmi`, `module`, anything else counts as other |
|
|
||||||
| `devices[].type_identifier` | TIA's type identifier; order number and firmware are taken from it unless given as `order_number` and `firmware`. A catalog order number with wildcards (`…-0Axx`) or a variant without a version (`//10002`) leaves the device not matched |
|
|
||||||
| `devices[].security` | a CPU's settings as configured in the project; each is `{"value": …}` when read, `{"unreadable": "<why>"}` when Openness could not read it, absent when not looked at |
|
|
||||||
| `security.access_level` | `full_access_including_failsafe`, `full_access`, `read_access`, `hmi_access`, `no_access`, `none` |
|
|
||||||
| `blocks[].kind` | `ob`, `fb`, `fc`, `db`, `udt` |
|
|
||||||
| `blocks[].file` | where the block's export lies in the zip: SimaticML (`.xml`), SIMATIC SD (`.s7dcl` with its `.s7res`, V21) or SCL (`.scl`) |
|
|
||||||
| `blocks[].protected` | know-how protected: no `file`, listed as not analysable |
|
|
||||||
|
|
||||||
## Dynamic testing — ICS protocol probe
|
## Dynamic testing — ICS protocol probe
|
||||||
|
|
||||||
Beyond the static analysis, Prüfwerk can **probe the running device** over
|
Beyond the static analysis, Prüfwerk can **probe the running device** over
|
||||||
|
|||||||
Reference in new issue
Block a user