Skip to main content

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