Skip to main content

sandbox/
prepare.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Control-side preparation: the [`prepare`](crate::prepare) stage and the
5//! plain-data [`SandboxProcessConfig`] it returns.
6//!
7//! # Why data, not a builder mutation
8//!
9//! Rather than mutating a platform process builder, this crate computes a
10//! [`SandboxProcessConfig`] and hands it back to the caller, which passes it
11//! intact to the platform process builder. That keeps `support/sandbox` free
12//! of any dependency on `mesh` or `pal`: the sandbox decides *what* the
13//! child's launch environment must be; PAL decides *how* to realize it.
14//!
15//! # Handle hygiene is the caller's job
16//!
17//! There is no grant envelope and no in-crate FD sweep. [`SandboxProcessConfig`]
18//! reports exactly which handles must remain inheritable in
19//! [`SandboxProcessConfig::inherit_handles`]; the platform process builder is
20//! responsible for retaining those handles and its configured standard I/O,
21//! while closing every other descriptor in the pre-exec child context.
22
23use crate::Error;
24use crate::profile::Profile;
25
26/// A child-visible, platform-native handle value: a target file-descriptor
27/// number on Unix, or an inherited `HANDLE` value on Windows.
28///
29/// Passing a `RawHandle` records intent to retain that child-visible value; it
30/// does not transfer ownership of any parent-side source handle. The owner
31/// must keep the source handle alive until the child exists.
32#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
33pub struct RawHandle(pub u64);
34
35/// Per-spawn identity for the worker.
36///
37/// On Unix, the control process's host UID/GID are retained; custom host
38/// identities are not supported. On Linux, namespace UID/GID 0 map to the
39/// spawning process's effective UID/GID.
40///
41/// On Windows, the AppContainer moniker is reflected in the Windows launch
42/// preparation. The AppContainer field is only available on Windows.
43///
44/// Custom host UID/GID inputs cannot be supplied:
45///
46/// ```compile_fail
47/// let identity = sandbox::Identity {
48///     uid: Some(0),
49///     ..Default::default()
50/// };
51/// ```
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Identity {
54    /// The Windows AppContainer moniker the worker should run under.
55    #[cfg(windows)]
56    pub app_container: Option<String>,
57}
58
59/// The result of [`prepare`](crate::prepare): everything the platform process
60/// builder needs to apply before the spawn.
61///
62/// It is deliberately inert plain data — no file descriptors are touched, no
63/// process APIs are called. The caller passes the value intact to the platform
64/// process builder.
65#[derive(Debug, Clone, Default)]
66pub struct SandboxProcessConfig {
67    /// Linux namespace creation and current-user mapping requirements.
68    #[cfg(target_os = "linux")]
69    pub linux: LinuxPreparation,
70    /// Windows LPAC construction data. The caller turns this into an
71    /// AppContainer SID, a capability SID array, and a `STARTUPINFOEX`
72    /// attribute list.
73    #[cfg(windows)]
74    pub windows: WindowsPreparation,
75    /// The handles that must remain inheritable across the spawn. Every
76    /// descriptor *not* listed here, or configured as standard I/O by the
77    /// process builder, must be closed before the child is reached.
78    pub inherit_handles: Vec<RawHandle>,
79}
80
81/// Linux-specific launch requirements for a [`SandboxProcessConfig`].
82#[cfg(target_os = "linux")]
83#[derive(Debug, Clone, Default)]
84pub struct LinuxPreparation {
85    /// Linux `CLONE_NEW*` flags to pass to the operation that creates the
86    /// child. Zero when the debug sandbox escape hatch is active.
87    ///
88    /// Namespace creation must happen as part of cloning the child so the
89    /// worker starts inside its namespaces. The platform process builder also
90    /// establishes the child user namespace's uid/gid mappings before exec.
91    /// Confined Linux launches require user, mount, and IPC namespaces, plus
92    /// a network namespace unless the profile allows unrestricted networking.
93    pub clone_flags: u64,
94    /// Map user and group ID 0 in the Linux user namespace to the spawning
95    /// process's effective user and group IDs.
96    pub map_current_user: bool,
97}
98
99/// The Windows-specific half of a [`SandboxProcessConfig`]: the data a caller
100/// needs to build an LPAC token and launch the worker into it.
101///
102/// This crate does not link `windows-sys` or call any Win32 API; it only
103/// describes *what* the LPAC configuration must be. The caller performs
104/// `DeriveAppContainerSid`, builds the `SID_AND_ATTRIBUTES[]` from the
105/// capability monikers, and sets the mitigation flags below on the
106/// `STARTUPINFOEX` / `SetProcessMitigationPolicy` surface.
107#[cfg(windows)]
108#[derive(Debug, Clone, Default)]
109pub struct WindowsPreparation {
110    /// The AppContainer moniker to derive the container SID from. `None` means
111    /// no explicit container (inherit — dev path).
112    pub app_container: Option<String>,
113    /// The LPAC capability monikers to grant (resolved to capability SIDs by
114    /// the caller). Empty by default: LPAC grants nothing it is not told to.
115    pub capabilities: Vec<&'static str>,
116    /// Opt out of `ALL_APPLICATION_PACKAGES` — the bit that makes this LPAC
117    /// rather than a plain AppContainer. Always `true`; a false value would
118    /// silently weaken the sandbox.
119    pub lpac_opt_out: bool,
120    /// Apply `ProcessImageLoadPolicy(NoRemoteImages)` — deny loading images
121    /// from remote sources.
122    pub no_remote_images: bool,
123    /// Apply `ProcessSystemCallDisablePolicy` (Win32k lockdown) — no worker
124    /// needs the GUI subsystem.
125    pub win32k_lockdown: bool,
126    /// Apply `ProcessChildProcessPolicy` — forbid the worker from spawning
127    /// children.
128    pub disallow_child_processes: bool,
129}
130
131/// STAGE 1 — control process, immediately before the spawn.
132///
133/// Computes the launch-time configuration for a confined worker and returns it
134/// as plain data. It does **not** mutate any process builder, touch any file
135/// descriptor, or call any process-creation API — the caller passes the
136/// returned [`SandboxProcessConfig`] to its platform process builder.
137///
138/// * `profile` — the worker's linked policy. On Linux only its launch-relevant
139///   bits are consulted here (the worker self-applies the rest in
140///   [`apply`](crate::apply)); on Windows its entire LPAC portion is reflected
141///   into the Windows launch preparation.
142/// * `identity` — the per-spawn identity. On Windows, its AppContainer
143///   configuration is reflected in the Windows launch preparation. Unix
144///   launches retain the spawning process's host UID/GID.
145/// * `handles` — the handles to keep inheritable. They are echoed into
146///   [`SandboxProcessConfig::inherit_handles`]; the platform process builder
147///   closes every other descriptor except its configured standard I/O.
148///
149/// # Example
150///
151/// ```
152/// use sandbox::{Identity, Profile, RawHandle};
153///
154/// let profile = Profile::deny_all().build();
155/// let handles = [RawHandle(3)];
156/// let preparation = sandbox::prepare(&profile, &Identity::default(), &handles)?;
157/// # Ok::<(), sandbox::Error>(())
158/// ```
159///
160/// This only records the child-visible descriptor number. The process builder
161/// must map an owned source descriptor to that number and apply the preparation
162/// before spawning; the worker must still call [`apply`](crate::apply).
163pub fn prepare(
164    profile: &Profile,
165    identity: &Identity,
166    handles: &[RawHandle],
167) -> Result<SandboxProcessConfig, Error> {
168    #[cfg(not(windows))]
169    let _ = identity;
170    #[cfg(not(any(target_os = "linux", windows)))]
171    let _ = profile;
172
173    Ok(SandboxProcessConfig {
174        #[cfg(target_os = "linux")]
175        linux: if crate::sandbox_disabled() {
176            LinuxPreparation::default()
177        } else {
178            LinuxPreparation {
179                clone_flags: linux_clone_flags(profile),
180                map_current_user: true,
181            }
182        },
183        #[cfg(windows)]
184        windows: windows_preparation(profile, identity),
185        inherit_handles: handles.to_vec(),
186    })
187}
188
189#[cfg(target_os = "linux")]
190fn linux_clone_flags(profile: &Profile) -> u64 {
191    let mut flags = libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWIPC;
192    if profile.inner.network != crate::Network::Unrestricted {
193        flags |= libc::CLONE_NEWNET;
194    }
195    flags as u64
196}
197
198/// Reflect the profile's Windows-relevant policy into LPAC construction data.
199#[cfg(windows)]
200fn windows_preparation(profile: &Profile, identity: &Identity) -> WindowsPreparation {
201    let capabilities = profile
202        .inner
203        .capabilities
204        .iter()
205        .map(|c| c.moniker())
206        .collect();
207
208    // Network policy is not yet reflected into LPAC capability SIDs. The
209    // Windows worker-side implementation remains unsupported.
210
211    WindowsPreparation {
212        app_container: identity.app_container.clone(),
213        capabilities,
214        lpac_opt_out: true,
215        no_remote_images: true,
216        win32k_lockdown: true,
217        disallow_child_processes: true,
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    #[cfg(windows)]
225    use crate::profile::Capability;
226
227    #[test]
228    fn prepare_preserves_handles_and_self_maps() {
229        let profile = Profile::deny_all().build();
230        let handles = [RawHandle(3), RawHandle(7)];
231
232        let prep = prepare(&profile, &Identity::default(), &handles).unwrap();
233
234        assert_eq!(prep.inherit_handles, handles);
235        #[cfg(target_os = "linux")]
236        {
237            assert_eq!(
238                prep.linux.clone_flags,
239                (libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWIPC | libc::CLONE_NEWNET)
240                    as u64
241            );
242            assert!(prep.linux.map_current_user);
243        }
244    }
245
246    #[cfg(target_os = "linux")]
247    #[test]
248    fn filesystem_grants_preserve_default_namespaces() {
249        let profile = Profile::deny_all().read_exec("/usr/lib").build();
250
251        assert_eq!(
252            linux_clone_flags(&profile),
253            (libc::CLONE_NEWUSER | libc::CLONE_NEWNET | libc::CLONE_NEWNS | libc::CLONE_NEWIPC)
254                as u64
255        );
256    }
257
258    #[cfg(target_os = "linux")]
259    #[test]
260    fn unrestricted_network_omits_network_namespace() {
261        let profile = Profile::deny_all()
262            .network(crate::Network::Unrestricted)
263            .build();
264
265        assert_eq!(
266            linux_clone_flags(&profile),
267            (libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWIPC) as u64
268        );
269    }
270
271    #[cfg(target_os = "linux")]
272    #[test]
273    fn unrestricted_network_keeps_filesystem_namespace() {
274        let profile = Profile::deny_all()
275            .network(crate::Network::Unrestricted)
276            .read_exec("/usr/lib")
277            .build();
278
279        assert_eq!(
280            linux_clone_flags(&profile),
281            (libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWIPC) as u64
282        );
283    }
284
285    #[cfg(windows)]
286    #[test]
287    fn windows_preparation_reflects_capabilities_and_hardening() {
288        let profile = Profile::deny_all()
289            .capability(Capability::LPAC_COM)
290            .capability(Capability::REGISTRY_READ)
291            .build();
292        let identity = Identity {
293            app_container: Some("worker.net".to_string()),
294        };
295
296        let win = prepare(&profile, &identity, &[]).unwrap().windows;
297
298        assert_eq!(win.app_container.as_deref(), Some("worker.net"));
299        assert_eq!(win.capabilities, vec!["lpacCom", "registryRead"]);
300        assert!(win.lpac_opt_out);
301        assert!(win.no_remote_images);
302        assert!(win.win32k_lockdown);
303        assert!(win.disallow_child_processes);
304    }
305}