sandbox/profile.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The sandbox policy vocabulary: [`Profile`] and its [`Builder`],
5//! plus the additive-only [`Restrictions`] ratchet consumed by
6//! [`tighten`](crate::tighten).
7//!
8//! # Default-deny by construction
9//!
10//! A policy starts from [`Profile::deny_all`]: no explicit filesystem grants,
11//! isolated networking, and no seccomp filter. Filesystem grants and platform
12//! capabilities add authority; syscall denials can only accumulate. Supplied
13//! handles retain their authority regardless of the path grants.
14//!
15//! # Policy authoring vs. tightening
16//!
17//! [`Builder`] selects authority at policy-authoring time.
18//! [`Restrictions`] is the complementary, additive-only *narrowing* spec: it
19//! can only ever subtract from an already-applied profile, so a non-monotonic
20//! ratchet is unrepresentable rather than a runtime error.
21//!
22//! # Platform neutrality
23//!
24//! The vocabulary is intent-level and platform-neutral. No third-party
25//! sandbox type (`landlock::*`, `seccompiler::*`, `caps::*`, `windows_sys::*`)
26//! ever crosses this surface. Where a dimension has no analogue on a platform,
27//! the backend treats the grant as a no-op rather than an error.
28
29use std::path::Path;
30use std::path::PathBuf;
31
32/// An opaque, immutable sandbox policy.
33///
34/// Sandbox policies, such as those in [`profiles`](crate::profiles), build
35/// a `Profile` from [`Profile::deny_all`] by adding additional permissions,
36/// and are compiled into the program (the worker on Linux; the control
37/// process *and* the worker on Windows).
38#[derive(Debug, Clone)]
39pub struct Profile {
40 pub(crate) inner: ProfileInner,
41}
42
43impl Profile {
44 /// Start a policy with no explicit filesystem grants and [`Network::None`].
45 ///
46 /// Syscall filtering is independently opt-in: the default is
47 /// [`Syscalls::Unfiltered`]. The Linux backend still provides implicit
48 /// scratch storage and a best-effort proc view; see [`Builder`].
49 pub fn deny_all() -> Builder {
50 Builder {
51 inner: ProfileInner::default(),
52 }
53 }
54
55 /// Reopen a finished profile as a [`Builder`] to derive a new profile.
56 ///
57 /// The builder starts from a clone of this profile's grants, so the
58 /// original is left intact and any number of variants can be derived from a
59 /// single base. Filesystem grants and capabilities can only grow, syscall
60 /// denials can only be added, and the scalar dimensions (`name` and
61 /// `network`) are replaced by a later call.
62 ///
63 /// Prefer exposing a reusable base as a `fn() -> Builder` — see
64 /// [`profiles`](crate::profiles) — and reach for `edit` only when you
65 /// already hold a built [`Profile`], e.g. one handed to you by another
66 /// crate.
67 ///
68 /// ```
69 /// use sandbox::Profile;
70 ///
71 /// let base = Profile::deny_all().name("base").read_exec("/usr/lib").build();
72 /// let worker = base.edit().name("worker").read_write("/run/worker").build();
73 /// assert_eq!(worker.name(), "worker");
74 /// ```
75 pub fn edit(&self) -> Builder {
76 Builder {
77 inner: self.inner.clone(),
78 }
79 }
80
81 /// The human-readable name of the profile, used only in diagnostics.
82 pub fn name(&self) -> &'static str {
83 self.inner.name
84 }
85}
86
87/// Policy builder for filesystem grants, network scope, and syscall denials.
88///
89/// Start with [`Profile::deny_all`] or derive a policy with [`Profile::edit`].
90/// Filesystem grants and capabilities accumulate, network scope is replaced by
91/// each [`network`](Self::network) call, and syscall denials compose by union.
92/// Post-`apply` narrowing is separate; see [`Restrictions`].
93///
94/// # Example
95///
96/// ```
97/// use sandbox::{Network, Profile, Syscalls};
98///
99/// let profile = Profile::deny_all()
100/// .name("example_worker")
101/// .read_exec("/usr/lib")
102/// .read_write("/var/lib/worker")
103/// .network(Network::None)
104/// .syscalls(Syscalls::deny(["execve", "execveat"]))
105/// .build();
106/// ```
107///
108/// # Linux filesystem grants
109///
110/// Grants bind existing host paths at the same paths in the worker's root.
111/// Host-side symlinks are followed when binding a source. The bind captures the
112/// source at startup; replacing the host file by rename does not retarget it.
113/// Ordinary grants preserve host restrictions and add `nosuid` and `nodev`;
114/// use [`device`](Self::device) for a single device node.
115///
116/// Grants for the filesystem root (`/`) are unsupported and rejected by
117/// [`apply`](crate::apply) before staging or mounting the filesystem.
118///
119/// Duplicate grants and lexically nested paths combine independently of
120/// declaration order, retaining permissions already granted by an ancestor.
121/// Combinations requiring both write and execute access are rejected during
122/// [`apply`](crate::apply).
123///
124/// The backend also provides writable scratch storage at `/tmp` and requires
125/// either a fresh `/proc` mount or a restricted bind of the host's `/proc`.
126/// These are implicit backend facilities, not explicit grants added by this
127/// builder. Landlock, where enforced, further limits proc access; the proc
128/// mount's own restrictions still apply.
129#[derive(Debug, Clone)]
130#[must_use]
131pub struct Builder {
132 inner: ProfileInner,
133}
134
135impl Builder {
136 /// Attach a human-readable name used in tracing and error messages. Not
137 /// consulted by the sandbox itself.
138 pub fn name(mut self, name: &'static str) -> Self {
139 self.inner.name = name;
140 self
141 }
142
143 /// Grant read-only access to `path`, without allowing execution.
144 ///
145 /// On Linux the bind is read-only and `noexec`; directory traversal is
146 /// still allowed. Use [`Builder::read_exec`] for shared libraries,
147 /// interpreters, and other executable code.
148 pub fn read(mut self, path: impl AsRef<Path>) -> Self {
149 self.push_fs(path.as_ref().to_path_buf(), Access::Read);
150 self
151 }
152
153 /// Grant read and execute access to `path`, without allowing writes.
154 ///
155 /// Use this for executable mappings, including shared libraries, rather
156 /// than [`Builder::read`].
157 pub fn read_exec(mut self, path: impl AsRef<Path>) -> Self {
158 self.push_fs(path.as_ref().to_path_buf(), Access::ReadExec);
159 self
160 }
161
162 /// Grant read and write access to `path`. The path is mounted
163 /// non-executable, so a worker cannot execute data it can write.
164 pub fn read_write(mut self, path: impl AsRef<Path>) -> Self {
165 self.push_fs(path.as_ref().to_path_buf(), Access::ReadWrite);
166 self
167 }
168
169 /// Grant read, write, and ioctl access to a single device node.
170 ///
171 /// Unlike ordinary filesystem grants, this permits device-node use.
172 /// The Linux backend rejects sources that are not character or block
173 /// devices. Existing host mount restrictions and device permissions remain.
174 pub fn device(mut self, path: impl AsRef<Path>) -> Self {
175 self.push_fs(path.as_ref().to_path_buf(), Access::Device);
176 self
177 }
178
179 /// Grant network reachability up to `scope`.
180 ///
181 /// The default (from [`Profile::deny_all`]) is [`Network::None`] — an
182 /// empty network namespace with no peer. [`Network::Unrestricted`] keeps
183 /// the worker in the caller's network namespace.
184 pub fn network(mut self, scope: Network) -> Self {
185 self.inner.network = scope;
186 self
187 }
188
189 /// Add to the worker's syscall-filtering policy.
190 ///
191 /// Syscall filtering is opt-in per worker class: the default is
192 /// [`Syscalls::Unfiltered`] (no seccomp filter). [`Syscalls::Deny`]
193 /// installs a seccomp filter that blocks the crate's built-in set of
194 /// dangerous, namespace-escape, and historically CVE-prone syscalls, plus
195 /// any additional syscalls named in the list.
196 ///
197 /// Successive calls compose monotonically: deny lists are unioned while
198 /// preserving first-seen order, and [`Syscalls::Unfiltered`] is the
199 /// identity. Once a base profile opts into filtering, a derived profile
200 /// cannot remove that filter or any of its denials.
201 pub fn syscalls(mut self, policy: Syscalls) -> Self {
202 if let Syscalls::Deny(additional) = policy {
203 match &mut self.inner.syscalls {
204 current @ Syscalls::Unfiltered => *current = Syscalls::Deny(additional),
205 Syscalls::Deny(existing) => {
206 for name in additional {
207 if !existing.contains(&name) {
208 existing.push(name);
209 }
210 }
211 }
212 }
213 }
214 self
215 }
216
217 /// Grant a named platform capability (e.g. a Windows LPAC capability).
218 ///
219 /// Capabilities with no analogue on the current platform are a no-op.
220 pub fn capability(mut self, cap: Capability) -> Self {
221 self.inner.capabilities.push(cap);
222 self
223 }
224
225 /// Finalize the policy.
226 pub fn build(self) -> Profile {
227 Profile { inner: self.inner }
228 }
229
230 fn push_fs(&mut self, path: PathBuf, access: Access) {
231 self.inner.fs.push(FsGrant { path, access });
232 }
233}
234
235/// Network reachability granted to the worker.
236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
237pub enum Network {
238 /// No network at all — an empty network namespace with no peer.
239 #[default]
240 None,
241 /// Preserve the caller's network namespace and ambient connectivity.
242 Unrestricted,
243}
244
245/// Syscall-filtering policy (Linux; opt-in per worker class).
246///
247/// The crate uses a **denylist** model rather than an allowlist: a worker's
248/// full set of *needed* syscalls cannot be reliably enumerated, so the filter
249/// instead blocks a curated set of syscalls that a sandboxed worker never
250/// legitimately needs and that are known namespace-escape or kernel-CVE
251/// vectors.
252#[derive(Debug, Clone, Default, PartialEq, Eq)]
253pub enum Syscalls {
254 /// Install no seccomp filter. The worker retains the ambient syscall
255 /// surface; confinement rests on namespaces, credentials, and
256 /// `no_new_privs`.
257 #[default]
258 Unfiltered,
259 /// Install a seccomp filter that always blocks the crate's built-in set of
260 /// dangerous syscalls — mount/namespace manipulation, module loading,
261 /// `ptrace`, `kexec`, keyring access, and other escape or CVE vectors, plus
262 /// argument-level guards on `ioctl`, `clone`, `prctl`, and `socket` — and
263 /// additionally blocks every syscall named here. An empty list installs
264 /// just the built-in baseline. Unknown names are a hard error at apply
265 /// time. On x86-64, workers and their libraries must use the native 64-bit
266 /// syscall ABI; both i386 and x32 syscall ABIs are rejected.
267 Deny(Vec<String>),
268}
269
270impl Syscalls {
271 /// Deny the supplied syscall names in addition to the built-in baseline.
272 pub fn deny<I, S>(names: I) -> Self
273 where
274 I: IntoIterator<Item = S>,
275 S: Into<String>,
276 {
277 Self::Deny(names.into_iter().map(Into::into).collect())
278 }
279}
280
281/// An opaque, named platform capability, constructed from crate-provided
282/// constants. The consumer never sees the underlying SID or grant.
283///
284/// Capabilities are Windows LPAC concepts; on other platforms they are a
285/// no-op.
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub struct Capability(pub(crate) CapabilityKind);
288
289impl Capability {
290 /// The `lpacCom` capability — COM activation under LPAC.
291 pub const LPAC_COM: Capability = Capability(CapabilityKind::LpacCom);
292 /// The `lpacCryptoServices` capability — cryptographic service access
293 /// under LPAC.
294 pub const LPAC_CRYPTO_SERVICES: Capability = Capability(CapabilityKind::LpacCryptoServices);
295 /// The `registryRead` capability — read access to policy under the
296 /// registry.
297 pub const REGISTRY_READ: Capability = Capability(CapabilityKind::RegistryRead);
298
299 /// The stable capability moniker, for diagnostics and for a Windows
300 /// consumer to resolve into a capability SID.
301 pub fn moniker(self) -> &'static str {
302 match self.0 {
303 CapabilityKind::LpacCom => "lpacCom",
304 CapabilityKind::LpacCryptoServices => "lpacCryptoServices",
305 CapabilityKind::RegistryRead => "registryRead",
306 }
307 }
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub(crate) enum CapabilityKind {
312 LpacCom,
313 LpacCryptoServices,
314 RegistryRead,
315}
316
317/// A narrow, additive-only ratchet consumed by [`tighten`](crate::tighten).
318///
319/// It can express only the primitives that are safe to stack onto an
320/// already-applied sandbox: additional syscall denials and a further-restricted
321/// path. The one-shot, authority-consuming primitives — namespaces,
322/// credentials, and mounts — are absent from this type, so a non-monotonic
323/// ratchet is *unrepresentable*.
324#[derive(Debug, Clone)]
325pub struct Restrictions {
326 #[cfg_attr(all(not(target_os = "linux"), not(test)), expect(dead_code))]
327 pub(crate) inner: RestrictionsInner,
328}
329
330impl Restrictions {
331 /// Start from "no additional restriction"; every method on the returned
332 /// builder can only narrow further.
333 pub fn none() -> RestrictionsBuilder {
334 RestrictionsBuilder {
335 inner: RestrictionsInner::default(),
336 }
337 }
338}
339
340/// Narrowing-only ratchet builder. There is deliberately no "unfiltered"
341/// escape here — a ratchet only ever subtracts.
342#[derive(Debug, Clone)]
343#[must_use]
344pub struct RestrictionsBuilder {
345 inner: RestrictionsInner,
346}
347
348impl RestrictionsBuilder {
349 /// Block additional syscalls beyond those the applied profile already
350 /// denies, installed as an additional stacked seccomp filter. The kernel
351 /// takes the most restrictive verdict across every installed filter, so a
352 /// stacked denylist can only ever narrow the surface further.
353 ///
354 /// Repeated calls union the denials, deduplicating in first-seen order.
355 pub fn syscalls(mut self, deny: &'static [&'static str]) -> Self {
356 let existing = self.inner.syscalls.get_or_insert_with(Vec::new);
357 for &name in deny {
358 if !existing.contains(&name) {
359 existing.push(name);
360 }
361 }
362 self
363 }
364
365 /// Enforce an additional restriction that *removes* access to a path the
366 /// applied profile previously permitted. It can never add access.
367 ///
368 /// Not implemented: [`tighten`](crate::tighten) rejects path revocation on
369 /// Linux with [`Error::RequiredPrimitiveUnavailable`](crate::Error::RequiredPrimitiveUnavailable).
370 pub fn revoke_path(mut self, path: impl AsRef<Path>) -> Self {
371 self.inner.revoke_paths.push(path.as_ref().to_path_buf());
372 self
373 }
374
375 /// Finalize the ratchet.
376 pub fn build(self) -> Restrictions {
377 Restrictions { inner: self.inner }
378 }
379}
380
381// ---------------------------------------------------------------------------
382// Internal representation
383// ---------------------------------------------------------------------------
384
385#[derive(Debug, Clone)]
386pub(crate) struct ProfileInner {
387 pub(crate) name: &'static str,
388 pub(crate) fs: Vec<FsGrant>,
389 pub(crate) network: Network,
390 pub(crate) syscalls: Syscalls,
391 pub(crate) capabilities: Vec<Capability>,
392}
393
394impl Default for ProfileInner {
395 fn default() -> Self {
396 Self {
397 name: "unnamed",
398 fs: Vec::new(),
399 network: Network::None,
400 syscalls: Syscalls::Unfiltered,
401 capabilities: Vec::new(),
402 }
403 }
404}
405
406#[derive(Debug, Clone)]
407#[cfg_attr(not(target_os = "linux"), expect(dead_code))]
408pub(crate) struct FsGrant {
409 pub(crate) path: PathBuf,
410 pub(crate) access: Access,
411}
412
413#[derive(Debug, Clone, Default)]
414pub(crate) struct RestrictionsInner {
415 pub(crate) syscalls: Option<Vec<&'static str>>,
416 pub(crate) revoke_paths: Vec<PathBuf>,
417}
418
419/// Access mode for a filesystem grant. Internal — the public builder exposes
420/// [`Builder::read`], [`Builder::read_exec`], [`Builder::read_write`], and [`Builder::device`],
421/// mapped to the mount flags and Landlock rights the backend needs.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423pub(crate) enum Access {
424 /// Read only. No write or execute.
425 Read,
426 /// Read + execute. No write.
427 ReadExec,
428 /// Read + write. No execute.
429 ReadWrite,
430 /// Read + write + ioctl for a single device node. No execute.
431 Device,
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437 #[cfg(target_os = "linux")]
438 use test_with_tracing::test;
439
440 #[test]
441 fn restriction_syscall_denials_are_additive_and_deduplicated() {
442 let restrictions = Restrictions::none()
443 .syscalls(&["socket", "connect"])
444 .syscalls(&["connect", "kill"])
445 .syscalls(&[])
446 .build();
447
448 assert_eq!(
449 restrictions.inner.syscalls.as_deref(),
450 Some(["socket", "connect", "kill"].as_slice()),
451 );
452 }
453
454 #[test]
455 fn deny_all_defaults_to_no_network_no_seccomp() {
456 let profile = Profile::deny_all().build();
457 assert_eq!(profile.inner.network, Network::None);
458 assert!(matches!(profile.inner.syscalls, Syscalls::Unfiltered));
459 assert!(profile.inner.fs.is_empty());
460 }
461
462 #[test]
463 fn network_grant_is_stored() {
464 let profile = Profile::deny_all().network(Network::Unrestricted).build();
465 assert_eq!(profile.inner.network, Network::Unrestricted);
466 }
467
468 #[test]
469 fn syscalls_deny_is_stored() {
470 let profile = Profile::deny_all()
471 .syscalls(Syscalls::deny(["socket"]))
472 .build();
473 assert_eq!(
474 profile.inner.syscalls,
475 Syscalls::Deny(vec!["socket".to_string()])
476 );
477 }
478
479 #[test]
480 fn syscall_denials_are_additive_and_deduplicated() {
481 let profile = Profile::deny_all()
482 .syscalls(Syscalls::deny(["socket", "kill"]))
483 .syscalls(Syscalls::deny(["kill", "tkill"]))
484 .build();
485
486 assert_eq!(
487 profile.inner.syscalls,
488 Syscalls::Deny(vec![
489 "socket".to_string(),
490 "kill".to_string(),
491 "tkill".to_string(),
492 ])
493 );
494 }
495
496 #[test]
497 fn unfiltered_does_not_remove_existing_syscall_denials() {
498 let profile = Profile::deny_all()
499 .syscalls(Syscalls::deny(["socket"]))
500 .syscalls(Syscalls::Unfiltered)
501 .build();
502
503 assert_eq!(
504 profile.inner.syscalls,
505 Syscalls::Deny(vec!["socket".to_string()])
506 );
507 }
508
509 #[test]
510 fn edited_profile_adds_to_existing_syscall_denials() {
511 let base = Profile::deny_all()
512 .syscalls(Syscalls::deny(["socket"]))
513 .build();
514 let derived = base.edit().syscalls(Syscalls::deny(["kill"])).build();
515
516 assert_eq!(
517 derived.inner.syscalls,
518 Syscalls::Deny(vec!["socket".to_string(), "kill".to_string()])
519 );
520 }
521}