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