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