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::{
32 ElfError, Resolved, in_merged_usr, resolve as resolve_libraries,
33 resolve_in as resolve_libraries_in,
34};
35#[cfg(target_os = "linux")]
36pub use linux::landlock::MIN_ABI;
37
38/// Name of the environment variable carrying the effective policy into a cant, so that a
39/// nested `cant` can explain and pre-check attenuation. It is informational: the kernel
40/// enforces the real restrictions, and a forged value cannot widen them.
41pub const POLICY_ENV: &str = "CANT_POLICY";
42
43/// Files every program may need to read: the loader cache, locale, time zone, terminfo, the CA
44/// trust store and a few devices.
45pub const RUNTIME_READ: &[&str] = &[
46 "/etc/ld.so.cache",
47 "/etc/ld.so.preload",
48 "/etc/localtime",
49 "/usr/share/zoneinfo",
50 "/usr/lib/locale",
51 "/usr/share/locale",
52 "/etc/locale.alias",
53 "/usr/share/terminfo",
54 "/usr/lib/terminfo",
55 "/lib/terminfo",
56 "/etc/terminfo",
57 // The host's public CA trust store, for TLS (Debian/Ubuntu, Fedora/RHEL, Alpine, openSUSE).
58 // Only these: never `/etc/ssl` or `/etc/pki` as a whole, which hold `private/` key
59 // directories. Symlinked entries resolve into the directories listed after them.
60 "/etc/ssl/certs",
61 "/etc/ssl/cert.pem",
62 "/etc/ssl/ca-bundle.pem",
63 "/etc/pki/tls/certs",
64 "/etc/pki/ca-trust/extracted",
65 "/usr/share/ca-certificates",
66 "/var/lib/ca-certificates",
67 "/dev/zero",
68 "/dev/urandom",
69 "/dev/random",
70];
71
72/// What name resolution reads, granted (read-only) to every cant with `network = true`:
73/// without them a program may reach the network but can't look up a host name. They hold no
74/// secrets. A symlinked `/etc/resolv.conf` (systemd-resolved) resolves to its target.
75pub const NETWORK_READ: &[&str] = &[
76 "/etc/resolv.conf",
77 "/etc/hosts",
78 "/etc/nsswitch.conf",
79 "/etc/host.conf",
80 "/etc/gai.conf",
81];
82
83/// Devices every program may read and write.
84pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];
85
86/// The system's dynamic loaders. A cant that may execute files in a directory (cargo's build
87/// scripts in `$CWD`) gets these, because the kernel needs execute access to a program's
88/// loader to start it, and `cant` can't know in advance which files will run. Programs whose
89/// libraries `cant` resolves get their own loader anyway.
90pub const DYNAMIC_LOADERS: &[&str] = &[
91 "/lib64/ld-linux-x86-64.so.2",
92 "/lib/ld-linux-aarch64.so.1",
93 "/lib/ld-linux-riscv64-lp64d.so.1",
94 "/lib/ld-musl-x86_64.so.1",
95 "/lib/ld-musl-aarch64.so.1",
96 "/lib/ld-musl-riscv64.so.1",
97];
98
99/// How to start a can's program: through the can's own ELF loader, with the can's own
100/// libraries, and nothing resolved from the host.
101#[derive(Debug, Clone, Default)]
102pub struct CanStart {
103 /// The bundled loader (`<root>/lib64/ld-linux-x86-64.so.2`); `None` for a static program.
104 pub loader: Option<PathBuf>,
105 /// Directories searched for shared libraries, in order.
106 pub library_path: Vec<PathBuf>,
107}
108
109/// Everything needed to start a cant.
110#[derive(Debug, Clone)]
111pub struct Plan {
112 /// Cant name, for messages.
113 pub cant: String,
114 /// Canonical path of the executable.
115 pub program: PathBuf,
116 /// The program the cant is about: `program` itself, except for a can, where `program` is
117 /// the can's bundled loader and this is the program it starts.
118 pub entrypoint: PathBuf,
119 /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
120 pub argv0: OsString,
121 /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
122 pub args: Vec<OsString>,
123 /// The complete environment of the program.
124 pub env: Vec<(OsString, OsString)>,
125 /// The policy to enforce (this cant's own layer).
126 pub policy: Policy,
127 /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
128 /// `cant` is not itself running inside a cant).
129 pub effective: Policy,
130 /// Whether an enclosing cant's policy was found.
131 pub nested: bool,
132 /// Shared libraries that could not be found (the loader will report them if needed).
133 pub missing_libs: Vec<String>,
134}
135
136/// Errors from planning or launching.
137#[derive(Debug, thiserror::Error)]
138pub enum LaunchError {
139 /// Not running on Linux.
140 #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
141 Unsupported,
142 /// The CPU architecture has no seccomp support in this build.
143 #[error("unsupported CPU architecture {0}")]
144 UnsupportedArch(&'static str),
145 /// The executable could not be analysed.
146 #[cfg(target_os = "linux")]
147 #[error(transparent)]
148 Elf(#[from] ElfError),
149 /// A can's library directories can't be passed to its loader.
150 #[error("the can's library directories can't be passed to its loader: {0}")]
151 CanLibraryPath(String),
152 /// Landlock is not available.
153 #[error(
154 "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
155 )]
156 LandlockUnavailable,
157 /// Landlock is too old to enforce the policy faithfully.
158 #[error(
159 "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
160 )]
161 LandlockTooOld {
162 /// The kernel's ABI.
163 abi: i32,
164 },
165 /// Building or applying the Landlock ruleset failed.
166 #[error("Landlock setup failed: {0}")]
167 Landlock(String),
168 /// Building or applying a seccomp filter failed.
169 #[error("seccomp setup failed: {0}")]
170 Seccomp(String),
171 /// A writable command-line file could not be created.
172 #[error("cannot create {path}: {source}")]
173 Create {
174 /// The file.
175 path: PathBuf,
176 /// Cause.
177 source: std::io::Error,
178 },
179 /// Running inside another cant that may not run this cant's program.
180 #[error(
181 "{cant} isn't available here: the enclosing cant may not run {shown} \
182 (list `{cant}` in its capabilities.cants)"
183 )]
184 ParentCannotRun {
185 /// Cant name.
186 cant: String,
187 /// The program, for display.
188 shown: String,
189 },
190 /// The enclosing cant does not allow a file named on the command line.
191 #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
192 ParentDenies {
193 /// Cant name.
194 cant: String,
195 /// "read", "write" or "execute".
196 verb: &'static str,
197 /// The path, for display.
198 shown: String,
199 },
200 /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
201 #[error("malformed {POLICY_ENV}: {0}")]
202 ParentPolicy(String),
203 /// `execve` failed.
204 #[error("cannot execute {program}: {source}")]
205 Exec {
206 /// The program.
207 program: PathBuf,
208 /// Cause.
209 source: std::io::Error,
210 },
211}
212
213/// Facts about the running kernel, for `cant check`.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct KernelSupport {
216 /// Landlock ABI, if Landlock is available.
217 pub landlock_abi: Option<i32>,
218 /// Whether this build can install seccomp filters on this architecture.
219 pub seccomp_arch: bool,
220}
221
222/// Completes `built` into a launch plan.
223///
224/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
225#[cfg(target_os = "linux")]
226pub fn plan(
227 manifest: &cant_manifest::Manifest,
228 built: cant_policy::Built,
229 user_args: &[OsString],
230 parent: Option<&Policy>,
231 home: &std::path::Path,
232 can: Option<&CanStart>,
233) -> Result<Plan, LaunchError> {
234 linux::plan(manifest, built, user_args, parent, home, can)
235}
236
237/// Completes `built` into a launch plan (unsupported on this OS).
238#[cfg(not(target_os = "linux"))]
239pub fn plan(
240 _manifest: &cant_manifest::Manifest,
241 _built: cant_policy::Built,
242 _user_args: &[OsString],
243 _parent: Option<&Policy>,
244 _home: &std::path::Path,
245 _can: Option<&CanStart>,
246) -> Result<Plan, LaunchError> {
247 Err(LaunchError::Unsupported)
248}
249
250/// Enforces `plan` and replaces the current process with the program.
251/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
252#[cfg(target_os = "linux")]
253pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
254 linux::exec(plan, warn)
255}
256
257/// Enforces `plan` and replaces the current process (unsupported on this OS).
258#[cfg(not(target_os = "linux"))]
259pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
260 LaunchError::Unsupported
261}
262
263/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
264/// process (the only way to learn the ABI through the `landlock` crate), so call it only
265/// from a process that is about to exit, such as `cant check`.
266#[cfg(target_os = "linux")]
267pub fn probe_kernel() -> KernelSupport {
268 KernelSupport {
269 landlock_abi: linux::landlock::probe_abi(),
270 seccomp_arch: cfg!(any(
271 target_arch = "x86_64",
272 target_arch = "aarch64",
273 target_arch = "riscv64"
274 )),
275 }
276}
277
278/// Probes kernel support (nothing is supported on this OS).
279#[cfg(not(target_os = "linux"))]
280pub fn probe_kernel() -> KernelSupport {
281 KernelSupport {
282 landlock_abi: None,
283 seccomp_arch: false,
284 }
285}