openmoat_core/boundary.rs
1//! The sandbox boundary one `openmoat run` has (ADR-089): which tier was asked
2//! for and which started, every downgrade and why, how the network is held,
3//! the Landlock ABI, whether tool commands get the relay token, and for each
4//! restriction whether the system has it, the run asks for it, it applied and
5//! a check after the agent started confirmed it.
6//!
7//! Pure data: the CLI fills it from the platform and the launch, writes it to
8//! the audit log as one row on every run and prints it for
9//! `openmoat run --print-boundary`. Its JSON form is what scripts read, so
10//! fields are only added, and [`VERSION`] moves when one changes meaning.
11
12use serde::{Deserialize, Serialize};
13
14mod score;
15pub use score::{
16 ProtectionScore, ScoreItem, WEIGHTS_LINUX, WEIGHTS_MACOS, WEIGHTS_WINDOWS, weights,
17};
18
19/// The version of the record's JSON form.
20pub const VERSION: u32 = 1;
21
22/// The boundary of one run.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct EffectiveBoundary {
25 /// [`VERSION`].
26 pub version: u32,
27 /// The operating system (`linux`, `macos`, …).
28 pub os: String,
29 /// What the command line asked for.
30 pub requested: Requested,
31 /// The tier that starts.
32 pub tier: Tier,
33 /// Every way this run is weaker than the full boundary, each with why.
34 pub downgrades: Vec<Downgrade>,
35 /// How the agent's network is held.
36 pub network: Network,
37 /// Linux: the kernel's Landlock ABI and what `restrict_self` reported.
38 pub landlock: Option<Landlock>,
39 /// Whether tool commands receive the hook relay token (ADR-075).
40 pub tool_token: ToolToken,
41 /// Each restriction the platform has, in a fixed order.
42 pub restrictions: Vec<Restriction>,
43 /// What the check after the agent started found; `None` before the
44 /// agent starts (`--print-boundary`) or where no report came back.
45 pub launch: Option<LaunchCheck>,
46 /// Which inherited variables reach the agent (ADR-105), names only;
47 /// absent from records written before it was added.
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub environment: Option<RunEnvironment>,
50 /// The protection score of this run (ADR-108): which of the platform's
51 /// kernel features are in force, out of 100, with the missing ones named.
52 /// Set by [`Self::rescore`], which [`Self::launched`] calls again; absent
53 /// from records written before it was added.
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub score: Option<ProtectionScore>,
56}
57
58/// What of the environment `openmoat run` was started from reaches the
59/// program it starts (ADR-105). Names only: a value is never in the record.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct RunEnvironment {
62 /// Whether only the allowlist passes, rather than every inherited name.
63 pub scrubbed: bool,
64 /// What chose it, in the words the run notice uses.
65 pub why: String,
66 /// Scrubbed: the inherited names that pass, sorted. Inherited: empty,
67 /// since every name passes, a brokered secret's excepted.
68 pub passed: Vec<String>,
69 /// The inherited names the program does not get, sorted; empty when the
70 /// environment is inherited.
71 pub withheld: Vec<String>,
72 /// The names that hold a brokered secret's placeholder instead of its
73 /// value (ADR-020), sorted.
74 pub brokered: Vec<String>,
75}
76
77/// The tier asked for on the command line.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Requested {
81 /// Neither `--isolate` nor `--no-isolate`: the platform's default.
82 Default,
83 /// `--isolate`.
84 Isolated,
85 /// `--no-isolate`.
86 Lightweight,
87}
88
89/// The tiers of ADR-018.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum Tier {
93 /// The agent's own sandbox and OpenMoat's hooks, without `openmoat run`;
94 /// named so a record compares with a hook-only session, never one a run starts.
95 Standard,
96 /// Landlock and seccomp, or Seatbelt, over the whole machine; on Windows
97 /// a write-restricted token in a job object, which holds writes only.
98 Lightweight,
99 /// bubblewrap's own view of the machine around the same rules.
100 Isolated,
101}
102
103/// One way the run is weaker than the full boundary.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Downgrade {
106 /// What is weaker.
107 pub what: Weaker,
108 /// Whether the person chose it (`--no-isolate`) rather than the system
109 /// lacking what it needs.
110 pub chosen: bool,
111 /// Why, in the words the run notice uses.
112 pub why: String,
113}
114
115/// What a [`Downgrade`] weakens.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum Weaker {
119 /// The Lightweight tier instead of the Isolated one.
120 Tier,
121 /// The network restricted by port only instead of a namespace.
122 Network,
123 /// The project's top granted whole instead of entry by entry, by the
124 /// person's own `sandbox.project_top: writable` (ADR-090): `.env`,
125 /// `.git/hooks` and `.moat` there are open to commands.
126 ProjectTop,
127}
128
129/// How the agent's network is held.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct Network {
132 /// The mode.
133 pub mode: NetworkMode,
134 /// The proxy's loopback port, once the run has one.
135 pub proxy_port: Option<u16>,
136}
137
138/// The ways `openmoat run` holds the network.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "snake_case")]
141pub enum NetworkMode {
142 /// A network namespace whose only interface is loopback; the proxy is
143 /// the only way out (Linux, bubblewrap).
144 Namespace,
145 /// Landlock's TCP port rule alone: any host on the proxy's port is
146 /// reachable (Linux without a usable bubblewrap).
147 PortOnly,
148 /// The Seatbelt profile allows the proxy's address alone (macOS).
149 Profile,
150 /// The proxy variables alone (`HTTP_PROXY`, `HTTPS_PROXY`, …): nothing in
151 /// the operating system holds the network, so a program that ignores them
152 /// connects directly (Windows, ADR-115).
153 ProxyVariables,
154}
155
156/// The Landlock part of the record (Linux).
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct Landlock {
159 /// The kernel's ABI, also where it is newer than the `landlock` crate knows.
160 pub abi: Option<u32>,
161 /// Why there is no usable Landlock, when there is none.
162 pub unavailable: Option<String>,
163 /// What `restrict_self` reported for the agent's ruleset; `None` before
164 /// the agent starts, when [`Self::abi`] comes from a probe.
165 pub enforcement: Option<Enforcement>,
166}
167
168/// Landlock's `RulesetStatus`.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum Enforcement {
172 /// Every right asked for applies.
173 Full,
174 /// The required rights apply; a best-effort one the kernel lacks does not.
175 Partial,
176 /// Nothing applies.
177 None,
178}
179
180/// Whether tool commands receive the hook relay token (ADR-075).
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case", tag = "state", content = "why")]
183pub enum ToolToken {
184 /// A wrapper in front of the agent's tool shell drops it.
185 Withheld,
186 /// The host's own integration takes it out of the environment.
187 WithheldByIntegration,
188 /// Tool commands keep it: why.
189 NotWithheld(String),
190 /// The program is no agent OpenMoat knows, so no token handling applies.
191 UnknownAgent,
192}
193
194/// The restrictions a record names.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "snake_case")]
197pub enum Mechanism {
198 /// macOS: the Seatbelt profile `sandbox-exec` applies.
199 Seatbelt,
200 /// Landlock's file rights (ABI 1 to 3).
201 LandlockFilesystem,
202 /// Landlock's TCP connect rule for the proxy's port (ABI 4).
203 LandlockTcpPort,
204 /// Abstract Unix sockets and signals scoped to the sandbox (ABI 6,
205 /// best effort).
206 LandlockScopes,
207 /// Pathname Unix sockets made outside the sandbox refused (ABI 9, best
208 /// effort).
209 LandlockResolveUnix,
210 /// Every UDP bind, connect and send refused (ABI 10, best effort, ADR-108):
211 /// the kernel's own rule beside the seccomp filter's refusal of UDP sockets.
212 LandlockUdp,
213 /// The seccomp filters.
214 Seccomp,
215 /// `PR_SET_NO_NEW_PRIVS`: no set-user-ID gain across `exec`.
216 NoNewPrivs,
217 /// The agent's own network namespace (bubblewrap).
218 NetworkNamespace,
219 /// bubblewrap's view of the machine: the project without its denied
220 /// paths, the read roots and `--write` paths (the Isolated tier).
221 IsolatedView,
222 /// Windows: the agent's write-restricted token (ADR-115). A write needs
223 /// the run's own SIDs to be granted it too, and they are granted only on
224 /// the project, the run's temp directory and `--write` paths.
225 RestrictedToken,
226 /// Windows: the job object the agent and every process it starts are in,
227 /// which kills them all when the run ends and lets none break away.
228 JobObject,
229 /// Windows: a Windows Filtering Platform filter holding the network to
230 /// the proxy. Not part of OpenMoat's Windows tier yet, so never in force.
231 WfpNetwork,
232 /// Windows: reads the policy denies refused by the operating system. A
233 /// write-restricted token does not restrict reads, so never in force;
234 /// the hook decides every read.
235 WindowsReadDeny,
236}
237
238impl Mechanism {
239 /// The name the JSON form and the run's output use.
240 #[must_use]
241 pub fn id(self) -> &'static str {
242 match self {
243 Self::Seatbelt => "seatbelt",
244 Self::LandlockFilesystem => "landlock_filesystem",
245 Self::LandlockTcpPort => "landlock_tcp_port",
246 Self::LandlockScopes => "landlock_scopes",
247 Self::LandlockResolveUnix => "landlock_resolve_unix",
248 Self::LandlockUdp => "landlock_udp",
249 Self::Seccomp => "seccomp",
250 Self::NoNewPrivs => "no_new_privs",
251 Self::NetworkNamespace => "network_namespace",
252 Self::IsolatedView => "isolated_view",
253 Self::RestrictedToken => "restricted_token",
254 Self::JobObject => "job_object",
255 Self::WfpNetwork => "wfp_network",
256 Self::WindowsReadDeny => "windows_read_deny",
257 }
258 }
259}
260
261/// One restriction of the run.
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct Restriction {
264 /// Which.
265 pub name: Mechanism,
266 /// This system has it.
267 pub available: bool,
268 /// This run asks for it.
269 pub configured: bool,
270 /// The kernel or tool reported it in force; `None` before the agent
271 /// starts, or where nothing reports it.
272 pub applied: Option<bool>,
273 /// A check after the agent started confirmed it (`/proc/<pid>/status`);
274 /// `None` where no such check exists (Landlock's rules cannot be read
275 /// back, Seatbelt has no `/proc`).
276 pub tested: Option<bool>,
277}
278
279impl Restriction {
280 /// A restriction as planned: not yet applied or tested.
281 #[must_use]
282 pub fn planned(name: Mechanism, available: bool, configured: bool) -> Self {
283 Self {
284 name,
285 available,
286 configured,
287 applied: None,
288 tested: None,
289 }
290 }
291
292 /// Whether the run asked for it, the system has it, and the launch found
293 /// it not applied or not in force. Once the agent started (`launched`),
294 /// what the tier promises must be confirmed: unknown counts as missing
295 /// for the seccomp filters and `no_new_privs` (`tested`), and for
296 /// Landlock's required rights and bubblewrap's namespace and view
297 /// (`applied`). Best-effort steps and Seatbelt, which nothing reports,
298 /// are missing only when reported off. On Windows the token and the job
299 /// must be confirmed on the agent's own process (`tested`).
300 #[must_use]
301 pub fn missing(&self, launched: bool) -> bool {
302 if !self.configured || !self.available {
303 return false;
304 }
305 let reported_off = self.applied == Some(false) || self.tested == Some(false);
306 let confirmed = match self.name {
307 Mechanism::Seccomp
308 | Mechanism::NoNewPrivs
309 | Mechanism::RestrictedToken
310 | Mechanism::JobObject => self.tested == Some(true),
311 Mechanism::LandlockFilesystem
312 | Mechanism::LandlockTcpPort
313 | Mechanism::NetworkNamespace
314 | Mechanism::IsolatedView => self.applied == Some(true),
315 Mechanism::LandlockScopes
316 | Mechanism::LandlockResolveUnix
317 | Mechanism::LandlockUdp
318 | Mechanism::Seatbelt
319 | Mechanism::WfpNetwork
320 | Mechanism::WindowsReadDeny => true,
321 };
322 reported_off || (launched && !confirmed)
323 }
324}
325
326/// What the launch reported, from the process that started the agent: the
327/// result of `restrict_self` and the seccomp filters, and the agent's
328/// `/proc/<pid>/status` read after it started.
329#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
330pub struct LaunchCheck {
331 /// The kernel's Landlock ABI, as `restrict_self` reported it.
332 pub landlock_abi: Option<u32>,
333 /// The ruleset's enforcement, as `restrict_self` reported it.
334 pub landlock: Option<Enforcement>,
335 /// `restrict_self` set `no_new_privs`.
336 pub no_new_privs_set: Option<bool>,
337 /// How many seccomp filters were applied.
338 pub seccomp_filters: Option<u32>,
339 /// The `Seccomp_filters:` count of the thread that started the agent,
340 /// before it applied them: filters a parent (a container runtime, a
341 /// service manager) had already set.
342 pub inherited_seccomp_filters: Option<u32>,
343 /// The agent's `Seccomp_filters:` count.
344 pub proc_seccomp_filters: Option<u32>,
345 /// The agent's `NoNewPrivs:` line read `1`. It may have been set by a
346 /// parent already; what counts is that it is in force.
347 pub proc_no_new_privs: Option<bool>,
348 /// The agent's `Seccomp:` line read `2` (filter mode) and its filter count
349 /// is the inherited count plus the filters applied, so the filters in
350 /// force include this run's, not only a parent's.
351 pub proc_seccomp_filter: Option<bool>,
352 /// The report came from `openmoat isolated` inside bubblewrap.
353 pub in_bubblewrap: bool,
354 /// Windows: the agent's process was created with the write-restricted
355 /// token (`CreateProcessAsUserW` took it); absent from other records.
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub restricted_token: Option<bool>,
358 /// Windows: the agent's own token, read back before it ran, is restricted
359 /// (`IsTokenRestricted`).
360 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub agent_token_restricted: Option<bool>,
362 /// Windows: the agent was put in the run's kill-on-close job before it ran.
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub job_object: Option<bool>,
365 /// Windows: the agent's process, checked before it ran, is in that job
366 /// (`IsProcessInJob`).
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub agent_in_job: Option<bool>,
369 /// Why the launch was stopped, when it was.
370 pub failure: Option<String>,
371}
372
373impl LaunchCheck {
374 /// What the tier promises and the check found missing on Linux: a ruleset
375 /// not enforced, `no_new_privs` or the seccomp filter not in force in the
376 /// agent. Empty when everything is in force.
377 #[must_use]
378 pub fn linux_gaps(&self) -> Vec<&'static str> {
379 let mut gaps = Vec::new();
380 if self.landlock != Some(Enforcement::Full) && self.landlock != Some(Enforcement::Partial) {
381 gaps.push("the Landlock rules are not enforced");
382 }
383 if self.proc_no_new_privs != Some(true) {
384 gaps.push("the agent's /proc status does not show `NoNewPrivs: 1`");
385 }
386 if self.proc_seccomp_filter != Some(true) {
387 gaps.push(
388 "the agent's /proc status does not show `Seccomp: 2` with this run's filters \
389 added to the inherited ones (`Seccomp_filters`)",
390 );
391 }
392 gaps
393 }
394
395 /// The check's failure: the one the reporting process gave, else the
396 /// [`Self::linux_gaps`] found here, so a report is never taken on trust.
397 #[must_use]
398 pub fn linux_failure(&self) -> Option<String> {
399 let gaps = self.linux_gaps();
400 self.failure
401 .clone()
402 .or_else(|| (!gaps.is_empty()).then(|| gaps.join("; ")))
403 }
404}
405
406impl EffectiveBoundary {
407 /// Whether anything is weaker than the full boundary.
408 #[must_use]
409 pub fn downgraded(&self) -> bool {
410 !self.downgrades.is_empty()
411 }
412
413 /// The restriction named `name`, if the platform has it.
414 #[must_use]
415 pub fn restriction(&self, name: Mechanism) -> Option<&Restriction> {
416 self.restrictions.iter().find(|r| r.name == name)
417 }
418
419 /// Fold what the launch reported into the record: what applied, what the
420 /// check after the start confirmed, and the ABI `restrict_self` saw in
421 /// place of the probe's.
422 pub fn launched(&mut self, check: LaunchCheck) {
423 if let Some(landlock) = &mut self.landlock {
424 if check.landlock_abi.is_some() {
425 landlock.abi = check.landlock_abi;
426 }
427 landlock.enforcement = check.landlock;
428 }
429 let abi = self.landlock.as_ref().and_then(|l| l.abi);
430 let enforced = check.landlock.map(|e| e != Enforcement::None);
431 // A step the kernel's ABI lacks is not applied, whatever the ruleset
432 // reports. One the kernel has applies only when the ruleset is fully
433 // enforced; a partial one may lack exactly that step, so it is unknown.
434 let step = |from: u32| match (check.landlock, abi) {
435 (Some(Enforcement::None), _) => Some(false),
436 (_, Some(abi)) if abi < from => Some(false),
437 (Some(Enforcement::Full), Some(_)) => Some(true),
438 _ => None,
439 };
440 for restriction in &mut self.restrictions {
441 let (applied, tested) = match restriction.name {
442 Mechanism::LandlockFilesystem | Mechanism::LandlockTcpPort => (enforced, None),
443 Mechanism::LandlockScopes => (step(6), None),
444 Mechanism::LandlockResolveUnix => (step(9), None),
445 Mechanism::LandlockUdp => (step(10), None),
446 Mechanism::Seccomp => (
447 check.seccomp_filters.map(|n| n > 0),
448 check.proc_seccomp_filter,
449 ),
450 Mechanism::NoNewPrivs => (check.no_new_privs_set, check.proc_no_new_privs),
451 Mechanism::NetworkNamespace | Mechanism::IsolatedView => {
452 (Some(check.in_bubblewrap), None)
453 }
454 Mechanism::RestrictedToken => {
455 (check.restricted_token, check.agent_token_restricted)
456 }
457 Mechanism::JobObject => (check.job_object, check.agent_in_job),
458 Mechanism::Seatbelt | Mechanism::WfpNetwork | Mechanism::WindowsReadDeny => {
459 (None, None)
460 }
461 };
462 if restriction.configured {
463 restriction.applied = applied;
464 restriction.tested = tested;
465 }
466 }
467 self.launch = Some(check);
468 self.rescore();
469 }
470
471 /// Work out [`Self::score`] from the record as it stands.
472 pub fn rescore(&mut self) {
473 self.score = Some(score::of(self));
474 }
475
476 /// The restrictions the run asked for, the system has, and the launch
477 /// found missing; with the launch's own failure, if it stopped the agent.
478 #[must_use]
479 pub fn missing(&self) -> Vec<String> {
480 let mut missing: Vec<String> = self
481 .restrictions
482 .iter()
483 .filter(|r| r.missing(self.launch.is_some()))
484 .map(|r| r.name.id().to_owned())
485 .collect();
486 if let Some(failure) = self.launch.as_ref().and_then(|l| l.failure.clone()) {
487 missing.push(failure);
488 }
489 missing
490 }
491}
492
493#[cfg(test)]
494mod tests;