ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Trusted Platform Module (TPM) monitoring.
//!
//! Detects TPM presence, version, manufacturer, and capabilities.
//!
//! # Platform Support
//!
//! - **Linux**: Reads `/sys/class/tpm/`, `/dev/tpm*`
//! - **Windows**: Uses WMI (`Win32_Tpm`) and registry
//! - **macOS**: Checks Secure Enclave presence (Apple's TPM equivalent)
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::tpm::TpmMonitor;
//!
//! let monitor = TpmMonitor::new().unwrap();
//! if let Some(tpm) = monitor.tpm() {
//!     println!("TPM {} - v{} by {}", tpm.device, tpm.version, tpm.manufacturer);
//! }
//! ```

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// TPM specification version
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TpmVersion {
    /// TPM 1.2
    V1_2,
    /// TPM 2.0
    V2_0,
    /// Apple Secure Enclave (T1/T2/Apple Silicon)
    SecureEnclave,
    /// Unknown version
    Unknown,
}

/// TPM status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TpmStatus {
    /// TPM is enabled and ready
    Enabled,
    /// TPM exists but is disabled in BIOS/firmware
    Disabled,
    /// TPM is in a locked state
    Locked,
    /// Status unknown
    Unknown,
}

/// Information about the TPM device
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TpmInfo {
    /// Device name (e.g., "tpm0")
    pub device: String,
    /// TPM version
    pub version: TpmVersion,
    /// Current status
    pub status: TpmStatus,
    /// Manufacturer name
    pub manufacturer: String,
    /// Firmware version
    pub firmware_version: String,
    /// Device path
    pub device_path: String,
    /// Whether the TPM is the system's primary/active TPM
    pub is_primary: bool,
    /// Supported algorithms (SHA-1, SHA-256, RSA, ECC, etc.).
    ///
    /// `None` when the platform was not asked or did not say. An empty `Vec` is
    /// a different answer: enumerated, and none were reported. Until 6.0.0 a
    /// Linux TPM whose `pcr-*` directories were unreadable was given the
    /// standard TPM 2.0 list under a comment reading "Default for TPM 2.0",
    /// Windows derived the list from the specification version, and macOS
    /// asserted `AES-256`, `SHA-256` and `ECC-P256` for every Secure Enclave.
    pub algorithms: Option<Vec<String>>,
    /// PCR bank count. `None` when it was not read -- never 24, which was the
    /// Windows constant, and never 0, which was both "no banks" and "did not
    /// look" on three platforms.
    pub pcr_banks: Option<u32>,
    /// Whether platform integrity measurements are active.
    ///
    /// `None` when it could not be established. `Some(true)` on Windows means a
    /// Measured Boot log was found, not that a TPM exists: the previous value
    /// was a literal `true` under the comment "Windows with TPM implies
    /// measured boot", which is an inference, and an unsound one -- a machine
    /// can have a TPM with measured boot switched off.
    pub measured_boot: Option<bool>,
}

/// Monitor for TPM devices
pub struct TpmMonitor {
    tpm_info: Option<TpmInfo>,
}

/// The `PNPDeviceID`s `query` returns, one per line, read through an
/// in-process WMI connection.
#[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"))
}

/// The TPM specification a Windows security device node declares.
///
/// The ACPI hardware id is the declaration: `MSFT0101` is the TPM 2.0 device
/// and `PNP0C31` the TPM 1.2 one, both assigned rather than descriptive. This
/// is not the friendly name "Trusted Platform Module 2.0" that sits beside it
/// -- reading the version out of a display string is the substring guessing
/// this crate removes wherever it finds it, and the same node would answer in a
/// localised name on another machine.
///
/// The list may hold several security devices; on the development host it holds
/// the AMD PSP alongside the TPM. Anything that is not one of the two known ids
/// is passed over rather than treated as a TPM of unknown version.
/// Count the hash banks a Linux TPM exposes as `pcr-<alg>` directories.
///
/// `None` when the directory cannot be read or holds no `pcr-*` entries:
/// neither is a count of zero banks.
#[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)
}

