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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
//! CPU vulnerability mitigations and kernel security monitoring.
//!
//! Detects CPU vulnerabilities (Spectre, Meltdown, MDS, etc.) and their
//! mitigation status, kernel security modules (SELinux, AppArmor),
//! ASLR configuration, Secure Boot chain, and security feature compliance
//! scoring.
//!
//! ## Platform Support
//!
//! - **Linux**: `/sys/devices/system/cpu/vulnerabilities/`, `/proc/sys/kernel/`, LSM
//! - **Windows**: `Get-SpeculationControlSettings`, Windows Security Center
//! - **macOS**: `sysctl kern.hv_support`, system integrity protection

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// CPU vulnerability status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MitigationStatus {
    /// Not affected by this vulnerability.
    NotAffected,
    /// Vulnerable and not mitigated.
    Vulnerable,
    /// Mitigated (with possible performance impact).
    Mitigated,
    /// Partially mitigated.
    PartiallyMitigated,
    /// Unknown status.
    Unknown,
}

impl std::fmt::Display for MitigationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotAffected => write!(f, "Not Affected"),
            Self::Vulnerable => write!(f, "Vulnerable"),
            Self::Mitigated => write!(f, "Mitigated"),
            Self::PartiallyMitigated => write!(f, "Partially Mitigated"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// A CPU vulnerability and its mitigation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuVulnerability {
    /// Vulnerability name (e.g. "spectre_v1", "meltdown", "mds").
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// CVE identifier(s) if known.
    pub cve: Vec<String>,
    /// Mitigation status.
    pub status: MitigationStatus,
    /// Raw mitigation string from the kernel.
    pub raw_status: String,
    /// Whether the mitigation has a performance impact.
    pub performance_impact: bool,
    /// Estimated performance impact percentage (inferred).
    pub estimated_impact_pct: f64,
}

/// Kernel security module type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SecurityModule {
    SELinux,
    AppArmor,
    Smack,
    TOMOYO,
    Yama,
    LoadPin,
    SafeSetID,
    Lockdown,
    BPF,
    Landlock,
    WindowsDefender,
    Gatekeeper, // macOS
    SIP,        // macOS System Integrity Protection
    None,
}

impl std::fmt::Display for SecurityModule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SELinux => write!(f, "SELinux"),
            Self::AppArmor => write!(f, "AppArmor"),
            Self::Smack => write!(f, "Smack"),
            Self::TOMOYO => write!(f, "TOMOYO"),
            Self::Yama => write!(f, "Yama"),
            Self::LoadPin => write!(f, "LoadPin"),
            Self::SafeSetID => write!(f, "SafeSetID"),
            Self::Lockdown => write!(f, "Lockdown"),
            Self::BPF => write!(f, "BPF"),
            Self::Landlock => write!(f, "Landlock"),
            Self::WindowsDefender => write!(f, "Windows Defender"),
            Self::Gatekeeper => write!(f, "Gatekeeper"),
            Self::SIP => write!(f, "SIP"),
            Self::None => write!(f, "None"),
        }
    }
}

/// LSM (Linux Security Module) status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LsmStatus {
    /// Module type.
    pub module: SecurityModule,
    /// Whether the module is enabled/active.
    pub enabled: bool,
    /// Mode (e.g. "enforcing", "permissive"), where a reader could read one.
    /// `None` when no mode was read: Linux reads one for SELinux only, and a
    /// module whose mode file is unreadable has no mode to report.
    pub mode: Option<String>,
}

