feat(devices): a target's Siemens controllers against Siemens' advisories (SPS 4a)
DeviceCheck in core puts a device's state and advisory rows together with the scan's matcher. Siemens writes a fix only as vendor_fix text, so its firmware is read from there too. The agent serves the target's devices and an order number lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
This commit is contained in:
1 parent
13e848631d
commit
a58c7a1f96
7 files changed
+705
-3
No files matched your search
@@ -0,0 +1,233 @@
|
||||
//! A target's Siemens controllers against Siemens' advisories (SPS item 4a):
|
||||
//! `GET /api/v1/targets/{id}/devices` for its page, and
|
||||
//! `GET /api/v1/devices/lookup` to recognise an order number while it is
|
||||
//! typed.
|
||||
//!
|
||||
//! Both read the advisory index as it is now, so a device shows its state
|
||||
//! as soon as it is entered; its CVE alerts follow at the target's next scan.
|
||||
|
||||
use axum::extract::{Extension, Path, Query};
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::dto::{tenant_db, AgentExt, ApiResponse, ApiResult};
|
||||
use crate::pipeline::csaf_match::{AdvisoryIndex, Wanted};
|
||||
use compliance_core::csaf_ingest::Advisory;
|
||||
use compliance_core::device_check::{DeviceCheck, DeviceName};
|
||||
use compliance_core::models::plc_device::normalised_order_number;
|
||||
use compliance_core::models::PlcDevice;
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
/// The provider whose advisories name devices by order number.
|
||||
const PROVIDER: &str = "siemens";
|
||||
|
||||
/// Siemens' advisories naming any of `order_numbers` (normalised).
|
||||
async fn advisories_naming(
|
||||
index: &dyn AdvisoryIndex,
|
||||
order_numbers: Vec<String>,
|
||||
) -> Result<Vec<Advisory>, StatusCode> {
|
||||
let wanted = Wanted {
|
||||
order_numbers,
|
||||
..Wanted::default()
|
||||
};
|
||||
let rows = index.relevant(&wanted).await.map_err(|e| {
|
||||
tracing::warn!("Failed to read the advisory index: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter(|(provider, _)| provider == PROVIDER)
|
||||
.map(|(_, advisory)| advisory)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Each of `devices` against `advisories`.
|
||||
fn checks(devices: Vec<PlcDevice>, advisories: &[Advisory]) -> Vec<DeviceCheck> {
|
||||
devices
|
||||
.into_iter()
|
||||
.map(|device| DeviceCheck::new(device, advisories))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Siemens controllers target `id` runs on, each with the advisories
|
||||
/// naming it.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/targets/{id}/devices",
|
||||
tag = "Targets",
|
||||
params(("id" = String, Path, description = "The target's id")),
|
||||
responses(
|
||||
(status = 200, description = "The target's devices in the order entered, each with the Siemens advisories naming it and whether one affects its firmware"),
|
||||
(status = 400, description = "Not a target id"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 404, description = "No such target"),
|
||||
(status = 500, description = "The target or the advisory index could not be read"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn list_devices(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Vec<DeviceCheck>> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.find_one(doc! { "_id": oid })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let mut order_numbers: Vec<String> = target
|
||||
.devices
|
||||
.iter()
|
||||
.map(|d| d.order_number.clone())
|
||||
.collect();
|
||||
order_numbers.sort();
|
||||
order_numbers.dedup();
|
||||
let advisories = if order_numbers.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
advisories_naming(agent.advisory_index.as_ref(), order_numbers).await?
|
||||
};
|
||||
let devices = checks(target.devices, &advisories);
|
||||
Ok(Json(ApiResponse {
|
||||
total: Some(devices.len() as u64),
|
||||
data: devices,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `?order_number=` of [`lookup_device`].
|
||||
#[derive(Debug, Deserialize, utoipa::IntoParams)]
|
||||
pub struct LookupParams {
|
||||
/// The order number as typed (`6es7511-1ak02-0ab0`).
|
||||
pub order_number: String,
|
||||
}
|
||||
|
||||
/// What Siemens' advisories know of an order number.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DeviceLookup {
|
||||
/// The order number, normalised (`6ES7511-1AK02-0AB0`).
|
||||
pub order_number: String,
|
||||
/// Whether it has a Siemens order number's shape.
|
||||
pub valid: bool,
|
||||
/// What Siemens calls it, from the newest advisory naming it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub product: Option<DeviceName>,
|
||||
/// How many advisories name it.
|
||||
pub advisories: usize,
|
||||
}
|
||||
|
||||
/// What Siemens' advisories know of an order number, to recognise it while
|
||||
/// it is typed. Public data only: nothing of the tenant is read.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/v1/devices/lookup",
|
||||
tag = "Targets",
|
||||
params(LookupParams),
|
||||
responses(
|
||||
(status = 200, description = "The order number normalised, whether it has a Siemens order number's shape, and, when advisories name it, the product's name and how many"),
|
||||
(status = 401, description = "No valid bearer token"),
|
||||
(status = 500, description = "The advisory index could not be read"),
|
||||
)
|
||||
)]
|
||||
#[tracing::instrument(skip_all)]
|
||||
pub async fn lookup_device(
|
||||
Extension(agent): AgentExt,
|
||||
_tenant: TenantCtx,
|
||||
Query(params): Query<LookupParams>,
|
||||
) -> ApiResult<DeviceLookup> {
|
||||
let order_number = normalised_order_number(¶ms.order_number);
|
||||
// Any firmware: only the shape of the order number is checked here.
|
||||
let Ok(device) = PlcDevice::new(&order_number, "0", None) else {
|
||||
return Ok(Json(ApiResponse {
|
||||
data: DeviceLookup {
|
||||
order_number,
|
||||
valid: false,
|
||||
product: None,
|
||||
advisories: 0,
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}));
|
||||
};
|
||||
let advisories =
|
||||
advisories_naming(agent.advisory_index.as_ref(), vec![order_number.clone()]).await?;
|
||||
let check = DeviceCheck::new(device, &advisories);
|
||||
Ok(Json(ApiResponse {
|
||||
data: DeviceLookup {
|
||||
order_number,
|
||||
valid: true,
|
||||
product: check.product,
|
||||
advisories: check.advisories.len(),
|
||||
},
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures_util::future::BoxFuture;
|
||||
|
||||
/// An index answering with the synthetic Siemens advisory, and a CODESYS
|
||||
/// one that must never reach a device.
|
||||
struct Fixture;
|
||||
|
||||
impl AdvisoryIndex for Fixture {
|
||||
fn relevant<'a>(
|
||||
&'a self,
|
||||
wanted: &'a Wanted,
|
||||
) -> BoxFuture<'a, Result<Vec<(String, Advisory)>, String>> {
|
||||
assert!(wanted.providers.is_empty() && wanted.purls.is_empty());
|
||||
let doc: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../../../../compliance-core/tests/fixtures/csaf/siemens-synthetic.json"
|
||||
))
|
||||
.unwrap();
|
||||
let siemens = compliance_core::csaf_ingest::parse(&doc).unwrap();
|
||||
let mut codesys = siemens.clone();
|
||||
codesys.id = "VDE-2026-0001".into();
|
||||
Box::pin(async move {
|
||||
Ok(vec![
|
||||
("siemens".to_string(), siemens),
|
||||
("codesys".to_string(), codesys),
|
||||
])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn devices_are_checked_against_siemens_advisories_only() {
|
||||
let advisories = advisories_naming(&Fixture, vec!["6ES7511-1AK02-0AB0".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(advisories.len(), 1);
|
||||
let devices = checks(
|
||||
vec![
|
||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.4", None).unwrap(),
|
||||
PlcDevice::new("6ES7511-1AK02-0AB0", "3.1.5", None).unwrap(),
|
||||
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||
],
|
||||
&advisories,
|
||||
);
|
||||
use compliance_core::device_check::DeviceState;
|
||||
let states: Vec<DeviceState> = devices.iter().map(DeviceCheck::state).collect();
|
||||
assert_eq!(
|
||||
states,
|
||||
[
|
||||
DeviceState::Affected,
|
||||
DeviceState::NotAffected,
|
||||
DeviceState::NotNamed
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
devices[0].advisories[0].fixed_from.as_deref(),
|
||||
Some("3.1.5")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod cve_matrix;
|
||||
pub mod dast;
|
||||
mod delivery;
|
||||
pub mod demo_seed;
|
||||
pub mod devices;
|
||||
pub mod dto;
|
||||
pub mod evidence;
|
||||
pub mod finding_breakdown;
|
||||
|
||||
@@ -98,6 +98,9 @@ fn described_routes() -> OpenApiRouter {
|
||||
handlers::onboarding::delete_target
|
||||
))
|
||||
.routes(routes!(handlers::onboarding::add_artifact))
|
||||
// A target's Siemens controllers against Siemens' advisories (SPS 4a).
|
||||
.routes(routes!(handlers::devices::list_devices))
|
||||
.routes(routes!(handlers::devices::lookup_device))
|
||||
.routes(routes!(handlers::onboarding::list_webhook_deliveries))
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||
|
||||
@@ -175,14 +175,32 @@ impl Advisory {
|
||||
self.fixed_versions_where(vulnerability, |p| normalised_name(&p.name) == wanted)
|
||||
}
|
||||
|
||||
/// The fixed versions of `vulnerability` for the device with order number
|
||||
/// `order_number`, as [`Self::fixed_versions`] gives them by name.
|
||||
/// The fixed firmware of `vulnerability` for the device with order
|
||||
/// number `order_number`, lowest first: the exact versions of its fixed
|
||||
/// products, and the version a vendor fix for one of its products names
|
||||
/// (Siemens marks its products only affected and writes the fix as
|
||||
/// `Update to V3.1.5 or later version`).
|
||||
pub fn fixed_device_versions(
|
||||
&self,
|
||||
vulnerability: &AdvisoryVulnerability,
|
||||
order_number: &str,
|
||||
) -> Vec<String> {
|
||||
self.fixed_versions_where(vulnerability, |p| p.has_order_number(order_number))
|
||||
let is_it = |id: &String| {
|
||||
self.product(id)
|
||||
.is_some_and(|p| p.has_order_number(order_number))
|
||||
};
|
||||
let mut versions =
|
||||
self.fixed_versions_where(vulnerability, |p| p.has_order_number(order_number));
|
||||
versions.extend(
|
||||
vulnerability
|
||||
.remediations
|
||||
.iter()
|
||||
.filter(|r| r.category == "vendor_fix" && r.product_ids.iter().any(is_it))
|
||||
.filter_map(|r| version_in_text(&r.details)),
|
||||
);
|
||||
versions.sort_by(|a, b| cmp_dotted(a, b));
|
||||
versions.dedup();
|
||||
versions
|
||||
}
|
||||
|
||||
/// The exact versions of the fixed products `is_it` picks, oldest first.
|
||||
@@ -204,6 +222,21 @@ impl Advisory {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first version a text names after a `V` (`Update to V3.1.5 or later
|
||||
/// version` names `3.1.5`), if any.
|
||||
fn version_in_text(text: &str) -> Option<String> {
|
||||
text.match_indices(['V', 'v']).find_map(|(at, _)| {
|
||||
let version: String = text[at + 1..]
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit() || *c == '.')
|
||||
.collect();
|
||||
let version = version.trim_end_matches('.');
|
||||
version
|
||||
.starts_with(|c: char| c.is_ascii_digit())
|
||||
.then(|| version.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// The text at `key` of `value`, trimmed, if not empty.
|
||||
fn text(value: &serde_json::Value, key: &str) -> Option<String> {
|
||||
value
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
//! A Siemens controller against the advisories that name it (SPS item 4a):
|
||||
//! what its page shows before the next scan does.
|
||||
//!
|
||||
//! The matching is the scan's ([`AdvisoryProduct::covers_device`],
|
||||
//! [`Advisory::fixed_device_versions`]), so a device's light and its CVE
|
||||
//! alerts never disagree once the target is scanned.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::csaf_ingest::{Advisory, AdvisoryProduct, AdvisoryVulnerability};
|
||||
use crate::models::PlcDevice;
|
||||
use crate::version::cmp_dotted;
|
||||
|
||||
/// What Siemens calls the device, from an advisory's product name.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DeviceName {
|
||||
/// The full name without the order number (`SIMATIC S7-1500 CPU 1511-1 PN`).
|
||||
pub name: String,
|
||||
/// The part from `CPU` on (`CPU 1511-1 PN`), or the full name.
|
||||
pub short: String,
|
||||
/// The series before `CPU` without the brand (`S7-1500`, `ET 200SP`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub family: Option<String>,
|
||||
}
|
||||
|
||||
impl DeviceName {
|
||||
/// The name in an advisory product's name `product` (`SIMATIC S7-1500
|
||||
/// CPU 1511-1 PN (6ES7511-1AK02-0AB0)`): the order number in brackets
|
||||
/// and a version after it are dropped. `None` for an empty name.
|
||||
pub fn from_product(product: &str) -> Option<Self> {
|
||||
let name = product
|
||||
.split_once(" (")
|
||||
.map_or(product, |(name, _)| name)
|
||||
.trim();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (short, family) = match name.find("CPU ") {
|
||||
Some(at) if at > 0 => {
|
||||
let series = name[..at].trim();
|
||||
let series = series.strip_prefix("SIMATIC").unwrap_or(series).trim();
|
||||
(
|
||||
&name[at..],
|
||||
(!series.is_empty()).then(|| series.to_string()),
|
||||
)
|
||||
}
|
||||
_ => (name, None),
|
||||
};
|
||||
Some(Self {
|
||||
name: name.to_string(),
|
||||
short: short.to_string(),
|
||||
family,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One advisory naming the device, as its page lists it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DeviceAdvisory {
|
||||
/// Its id (`SSA-019113`).
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
/// Its page, which Siemens' terms ask every use to link.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
/// The CVEs it lists for the device.
|
||||
pub cves: Vec<String>,
|
||||
/// The highest CVSS base severity of those (`HIGH`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub severity: Option<String>,
|
||||
/// Whether one of them affects the device's firmware.
|
||||
pub affected: bool,
|
||||
/// The firmware that fixes all of them that apply: those affecting the
|
||||
/// device when it is affected, otherwise all it lists. `None` when one
|
||||
/// has no fix.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fixed_from: Option<String>,
|
||||
}
|
||||
|
||||
/// A device's state in the advisories.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeviceState {
|
||||
/// An advisory affects its firmware.
|
||||
Affected,
|
||||
/// Advisories name it, none affects its firmware.
|
||||
NotAffected,
|
||||
/// No advisory names its order number.
|
||||
NotNamed,
|
||||
}
|
||||
|
||||
/// A device and the advisories naming it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DeviceCheck {
|
||||
#[serde(flatten)]
|
||||
pub device: PlcDevice,
|
||||
/// What Siemens calls it, from the newest advisory naming it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub product: Option<DeviceName>,
|
||||
/// The advisories naming it: affecting it first, then by severity.
|
||||
pub advisories: Vec<DeviceAdvisory>,
|
||||
}
|
||||
|
||||
impl DeviceCheck {
|
||||
/// The device against `advisories`, Siemens' in any order.
|
||||
pub fn new(device: PlcDevice, advisories: &[Advisory]) -> Self {
|
||||
let mut naming: Vec<&Advisory> = advisories
|
||||
.iter()
|
||||
.filter(|a| {
|
||||
a.products
|
||||
.iter()
|
||||
.any(|p| p.has_order_number(&device.order_number))
|
||||
})
|
||||
.collect();
|
||||
// Newest first, so the name is the one Siemens uses now.
|
||||
naming.sort_by(|a, b| b.updated.cmp(&a.updated).then_with(|| a.id.cmp(&b.id)));
|
||||
let product = naming.iter().find_map(|a| {
|
||||
a.products
|
||||
.iter()
|
||||
.filter(|p| p.has_order_number(&device.order_number))
|
||||
.find_map(|p| DeviceName::from_product(&p.name))
|
||||
});
|
||||
let mut rows: Vec<DeviceAdvisory> =
|
||||
naming.into_iter().filter_map(|a| row(a, &device)).collect();
|
||||
rows.sort_by(|a, b| {
|
||||
b.affected
|
||||
.cmp(&a.affected)
|
||||
.then_with(|| severity_rank(&b.severity).cmp(&severity_rank(&a.severity)))
|
||||
.then_with(|| a.id.cmp(&b.id))
|
||||
});
|
||||
Self {
|
||||
device,
|
||||
product,
|
||||
advisories: rows,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an advisory affects it, names it only, or none names it.
|
||||
pub fn state(&self) -> DeviceState {
|
||||
if self.advisories.iter().any(|a| a.affected) {
|
||||
DeviceState::Affected
|
||||
} else if self.advisories.is_empty() {
|
||||
DeviceState::NotNamed
|
||||
} else {
|
||||
DeviceState::NotAffected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Advisory `advisory`'s row for `device`, when one of its vulnerabilities
|
||||
/// lists one of the device's products.
|
||||
fn row(advisory: &Advisory, device: &PlcDevice) -> Option<DeviceAdvisory> {
|
||||
let order_number = device.order_number.as_str();
|
||||
let products: Vec<&AdvisoryProduct> = advisory
|
||||
.products
|
||||
.iter()
|
||||
.filter(|p| p.has_order_number(order_number))
|
||||
.collect();
|
||||
let lists = |ids: &[String]| {
|
||||
ids.iter()
|
||||
.any(|id| products.iter().any(|p| &p.product_id == id))
|
||||
};
|
||||
let named: Vec<&AdvisoryVulnerability> = advisory
|
||||
.vulnerabilities
|
||||
.iter()
|
||||
.filter(|v| lists(&v.affected) || lists(&v.fixed) || lists(&v.not_affected))
|
||||
.collect();
|
||||
if named.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let affects = |v: &AdvisoryVulnerability| {
|
||||
v.affected.iter().any(|id| {
|
||||
advisory
|
||||
.product(id)
|
||||
.is_some_and(|p| p.covers_device(order_number, &device.firmware))
|
||||
})
|
||||
};
|
||||
let affecting: Vec<&AdvisoryVulnerability> =
|
||||
named.iter().copied().filter(|v| affects(v)).collect();
|
||||
let affected = !affecting.is_empty();
|
||||
let fixing = if affected { &affecting } else { &named };
|
||||
// The fix of each: the lowest fixed firmware above the device's when it
|
||||
// is affected, the lowest at all otherwise. The row's is the highest.
|
||||
let fixed_from = fixing
|
||||
.iter()
|
||||
.map(|v| {
|
||||
advisory
|
||||
.fixed_device_versions(v, order_number)
|
||||
.into_iter()
|
||||
.find(|f| !affected || cmp_dotted(f, &device.firmware).is_gt())
|
||||
})
|
||||
.try_fold(None::<String>, |highest, fix| {
|
||||
let fix = fix?;
|
||||
Some(Some(match highest {
|
||||
Some(h) if cmp_dotted(&h, &fix).is_ge() => h,
|
||||
_ => fix,
|
||||
}))
|
||||
})
|
||||
.flatten();
|
||||
let severity = named
|
||||
.iter()
|
||||
.filter_map(|v| v.severity.clone())
|
||||
.max_by_key(|s| severity_rank(&Some(s.clone())));
|
||||
let mut cves: Vec<String> = named.iter().filter_map(|v| v.cve.clone()).collect();
|
||||
cves.sort();
|
||||
cves.dedup();
|
||||
Some(DeviceAdvisory {
|
||||
id: advisory.id.clone(),
|
||||
title: advisory.title.clone(),
|
||||
url: advisory.url.clone(),
|
||||
cves,
|
||||
severity,
|
||||
affected,
|
||||
fixed_from,
|
||||
})
|
||||
}
|
||||
|
||||
/// A CVSS base severity's order: `CRITICAL` highest, none lowest.
|
||||
fn severity_rank(severity: &Option<String>) -> u8 {
|
||||
match severity.as_deref().map(str::to_ascii_uppercase).as_deref() {
|
||||
Some("CRITICAL") => 4,
|
||||
Some("HIGH") => 3,
|
||||
Some("MEDIUM") => 2,
|
||||
Some("LOW") => 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::csaf_ingest::Remediation;
|
||||
|
||||
fn product(id: &str, name: &str, range: &str) -> AdvisoryProduct {
|
||||
let order_number = name
|
||||
.split_once('(')
|
||||
.and_then(|(_, rest)| rest.split_once(')'))
|
||||
.map(|(on, _)| on.to_string());
|
||||
AdvisoryProduct {
|
||||
product_id: id.into(),
|
||||
vendor: Some("Siemens".into()),
|
||||
family: None,
|
||||
name: name.into(),
|
||||
version: None,
|
||||
version_range: Some(range.into()),
|
||||
cpe: None,
|
||||
purl: None,
|
||||
model_numbers: order_number.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn vulnerability(
|
||||
cve: &str,
|
||||
severity: &str,
|
||||
affected: &[&str],
|
||||
fix: Option<(&str, &[&str])>,
|
||||
) -> AdvisoryVulnerability {
|
||||
AdvisoryVulnerability {
|
||||
cve: Some(cve.into()),
|
||||
severity: Some(severity.into()),
|
||||
affected: affected.iter().map(|s| s.to_string()).collect(),
|
||||
remediations: fix
|
||||
.map(|(details, ids)| Remediation {
|
||||
category: "vendor_fix".into(),
|
||||
details: details.into(),
|
||||
url: None,
|
||||
product_ids: ids.iter().map(|s| s.to_string()).collect(),
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn advisory(
|
||||
id: &str,
|
||||
updated: &str,
|
||||
products: Vec<AdvisoryProduct>,
|
||||
vulnerabilities: Vec<AdvisoryVulnerability>,
|
||||
) -> Advisory {
|
||||
Advisory {
|
||||
id: id.into(),
|
||||
title: format!("{id} title"),
|
||||
publisher: "Siemens ProductCERT".into(),
|
||||
url: Some(format!(
|
||||
"https://cert-portal.siemens.com/productcert/html/{id}.html"
|
||||
)),
|
||||
tlp: Some("WHITE".into()),
|
||||
updated: updated.into(),
|
||||
products,
|
||||
vulnerabilities,
|
||||
}
|
||||
}
|
||||
|
||||
const CPU: &str = "SIMATIC S7-1500 CPU 1511-1 PN (6ES7511-1AK02-0AB0)";
|
||||
|
||||
fn device(firmware: &str) -> PlcDevice {
|
||||
PlcDevice::new("6ES7511-1AK02-0AB0", firmware, Some("Hauptsteuerung")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn siemens_names_split_into_series_and_cpu() {
|
||||
assert_eq!(
|
||||
DeviceName::from_product(CPU),
|
||||
Some(DeviceName {
|
||||
name: "SIMATIC S7-1500 CPU 1511-1 PN".into(),
|
||||
short: "CPU 1511-1 PN".into(),
|
||||
family: Some("S7-1500".into()),
|
||||
})
|
||||
);
|
||||
let et =
|
||||
DeviceName::from_product("SIMATIC ET 200SP CPU 1512SP-1 PN (6ES7512-1DK01-0AB0) V3.0")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(et.short.as_str(), et.family.as_deref()),
|
||||
("CPU 1512SP-1 PN", Some("ET 200SP"))
|
||||
);
|
||||
let logo = DeviceName::from_product("LOGO! 8 BM (6ED1052-1MD08-0BA2)").unwrap();
|
||||
assert_eq!((logo.short.as_str(), logo.family), ("LOGO! 8 BM", None));
|
||||
assert_eq!(DeviceName::from_product(" (6ES7511-1AK02-0AB0)"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_is_affected_until_the_firmware_fixing_all_its_advisorys_cves() {
|
||||
let advisories = [advisory(
|
||||
"SSA-100001",
|
||||
"2026-10-01",
|
||||
vec![
|
||||
product("1", CPU, "vers:intdot/<3.1.5"),
|
||||
product("2", CPU, "vers:intdot/<3.1.7"),
|
||||
],
|
||||
vec![
|
||||
vulnerability(
|
||||
"CVE-2026-1",
|
||||
"MEDIUM",
|
||||
&["1"],
|
||||
Some(("Update to V3.1.5 or later version", &["1"])),
|
||||
),
|
||||
vulnerability(
|
||||
"CVE-2026-2",
|
||||
"HIGH",
|
||||
&["2"],
|
||||
Some(("Update to V3.1.7 or later version", &["2"])),
|
||||
),
|
||||
],
|
||||
)];
|
||||
|
||||
let old = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||
assert_eq!(old.state(), DeviceState::Affected);
|
||||
let row = &old.advisories[0];
|
||||
assert_eq!(row.cves, ["CVE-2026-1", "CVE-2026-2"]);
|
||||
assert_eq!(row.severity.as_deref(), Some("HIGH"));
|
||||
assert_eq!(row.fixed_from.as_deref(), Some("3.1.7"));
|
||||
assert_eq!(old.product.as_ref().unwrap().short, "CPU 1511-1 PN");
|
||||
|
||||
let between = DeviceCheck::new(device("3.1.6"), &advisories);
|
||||
assert_eq!(between.advisories[0].fixed_from.as_deref(), Some("3.1.7"));
|
||||
|
||||
let current = DeviceCheck::new(device("3.1.7"), &advisories);
|
||||
assert_eq!(current.state(), DeviceState::NotAffected);
|
||||
assert!(!current.advisories[0].affected);
|
||||
assert_eq!(current.advisories[0].fixed_from.as_deref(), Some("3.1.7"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_affecting_cve_without_a_fix_leaves_no_fixed_firmware() {
|
||||
let advisories = [advisory(
|
||||
"SSA-100002",
|
||||
"2026-10-01",
|
||||
vec![product("1", CPU, "vers:all/*")],
|
||||
vec![vulnerability("CVE-2026-3", "LOW", &["1"], None)],
|
||||
)];
|
||||
let check = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||
assert!(check.advisories[0].affected);
|
||||
assert_eq!(check.advisories[0].fixed_from, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_put_affecting_and_severe_first_and_skip_other_devices() {
|
||||
let other = "SIMATIC S7-1500 CPU 1513-1 PN (6ES7513-1AL02-0AB0)";
|
||||
let advisories = [
|
||||
advisory(
|
||||
"SSA-1",
|
||||
"2026-01-01",
|
||||
vec![product("1", CPU, "vers:intdot/<2.0")],
|
||||
vec![vulnerability("CVE-1", "CRITICAL", &["1"], None)],
|
||||
),
|
||||
advisory(
|
||||
"SSA-2",
|
||||
"2026-02-01",
|
||||
vec![product("1", CPU, "vers:all/*")],
|
||||
vec![vulnerability("CVE-2", "MEDIUM", &["1"], None)],
|
||||
),
|
||||
advisory(
|
||||
"SSA-3",
|
||||
"2026-03-01",
|
||||
vec![product("1", CPU, "vers:all/*")],
|
||||
vec![vulnerability("CVE-3", "HIGH", &["1"], None)],
|
||||
),
|
||||
advisory(
|
||||
"SSA-4",
|
||||
"2026-04-01",
|
||||
vec![product("1", other, "vers:all/*")],
|
||||
vec![vulnerability("CVE-4", "CRITICAL", &["1"], None)],
|
||||
),
|
||||
];
|
||||
let check = DeviceCheck::new(device("3.1.4"), &advisories);
|
||||
let ids: Vec<&str> = check.advisories.iter().map(|a| a.id.as_str()).collect();
|
||||
assert_eq!(ids, ["SSA-3", "SSA-2", "SSA-1"]);
|
||||
assert_eq!(
|
||||
DeviceCheck::new(
|
||||
PlcDevice::new("6ES7516-3AN02-0AB0", "3.0", None).unwrap(),
|
||||
&advisories
|
||||
)
|
||||
.state(),
|
||||
DeviceState::NotNamed
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod cve_groups;
|
||||
pub mod cve_history;
|
||||
pub mod cve_matrix;
|
||||
pub mod db;
|
||||
pub mod device_check;
|
||||
pub mod encoding;
|
||||
pub mod enisa_docs;
|
||||
pub mod error;
|
||||
|
||||
@@ -148,3 +148,14 @@ fn live_advisories_of_the_default_providers_are_read() {
|
||||
assert!(!advisory.vulnerabilities.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_siemens_fix_is_read_from_its_vendor_fix_text_for_the_device_only() {
|
||||
let a = fixture("siemens-synthetic.json");
|
||||
let v = &a.vulnerabilities[0];
|
||||
// Product 2 is fixed at 3.1.5, and the vendor fix for product 1 says
|
||||
// "Update to V3.1.5 or later version": one version.
|
||||
assert_eq!(a.fixed_device_versions(v, "6es7511-1ak02-0ab0"), ["3.1.5"]);
|
||||
// The fix names product 1 only, not the other CPU.
|
||||
assert!(a.fixed_device_versions(v, "6ES7513-1AL02-0AB0").is_empty());
|
||||
}
|
||||
Reference in new issue
Block a user