cant_launch/lib.rs
1//! Sandbox setup and exec for Cantainer.
2//!
3//! [`plan`] completes a policy with what the executable needs to start (its ELF interpreter,
4//! shared libraries and a small runtime base), filters the environment and builds argv.
5//! [`exec`] then makes the kernel enforce the plan and replaces the current process with the
6//! program:
7//!
8//! 1. create writable command-line files that do not exist yet (so they have an inode),
9//! 2. Landlock: deny by default, allow each grant (also sets `no_new_privs`),
10//! 3. seccomp: baseline deny list plus the socket families the policy does not allow,
11//! 4. `execve`.
12//!
13//! There is no supervisor process: exit status, signals and the terminal belong to the
14//! program, exactly as if it had been run directly. Restrictions are inherited by everything
15//! it starts and cannot be lifted.
16//!
17//! Linux only. On other systems every entry point returns [`LaunchError::Unsupported`], so the
18//! workspace still builds on macOS for editing.
19
20#![forbid(unsafe_code)]
21
22use std::ffi::OsString;
23use std::path::PathBuf;
24
25use cant_policy::Policy;
26
27#[cfg(target_os = "linux")]
28mod linux;
29
30#[cfg(target_os = "linux")]
31pub use linux::elf::{ElfError, Resolved, resolve as resolve_libraries};
32#[cfg(target_os = "linux")]
33pub use linux::landlock::MIN_ABI;
34
35/// Name of the environment variable carrying the effective policy into a cant, so that a
36/// nested `cant` can explain and pre-check attenuation. It is informational: the kernel
37/// enforces the real restrictions, and a forged value cannot widen them.
38pub const POLICY_ENV: &str = "CANT_POLICY";
39
40/// Files every dynamically linked program may need to read.
41pub const RUNTIME_READ: &[&str] = &[
42 "/etc/ld.so.cache",
43 "/etc/ld.so.preload",
44 "/etc/localtime",
45 "/usr/share/zoneinfo",
46 "/usr/lib/locale",
47 "/usr/share/locale",
48 "/etc/locale.alias",
49 "/usr/share/terminfo",
50 "/usr/lib/terminfo",
51 "/lib/terminfo",
52 "/etc/terminfo",
53 "/dev/zero",
54 "/dev/urandom",
55 "/dev/random",
56];
57
58/// Devices every program may read and write.
59pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];
60
61/// The system's dynamic loaders. A cant that may execute files in a directory (cargo's build
62/// scripts in `$CWD`) gets these, because the kernel needs execute access to a program's
63/// loader to start it, and `cant` can't know in advance which files will run. Programs whose
64/// libraries `cant` resolves get their own loader anyway.
65pub const DYNAMIC_LOADERS: &[&str] = &[
66 "/lib64/ld-linux-x86-64.so.2",
67 "/lib/ld-linux-aarch64.so.1",
68 "/lib/ld-linux-riscv64-lp64d.so.1",
69 "/lib/ld-musl-x86_64.so.1",
70 "/lib/ld-musl-aarch64.so.1",
71 "/lib/ld-musl-riscv64.so.1",
72];
73
74/// Everything needed to start a cant.
75#[derive(Debug, Clone)]
76pub struct Plan {
77 /// Cant name, for messages.
78 pub cant: String,
79 /// Canonical path of the executable.
80 pub program: PathBuf,
81 /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
82 pub argv0: OsString,
83 /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
84 pub args: Vec<OsString>,
85 /// The complete environment of the program.
86 pub env: Vec<(OsString, OsString)>,
87 /// The policy to enforce (this cant's own layer).
88 pub policy: Policy,
89 /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
90 /// `cant` is not itself running inside a cant).
91 pub effective: Policy,
92 /// Whether an enclosing cant's policy was found.
93 pub nested: bool,
94 /// Shared libraries that could not be found (the loader will report them if needed).
95 pub missing_libs: Vec<String>,
96}
97
98/// Errors from planning or launching.
99#[derive(Debug, thiserror::Error)]
100pub enum LaunchError {
101 /// Not running on Linux.
102 #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
103 Unsupported,
104 /// The CPU architecture has no seccomp support in this build.
105 #[error("unsupported CPU architecture {0}")]
106 UnsupportedArch(&'static str),
107 /// The executable could not be analysed.
108 #[cfg(target_os = "linux")]
109 #[error(transparent)]
110 Elf(#[from] ElfError),
111 /// Landlock is not available.
112 #[error(
113 "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
114 )]
115 LandlockUnavailable,
116 /// Landlock is too old to enforce the policy faithfully.
117 #[error(
118 "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
119 )]
120 LandlockTooOld {
121 /// The kernel's ABI.
122 abi: i32,
123 },
124 /// Building or applying the Landlock ruleset failed.
125 #[error("Landlock setup failed: {0}")]
126 Landlock(String),
127 /// Building or applying a seccomp filter failed.
128 #[error("seccomp setup failed: {0}")]
129 Seccomp(String),
130 /// A writable command-line file could not be created.
131 #[error("cannot create {path}: {source}")]
132 Create {
133 /// The file.
134 path: PathBuf,
135 /// Cause.
136 source: std::io::Error,
137 },
138 /// Running inside another cant that may not run this cant's program.
139 #[error(
140 "{cant} isn't available here: the enclosing cant may not run {shown} \
141 (list `{cant}` in its capabilities.cants)"
142 )]
143 ParentCannotRun {
144 /// Cant name.
145 cant: String,
146 /// The program, for display.
147 shown: String,
148 },
149 /// The enclosing cant does not allow a file named on the command line.
150 #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
151 ParentDenies {
152 /// Cant name.
153 cant: String,
154 /// "read", "write" or "execute".
155 verb: &'static str,
156 /// The path, for display.
157 shown: String,
158 },
159 /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
160 #[error("malformed {POLICY_ENV}: {0}")]
161 ParentPolicy(String),
162 /// `execve` failed.
163 #[error("cannot execute {program}: {source}")]
164 Exec {
165 /// The program.
166 program: PathBuf,
167 /// Cause.
168 source: std::io::Error,
169 },
170}
171
172/// Facts about the running kernel, for `cant check`.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub struct KernelSupport {
175 /// Landlock ABI, if Landlock is available.
176 pub landlock_abi: Option<i32>,
177 /// Whether this build can install seccomp filters on this architecture.
178 pub seccomp_arch: bool,
179}
180
181/// Completes `built` into a launch plan.
182///
183/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
184#[cfg(target_os = "linux")]
185pub fn plan(
186 manifest: &cant_manifest::Manifest,
187 built: cant_policy::Built,
188 user_args: &[OsString],
189 parent: Option<&Policy>,
190 home: &std::path::Path,
191) -> Result<Plan, LaunchError> {
192 linux::plan(manifest, built, user_args, parent, home)
193}
194
195/// Completes `built` into a launch plan (unsupported on this OS).
196#[cfg(not(target_os = "linux"))]
197pub fn plan(
198 _manifest: &cant_manifest::Manifest,
199 _built: cant_policy::Built,
200 _user_args: &[OsString],
201 _parent: Option<&Policy>,
202 _home: &std::path::Path,
203) -> Result<Plan, LaunchError> {
204 Err(LaunchError::Unsupported)
205}
206
207/// Enforces `plan` and replaces the current process with the program.
208/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
209#[cfg(target_os = "linux")]
210pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
211 linux::exec(plan, warn)
212}
213
214/// Enforces `plan` and replaces the current process (unsupported on this OS).
215#[cfg(not(target_os = "linux"))]
216pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
217 LaunchError::Unsupported
218}
219
220/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
221/// process (the only way to learn the ABI through the `landlock` crate), so call it only
222/// from a process that is about to exit, such as `cant check`.
223#[cfg(target_os = "linux")]
224pub fn probe_kernel() -> KernelSupport {
225 KernelSupport {
226 landlock_abi: linux::landlock::probe_abi(),
227 seccomp_arch: cfg!(any(
228 target_arch = "x86_64",
229 target_arch = "aarch64",
230 target_arch = "riscv64"
231 )),
232 }
233}
234
235/// Probes kernel support (nothing is supported on this OS).
236#[cfg(not(target_os = "linux"))]
237pub fn probe_kernel() -> KernelSupport {
238 KernelSupport {
239 landlock_abi: None,
240 seccomp_arch: false,
241 }
242}