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/// How to start a can's program: through the can's own ELF loader, with the can's own
75/// libraries, and nothing resolved from the host.
76#[derive(Debug, Clone, Default)]
77pub struct CanStart {
78 /// The bundled loader (`<root>/lib64/ld-linux-x86-64.so.2`); `None` for a static program.
79 pub loader: Option<PathBuf>,
80 /// Directories searched for shared libraries, in order.
81 pub library_path: Vec<PathBuf>,
82}
83
84/// Everything needed to start a cant.
85#[derive(Debug, Clone)]
86pub struct Plan {
87 /// Cant name, for messages.
88 pub cant: String,
89 /// Canonical path of the executable.
90 pub program: PathBuf,
91 /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
92 pub argv0: OsString,
93 /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
94 pub args: Vec<OsString>,
95 /// The complete environment of the program.
96 pub env: Vec<(OsString, OsString)>,
97 /// The policy to enforce (this cant's own layer).
98 pub policy: Policy,
99 /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
100 /// `cant` is not itself running inside a cant).
101 pub effective: Policy,
102 /// Whether an enclosing cant's policy was found.
103 pub nested: bool,
104 /// Shared libraries that could not be found (the loader will report them if needed).
105 pub missing_libs: Vec<String>,
106}
107
108/// Errors from planning or launching.
109#[derive(Debug, thiserror::Error)]
110pub enum LaunchError {
111 /// Not running on Linux.
112 #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
113 Unsupported,
114 /// The CPU architecture has no seccomp support in this build.
115 #[error("unsupported CPU architecture {0}")]
116 UnsupportedArch(&'static str),
117 /// The executable could not be analysed.
118 #[cfg(target_os = "linux")]
119 #[error(transparent)]
120 Elf(#[from] ElfError),
121 /// A can's library directories can't be passed to its loader.
122 #[error("the can's library directories can't be passed to its loader: {0}")]
123 CanLibraryPath(String),
124 /// Landlock is not available.
125 #[error(
126 "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
127 )]
128 LandlockUnavailable,
129 /// Landlock is too old to enforce the policy faithfully.
130 #[error(
131 "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
132 )]
133 LandlockTooOld {
134 /// The kernel's ABI.
135 abi: i32,
136 },
137 /// Building or applying the Landlock ruleset failed.
138 #[error("Landlock setup failed: {0}")]
139 Landlock(String),
140 /// Building or applying a seccomp filter failed.
141 #[error("seccomp setup failed: {0}")]
142 Seccomp(String),
143 /// A writable command-line file could not be created.
144 #[error("cannot create {path}: {source}")]
145 Create {
146 /// The file.
147 path: PathBuf,
148 /// Cause.
149 source: std::io::Error,
150 },
151 /// Running inside another cant that may not run this cant's program.
152 #[error(
153 "{cant} isn't available here: the enclosing cant may not run {shown} \
154 (list `{cant}` in its capabilities.cants)"
155 )]
156 ParentCannotRun {
157 /// Cant name.
158 cant: String,
159 /// The program, for display.
160 shown: String,
161 },
162 /// The enclosing cant does not allow a file named on the command line.
163 #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
164 ParentDenies {
165 /// Cant name.
166 cant: String,
167 /// "read", "write" or "execute".
168 verb: &'static str,
169 /// The path, for display.
170 shown: String,
171 },
172 /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
173 #[error("malformed {POLICY_ENV}: {0}")]
174 ParentPolicy(String),
175 /// `execve` failed.
176 #[error("cannot execute {program}: {source}")]
177 Exec {
178 /// The program.
179 program: PathBuf,
180 /// Cause.
181 source: std::io::Error,
182 },
183}
184
185/// Facts about the running kernel, for `cant check`.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct KernelSupport {
188 /// Landlock ABI, if Landlock is available.
189 pub landlock_abi: Option<i32>,
190 /// Whether this build can install seccomp filters on this architecture.
191 pub seccomp_arch: bool,
192}
193
194/// Completes `built` into a launch plan.
195///
196/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
197#[cfg(target_os = "linux")]
198pub fn plan(
199 manifest: &cant_manifest::Manifest,
200 built: cant_policy::Built,
201 user_args: &[OsString],
202 parent: Option<&Policy>,
203 home: &std::path::Path,
204 can: Option<&CanStart>,
205) -> Result<Plan, LaunchError> {
206 linux::plan(manifest, built, user_args, parent, home, can)
207}
208
209/// Completes `built` into a launch plan (unsupported on this OS).
210#[cfg(not(target_os = "linux"))]
211pub fn plan(
212 _manifest: &cant_manifest::Manifest,
213 _built: cant_policy::Built,
214 _user_args: &[OsString],
215 _parent: Option<&Policy>,
216 _home: &std::path::Path,
217 _can: Option<&CanStart>,
218) -> Result<Plan, LaunchError> {
219 Err(LaunchError::Unsupported)
220}
221
222/// Enforces `plan` and replaces the current process with the program.
223/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
224#[cfg(target_os = "linux")]
225pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
226 linux::exec(plan, warn)
227}
228
229/// Enforces `plan` and replaces the current process (unsupported on this OS).
230#[cfg(not(target_os = "linux"))]
231pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
232 LaunchError::Unsupported
233}
234
235/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
236/// process (the only way to learn the ABI through the `landlock` crate), so call it only
237/// from a process that is about to exit, such as `cant check`.
238#[cfg(target_os = "linux")]
239pub fn probe_kernel() -> KernelSupport {
240 KernelSupport {
241 landlock_abi: linux::landlock::probe_abi(),
242 seccomp_arch: cfg!(any(
243 target_arch = "x86_64",
244 target_arch = "aarch64",
245 target_arch = "riscv64"
246 )),
247 }
248}
249
250/// Probes kernel support (nothing is supported on this OS).
251#[cfg(not(target_os = "linux"))]
252pub fn probe_kernel() -> KernelSupport {
253 KernelSupport {
254 landlock_abi: None,
255 seccomp_arch: false,
256 }
257}