Skip to main content

openmoat_core/boundary/
score.rs

1//! The protection score of a run (ADR-108): each kernel feature `openmoat run`
2//! can use on the platform carries a weight, the weights of one platform add up
3//! to 100, and the score is the sum of the weights of the features in force.
4//! Every feature that is not in force is named with what would bring it, so
5//! the number never stands alone.
6//!
7//! A score compares runs on one operating system, not operating systems: each
8//! platform's 100 is everything OpenMoat's sandbox there can enforce. A
9//! session without `openmoat run` and without a sandbox of the agent's own
10//! scores 0 (the hook alone). `sandbox.strict: true` refuses a run whose score
11//! is below 100 ([`ProtectionScore::complete`]).
12
13use serde::{Deserialize, Serialize};
14
15use super::{EffectiveBoundary, Mechanism, Restriction, Weaker};
16
17/// The weights on Linux: files and the seccomp filter first, then the network
18/// (port rule, namespace), the view of the machine, and the newer Landlock
19/// steps that stand beside the seccomp filter.
20pub const WEIGHTS_LINUX: [(Mechanism, u32); 9] = [
21    (Mechanism::LandlockFilesystem, 25),
22    (Mechanism::LandlockTcpPort, 10),
23    (Mechanism::Seccomp, 15),
24    (Mechanism::NoNewPrivs, 5),
25    (Mechanism::LandlockScopes, 5),
26    (Mechanism::LandlockResolveUnix, 5),
27    (Mechanism::LandlockUdp, 5),
28    (Mechanism::NetworkNamespace, 15),
29    (Mechanism::IsolatedView, 15),
30];
31
32/// The weights on macOS: the Seatbelt profile holds files, the network (the
33/// proxy's address alone) and the Mach services in one.
34pub const WEIGHTS_MACOS: [(Mechanism, u32); 1] = [(Mechanism::Seatbelt, 100)];
35
36/// The weights on Windows (ADR-115): the write-restricted token holds writes,
37/// the job object the process tree. The network and reads carry weight too,
38/// and OpenMoat's Windows tier has neither (no WFP filter; a write-restricted
39/// token does not restrict reads), so a Windows run scores at most 55: the
40/// number says how much of a full boundary is missing, not only what is there.
41pub const WEIGHTS_WINDOWS: [(Mechanism, u32); 4] = [
42    (Mechanism::RestrictedToken, 45),
43    (Mechanism::JobObject, 10),
44    (Mechanism::WfpNetwork, 30),
45    (Mechanism::WindowsReadDeny, 15),
46];
47
48/// The weights of `os` (`std::env::consts::OS`); empty where `openmoat run`
49/// has no sandbox.
50#[must_use]
51pub fn weights(os: &str) -> &'static [(Mechanism, u32)] {
52    match os {
53        "linux" => &WEIGHTS_LINUX,
54        "macos" => &WEIGHTS_MACOS,
55        "windows" => &WEIGHTS_WINDOWS,
56        _ => &[],
57    }
58}
59
60/// Whether OpenMoat's sandbox has `name` at all: the Windows network filter
61/// and read denial are weighted but not built, so they are named as such
62/// rather than as something this system lacks.
63fn built(name: Mechanism) -> bool {
64    !matches!(name, Mechanism::WfpNetwork | Mechanism::WindowsReadDeny)
65}
66
67/// A run's score.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct ProtectionScore {
70    /// 0 to 100.
71    pub points: u32,
72    /// Every weighted feature of the platform, in the table's order.
73    pub items: Vec<ScoreItem>,
74}
75
76/// One feature of the score.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct ScoreItem {
79    /// Which.
80    pub name: Mechanism,
81    /// Its share of 100.
82    pub weight: u32,
83    /// Planned: it will apply. Once the agent started: it was confirmed.
84    pub in_force: bool,
85    /// Why it is not in force and what would bring it; `None` when it is.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub missing: Option<String>,
88}
89
90impl ProtectionScore {
91    /// Whether every feature of the platform is in force: what
92    /// `sandbox.strict: true` requires. A platform without a sandbox is never
93    /// complete.
94    #[must_use]
95    pub fn complete(&self) -> bool {
96        !self.items.is_empty() && self.items.iter().all(|i| i.in_force)
97    }
98
99    /// `name (why)` for each feature not in force, in the table's order.
100    #[must_use]
101    pub fn missing(&self) -> Vec<String> {
102        self.items
103            .iter()
104            .filter_map(|i| Some(format!("{} ({})", i.name.id(), i.missing.as_ref()?)))
105            .collect()
106    }
107
108    /// One line: `75/100`, then what is missing.
109    #[must_use]
110    pub fn line(&self) -> String {
111        let missing = self.missing();
112        if self.items.is_empty() {
113            return "0/100: `openmoat run` has no sandbox on this system".to_owned();
114        }
115        if missing.is_empty() {
116            return format!(
117                "{}/100: every kernel feature it uses is in force",
118                self.points
119            );
120        }
121        format!("{}/100; missing: {}", self.points, missing.join("; "))
122    }
123}
124
125/// What brings `name` where it is missing.
126fn needs(name: Mechanism) -> &'static str {
127    match name {
128        Mechanism::LandlockFilesystem | Mechanism::LandlockTcpPort => {
129            "needs Landlock ABI 4, Linux 6.7"
130        }
131        Mechanism::LandlockScopes => "needs Landlock ABI 6, Linux 6.12",
132        Mechanism::LandlockResolveUnix => "needs Landlock ABI 9, Linux 7.1",
133        Mechanism::LandlockUdp => {
134            "needs Landlock ABI 10, Linux 7.2; the seccomp filter still refuses UDP sockets"
135        }
136        Mechanism::Seccomp => "needs seccomp",
137        Mechanism::NoNewPrivs => "needs `no_new_privs`",
138        Mechanism::NetworkNamespace => {
139            "needs bubblewrap that can make a user namespace; `openmoat doctor` names the fix"
140        }
141        Mechanism::IsolatedView => "needs the Isolated tier: bubblewrap, `openmoat run --isolate`",
142        Mechanism::Seatbelt => "needs `sandbox-exec`",
143        Mechanism::RestrictedToken => "needs `CreateRestrictedToken` and `CreateProcessAsUserW`",
144        Mechanism::JobObject => "needs a job object the agent can be put in",
145        Mechanism::WfpNetwork => {
146            "a Windows Filtering Platform filter; until then the network goes through the proxy \
147             only for programs that honour HTTP_PROXY and HTTPS_PROXY"
148        }
149        Mechanism::WindowsReadDeny => {
150            "a write-restricted token does not restrict reads, so the hook decides every read"
151        }
152    }
153}
154
155/// Whether the launch confirmed `r`. Seatbelt reports nothing back, but
156/// `sandbox-exec` does not start the program when it cannot apply the profile,
157/// so a started agent has it.
158fn confirmed(r: &Restriction) -> bool {
159    r.name == Mechanism::Seatbelt || r.applied == Some(true) || r.tested == Some(true)
160}
161
162/// The score of `record`.
163pub(super) fn of(record: &EffectiveBoundary) -> ProtectionScore {
164    let launched = record.launch.is_some();
165    let failed = record.launch.as_ref().is_some_and(|l| l.failure.is_some());
166    let tier_chosen_away = record
167        .downgrades
168        .iter()
169        .any(|d| d.what == Weaker::Tier && d.chosen);
170    let bubblewrap = |name| matches!(name, Mechanism::IsolatedView | Mechanism::NetworkNamespace);
171    let items: Vec<ScoreItem> = weights(&record.os)
172        .iter()
173        .map(|&(name, weight)| {
174            let missing = match record.restriction(name) {
175                None => Some("not part of this run's sandbox".to_owned()),
176                Some(_) if !built(name) => Some(format!(
177                    "not in OpenMoat's Windows tier yet: {}",
178                    needs(name)
179                )),
180                // `--no-isolate` gives the tier's namespace and view up on purpose.
181                Some(r) if !r.available && tier_chosen_away && bubblewrap(name) => {
182                    Some(format!("this run does not ask for it: {}", needs(name)))
183                }
184                Some(r) if !r.available => Some(format!("not on this system: {}", needs(name))),
185                Some(r) if !r.configured => {
186                    Some(format!("this run does not ask for it: {}", needs(name)))
187                }
188                Some(r) if r.applied == Some(false) || r.tested == Some(false) => {
189                    Some("reported not in force after the start".to_owned())
190                }
191                Some(_) if failed => Some("the start failed".to_owned()),
192                Some(r) if launched && !confirmed(r) => {
193                    Some("not confirmed in force after the start".to_owned())
194                }
195                Some(_) => None,
196            };
197            ScoreItem {
198                name,
199                weight,
200                in_force: missing.is_none(),
201                missing,
202            }
203        })
204        .collect();
205    let points = items.iter().filter(|i| i.in_force).map(|i| i.weight).sum();
206    ProtectionScore { points, items }
207}