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