Files
pruefwerk/compliance-core/src/device_check.rs
T
sharang 2d3311bd09
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m5s
CI / Deploy MCP (push) Successful in 2m54s
CI / Deploy Dashboard (push) Successful in 6m29s
CI / Deploy Agent (push) Successful in 8m16s
feat(devices): a target's Siemens controllers on a DIN rail (SPS 4a part 2) (#1078)
2026-11-28 22:09:06 +00:00

436 lines
15 KiB
Rust

//! 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>,
}
/// What Siemens' advisories know of an order number, to recognise it while
/// it is typed.
#[derive(Debug, Clone, PartialEq, Eq, 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,
}
/// 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
);
}
}