/// Kernel hardening features.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelHardening {
    /// ASLR level (0=disabled, 1=partial, 2=full), or `None` where it was not
    /// read. Linux reads `kernel.randomize_va_space`; Windows and macOS do not
    /// read it here. The readers used to assert `2` on those platforms, and
    /// Linux used `unwrap_or(0)`, which reported an unreadable sysctl as
    /// disabled. Neither is a reading.
    pub aslr_level: Option<u32>,
    /// Whether kernel pointer leak protection is enabled (`kptr_restrict`),
    /// or `None` where the setting does not exist.
    ///
    /// These four are **Linux kernel tunables**. The Windows and macOS readers
    /// asserted `true` for all of them, which is not a translation of the
    /// mechanism onto those platforms — there is no `/proc/sys/kernel/
    /// kptr_restrict` to be true. Two of them feed the posture score directly,
    /// so the score was three points higher on Windows and macOS for hardening
    /// nothing had checked.
    pub kptr_restrict: Option<bool>,
    /// Whether dmesg is restricted to root. See [`Self::kptr_restrict`].
    pub dmesg_restrict: Option<bool>,
    /// Whether unprivileged BPF is disabled. See [`Self::kptr_restrict`].
    pub unprivileged_bpf_disabled: Option<bool>,
    /// Whether ptrace is restricted (Yama scope), or `None` where it was not
    /// read. Only Linux reads `kernel.yama.ptrace_scope`. The Windows and macOS
    /// readers used to assert a scope they never checked.
    pub ptrace_scope: Option<u32>,
    /// Whether kernel module loading is locked down (`kernel.modules_disabled`
    /// on Linux), or `None` where it was not read.
    pub modules_locked: Option<bool>,
    /// The active kernel lockdown mode (`none`, `integrity` or `confidentiality`),
    /// or `None` where the kernel does not report one. Read from the bracketed
    /// token in `/sys/kernel/security/lockdown`; the whole file used to be stored.
    pub lockdown_mode: Option<String>,
    /// Whether Secure Boot is enabled, or `None` where it could not be read.
    ///
    /// The Windows reader shelled out to `Confirm-SecureBootUEFI`, which
    /// **requires elevation**, and `unwrap_or(false)` turned an unelevated run
    /// into "Secure Boot is off" — raising a medium-severity finding that may
    /// be untrue. `afb377d` established that the state is readable unelevated
    /// from `SYSTEM\CurrentControlSet\Control\SecureBoot\State`, and
    /// `platform::windows::secure_boot_enabled` already does exactly that.
    pub secure_boot: Option<bool>,
    /// Stack protector enabled, or `None` where it was not read.
    ///
    /// Every platform wrote `true`; the Linux one under a comment reading
    /// "Most modern kernels have this". Most is not this one.
    pub stack_protector: Option<bool>,
}

/// Overall security posture score.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityPosture {
    /// Score from 0-100, or `None` when no CPU vulnerability was enumerated
    /// (the score would otherwise assume every one is mitigated).
    pub score: Option<u32>,
    /// Risk level.
    pub risk_level: String,
    /// Individual component scores.
    pub component_scores: Vec<(String, u32)>,
    /// Findings and recommendations.
    pub findings: Vec<SecurityFinding>,
}

/// A security finding with severity.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityFinding {
    /// Finding severity: "critical", "high", "medium", "low", "info".
    pub severity: String,
    /// Short title.
    pub title: String,
    /// Detailed description.
    pub description: String,
    /// Suggested remediation.
    pub remediation: String,
}

/// Security mitigations monitor.
pub struct SecurityMitigationsMonitor {
    /// CPU vulnerabilities.
    pub vulnerabilities: Vec<CpuVulnerability>,
    /// Active security modules.
    pub security_modules: Vec<LsmStatus>,
    /// Kernel hardening status.
    pub hardening: KernelHardening,
    /// Overall security posture.
    pub posture: SecurityPosture,
}

impl SecurityMitigationsMonitor {
    /// Create a new monitor, detecting all mitigations.
    pub fn new() -> Result<Self, IronError> {
        let vulnerabilities = Self::detect_vulnerabilities()?;
        let security_modules = Self::detect_security_modules()?;
        let hardening = Self::detect_hardening()?;
        let posture = Self::compute_posture(&vulnerabilities, &security_modules, &hardening);

        Ok(Self {
            vulnerabilities,
            security_modules,
            hardening,
            posture,
        })
    }

