Skip to main content

sys_lib/device/
report.rs

1//! How far to trust the id on this machine, without revealing any value.
2
3use core::fmt;
4
5use super::{Anchor, Basis, Raw, Reading, read_anchor};
6use crate::{os::Confidence, virt};
7
8/// The state of every source, with no values in it.
9///
10/// ```
11/// use sys_lib::device;
12///
13/// let report = device::report();
14/// println!("{report}");
15/// if !report.clone_risk.is_empty() {
16///     println!("this id may be shared with other machines: {:?}", report.clone_risk);
17/// }
18/// ```
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct StabilityReport {
22    /// One per [`Anchor`], in `Anchor` order.
23    pub sources: Vec<SourceStatus>,
24    /// Whether [`Basis::Install`] has a usable source.
25    pub default_basis_available: bool,
26    /// What suggests this id may be shared; empty when nothing does.
27    pub clone_risk: Vec<CloneRisk>,
28    /// How far to trust the [`Basis::Install`] id.
29    pub confidence: Confidence,
30    /// What would change the [`Basis::Install`] id on this OS.
31    pub changes_on: Vec<ChangeEvent>,
32}
33
34/// One source and its state.
35#[derive(Clone, Copy, PartialEq, Eq, Debug)]
36#[non_exhaustive]
37pub struct SourceStatus {
38    /// The source.
39    pub anchor: Anchor,
40    /// Its state.
41    pub state: SourceState,
42}
43
44/// What became of reading a source.
45#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
46#[non_exhaustive]
47pub enum SourceState {
48    /// A usable value exists.
49    Present,
50    /// No value exists.
51    Absent,
52    /// The value is one manufacturers and hypervisors ship, treated as absent.
53    Placeholder,
54    /// The OS refused; on Linux the DMI identifiers need root.
55    PermissionDenied,
56    /// This OS has no such source.
57    Unsupported,
58}
59
60/// What suggests an id may be shared with other machines.
61#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
62#[non_exhaustive]
63pub enum CloneRisk {
64    /// Running in a container: every container of one image may share an id.
65    Container,
66    /// Running in a VM: clones of one template share an id until regenerated.
67    VirtualMachine,
68    /// `/etc/machine-id` is empty or `uninitialized`.
69    MachineIdUninitialized,
70    /// A container with a machine id, which came from its image.
71    SharedImageLikely,
72}
73
74/// What would change an id.
75#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
76#[non_exhaustive]
77pub enum ChangeEvent {
78    /// The OS is reinstalled.
79    OsReinstall,
80    /// The main board is replaced.
81    BoardReplacement,
82    /// The network card is replaced.
83    NicReplacement,
84    /// The CPU is upgraded.
85    CpuUpgrade,
86    /// The VM is created again.
87    VmRecreated,
88    /// The container is created again.
89    ContainerRecreated,
90    /// An administrator sets a new value.
91    AdminReset,
92}
93
94/// Probes every source once. Sources only: no application id is needed, and no
95/// value appears in the result.
96#[must_use]
97pub fn report() -> StabilityReport {
98    let sources: Vec<SourceStatus> = Anchor::ALL
99        .into_iter()
100        .map(|anchor| {
101            let mut raw = Raw::new();
102            let state = match read_anchor(anchor, &mut raw) {
103                Reading::Value(_) => SourceState::Present,
104                Reading::Absent => SourceState::Absent,
105                Reading::Placeholder => SourceState::Placeholder,
106                Reading::PermissionDenied => SourceState::PermissionDenied,
107                Reading::Unsupported => SourceState::Unsupported,
108            };
109            SourceStatus { anchor, state }
110        })
111        .collect();
112    assess(sources, virt::is_container(), virt::is_vm())
113}
114
115/// The anchors behind [`Basis::Install`] on this OS.
116fn install_state(sources: &[SourceStatus]) -> SourceState {
117    let anchor = Basis::Install.anchors()[0];
118    sources
119        .iter()
120        .find(|s| s.anchor == anchor)
121        .map_or(SourceState::Absent, |s| s.state)
122}
123
124fn assess(sources: Vec<SourceStatus>, container: bool, vm: bool) -> StabilityReport {
125    let state = install_state(&sources);
126    let available = state == SourceState::Present;
127    let mut clone_risk = Vec::new();
128    if container {
129        clone_risk.push(CloneRisk::Container);
130    }
131    if vm {
132        clone_risk.push(CloneRisk::VirtualMachine);
133    }
134    if state == SourceState::Placeholder {
135        clone_risk.push(CloneRisk::MachineIdUninitialized);
136    }
137    if container && available {
138        clone_risk.push(CloneRisk::SharedImageLikely);
139    }
140    let confidence = if !available {
141        Confidence::None
142    } else if container {
143        Confidence::Low
144    } else if vm {
145        Confidence::Medium
146    } else {
147        Confidence::High
148    };
149    let mut changes_on = if cfg!(any(target_os = "macos", target_os = "ios")) {
150        vec![ChangeEvent::BoardReplacement]
151    } else {
152        vec![ChangeEvent::OsReinstall, ChangeEvent::AdminReset]
153    };
154    if vm {
155        changes_on.push(ChangeEvent::VmRecreated);
156    }
157    if container {
158        changes_on.push(ChangeEvent::ContainerRecreated);
159    }
160    StabilityReport {
161        sources,
162        default_basis_available: available,
163        clone_risk,
164        confidence,
165        changes_on,
166    }
167}
168
169impl fmt::Display for StabilityReport {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        for s in &self.sources {
172            let state = match s.state {
173                SourceState::Present => "present",
174                SourceState::Absent => "absent",
175                SourceState::Placeholder => "placeholder",
176                SourceState::PermissionDenied => "permission denied",
177                SourceState::Unsupported => "unsupported",
178            };
179            writeln!(f, "{:<16}{state}", s.anchor.name())?;
180        }
181        writeln!(f, "{:<16}{:?}", "confidence", self.confidence)?;
182        write!(f, "{:<16}{:?}", "clone risk", self.clone_risk)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    fn sources(state: SourceState) -> Vec<SourceStatus> {
191        Anchor::ALL
192            .into_iter()
193            .map(|anchor| SourceStatus { anchor, state })
194            .collect()
195    }
196
197    #[test]
198    fn test_report_bare_metal() {
199        let r = assess(sources(SourceState::Present), false, false);
200        assert!(r.default_basis_available);
201        assert!(r.clone_risk.is_empty());
202        assert_eq!(r.confidence, Confidence::High);
203    }
204
205    #[test]
206    fn test_report_clone_risks() {
207        // E-71, E-72.
208        let r = assess(sources(SourceState::Present), true, true);
209        assert_eq!(
210            r.clone_risk,
211            vec![
212                CloneRisk::Container,
213                CloneRisk::VirtualMachine,
214                CloneRisk::SharedImageLikely
215            ]
216        );
217        assert_eq!(r.confidence, Confidence::Low);
218        assert!(r.changes_on.contains(&ChangeEvent::ContainerRecreated));
219        assert_eq!(
220            assess(sources(SourceState::Present), false, true).confidence,
221            Confidence::Medium
222        );
223        // E-69.
224        let r = assess(sources(SourceState::Placeholder), false, false);
225        assert_eq!(r.clone_risk, vec![CloneRisk::MachineIdUninitialized]);
226        assert!(!r.default_basis_available);
227        assert_eq!(r.confidence, Confidence::None);
228    }
229
230    #[test]
231    fn test_report_live_has_every_source_and_no_values() {
232        let r = report();
233        assert_eq!(r.sources.len(), Anchor::ALL.len());
234        let text = r.to_string();
235        assert!(text.contains("install id") && text.contains("confidence"));
236    }
237}