sandbox/lib.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Default-deny worker-process sandboxing for OpenVMM and OpenHCL.
5//!
6//! A [`Profile`] describes filesystem grants, network scope, and optional
7//! syscall denials. [`prepare`] computes launch requirements; [`apply`]
8//! establishes worker-side confinement. Selecting and enabling a policy is the
9//! consumer's responsibility, not an automatic consequence of using this crate.
10//!
11//! # Integration status and limits
12//!
13//! PAL supports prepared Linux sandbox launches, and Mesh accepts optional
14//! sandbox profiles. Existing OpenVMM workers are not yet enabled: they still
15//! use ordinary launches and do not call the required early worker-side
16//! [`apply`]. Tracing and profiling are separate changes.
17//!
18//! On Linux, self-mapped workers retain their host UID/GID and PID visibility.
19//! Cross-process signaling is not yet restricted, so this is not a complete
20//! isolation boundary against other processes running under the same host UID.
21//!
22//! # Three stages
23//!
24//! Sandboxing happens in named, ordered stages:
25//!
26//! 1. [`prepare`] — runs in the *control* process, just before it spawns the
27//! worker. It returns a plain-data [`SandboxProcessConfig`] describing the
28//! child's launch environment (which Linux namespaces to create, which
29//! handles stay inheritable, whether to self-map IDs, and — on Windows — the
30//! LPAC construction data). The caller passes that prepared configuration
31//! intact to the platform process builder, which performs the spawn.
32//! This crate deliberately depends on neither `mesh` nor `pal`: it decides
33//! *what* the launch environment must be; PAL decides *how* to apply it.
34//! 2. [`apply`] — the **first statement of the worker's `main()`**. On Linux the
35//! worker configures the namespaces it was cloned into, then applies
36//! `pivot_root`, capability drop, hardening, `no_new_privs`, and optional
37//! seccomp. It must run before any thread is spawned, any async runtime
38//! starts, or any untrusted input is consumed.
39//! 3. [`tighten`] — an optional, additive-only ratchet a worker calls once it
40//! has finished initializing, to shed its init-only authority. It takes
41//! [`Restrictions`], a type that can only ever *narrow*.
42//!
43//! # Handle hygiene is the process builder's job
44//!
45//! There is no grant envelope and no descriptor sweep inside this crate.
46//! [`prepare`] reports exactly which handles must remain inheritable;
47//! the platform process builder keeps those and its configured standard I/O
48//! inheritable while closing or marking every other descriptor before the
49//! child is reached.
50//!
51//! # Platform support
52//!
53//! The Linux backend is implemented. On Windows the launch-time LPAC data is
54//! produced by [`prepare`], but the post-launch [`apply`]/[`tighten`] half is not yet
55//! implemented and returns [`Error::UnsupportedPlatform`] rather than a silent
56//! no-op (fail-loud). Other platforms are unsupported.
57//!
58//! Linux namespace creation and UID/GID mapping must be permitted by host
59//! policy. Kernel support alone is not sufficient; this crate does not install
60//! AppArmor policy or change system security settings.
61
62#![warn(missing_docs)]
63
64mod prepare;
65mod profile;
66mod syscall_denylist;
67
68#[cfg(target_os = "linux")]
69mod linux;
70#[cfg(target_os = "linux")]
71mod unix;
72#[cfg(windows)]
73mod windows;
74
75pub mod profiles;
76
77pub use prepare::Identity;
78#[cfg(target_os = "linux")]
79pub use prepare::LinuxPreparation;
80pub use prepare::RawHandle;
81pub use prepare::SandboxProcessConfig;
82#[cfg(windows)]
83pub use prepare::WindowsPreparation;
84pub use prepare::prepare;
85pub use profile::Builder;
86pub use profile::Capability;
87pub use profile::Network;
88pub use profile::Profile;
89pub use profile::Restrictions;
90pub use profile::RestrictionsBuilder;
91pub use profile::Syscalls;
92pub use syscall_denylist::DeniedSyscall;
93pub use syscall_denylist::Enforcement;
94pub use syscall_denylist::platform_syscall_denylist;
95
96#[cfg(target_os = "linux")]
97pub use unix::seccomp::nr_for_name;
98
99/// Process exit code used when a required sandbox primitive fails to apply.
100///
101/// A worker whose [`apply`] returns an [`Error`] should exit with this code so
102/// the control process can distinguish a sandbox failure from an ordinary
103/// worker crash. Distinct and stable so tooling and tests can assert on it.
104pub const EXIT_SANDBOX_FAILED: i32 = 90;
105
106/// Environment variable that disables the sandbox — **debug builds only**.
107///
108/// When this crate is built with `debug_assertions` and this variable is
109/// present in the environment, [`apply`] and [`tighten`] become no-ops so a
110/// developer can run a worker outside its confinement while iterating. Release
111/// builds ignore it entirely: the sandbox can never be switched off by an
112/// environment variable a compromised process could set.
113pub const DISABLE_ENV: &str = "OPENVMM_SANDBOX_DISABLE";
114
115/// An error produced while preparing or applying a sandbox.
116#[derive(Debug, thiserror::Error)]
117#[non_exhaustive]
118pub enum Error {
119 /// The current build has no sandbox backend for this operating system, or
120 /// the backend's worker-side half is not yet implemented (Windows).
121 /// Returned instead of silently running unconfined.
122 #[error("sandbox is not implemented on this platform")]
123 UnsupportedPlatform,
124
125 /// A primitive the platform must support to honor the profile is
126 /// unavailable in this environment.
127 #[error("required sandbox primitive unavailable: {0}")]
128 RequiredPrimitiveUnavailable(&'static str),
129
130 /// A required sandbox primitive failed while being applied. Carries the
131 /// primitive's name and the underlying OS error.
132 #[error("required sandbox primitive `{primitive}` failed to apply")]
133 ApplyFailed {
134 /// The name of the primitive that failed (e.g. `"user_namespace"`).
135 primitive: &'static str,
136 /// The underlying OS error.
137 #[source]
138 source: std::io::Error,
139 },
140}
141
142/// STAGE 2 — worker, the first statement of `main()`.
143///
144/// Applies `profile` to the current process. On Linux the process must already
145/// have been cloned with the flags returned by [`prepare`]; this configures
146/// those namespaces and establishes the remaining sandbox. See the crate docs
147/// for the required single-threaded, run-first ordering. Returns [`Error`] if
148/// any *required* primitive fails — the worker should then exit with
149/// [`EXIT_SANDBOX_FAILED`].
150///
151/// Failure does not roll back restrictions already applied. Do not initialize
152/// the worker or retry in the partially confined process after an error.
153/// Landlock is supplementary on Linux: its absence or failure can leave the
154/// mount-based filesystem boundary in force without returning an error.
155///
156/// In debug builds, becomes a no-op when [`DISABLE_ENV`] is set (see its docs).
157///
158/// # Example
159///
160/// In a worker entry point launched with the matching [`prepare`] configuration:
161///
162/// ```no_run
163/// if let Err(error) = sandbox::apply(&sandbox::profiles::tpm_worker().build()) {
164/// eprintln!("sandbox failed: {error}");
165/// std::process::exit(sandbox::EXIT_SANDBOX_FAILED);
166/// }
167/// // Join Mesh and initialize the worker only after confinement succeeds.
168/// ```
169pub fn apply(profile: &Profile) -> Result<(), Error> {
170 if sandbox_disabled() {
171 tracing::warn!(
172 profile = profile.name(),
173 "sandbox disabled via {DISABLE_ENV}; running unconfined (debug build only)",
174 );
175 return Ok(());
176 }
177
178 #[cfg(target_os = "linux")]
179 {
180 linux::apply(profile)
181 }
182 #[cfg(all(windows, not(target_os = "linux")))]
183 {
184 windows::apply(profile)
185 }
186 #[cfg(not(any(target_os = "linux", windows)))]
187 {
188 let _ = profile;
189 Err(Error::UnsupportedPlatform)
190 }
191}
192
193/// STAGE 3 (optional) — worker, after its own initialization.
194///
195/// Stacks the additive-only `restrictions` onto the already-applied sandbox.
196/// Unlike [`apply`], it may run multi-threaded: Linux synchronizes syscall
197/// filters across all threads with seccomp TSYNC. Returns [`Error`] if
198/// synchronization fails or is unsupported, with no thread-local fallback.
199/// The worker should then exit with [`EXIT_SANDBOX_FAILED`]; restrictions
200/// installed before the failure remain in effect.
201///
202/// In debug builds, becomes a no-op when [`DISABLE_ENV`] is set.
203///
204/// # Example
205///
206/// After successful [`apply`] and worker initialization:
207///
208/// ```no_run
209/// let restrictions = sandbox::Restrictions::none()
210/// .syscalls(&["execve", "socket", "connect"])
211/// .build();
212/// if let Err(error) = sandbox::tighten(&restrictions) {
213/// eprintln!("sandbox tightening failed: {error}");
214/// std::process::exit(sandbox::EXIT_SANDBOX_FAILED);
215/// }
216/// ```
217pub fn tighten(restrictions: &Restrictions) -> Result<(), Error> {
218 if sandbox_disabled() {
219 return Ok(());
220 }
221
222 #[cfg(target_os = "linux")]
223 {
224 linux::tighten(restrictions)
225 }
226 #[cfg(all(windows, not(target_os = "linux")))]
227 {
228 windows::tighten(restrictions)
229 }
230 #[cfg(not(any(target_os = "linux", windows)))]
231 {
232 let _ = restrictions;
233 Err(Error::UnsupportedPlatform)
234 }
235}
236
237/// Whether the dev-only disable escape is active. Always `false` in release
238/// builds, regardless of the environment.
239fn sandbox_disabled() -> bool {
240 cfg!(debug_assertions) && std::env::var_os(DISABLE_ENV).is_some()
241}