use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TpmVersion {
V1_2,
V2_0,
SecureEnclave,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TpmStatus {
Enabled,
Disabled,
Locked,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TpmInfo {
pub device: String,
pub version: TpmVersion,
pub status: TpmStatus,
pub manufacturer: String,
pub firmware_version: String,
pub device_path: String,
pub is_primary: bool,
pub algorithms: Option<Vec<String>>,
pub pcr_banks: Option<u32>,
pub measured_boot: Option<bool>,
}
pub struct TpmMonitor {
tpm_info: Option<TpmInfo>,
}
#[cfg(target_os = "windows")]
fn security_device_ids(query: &str) -> Result<String, IronError> {
let rows = crate::platform::windows::wmi_query("root\\CIMV2", query)?;
Ok(rows
.iter()
.map(|row| crate::platform::windows::wmi_str(row, "PNPDeviceID"))
.filter(|id| !id.is_empty())
.collect::<Vec<_>>()
.join("\n"))
}
#[cfg(target_os = "linux")]
fn count_pcr_banks(base: &std::path::Path) -> Option<u32> {
let entries = std::fs::read_dir(base).ok()?;
let banks = entries
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().starts_with("pcr-") && e.path().is_dir())
.count() as u32;
(banks > 0).then_some(banks)
}
#[cfg(any(target_os = "windows", test))]
fn status_from_flags(enabled: Option<bool>, activated: Option<bool>) -> TpmStatus {
match (enabled, activated) {
(Some(false), _) => TpmStatus::Disabled,
(Some(true), Some(true)) => TpmStatus::Enabled,
(Some(true), Some(false)) => TpmStatus::Locked,
(Some(true), None) | (None, _) => TpmStatus::Unknown,
}
}
#[cfg(target_os = "windows")]
fn version_from_node(pnp_ids: &str) -> Option<TpmVersion> {
pnp_ids.lines().find_map(|line| {
let upper = line.trim().to_uppercase();
if upper.starts_with(r"ACPI\MSFT0101") {
Some(TpmVersion::V2_0)
} else if upper.starts_with(r"ACPI\PNP0C31") {
Some(TpmVersion::V1_2)
} else {
None
}
})
}
impl TpmMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self { tpm_info: None };
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.tpm_info = None;
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
Ok(())
}
pub fn tpm(&self) -> Option<&TpmInfo> {
self.tpm_info.as_ref()
}
pub fn has_tpm(&self) -> bool {
self.tpm_info.is_some()
}
pub fn has_tpm2(&self) -> bool {
self.tpm_info
.as_ref()
.map(|t| t.version == TpmVersion::V2_0)
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
let tpm_class = std::path::Path::new("/sys/class/tpm");
if !tpm_class.exists() {
return Ok(());
}
let entries = std::fs::read_dir(tpm_class)
.map_err(|e| IronError::System(format!("cannot read /sys/class/tpm: {e}")))?;
{
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("tpm") {
continue;
}
let base = entry.path();
let version = match std::fs::read_to_string(base.join("tpm_version_major")) {
Ok(major) => match major.trim() {
"2" => TpmVersion::V2_0,
"1" => TpmVersion::V1_2,
_ => TpmVersion::Unknown,
},
Err(_) => TpmVersion::Unknown,
};
let caps = std::fs::read_to_string(base.join("caps")).unwrap_or_default();
let mut manufacturer = String::new();
let mut firmware_version = String::new();
for line in caps.lines() {
if let Some(m) = line.strip_prefix("Manufacturer:") {
manufacturer = m.trim().to_string();
}
if let Some(v) = line.strip_prefix("Firmware version:") {
firmware_version = v.trim().to_string();
}
}
if manufacturer.is_empty() {
manufacturer = std::fs::read_to_string(base.join("device/description"))
.unwrap_or_default()
.trim()
.to_string();
}
let pcr_banks = count_pcr_banks(&base);
let algorithms = pcr_banks.map(|_| {
["sha1", "sha256", "sha384", "sha512", "sm3-256"]
.iter()
.filter(|algo| base.join(format!("pcr-{}", algo)).exists())
.map(|algo| algo.to_uppercase())
.collect::<Vec<String>>()
});
let measured_boot = (std::path::Path::new("/sys/kernel/security/ima").exists()
|| std::path::Path::new("/sys/kernel/security/tpm0/binary_bios_measurements")
.exists())
.then_some(true);
self.tpm_info = Some(TpmInfo {
device: name,
version,
status: TpmStatus::Enabled,
manufacturer,
firmware_version,
device_path: format!("/dev/{}", entry.file_name().to_string_lossy()),
is_primary: true,
algorithms,
pcr_banks,
measured_boot,
});
break; }
}
Ok(())
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
const WMI_TPM: &str = "Get-CimInstance -Namespace 'root/cimv2/Security/MicrosoftTpm' -ClassName Win32_Tpm -ErrorAction SilentlyContinue | Select-Object IsActivated_InitialValue, IsEnabled_InitialValue, IsOwned_InitialValue, ManufacturerIdTxt, ManufacturerVersion, SpecVersion, PhysicalPresenceVersionInfo | ConvertTo-Json -Compress";
const TPM_DEVICE_NODE: &str =
"SELECT PNPDeviceID FROM Win32_PnPEntity WHERE PNPClass = 'SecurityDevices'";
let wmi = if crate::platform::windows::is_elevated() == Some(false) {
Err(IronError::PermissionDenied(
"Win32_Tpm is readable only by Administrators, and this process is not elevated"
.into(),
))
} else {
crate::core::command::capture_json("powershell", &["-NoProfile", "-Command", WMI_TPM])
};
if let Ok(Some(val)) = &wmi {
let spec = val["SpecVersion"].as_str().unwrap_or("");
let version = if spec.starts_with("2.0") || spec.contains("2.0") {
TpmVersion::V2_0
} else if spec.starts_with("1.2") || spec.contains("1.2") {
TpmVersion::V1_2
} else {
TpmVersion::Unknown
};
let status = status_from_flags(
val["IsEnabled_InitialValue"].as_bool(),
val["IsActivated_InitialValue"].as_bool(),
);
let manufacturer = val["ManufacturerIdTxt"].as_str().unwrap_or("").to_string();
let firmware_version = val["ManufacturerVersion"]
.as_str()
.unwrap_or("")
.to_string();
self.tpm_info = Some(TpmInfo {
device: "tpm0".into(),
version,
status,
manufacturer,
firmware_version,
device_path: r"\\.\TPM".into(),
is_primary: true,
algorithms: None,
pcr_banks: None,
measured_boot: Self::measured_boot_windows(),
});
return Ok(());
}
let registry = {
use winreg::enums::HKEY_LOCAL_MACHINE;
match winreg::RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey(r"SYSTEM\CurrentControlSet\Services\TPM")
{
Ok(_) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
};
let present = match (®istry, wmi) {
(Ok(present), _) => *present,
(Err(registry_err), Err(wmi_err)) => {
return Err(IronError::System(format!(
"no TPM detection succeeded: the WMI class said {wmi_err}; the registry check \
said {registry_err}"
)))
}
(Err(registry_err), Ok(_)) => {
return Err(IronError::System(format!(
"the TPM service registry check could not be made: {registry_err}"
)));
}
};
if present {
let version = security_device_ids(TPM_DEVICE_NODE)
.ok()
.and_then(|text| version_from_node(&text))
.unwrap_or(TpmVersion::Unknown);
self.tpm_info = Some(TpmInfo {
device: "tpm0".into(),
version,
status: TpmStatus::Unknown,
manufacturer: String::new(),
firmware_version: String::new(),
device_path: r"\\.\TPM".into(),
is_primary: true,
algorithms: None,
pcr_banks: None,
measured_boot: Self::measured_boot_windows(),
});
}
Ok(())
}
#[cfg(target_os = "windows")]
fn measured_boot_windows() -> Option<bool> {
let dir = std::path::Path::new(r"C:\Windows\Logs\MeasuredBoot");
let logged = std::fs::read_dir(dir).ok()?.flatten().any(|e| {
e.path()
.extension()
.is_some_and(|x| x.eq_ignore_ascii_case("log"))
});
logged.then_some(true)
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
let text = crate::core::command::capture("system_profiler", &["SPHardwareDataType"])?;
{
{
let has_se = text.contains("Apple M")
|| text.contains("Apple T2")
|| text.contains("Apple T1");
if has_se {
self.tpm_info = Some(TpmInfo {
device: "sep0".into(),
version: TpmVersion::SecureEnclave,
status: TpmStatus::Enabled,
manufacturer: "Apple".into(),
firmware_version: String::new(),
device_path: String::new(),
is_primary: true,
algorithms: None,
pcr_banks: None,
measured_boot: None,
});
}
}
}
Ok(())
}
}
impl Default for TpmMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self { tpm_info: None })
}
}
impl std::fmt::Display for TpmVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::V1_2 => write!(f, "1.2"),
Self::V2_0 => write!(f, "2.0"),
Self::SecureEnclave => write!(f, "Secure Enclave"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tpm_monitor_creation() {
match TpmMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[cfg(target_os = "linux")]
#[test]
fn test_count_pcr_banks_counts_algorithm_directories() {
let dir = std::env::temp_dir().join(format!("ironmon-pcr-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for alg in ["pcr-sha1", "pcr-sha256", "pcr-sha384"] {
let bank = dir.join(alg);
std::fs::create_dir_all(&bank).unwrap();
for i in 0..24 {
std::fs::write(bank.join(i.to_string()), "").unwrap();
}
}
std::fs::write(dir.join("caps"), "").unwrap();
assert_eq!(count_pcr_banks(&dir), Some(3));
std::fs::remove_dir_all(&dir).unwrap();
}
#[cfg(target_os = "linux")]
#[test]
fn test_count_pcr_banks_none_without_banks() {
let dir = std::env::temp_dir().join(format!("ironmon-pcr-empty-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
assert_eq!(count_pcr_banks(&dir), None);
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(
count_pcr_banks(&dir),
None,
"a missing directory is None too"
);
}
#[test]
fn an_unreported_tpm_flag_is_not_a_disabled_tpm() {
assert_eq!(status_from_flags(None, None), TpmStatus::Unknown);
assert_eq!(status_from_flags(None, Some(true)), TpmStatus::Unknown);
assert_eq!(status_from_flags(Some(true), None), TpmStatus::Unknown);
assert_eq!(status_from_flags(Some(false), None), TpmStatus::Disabled);
assert_eq!(
status_from_flags(Some(true), Some(true)),
TpmStatus::Enabled
);
assert_eq!(
status_from_flags(Some(true), Some(false)),
TpmStatus::Locked
);
}
#[test]
fn test_tpm_monitor_default() {
let monitor = TpmMonitor::default();
let _ = monitor.has_tpm();
let _ = monitor.has_tpm2();
}
#[test]
fn test_tpm_version_display() {
assert_eq!(TpmVersion::V2_0.to_string(), "2.0");
assert_eq!(TpmVersion::V1_2.to_string(), "1.2");
assert_eq!(TpmVersion::SecureEnclave.to_string(), "Secure Enclave");
}
#[test]
fn test_tpm_info_serialization() {
let info = TpmInfo {
device: "tpm0".into(),
version: TpmVersion::V2_0,
status: TpmStatus::Enabled,
manufacturer: "IFX".into(),
firmware_version: "7.85".into(),
device_path: "/dev/tpm0".into(),
is_primary: true,
algorithms: Some(vec!["SHA-256".into(), "RSA".into()]),
pcr_banks: Some(24),
measured_boot: Some(true),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("tpm0"));
let _: TpmInfo = serde_json::from_str(&json).unwrap();
}
}
#[cfg(all(test, target_os = "windows"))]
mod windows_version_tests {
use super::{version_from_node, TpmVersion};
#[test]
fn the_acpi_hardware_id_names_the_specification() {
let listing =
"PCI\\VEN_1022&DEV_1649&SUBSYS_88771043&REV_00\\4&1EBE6A9C&0&0241\nACPI\\MSFT0101\\1\n";
assert_eq!(version_from_node(listing), Some(TpmVersion::V2_0));
}
#[test]
fn a_tpm_12_node_reads_as_12() {
assert_eq!(
version_from_node("ACPI\\PNP0C31\\0"),
Some(TpmVersion::V1_2)
);
}
#[test]
fn a_listing_with_no_tpm_node_states_nothing() {
assert_eq!(
version_from_node("PCI\\VEN_1022&DEV_1649&SUBSYS_88771043&REV_00\\4&1EBE6A9C&0&0241"),
None
);
assert_eq!(version_from_node(""), None);
}
}