Skip to main content

sys_lib/
security.rs

1//! The machine's security settings, read-only.
2//!
3//! For compliance reports, security tooling, and a service's start-up log. Like
4//! [`virt`](crate::virt), it is a report, not a control: each value is what the
5//! OS says, and an administrator controls the OS. Each field is `None` where
6//! the OS has no unprivileged answer. Raw identifiers (TPM endorsement keys,
7//! volume ids) are never read.
8//!
9//! ```
10//! use sys_lib::security;
11//!
12//! let p = security::posture();
13//! println!("{p}");
14//! for v in p.cpu_vulnerabilities.iter().filter(|v| v.status == security::VulnStatus::Vulnerable) {
15//!     println!("vulnerable: {} ({})", v.name, v.detail);
16//! }
17//! ```
18
19use core::fmt;
20
21/// The machine's security settings.
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct Posture {
25    /// UEFI Secure Boot is on.
26    pub secure_boot: Option<bool>,
27    /// The TPM, when the OS reports one. A machine without a TPM and one that
28    /// cannot tell are both `None`.
29    pub tpm: Option<Tpm>,
30    /// The encryption of the volume holding the OS.
31    pub disk_encryption: Option<Encryption>,
32    /// SELinux or AppArmor, and whether it enforces.
33    pub mandatory_access_control: Option<Mac>,
34    /// Address-space layout randomisation is on (for this process on Windows,
35    /// system-wide elsewhere).
36    pub aslr: Option<bool>,
37    /// The Linux kernel lockdown mode; on Windows, virtualization-based
38    /// security (`Integrity` when it runs).
39    pub kernel_lockdown: Option<Lockdown>,
40    /// macOS System Integrity Protection; Windows hypervisor-protected code
41    /// integrity (HVCI).
42    pub code_integrity: Option<bool>,
43    /// The host firewall is on (Windows: the active profile's).
44    pub firewall: Option<bool>,
45    /// What the kernel says about each known CPU vulnerability (Linux).
46    pub cpu_vulnerabilities: Vec<Vulnerability>,
47    /// This process runs as root or elevated Administrator
48    /// ([`process::is_elevated`](crate::process::is_elevated)).
49    pub elevated: Option<bool>,
50}
51
52/// A trusted platform module.
53#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
54#[non_exhaustive]
55pub struct Tpm {
56    /// Its specification version.
57    pub version: TpmVersion,
58}
59
60/// A TPM specification version.
61#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
62#[non_exhaustive]
63pub enum TpmVersion {
64    /// TPM 1.2.
65    V1_2,
66    /// TPM 2.0.
67    V2_0,
68}
69
70/// The encryption of a volume.
71#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
72#[non_exhaustive]
73pub enum Encryption {
74    /// Encrypted, by `kind`: `"LUKS"`, `"BitLocker"`, `"FileVault"`.
75    Enabled {
76        /// The scheme.
77        kind: &'static str,
78    },
79    /// Not encrypted.
80    Disabled,
81}
82
83/// A mandatory access control system.
84#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
85#[non_exhaustive]
86pub struct Mac {
87    /// `"SELinux"` or `"AppArmor"`.
88    pub kind: &'static str,
89    /// It enforces its policy, rather than only logging.
90    pub enforcing: bool,
91}
92
93/// How far the kernel restricts even root.
94#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
95#[non_exhaustive]
96pub enum Lockdown {
97    /// No restriction.
98    Off,
99    /// Root cannot modify the running kernel.
100    Integrity,
101    /// Root can neither modify nor read kernel memory.
102    Confidentiality,
103}
104
105/// One CPU vulnerability and what the kernel did about it.
106#[derive(Clone, Debug, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub struct Vulnerability {
109    /// The kernel's name: `"spectre_v2"`, `"meltdown"`.
110    pub name: String,
111    /// Its state.
112    pub status: VulnStatus,
113    /// The kernel's text: `"Mitigation: Enhanced / Automatic IBRS"`.
114    pub detail: String,
115}
116
117/// The state of a CPU vulnerability.
118#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
119#[non_exhaustive]
120pub enum VulnStatus {
121    /// This CPU is not affected.
122    NotAffected,
123    /// Affected, with a mitigation in place.
124    Mitigated,
125    /// Affected, without a full mitigation.
126    Vulnerable,
127    /// The kernel's text says neither.
128    Unknown,
129}
130
131impl VulnStatus {
132    /// The status of a Linux `/sys/devices/system/cpu/vulnerabilities/*` text.
133    #[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))]
134    pub(crate) fn of(detail: &str) -> VulnStatus {
135        if detail.starts_with("Not affected") {
136            Self::NotAffected
137        } else if detail.starts_with("Mitigation") {
138            Self::Mitigated
139        } else if detail.starts_with("Vulnerable") {
140            Self::Vulnerable
141        } else {
142            Self::Unknown
143        }
144    }
145}
146
147/// The machine's security settings, read once now. Never fails: each field the
148/// OS does not answer is `None`. Costs 0.1 to 2 ms [est.].
149#[must_use]
150pub fn posture() -> Posture {
151    let mut p = crate::sys::posture();
152    p.elevated = crate::process::is_elevated().ok();
153    p
154}
155
156impl fmt::Display for Posture {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        fn flag(v: Option<bool>) -> &'static str {
159            match v {
160                Some(true) => "on",
161                Some(false) => "off",
162                None => "unknown",
163            }
164        }
165        writeln!(f, "{:<18}{}", "secure boot", flag(self.secure_boot))?;
166        let tpm = match self.tpm.map(|t| t.version) {
167            Some(TpmVersion::V2_0) => "2.0",
168            Some(TpmVersion::V1_2) => "1.2",
169            None => "unknown",
170        };
171        writeln!(f, "{:<18}{tpm}", "tpm")?;
172        let enc = match self.disk_encryption {
173            Some(Encryption::Enabled { kind }) => kind,
174            Some(Encryption::Disabled) => "off",
175            None => "unknown",
176        };
177        writeln!(f, "{:<18}{enc}", "disk encryption")?;
178        match self.mandatory_access_control {
179            Some(m) => writeln!(
180                f,
181                "{:<18}{} {}",
182                "access control",
183                m.kind,
184                if m.enforcing {
185                    "enforcing"
186                } else {
187                    "permissive"
188                }
189            )?,
190            None => writeln!(f, "{:<18}unknown", "access control")?,
191        }
192        writeln!(f, "{:<18}{}", "aslr", flag(self.aslr))?;
193        let lockdown = match self.kernel_lockdown {
194            Some(Lockdown::Off) => "off",
195            Some(Lockdown::Integrity) => "integrity",
196            Some(Lockdown::Confidentiality) => "confidentiality",
197            None => "unknown",
198        };
199        writeln!(f, "{:<18}{lockdown}", "kernel lockdown")?;
200        writeln!(f, "{:<18}{}", "code integrity", flag(self.code_integrity))?;
201        writeln!(f, "{:<18}{}", "firewall", flag(self.firewall))?;
202        let vulnerable = self
203            .cpu_vulnerabilities
204            .iter()
205            .filter(|v| v.status == VulnStatus::Vulnerable)
206            .count();
207        writeln!(
208            f,
209            "{:<18}{} known, {vulnerable} vulnerable",
210            "cpu issues",
211            self.cpu_vulnerabilities.len()
212        )?;
213        write!(f, "{:<18}{}", "elevated", flag(self.elevated))
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn test_security_vuln_status_of() {
223        assert_eq!(VulnStatus::of("Not affected"), VulnStatus::NotAffected);
224        assert_eq!(
225            VulnStatus::of("Mitigation: Enhanced / Automatic IBRS"),
226            VulnStatus::Mitigated
227        );
228        assert_eq!(
229            VulnStatus::of("Vulnerable: no microcode"),
230            VulnStatus::Vulnerable
231        );
232        assert_eq!(
233            VulnStatus::of("Unknown: no mitigations"),
234            VulnStatus::Unknown
235        );
236        assert_eq!(VulnStatus::of(""), VulnStatus::Unknown);
237    }
238
239    #[test]
240    fn test_security_live_posture_displays() {
241        let p = posture();
242        let text = p.to_string();
243        assert!(text.contains("secure boot") && text.contains("elevated"));
244        assert_eq!(p.elevated, crate::process::is_elevated().ok());
245    }
246}