/// The TPM status from the two `Win32_Tpm` flags. A flag that was not reported
/// is `None`, and `None` names no status: `false` here would publish "Disabled"
/// for a TPM whose state was never read.
#[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 {
    /// Create a new TpmMonitor and detect TPM.
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self { tpm_info: None };
        monitor.refresh()?;
        Ok(monitor)
    }

    /// Refresh TPM detection.
    ///
    /// Returns `Err` when the detection failed, and `Ok` -- with or without a
    /// TPM -- only when it ran. The difference is not cosmetic here: the
    /// resolver publishes `board.tpm.present` as a **measured** `false` when
    /// this returns `Ok` and finds nothing, under a comment reading "a
    /// successful enumeration that found nothing is a reading: this machine has
    /// no TPM". That premise was false, because until 6.0.0 this could not
    /// report a failure at all, and "the query did not run" was published as
    /// "this machine has no TPM".
    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(())
    }

    /// Get the detected TPM info, if any.
    pub fn tpm(&self) -> Option<&TpmInfo> {
        self.tpm_info.as_ref()
    }

    /// Returns true if a TPM is present.
    pub fn has_tpm(&self) -> bool {
        self.tpm_info.is_some()
    }

    /// Returns true if TPM 2.0 is available.
    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() {
            // A real answer: this kernel exposes no TPM class at all.
            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();

                // Read TPM version from tpm_version_major
                // Only `tpm_version_major` says which specification the device
                // speaks. The device node used to decide it: `/dev/tpmrm0` was
                // read as 2.0 and `/dev/tpm0` as 1.2, which is a guess from the
                // node name when the kernel did not say, so an unreadable
                // attribute is now `Unknown`.
                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,
                };

                // Read manufacturer from caps
                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();
                    }
                }

                // Fallback vendor detection from device description
                if manufacturer.is_empty() {
                    manufacturer = std::fs::read_to_string(base.join("device/description"))
                        .unwrap_or_default()
                        .trim()
                        .to_string();
                }

                // PCR banks: one `pcr-<alg>` directory per hash bank. This used
                // to count the entries inside `pcr-sha256`, which are the PCR
                // registers (typically 24), not the banks.
                let pcr_banks = count_pcr_banks(&base);

                // Algorithms, from the `pcr-*` directories the driver exposes.
                // No `pcr-*` directory means the driver exposed no banks to
                // enumerate, so the list is `None`, not empty: an empty list is
                // a claim that the device has none. It used to be replaced with
                // the standard TPM 2.0 list, which is a specification talking,
                // not this device.
                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>>()
                });

                // Measured boot check (IMA or tpm_bios). Both paths existing is
                // evidence that measurements are active; neither existing is
                // not evidence that they are not, so the negative is `None`.
                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; // Usually only one TPM
            }
        }
        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        // Two sources, and the first is expected to fail on an ordinary
        // account: `root/cimv2/Security/MicrosoftTpm` answers "Access denied"
        // without elevation. So its failure is carried, not raised -- the
        // registry check below is what decides -- and only both failing is an
        // error. This is the same rule as `usb::refresh_windows`.
        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";
        // The security device's own node, which an ordinary account can read.
        // Its ACPI hardware id names the specification: `MSFT0101` is the
        // TPM 2.0 device and `PNP0C31` the TPM 1.2 one. See `version_from_node`.
        const TPM_DEVICE_NODE: &str =
            "SELECT PNPDeviceID FROM Win32_PnPEntity WHERE PNPClass = 'SecurityDevices'";

        // `MicrosoftTpm` grants Administrators only by default. Asked
        // unelevated, it took 6.6 s to say so on the machine this was measured
        // on -- most of a snapshot's TPM cost -- so an unelevated process
        // carries the refusal it would have received without making the
        // query. An elevated one, or one whose elevation cannot be read, asks.
        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
            };

            // A flag that is absent from the WMI row is not `false`. `false` here
            // would publish "Disabled" for a TPM whose state was never read, which
            // used to be the result on any row lacking the property. Only a
            // reported value can name a status.
            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,
                // Win32_Tpm publishes neither. The algorithm list here was
                // derived from `SpecVersion` -- what a TPM of that version is
                // required to support, not what this one reports -- and
                // `pcr_banks` was the constant 24.
                algorithms: None,
                pcr_banks: None,
                measured_boot: Self::measured_boot_windows(),
            });
            return Ok(());
        }

        // Fallback: whether the TPM service is registered. Read directly; this
        // was a PowerShell process spent on `Test-Path`, about a second.
        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 (&registry, 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(_)) => {
                // The privileged query ran and reported no TPM object; the
                // registry check is what would have confirmed it, and it did
                // not run. Neither answer is available.
                return Err(IronError::System(format!(
                    "the TPM service registry check could not be made: {registry_err}"
                )));
            }
        };

        if present {
            // The version is readable here without elevation, from the ACPI
            // hardware id of the security device node. `Win32_Tpm.SpecVersion`
            // above is the better source and answers "Access denied" on an
            // ordinary account, which left this path reporting `Unknown` and
            // the ontology saying "a TPM is present but its specification
            // version could not be determined" -- while `ACPI\MSFT0101\1` sat
            // in the device tree, readable, saying 2.0.
            // Queried through WMI in-process; it was a PowerShell session, about
            // a second of every snapshot.
            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,
                // Still unknown, and deliberately: a started driver is not the
                // TPM's own enabled flag, and `TPM_PT_PERMANENT` is what that
                // question asks. Reporting "enabled" because a device node is
                // in state OK would answer a different question in this one's
                // name -- and for a security property that is the wrong way to
                // be wrong.
                status: TpmStatus::Unknown,
                manufacturer: String::new(),
                firmware_version: String::new(),
                device_path: r"\\.\TPM".into(),
                is_primary: true,
                // This path learned that the TPM service is registered and
                // which specification the device node declares.
                algorithms: None,
                pcr_banks: None,
                measured_boot: Self::measured_boot_windows(),
            });
        }

        Ok(())
    }

    /// Whether Windows measured this boot, from the Measured Boot log.
    ///
    /// The boot loader writes the TCG log to `C:\Windows\Logs\MeasuredBoot`
    /// when measurements are active, so a `.log` there is evidence that they
    /// are. Its absence is not evidence that they are not -- the directory can
    /// be cleared, and policy can discard the logs -- so this answers
    /// `Some(true)` or `None` and never `Some(false)`.
    #[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> {
        // macOS uses Secure Enclave instead of discrete TPM
        // T1 chip (2016 MBP), T2 chip (2018+), Apple Silicon (M1+) all have SE
        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,
                        // `system_profiler` reports a chip name and nothing
                        // about the Secure Enclave's capabilities. The list
                        // here was what an SEP is documented to support.
                        algorithms: None,
                        // The SEP has no PCRs, which is why 0 was never a bank
                        // count. Secure boot on Apple silicon is a separate
                        // property this reader does not consult.
                        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::*;

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// This asserted `is_ok()`, which was true by construction until 6.0.0
    /// because `refresh` could not fail. Now that it can, the contract is
    /// weaker and more useful: **whatever happens, the caller can tell which
    /// happened.** A failure has to carry a reason, because a reason is the
    /// whole difference between "this machine has none" and "nobody looked".
    #[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);
        // Three banks, each holding 24 register files, plus an unrelated file.
        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};

    /// The exact output of the device-node query on the development host,
    /// where the AMD PSP is listed first and the TPM second.
    #[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() {
        // A security device that is not a TPM must not be read as a TPM of
        // unknown version: the caller reports the absence instead.
        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);
    }
}