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