    /// Refresh all data.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.vulnerabilities = Self::detect_vulnerabilities()?;
        self.security_modules = Self::detect_security_modules()?;
        self.hardening = Self::detect_hardening()?;
        self.posture = Self::compute_posture(
            &self.vulnerabilities,
            &self.security_modules,
            &self.hardening,
        );
        Ok(())
    }

    /// Get unmitigated vulnerabilities.
    pub fn unmitigated(&self) -> Vec<&CpuVulnerability> {
        self.vulnerabilities
            .iter()
            .filter(|v| v.status == MitigationStatus::Vulnerable)
            .collect()
    }

    /// Total estimated performance impact of all active mitigations.
    pub fn total_performance_impact(&self) -> f64 {
        self.vulnerabilities
            .iter()
            .filter(|v| v.status == MitigationStatus::Mitigated && v.performance_impact)
            .map(|v| v.estimated_impact_pct)
            .sum()
    }

    fn compute_posture(
        vulns: &[CpuVulnerability],
        lsms: &[LsmStatus],
        hardening: &KernelHardening,
    ) -> SecurityPosture {
        let mut score: i32 = 50; // Base score
        let mut findings = Vec::new();
        let mut components = Vec::new();

        // CPU vulnerability scoring (max 25 points)
        let vuln_count = vulns.len();
        let mitigated = vulns
            .iter()
            .filter(|v| {
                v.status == MitigationStatus::Mitigated || v.status == MitigationStatus::NotAffected
            })
            .count();
        let vulnerable = vulns
            .iter()
            .filter(|v| v.status == MitigationStatus::Vulnerable)
            .count();

        // Nothing enumerated is no evidence of mitigation. It used to score the
        // full 25 points, and with them a full posture. Now it scores nothing,
        // and the total below is unknown.
        if vuln_count > 0 {
            let vuln_score = ((mitigated as f64 / vuln_count as f64) * 25.0) as u32;
            score += vuln_score as i32;
            components.push(("CPU Vulnerability Mitigations".into(), vuln_score));
        }

        if vulnerable > 0 {
            findings.push(SecurityFinding {
                severity: "critical".into(),
                title: format!("{} unmitigated CPU vulnerabilities", vulnerable),
                description: "CPU vulnerabilities without active mitigations can be exploited for information disclosure or privilege escalation.".into(),
                remediation: "Update kernel and CPU microcode to latest versions.".into(),
            });
        }

        // LSM scoring (max 15 points)
        let active_lsm = lsms.iter().filter(|l| l.enabled).count();
        let lsm_score = (active_lsm as u32 * 5).min(15);
        score += lsm_score as i32;
        components.push(("Security Modules".into(), lsm_score));

        if active_lsm == 0 {
            findings.push(SecurityFinding {
                severity: "high".into(),
                title: "No mandatory access control active".into(),
                description: "No security module (SELinux, AppArmor, etc.) is enforcing mandatory access controls.".into(),
                remediation: "Enable SELinux or AppArmor in enforcing mode.".into(),
            });
        }

        // Hardening scoring (max 10 points)
        let mut hard_score: u32 = 0;
        // Only credit hardening that was actually observed. `None` scores
        // nothing and is not a finding, the same as an unread setting elsewhere.
        match hardening.aslr_level {
            Some(level) if level >= 2 => hard_score += 2,
            Some(level) => findings.push(SecurityFinding {
                severity: "medium".into(),
                title: "ASLR not at full level".into(),
                description: format!("ASLR level is {}, maximum is 2.", level),
                remediation: "Set kernel.randomize_va_space = 2".into(),
            }),
            None => {}
        }
        // `Some(false)` and `None` both score nothing, but only the first is a finding.
        if hardening.kptr_restrict == Some(true) {
            hard_score += 2;
        }
        if hardening.dmesg_restrict == Some(true) {
            hard_score += 1;
        }
        if hardening.ptrace_scope.is_some_and(|scope| scope >= 1) {
            hard_score += 2;
        }
        match hardening.secure_boot {
            Some(true) => hard_score += 3,
            // Only report it off when it was read and is off. An unread state
            // is not a security finding about the machine.
            Some(false) => findings.push(SecurityFinding {
                severity: "medium".into(),
                title: "Secure Boot not enabled".into(),
                description: "UEFI Secure Boot is not active.".into(),
                remediation: "Enable Secure Boot in UEFI firmware settings.".into(),
            }),
            None => findings.push(SecurityFinding {
                severity: "info".into(),
                title: "Secure Boot state not read".into(),
                description: "IronMonitor could not read the Secure Boot state on this platform."
                    .into(),
                remediation: "Check it in the UEFI firmware settings directly.".into(),
            }),
        }
        score += hard_score as i32;
        components.push(("Kernel Hardening".into(), hard_score));

        // Unknown when no vulnerability was enumerated, rather than a score
        // that assumes every one of them is mitigated.
        let final_score = (vuln_count > 0).then(|| score.clamp(0, 100) as u32);
        let risk_level = match final_score {
            Some(0..=30) => "Critical",
            Some(31..=50) => "High",
            Some(51..=70) => "Medium",
            Some(71..=85) => "Low",
            Some(86..=100) => "Minimal",
            _ => "Unknown",
        }
        .to_string();

        SecurityPosture {
            score: final_score,
            risk_level,
            component_scores: components,
            findings,
        }
    }

    #[cfg(target_os = "linux")]
    fn detect_vulnerabilities() -> Result<Vec<CpuVulnerability>, IronError> {
        let vuln_dir = std::path::Path::new("/sys/devices/system/cpu/vulnerabilities");
        let mut vulns = Vec::new();

        if !vuln_dir.exists() {
            return Ok(vulns);
        }

        let known_vulns = vec![
            (
                "spectre_v1",
                "Spectre Variant 1 (Bounds Check Bypass)",
                vec!["CVE-2017-5753"],
            ),
            (
                "spectre_v2",
                "Spectre Variant 2 (Branch Target Injection)",
                vec!["CVE-2017-5715"],
            ),
            (
                "meltdown",
                "Meltdown (Rogue Data Cache Load)",
                vec!["CVE-2017-5754"],
            ),
            (
                "spec_store_bypass",
                "Speculative Store Bypass",
                vec!["CVE-2018-3639"],
            ),
            (
                "l1tf",
                "L1 Terminal Fault",
                vec!["CVE-2018-3615", "CVE-2018-3620"],
            ),
            (
                "mds",
                "Microarchitectural Data Sampling",
                vec!["CVE-2018-12126", "CVE-2018-12127"],
            ),
            (
                "tsx_async_abort",
                "TSX Asynchronous Abort",
                vec!["CVE-2019-11135"],
            ),
            ("itlb_multihit", "ITLB Multihit", vec![]),
            (
                "srbds",
                "Special Register Buffer Data Sampling",
                vec!["CVE-2020-0543"],
            ),
            ("mmio_stale_data", "MMIO Stale Data", vec!["CVE-2022-21123"]),
            (
                "retbleed",
                "Return Address Branch Target Injection",
                vec!["CVE-2022-29900", "CVE-2022-29901"],
            ),
            (
                "spec_rstack_overflow",
                "Speculative Return Stack Overflow",
                vec!["CVE-2023-20569"],
            ),
            (
                "gather_data_sampling",
                "Gather Data Sampling (Downfall)",
                vec!["CVE-2022-40982"],
            ),
            (
                "rfds",
                "Register File Data Sampling",
                vec!["CVE-2023-28746"],
            ),
            ("gds", "Gather Data Sampling", vec!["CVE-2022-40982"]),
        ];

        for (file, desc, cves) in &known_vulns {
            let path = vuln_dir.join(file);
            if let Ok(status_str) = std::fs::read_to_string(&path) {
                let raw = status_str.trim().to_string();
                let (status, perf_impact, impact_pct) = Self::parse_vuln_status(&raw);

                vulns.push(CpuVulnerability {
                    name: file.to_string(),
                    description: desc.to_string(),
                    cve: cves.iter().map(|s| s.to_string()).collect(),
                    status,
                    raw_status: raw,
                    performance_impact: perf_impact,
                    estimated_impact_pct: impact_pct,
                });
            }
        }

        Ok(vulns)
    }

    #[cfg(target_os = "linux")]
    fn parse_vuln_status(raw: &str) -> (MitigationStatus, bool, f64) {
        let lower = raw.to_lowercase();
        if lower.starts_with("not affected") {
            (MitigationStatus::NotAffected, false, 0.0)
        } else if lower.starts_with("vulnerable") {
            (MitigationStatus::Vulnerable, false, 0.0)
        } else if lower.starts_with("mitigation:") {
            let perf_impact = lower.contains("retpoline")
                || lower.contains("ibrs")
                || lower.contains("stibp")
                || lower.contains("verw")
                || lower.contains("force");
            let impact = if lower.contains("retpoline") {
                3.0
            } else if lower.contains("ibrs") {
                5.0
            } else if lower.contains("verw") {
                2.0
            } else if perf_impact {
                1.5
            } else {
                0.5
            };
            (MitigationStatus::Mitigated, perf_impact, impact)
        } else {
            (MitigationStatus::Unknown, false, 0.0)
        }
    }

    #[cfg(target_os = "windows")]
    fn detect_vulnerabilities() -> Result<Vec<CpuVulnerability>, IronError> {
        // Returning an empty list meant `unmitigated()` reported zero, which
        // reads as "this machine has no unmitigated CPU vulnerabilities" when
        // it means "nothing was checked". Of every absence in this crate that
        // one is the least acceptable to guess at: a reassuring security
        // reading is acted on.
        Err(IronError::UnsupportedPlatform(
            "CPU vulnerability status is read from `/sys/devices/system/cpu/vulnerabilities`; Windows exposes it only through Get-SpeculationControlSettings, which needs Administrator"
                .into(),
        ))
    }

    #[cfg(target_os = "macos")]
    fn detect_vulnerabilities() -> Result<Vec<CpuVulnerability>, IronError> {
        // Returning an empty list meant `unmitigated()` reported zero, which
        // reads as "this machine has no unmitigated CPU vulnerabilities" when
        // it means "nothing was checked". Of every absence in this crate that
        // one is the least acceptable to guess at: a reassuring security
        // reading is acted on.
        Err(IronError::UnsupportedPlatform(
            "CPU vulnerability status is read from `/sys/devices/system/cpu/vulnerabilities`; macOS does not expose it"
                .into(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn detect_vulnerabilities() -> Result<Vec<CpuVulnerability>, IronError> {
        // Returning an empty list meant `unmitigated()` reported zero, which
        // reads as "this machine has no unmitigated CPU vulnerabilities" when
        // it means "nothing was checked". Of every absence in this crate that
        // one is the least acceptable to guess at: a reassuring security
        // reading is acted on.
        Err(IronError::UnsupportedPlatform(
            "CPU vulnerability status is read from `/sys/devices/system/cpu/vulnerabilities`; this platform does not expose it"
                .into(),
        ))
    }

    #[cfg(target_os = "linux")]
    fn detect_security_modules() -> Result<Vec<LsmStatus>, IronError> {
        let mut modules = Vec::new();

        // Check active LSMs
        if let Ok(lsm_list) = std::fs::read_to_string("/sys/kernel/security/lsm") {
            let lsms: Vec<&str> = lsm_list.trim().split(',').collect();
            for lsm in &lsms {
                let module = match *lsm {
                    "selinux" => SecurityModule::SELinux,
                    "apparmor" => SecurityModule::AppArmor,
                    "smack" => SecurityModule::Smack,
                    "tomoyo" => SecurityModule::TOMOYO,
                    "yama" => SecurityModule::Yama,
                    "loadpin" => SecurityModule::LoadPin,
                    "safesetid" => SecurityModule::SafeSetID,
                    "lockdown" => SecurityModule::Lockdown,
                    "bpf" => SecurityModule::BPF,
                    "landlock" => SecurityModule::Landlock,
                    _ => continue,
                };

                // Only SELinux has a mode this reader can read. Other modules used
                // to be given the literal "active" and an unreadable SELinux
                // enforce file the literal "unknown": both were status strings in
                // a mode field, not modes. They are `None` now.
                let mode = match module {
                    SecurityModule::SELinux => std::fs::read_to_string("/sys/fs/selinux/enforce")
                        .ok()
                        .and_then(|s| selinux_mode(&s)),
                    _ => None,
                };

                modules.push(LsmStatus {
                    module,
                    enabled: true,
                    mode,
                });
            }
        }

        Ok(modules)
    }

    #[cfg(target_os = "windows")]
    fn detect_security_modules() -> Result<Vec<LsmStatus>, IronError> {
        // Check Windows Defender
        let defender = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-MpComputerStatus | Select-Object RealTimeProtectionEnabled | ConvertTo-Json",
            ])
            .output();

        let mut modules = Vec::new();
        if let Ok(out) = defender {
            if out.status.success() {
                let text = String::from_utf8_lossy(&out.stdout);
                let enabled = text.contains("true");
                modules.push(LsmStatus {
                    module: SecurityModule::WindowsDefender,
                    enabled,
                    mode: Some(if enabled {
                        "real-time".into()
                    } else {
                        "disabled".into()
                    }),
                });
            }
        }

        Ok(modules)
    }

    #[cfg(target_os = "macos")]
    fn detect_security_modules() -> Result<Vec<LsmStatus>, IronError> {
        let mut modules = Vec::new();

        // Check SIP status
        let sip = std::process::Command::new("csrutil").arg("status").output();

        if let Ok(out) = sip {
            let text = String::from_utf8_lossy(&out.stdout);
            let enabled = text.contains("enabled");
            modules.push(LsmStatus {
                module: SecurityModule::SIP,
                enabled,
                mode: Some(if enabled {
                    "enabled".into()
                } else {
                    "disabled".into()
                }),
            });
        }

        Ok(modules)
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn detect_security_modules() -> Result<Vec<LsmStatus>, IronError> {
        Ok(Vec::new())
    }

    #[cfg(target_os = "linux")]
    fn detect_hardening() -> Result<KernelHardening, IronError> {
        let read_sysctl = |path: &str| -> String {
            std::fs::read_to_string(path)
                .map(|s| s.trim().to_string())
                .unwrap_or_default()
        };

        // An unreadable ASLR sysctl is not disabled ASLR. `unwrap_or(0)` used
        // to report it as level 0.
        let aslr = read_sysctl("/proc/sys/kernel/randomize_va_space")
            .parse::<u32>()
            .ok();

        // An unreadable or absent sysctl is not a disabled setting: older
        // kernels do not have all of these, and `unwrap_or(0)` reported every
        // missing file as hardening switched off.
        let kptr = read_sysctl("/proc/sys/kernel/kptr_restrict")
            .parse::<u32>()
            .ok()
            .map(|v| v > 0);

        let dmesg = read_sysctl("/proc/sys/kernel/dmesg_restrict")
            .parse::<u32>()
            .ok()
            .map(|v| v > 0);

        let bpf = read_sysctl("/proc/sys/kernel/unprivileged_bpf_disabled")
            .parse::<u32>()
            .ok()
            .map(|v| v > 0);

        // Yama absent means there is no scope to read, not an unrestricted one.
        // `unwrap_or(0)` used to report it as scope 0.
        let ptrace = read_sysctl("/proc/sys/kernel/yama/ptrace_scope")
            .parse::<u32>()
            .ok();

        // `modules_locked` was a literal `false` on every platform. This is the
        // kernel's own flag: 1 once module loading has been disabled for good.
        let modules_locked = read_sysctl("/proc/sys/kernel/modules_disabled")
            .parse::<u32>()
            .ok()
            .map(|v| v > 0);

        let lockdown = read_sysctl("/sys/kernel/security/lockdown");

        // Secure boot detection
        // This tested only that the efivar *exists*, which it does on every
        // UEFI system whether Secure Boot is on or off — so any UEFI Linux
        // machine reported Secure Boot enabled. The variable's last byte
        // carries the state, which `boot_config` already reads correctly.
        let secure_boot = std::fs::read(
            "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c",
        )
        .ok()
        .and_then(|data| data.last().map(|b| *b == 1));

        Ok(KernelHardening {
            aslr_level: aslr,
            kptr_restrict: kptr,
            dmesg_restrict: dmesg,
            unprivileged_bpf_disabled: bpf,
            ptrace_scope: ptrace,
            modules_locked,
            // The bracketed token. A missing file, or one with no bracket, is
            // no mode at all, not "none".
            lockdown_mode: active_lockdown_mode(&lockdown),
            secure_boot,
            stack_protector: None, // Most modern kernels have this
        })
    }

    #[cfg(target_os = "windows")]
    fn detect_hardening() -> Result<KernelHardening, IronError> {
        // `Confirm-SecureBootUEFI` needs elevation and returned `false` for a
        // permission error. The registry carries the same state unelevated.
        let sb = crate::platform::windows::secure_boot_enabled();

        Ok(KernelHardening {
            // Windows has ASLR, but this reader does not read its state.
            // "Always has ASLR" was asserted as level 2 without a check.
            aslr_level: None,
            // These four are Linux kernel tunables with no Windows equivalent.
            // Asserting `true` credited the posture score for hardening that
            // was never checked and does not exist in this form here.
            kptr_restrict: None,
            dmesg_restrict: None,
            unprivileged_bpf_disabled: None,
            // Yama is Linux-only. The reader used to report scope 0 here, which
            // read as "unrestricted" rather than "not applicable".
            ptrace_scope: None,
            modules_locked: None,
            lockdown_mode: None,
            secure_boot: sb,
            stack_protector: None,
        })
    }

    #[cfg(target_os = "macos")]
    fn detect_hardening() -> Result<KernelHardening, IronError> {
        Ok(KernelHardening {
            // macOS ASLR is not read here. "Always has ASLR" was asserted as 2.
            aslr_level: None,
            // Linux tunables with no macOS equivalent; none of this is read.
            kptr_restrict: None,
            dmesg_restrict: None,
            unprivileged_bpf_disabled: None,
            // Yama is Linux-only. Scope 1 was asserted, and it credited the
            // ptrace component of the score on every Mac.
            ptrace_scope: None,
            modules_locked: None,
            lockdown_mode: None,
            // "Apple Silicon always has Secure Boot" is not a reading, and this
            // code runs on Intel Macs too, where it depends on the T2 chip and
            // the user's Startup Security Utility setting.
            secure_boot: None,
            stack_protector: None,
        })
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn detect_hardening() -> Result<KernelHardening, IronError> {
        // Unsupported platform: none of these was read. Level 0 and `false` used
        // to be asserted here, which reads as ASLR off and modules unlocked.
        Ok(KernelHardening {
            aslr_level: None,
            kptr_restrict: None,
            dmesg_restrict: None,
            unprivileged_bpf_disabled: None,
            ptrace_scope: None,
            modules_locked: None,
            lockdown_mode: None,
            secure_boot: None,
            stack_protector: None,
        })
    }
}

impl Default for SecurityMitigationsMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            vulnerabilities: Vec::new(),
            security_modules: Vec::new(),
            hardening: KernelHardening {
                aslr_level: None,
                kptr_restrict: None,
                dmesg_restrict: None,
                unprivileged_bpf_disabled: None,
                ptrace_scope: None,
                modules_locked: None,
                lockdown_mode: None,
                secure_boot: None,
                stack_protector: None,
            },
            posture: SecurityPosture {
                score: None,
                risk_level: "Unknown".into(),
                component_scores: Vec::new(),
                findings: Vec::new(),
            },
        })
    }
}

