Skip to main content

sim_platform_ubuntu_pc/
sandbox.rs

1// SPDX-License-Identifier: MPL-2.0
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
6// conformance: Ubuntu sandbox realization refuses undeclared authority before spawning.
7
8use sim_lib_exec::{
9    BindingValue, MountAccess, ProcessAttempt, ProcessBudget, ProcessCancellation, ProcessRequest,
10    ProgramRef, ProjectRootRef, SandboxAttempt, SandboxControl, SandboxEvidence, SandboxLauncher,
11    SandboxRefusal, SandboxReport, SandboxRequest, SandboxResult,
12};
13use std::{
14    collections::BTreeMap,
15    io,
16    path::{Path, PathBuf},
17    process::{Command, Stdio},
18};
19
20/// Linux bubblewrap realization of the runtime-owned sandbox authority boundary.
21#[derive(Clone, Debug)]
22pub struct BwrapLauncher {
23    bwrap: PathBuf,
24    prlimit: PathBuf,
25    programs: BTreeMap<ProgramRef, PathBuf>,
26    sources: BTreeMap<String, PathBuf>,
27}
28
29/// Live readiness of the Ubuntu bubblewrap effect membrane.
30///
31/// This evidence certifies only bounded-effect confinement. It deliberately
32/// cannot represent projector purity or source qualification: bubblewrap
33/// exposes `/proc` and `/dev`, and declared mounts may contain semantic inputs
34/// outside a projector's selected immutable view.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct BwrapConfinementStatus {
37    /// Stable membrane implementation identity.
38    pub membrane: &'static str,
39    /// Whether both boot-authorized executables exist as files now.
40    pub available: bool,
41    /// Human-readable readiness detail.
42    pub detail: String,
43}
44
45impl BwrapLauncher {
46    /// Creates a boot-configured launcher. Paths are authority supplied, never request supplied.
47    #[must_use]
48    pub fn new(
49        bwrap: PathBuf,
50        prlimit: PathBuf,
51        programs: BTreeMap<ProgramRef, PathBuf>,
52        sources: BTreeMap<String, PathBuf>,
53    ) -> Self {
54        Self {
55            bwrap,
56            prlimit,
57            programs,
58            sources,
59        }
60    }
61
62    /// Probes the exact boot-resolved membrane executables without dispatch.
63    #[must_use]
64    pub fn confinement_status(&self) -> BwrapConfinementStatus {
65        let bwrap = self.bwrap.is_file();
66        let prlimit = self.prlimit.is_file();
67        BwrapConfinementStatus {
68            membrane: "platform/sandbox/ubuntu-bwrap",
69            available: bwrap && prlimit,
70            detail: format!("bwrap-file={bwrap};prlimit-file={prlimit};purity-qualified=false"),
71        }
72    }
73    fn refuse(&self, reason: impl Into<String>) -> SandboxAttempt {
74        SandboxAttempt::Refused(SandboxRefusal {
75            launcher: self.id().into(),
76            reason: reason.into(),
77            report: None,
78        })
79    }
80    fn command(&self, request: &SandboxRequest) -> Result<Command, String> {
81        if !self.bwrap.is_file() {
82            return Err("bubblewrap is unavailable".into());
83        }
84        if !self.prlimit.is_file() {
85            return Err("prlimit is unavailable".into());
86        }
87        let program = canonical_file(
88            self.programs
89                .get(&request.program)
90                .ok_or("program is not boot-authorized")?,
91        )?;
92        let mut command = Command::new(&self.bwrap);
93        command
94            .args([
95                "--die-with-parent",
96                "--new-session",
97                "--unshare-all",
98                "--unshare-net",
99                "--clearenv",
100                "--tmpfs",
101                "/",
102                "--proc",
103                "/proc",
104                "--dev",
105                "/dev",
106                "--dir",
107                "/work",
108                "--chdir",
109                "/work",
110                "--ro-bind",
111            ])
112            .arg(&program)
113            .arg("/sim-program")
114            .args(["--ro-bind"])
115            .arg(&self.prlimit)
116            .arg("/sim-prlimit");
117        for mount in request.policy.mounts() {
118            let source = canonical(
119                self.sources
120                    .get(&mount.source)
121                    .ok_or("mount source is not boot-authorized")?,
122            )?;
123            command
124                .arg(match mount.access {
125                    MountAccess::ReadOnly => "--ro-bind",
126                    MountAccess::Writable => "--bind",
127                })
128                .arg(source)
129                .arg(&mount.guest_path);
130        }
131        for (name, value) in request.environment.iter() {
132            let BindingValue::Literal(value) = value else {
133                return Err("sandbox environment permits literal bindings only".into());
134            };
135            command.arg("--setenv").arg(name).arg(value);
136        }
137        let limits = request.policy.limits();
138        command
139            .args(["--", "/sim-prlimit"])
140            .arg(format!("--cpu={}", limits.cpu_seconds))
141            .arg(format!("--as={}", limits.memory_bytes))
142            .arg(format!("--nproc={}", limits.process_count))
143            .arg(format!("--fsize={}", limits.file_bytes))
144            .args(["--", "/sim-program"])
145            .args(request.argv.iter().map(sim_lib_exec::ArgAtom::as_str))
146            .stdin(Stdio::piped())
147            .stdout(Stdio::piped())
148            .stderr(Stdio::piped());
149        Ok(command)
150    }
151}
152impl SandboxLauncher for BwrapLauncher {
153    fn id(&self) -> &'static str {
154        "platform/sandbox/ubuntu-bwrap"
155    }
156    fn launch(
157        &self,
158        request: &SandboxRequest,
159        cancellation: &ProcessCancellation,
160    ) -> SandboxAttempt {
161        let mut command = match self.command(request) {
162            Ok(v) => v,
163            Err(e) => return self.refuse(e),
164        };
165        let root = ProjectRootRef::new("sandbox-root").expect("constant is valid");
166        let process_request = ProcessRequest {
167            program: request.program.clone(),
168            argv: request.argv.clone(),
169            root,
170            environment: request.environment.clone(),
171            private_artifacts: vec![],
172            budget: ProcessBudget {
173                timeout_ms: request.policy.limits().wall_time_ms,
174                max_output_bytes: request.policy.limits().output_bytes,
175                stdin: Some(request.stdin.clone()),
176            },
177        };
178        let mut child = match command.spawn() {
179            Ok(v) => v,
180            Err(e) => return self.refuse(format!("bubblewrap spawn failed: {e}")),
181        };
182        let outcome = super::process::run_child(&mut child, &process_request, cancellation);
183        report(request, outcome, &self.sources)
184    }
185}
186fn canonical(path: &Path) -> Result<PathBuf, String> {
187    path.canonicalize()
188        .map_err(|e| format!("declared mount unavailable: {e}"))
189}
190fn canonical_file(path: &Path) -> Result<PathBuf, String> {
191    let path = canonical(path)?;
192    if !path.is_file() {
193        return Err("authorized program is not a file".into());
194    }
195    Ok(path)
196}
197fn report(
198    request: &SandboxRequest,
199    outcome: ProcessAttempt,
200    sources: &BTreeMap<String, PathBuf>,
201) -> SandboxAttempt {
202    let usage = writable_usage(request, sources);
203    let usage_observed = usage.is_ok();
204    let (files, bytes) = usage.unwrap_or((u64::MAX, u64::MAX));
205    let controls = request
206        .policy
207        .requirements()
208        .keys()
209        .map(|control| SandboxEvidence {
210            control: *control,
211            achieved: !matches!(
212                control,
213                SandboxControl::FileCount | SandboxControl::FileBytes
214            ) || usage_observed,
215            detail: match control {
216                SandboxControl::Network => "bubblewrap network namespace has no interfaces",
217                SandboxControl::Mounts => "only canonical boot-resolved mounts were bound",
218                SandboxControl::Root => "anonymous tmpfs root; no home or workspace mount",
219                SandboxControl::Environment => "bubblewrap clearenv plus literal declared bindings",
220                SandboxControl::Identity => "user and mount namespaces isolate host identity",
221                SandboxControl::Cpu => "RLIMIT_CPU applied by prlimit",
222                SandboxControl::Memory => "RLIMIT_AS applied by prlimit",
223                SandboxControl::WallTime => "capsule monotonic deadline",
224                SandboxControl::ProcessCount => "RLIMIT_NPROC applied by prlimit",
225                SandboxControl::FileCount if usage_observed => {
226                    "writable roots were inspected recursively at completion"
227                }
228                SandboxControl::FileCount => "writable-root file count could not be observed",
229                SandboxControl::FileBytes if usage_observed => {
230                    "RLIMIT_FSIZE plus recursive writable-root byte inspection"
231                }
232                SandboxControl::FileBytes => "writable-root file bytes could not be observed",
233                SandboxControl::Output => "shared bounded capture",
234                SandboxControl::Stdin => "validated bounded pipe",
235                SandboxControl::ProcessTree => "new session killed and reaped by capsule",
236            }
237            .into(),
238        })
239        .collect();
240    match outcome {
241        ProcessAttempt::Completed { receipt } => {
242            let mut hits = vec![];
243            if receipt.result.truncated {
244                hits.push("output_bytes".into());
245            }
246            if usage_observed {
247                if files > request.policy.limits().file_count {
248                    hits.push("file_count".into());
249                }
250                if bytes > request.policy.limits().file_bytes {
251                    hits.push("file_bytes".into());
252                }
253            } else {
254                hits.push("writable_root_observation".into());
255            }
256            SandboxAttempt::Completed(SandboxResult {
257                stdout: receipt.result.stdout.into_bytes(),
258                stderr: receipt.result.stderr.into_bytes(),
259                exit_code: receipt.result.exit_code,
260                report: SandboxReport {
261                    launcher: "platform/sandbox/ubuntu-bwrap".into(),
262                    controls,
263                    limit_hits: hits,
264                    cleanup: "normal completion; process group empty after pipe closure".into(),
265                },
266            })
267        }
268        ProcessAttempt::StoppedAfterTimeout { receipt } => SandboxAttempt::Stopped(SandboxReport {
269            launcher: "platform/sandbox/ubuntu-bwrap".into(),
270            controls,
271            limit_hits: vec!["wall_time".into()],
272            cleanup: receipt.cleanup,
273        }),
274        ProcessAttempt::StoppedAfterCancel { receipt } => SandboxAttempt::Stopped(SandboxReport {
275            launcher: "platform/sandbox/ubuntu-bwrap".into(),
276            controls,
277            limit_hits: vec!["cancellation".into()],
278            cleanup: receipt.cleanup,
279        }),
280        ProcessAttempt::NotDispatched { refusal } => SandboxAttempt::Refused(SandboxRefusal {
281            launcher: "platform/sandbox/ubuntu-bwrap".into(),
282            reason: match refusal {
283                sim_lib_exec::ProcessRefusal::Invalid(detail) => format!("invalid: {detail}"),
284                sim_lib_exec::ProcessRefusal::Refused(detail) => format!("refused: {detail}"),
285                sim_lib_exec::ProcessRefusal::SpawnFailed(detail) => {
286                    format!("spawn failed: {detail}")
287                }
288            },
289            report: None,
290        }),
291        ProcessAttempt::UnknownAfterDispatch { evidence } => {
292            SandboxAttempt::Unknown(SandboxRefusal {
293                launcher: "platform/sandbox/ubuntu-bwrap".into(),
294                reason: format!("{}: {}", evidence.stage, evidence.detail),
295                report: None,
296            })
297        }
298    }
299}
300
301fn writable_usage(
302    request: &SandboxRequest,
303    sources: &BTreeMap<String, PathBuf>,
304) -> Result<(u64, u64), String> {
305    let mut total = (0u64, 0u64);
306    for mount in request
307        .policy
308        .mounts()
309        .iter()
310        .filter(|mount| mount.access == MountAccess::Writable)
311    {
312        let root = canonical(
313            sources
314                .get(&mount.source)
315                .ok_or("writable mount source is not boot-authorized")?,
316        )?;
317        accumulate_usage(&root, &mut total)?;
318    }
319    Ok(total)
320}
321
322fn accumulate_usage(path: &Path, total: &mut (u64, u64)) -> Result<(), String> {
323    for entry in std::fs::read_dir(path).map_err(|error| format!("writable root: {error}"))? {
324        let entry = entry.map_err(|error| format!("writable entry: {error}"))?;
325        let metadata = std::fs::symlink_metadata(entry.path())
326            .map_err(|error| format!("writable metadata: {error}"))?;
327        if metadata.file_type().is_symlink() {
328            total.0 = total.0.saturating_add(1);
329        } else if metadata.is_dir() {
330            accumulate_usage(&entry.path(), total)?;
331        } else {
332            total.0 = total.0.saturating_add(1);
333            total.1 = total.1.saturating_add(metadata.len());
334        }
335    }
336    Ok(())
337}
338
339/// Finite owner-selected ceiling for one immutable prepared resource tree.
340///
341/// The ceiling is installation input, not an observed usage claim.
342#[derive(Clone, Copy, Debug, Eq, PartialEq)]
343pub struct ReadOnlyTreeLimits {
344    maximum_entries: usize,
345    maximum_bytes: usize,
346}
347
348impl ReadOnlyTreeLimits {
349    /// Selects one ceiling within the protected-tree hard maximum.
350    ///
351    /// # Errors
352    /// Refuses an empty ceiling or one above the shared protected-tree maximum.
353    pub fn new(maximum_entries: usize, maximum_bytes: usize) -> io::Result<Self> {
354        if maximum_entries == 0
355            || maximum_entries > sim_platform_linux::MAXIMUM_PINNED_BOOT_TREE_ENTRIES
356            || maximum_bytes == 0
357            || maximum_bytes > sim_platform_linux::MAXIMUM_PINNED_BOOT_TREE_BYTES
358        {
359            return Err(io::Error::new(
360                io::ErrorKind::InvalidInput,
361                "read-only tree limits exceed the protected hard maximum",
362            ));
363        }
364        Ok(Self {
365            maximum_entries,
366            maximum_bytes,
367        })
368    }
369
370    /// Selects a ceiling for an owner-materialized production input.
371    ///
372    /// # Errors
373    /// Refuses an empty ceiling or one above the shared protected-tree maximum.
374    pub fn production_input(maximum_entries: usize, maximum_bytes: usize) -> io::Result<Self> {
375        Self::new(maximum_entries, maximum_bytes)
376    }
377
378    /// Maximum directories plus files retained for this exact resource.
379    #[must_use]
380    pub const fn maximum_entries(self) -> usize {
381        self.maximum_entries
382    }
383
384    /// Maximum logical file bytes retained for this exact resource.
385    #[must_use]
386    pub const fn maximum_bytes(self) -> usize {
387        self.maximum_bytes
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use sim_lib_exec::{
395        ArgAtom, SandboxLimits, SandboxMount, SandboxPolicy, SandboxRequirement, SealedBindings,
396    };
397    fn policy() -> SandboxPolicy {
398        let controls = [
399            SandboxControl::Network,
400            SandboxControl::Mounts,
401            SandboxControl::Root,
402            SandboxControl::Environment,
403            SandboxControl::Identity,
404            SandboxControl::Cpu,
405            SandboxControl::Memory,
406            SandboxControl::WallTime,
407            SandboxControl::ProcessCount,
408            SandboxControl::FileCount,
409            SandboxControl::FileBytes,
410            SandboxControl::Output,
411            SandboxControl::Stdin,
412            SandboxControl::ProcessTree,
413        ];
414        SandboxPolicy::new(
415            controls
416                .into_iter()
417                .map(|c| (c, SandboxRequirement::Required)),
418            vec![SandboxMount {
419                source: "input".into(),
420                guest_path: "/input".into(),
421                access: MountAccess::ReadOnly,
422            }],
423            SandboxLimits {
424                cpu_seconds: 1,
425                memory_bytes: 1024 * 1024,
426                wall_time_ms: 100,
427                process_count: 2,
428                file_count: 2,
429                file_bytes: 1024,
430                output_bytes: 1024,
431                stdin_bytes: 16,
432            },
433        )
434        .unwrap()
435    }
436    #[test]
437    fn missing_bwrap_refuses_before_dispatch() {
438        // A regular executable cannot contain a child program.
439        let executable = std::env::current_exe().expect("test executable");
440        let launcher = BwrapLauncher::new(
441            executable.join("bwrap"),
442            executable,
443            BTreeMap::new(),
444            BTreeMap::new(),
445        );
446        let status = launcher.confinement_status();
447        assert!(!status.available);
448        assert_eq!(status.membrane, "platform/sandbox/ubuntu-bwrap");
449        assert!(status.detail.contains("purity-qualified=false"));
450        assert_eq!(launcher.id(), "platform/sandbox/ubuntu-bwrap");
451        let request = SandboxRequest::new(
452            ProgramRef::new("tool").unwrap(),
453            vec![],
454            SealedBindings::empty(),
455            vec![],
456            policy(),
457        )
458        .unwrap();
459        assert!(matches!(
460            launcher.launch(&request, &ProcessCancellation::default()),
461            SandboxAttempt::Refused(_)
462        ));
463    }
464    #[test]
465    fn command_is_anonymous_networkless_and_keeps_hostile_argument_literal() {
466        let executable = std::env::current_exe().unwrap();
467        let launcher = BwrapLauncher::new(
468            executable.clone(),
469            executable.clone(),
470            BTreeMap::from([(ProgramRef::new("tool").unwrap(), executable)]),
471            BTreeMap::from([("input".into(), PathBuf::from("/tmp"))]),
472        );
473        let hostile = "$(printf first); printf second";
474        let request = SandboxRequest::new(
475            ProgramRef::new("tool").unwrap(),
476            vec![ArgAtom::new(hostile).unwrap()],
477            SealedBindings::empty(),
478            vec![],
479            policy(),
480        )
481        .unwrap();
482        let command = launcher.command(&request).unwrap();
483        let args = command
484            .get_args()
485            .map(|v| v.to_string_lossy().into_owned())
486            .collect::<Vec<_>>();
487        assert!(
488            args.iter().any(|v| v == "--unshare-net") && args.iter().any(|v| v == "--clearenv")
489        );
490        assert!(args.iter().any(|v| v == hostile));
491        assert!(!args.iter().any(|v| v == "/home" || v == "/workspace"));
492    }
493
494    #[test]
495    fn production_input_stays_inside_the_protected_tree_ceiling() {
496        assert!(ReadOnlyTreeLimits::production_input(8193, 1).is_err());
497        assert!(ReadOnlyTreeLimits::production_input(0, 1).is_err());
498        let admitted = ReadOnlyTreeLimits::production_input(4096, 1).unwrap();
499        assert_eq!(admitted.maximum_entries(), 4096);
500        assert_eq!(admitted.maximum_bytes(), 1);
501    }
502}