/// The SELinux mode from `/sys/fs/selinux/enforce`: `1` is enforcing, `0` is
/// permissive. Any other content is not a mode, so it is `None`.
#[cfg(any(target_os = "linux", test))]
fn selinux_mode(enforce: &str) -> Option<String> {
    match enforce.trim() {
        "1" => Some("enforcing".into()),
        "0" => Some("permissive".into()),
        _ => None,
    }
}

/// The active kernel lockdown mode from `/sys/kernel/security/lockdown`.
///
/// The file lists every mode and brackets the active one, as in
/// `none [integrity] confidentiality`. `None` when no mode is bracketed.
#[cfg(any(target_os = "linux", test))]
fn active_lockdown_mode(file: &str) -> Option<String> {
    let open = file.find('[')?;
    let close = open + file[open..].find(']')?;
    let token = file[open + 1..close].trim();
    (!token.is_empty()).then(|| token.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mitigation_status_display() {
        assert_eq!(MitigationStatus::Mitigated.to_string(), "Mitigated");
        assert_eq!(MitigationStatus::Vulnerable.to_string(), "Vulnerable");
        assert_eq!(MitigationStatus::NotAffected.to_string(), "Not Affected");
    }

    #[test]
    fn test_posture_scoring() {
        let vulns = vec![
            CpuVulnerability {
                name: "spectre_v1".into(),
                description: "Spectre V1".into(),
                cve: vec!["CVE-2017-5753".into()],
                status: MitigationStatus::Mitigated,
                raw_status: "Mitigation: usercopy".into(),
                performance_impact: false,
                estimated_impact_pct: 0.5,
            },
            CpuVulnerability {
                name: "meltdown".into(),
                description: "Meltdown".into(),
                cve: vec!["CVE-2017-5754".into()],
                status: MitigationStatus::NotAffected,
                raw_status: "Not affected".into(),
                performance_impact: false,
                estimated_impact_pct: 0.0,
            },
        ];

        let lsms = vec![LsmStatus {
            module: SecurityModule::AppArmor,
            enabled: true,
            mode: Some("enforce".into()),
        }];

        let hardening = KernelHardening {
            aslr_level: Some(2),
            kptr_restrict: None,
            dmesg_restrict: None,
            unprivileged_bpf_disabled: None,
            ptrace_scope: Some(1),
            modules_locked: None,
            lockdown_mode: None,
            secure_boot: None,
            stack_protector: None,
        };

        let posture = SecurityMitigationsMonitor::compute_posture(&vulns, &lsms, &hardening);
        assert!(posture.score.is_some_and(|s| s >= 70)); // Good security posture
        assert!(posture.risk_level == "Low" || posture.risk_level == "Minimal");
    }

    #[test]
    fn lockdown_reports_the_bracketed_mode_only() {
        assert_eq!(
            active_lockdown_mode("none [integrity] confidentiality\n").as_deref(),
            Some("integrity")
        );
        assert_eq!(
            active_lockdown_mode("[none] integrity confidentiality").as_deref(),
            Some("none")
        );
        // Not a lockdown file: no bracket, so no mode.
        assert_eq!(active_lockdown_mode("none integrity confidentiality"), None);
        assert_eq!(active_lockdown_mode(""), None);
    }

    #[test]
    fn selinux_enforce_file_is_a_mode_only_when_it_says_so() {
        assert_eq!(selinux_mode("1\n").as_deref(), Some("enforcing"));
        assert_eq!(selinux_mode("0\n").as_deref(), Some("permissive"));
        // Any other content is not a mode; it must not become a status string.
        assert_eq!(selinux_mode(""), None);
        assert_eq!(selinux_mode("unknown"), None);
        assert_eq!(selinux_mode("2"), None);
    }

    #[test]
    fn nothing_enumerated_is_no_score() {
        let hardened = KernelHardening {
            aslr_level: Some(2),
            kptr_restrict: Some(true),
            dmesg_restrict: Some(true),
            unprivileged_bpf_disabled: None,
            ptrace_scope: Some(1),
            modules_locked: None,
            lockdown_mode: None,
            secure_boot: Some(true),
            stack_protector: None,
        };
        // Zero vulnerabilities enumerated must not read as a full score.
        let posture = SecurityMitigationsMonitor::compute_posture(&[], &[], &hardened);
        assert_eq!(posture.score, None);
        assert_eq!(posture.risk_level, "Unknown");
        assert!(posture
            .component_scores
            .iter()
            .all(|(name, _)| name != "CPU Vulnerability Mitigations"));
    }

    #[test]
    fn unread_hardening_is_neither_credited_nor_penalised() {
        let vulns = Vec::new();
        let lsms = Vec::new();
        let unread = KernelHardening {
            aslr_level: None,
            kptr_restrict: None,
            dmesg_restrict: None,
            unprivileged_bpf_disabled: None,
            ptrace_scope: None,
            modules_locked: None,
            lockdown_mode: None,
            secure_boot: None,
            stack_protector: None,
        };

        let posture = SecurityMitigationsMonitor::compute_posture(&vulns, &lsms, &unread);
        let hardening_score = posture
            .component_scores
            .iter()
            .find(|(name, _)| name == "Kernel Hardening")
            .map(|(_, score)| *score);
        assert_eq!(hardening_score, Some(0));
        // ASLR is only a finding when it was read and is below full.
        assert!(!posture
            .findings
            .iter()
            .any(|f| f.title == "ASLR not at full level"));
    }

    #[test]
    fn test_performance_impact() {
        let monitor = SecurityMitigationsMonitor {
            vulnerabilities: vec![
                CpuVulnerability {
                    name: "spectre_v2".into(),
                    description: "".into(),
                    cve: vec![],
                    status: MitigationStatus::Mitigated,
                    raw_status: "Mitigation: Retpolines".into(),
                    performance_impact: true,
                    estimated_impact_pct: 3.0,
                },
                CpuVulnerability {
                    name: "mds".into(),
                    description: "".into(),
                    cve: vec![],
                    status: MitigationStatus::Mitigated,
                    raw_status: "Mitigation: VERW".into(),
                    performance_impact: true,
                    estimated_impact_pct: 2.0,
                },
            ],
            security_modules: Vec::new(),
            hardening: KernelHardening {
                aslr_level: Some(2),
                kptr_restrict: None,
                dmesg_restrict: None,
                unprivileged_bpf_disabled: None,
                ptrace_scope: None,
                modules_locked: None,
                lockdown_mode: None,
                secure_boot: None,
                stack_protector: None,
            },
            posture: SecurityPosture {
                score: Some(50),
                risk_level: "Medium".into(),
                component_scores: vec![],
                findings: vec![],
            },
        };

        let impact = monitor.total_performance_impact();
        assert!((impact - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_monitor_default() {
        let monitor = SecurityMitigationsMonitor::default();
        let _unmitigated = monitor.unmitigated();
    }

    #[test]
    fn test_serialization() {
        let finding = SecurityFinding {
            severity: "high".into(),
            title: "Test finding".into(),
            description: "A test".into(),
            remediation: "Fix it".into(),
        };
        let json = serde_json::to_string(&finding).unwrap();
        assert!(json.contains("high"));
        let _: SecurityFinding = serde_json::from_str(&json).unwrap();
    }

    /// A platform that cannot read CPU vulnerabilities produces no report.
    ///
    /// `detect_vulnerabilities` returns `UnsupportedPlatform` off Linux, with
    /// a comment worth keeping: *"a reassuring security reading is acted on"*.
    /// That error is what makes `detect_hardening`'s non-Linux branches
    /// unreachable — they asserted `kptr_restrict`, `dmesg_restrict`,
    /// `unprivileged_bpf_disabled` and `stack_protector` as `true`, which are
    /// Linux kernel tunables with no equivalent there, and two of them feed
    /// the posture score.
    ///
    /// They are `None` now, but this test is the one that matters: **if
    /// someone implements vulnerability detection for another platform, the
    /// hardening branch beside it becomes live in the same commit.** This
    /// fails then, which is the moment to look at it.
    #[cfg(not(target_os = "linux"))]
    #[test]
    fn a_platform_without_vulnerability_data_publishes_no_posture() {
        let built = SecurityMitigationsMonitor::new();
        assert!(
            built.is_err(),
            concat!(
                "this platform now produces a security posture. Check that ",
                "detect_hardening does not assert Linux kernel tunables it ",
                "cannot read -- two of them add to the score."
            )
        );
    }

    /// Secure Boot is read from the variable's value, not its existence.
    ///
    /// The Linux reader tested `Path::exists()` on the efivar, which is
    /// present on every UEFI system whether Secure Boot is on or off, so any
    /// UEFI machine reported it enabled. `boot_config` already read the last
    /// byte correctly.
    #[cfg(target_os = "linux")]
    #[test]
    fn secure_boot_is_read_from_the_variable_not_its_presence() {
        let monitor = SecurityMitigationsMonitor::new().expect("a report on Linux");

        let path = std::path::Path::new(
            "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c",
        );
        if !path.exists() {
            assert_eq!(
                monitor.hardening.secure_boot, None,
                "no efivar to read, so no state to report"
            );
            return;
        }

        // Present: the answer must match the byte, not the file's existence.
        let expected = std::fs::read(path)
            .ok()
            .and_then(|d| d.last().map(|b| *b == 1));
        assert_eq!(monitor.hardening.secure_boot, expected);
    }

    /// An unread Secure Boot state is not a Secure Boot finding.
    #[cfg(target_os = "linux")]
    #[test]
    fn an_unread_secure_boot_state_is_not_a_medium_finding() {
        let monitor = SecurityMitigationsMonitor::new().expect("a report on Linux");
        if monitor.hardening.secure_boot.is_none() {
            assert!(
                !monitor
                    .posture
                    .findings
                    .iter()
                    .any(|f| f.title == "Secure Boot not enabled"),
                "Secure Boot was not read, so it must not be reported as off"
            );
        }
    }
}