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// No unsafe code, except in coverage builds (`cargo llvm-cov` sets `cfg(coverage)`): there,
21// `flush_coverage` calls the profiler runtime. Shipped and normal builds forbid unsafe code.
22#![cfg_attr(not(coverage), forbid(unsafe_code))]
23#![cfg_attr(coverage, deny(unsafe_code))]
24
25use std::ffi::OsString;
26use std::path::PathBuf;
27
28use cant_policy::Policy;
29
30#[cfg(target_os = "linux")]
31mod linux;
32
33pub mod netns;
34
35#[cfg(target_os = "linux")]
36pub use linux::elf::{
37    ElfError, Resolved, in_merged_usr, resolve as resolve_libraries,
38    resolve_in as resolve_libraries_in,
39};
40#[cfg(target_os = "linux")]
41pub use linux::landlock::MIN_ABI;
42
43/// Name of the environment variable carrying the effective policy into a cant, so that a
44/// nested `cant` can explain and pre-check attenuation. It is informational: the kernel
45/// enforces the real restrictions, and a forged value cannot widen them.
46pub const POLICY_ENV: &str = "CANT_POLICY";
47
48/// Files every program may need to read: the loader cache, locale, time zone, terminfo, the CA
49/// trust store and a few devices.
50pub const RUNTIME_READ: &[&str] = &[
51    "/etc/ld.so.cache",
52    "/etc/ld.so.preload",
53    "/etc/localtime",
54    "/usr/share/zoneinfo",
55    "/usr/lib/locale",
56    "/usr/share/locale",
57    "/etc/locale.alias",
58    "/usr/share/terminfo",
59    "/usr/lib/terminfo",
60    "/lib/terminfo",
61    "/etc/terminfo",
62    // The host's public CA trust store, for TLS (Debian/Ubuntu, Fedora/RHEL, Alpine, openSUSE).
63    // Only these: never `/etc/ssl` or `/etc/pki` as a whole, which hold `private/` key
64    // directories. Symlinked entries resolve into the directories listed after them.
65    "/etc/ssl/certs",
66    "/etc/ssl/cert.pem",
67    "/etc/ssl/ca-bundle.pem",
68    "/etc/pki/tls/certs",
69    "/etc/pki/ca-trust/extracted",
70    "/usr/share/ca-certificates",
71    "/var/lib/ca-certificates",
72    "/dev/zero",
73    "/dev/urandom",
74    "/dev/random",
75];
76
77/// What name resolution reads, granted (read-only) to every cant with `network = true`:
78/// without them a program may reach the network but can't look up a host name. They hold no
79/// secrets. A symlinked `/etc/resolv.conf` (systemd-resolved) resolves to its target.
80pub const NETWORK_READ: &[&str] = &[
81    "/etc/resolv.conf",
82    "/etc/hosts",
83    "/etc/nsswitch.conf",
84    "/etc/host.conf",
85    "/etc/gai.conf",
86];
87
88/// Devices every program may read and write.
89pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];
90
91/// The system's dynamic loaders. A cant that may execute files in a directory (cargo's build
92/// scripts in `$CWD`) gets these, because the kernel needs execute access to a program's
93/// loader to start it, and `cant` can't know in advance which files will run. Programs whose
94/// libraries `cant` resolves get their own loader anyway.
95pub const DYNAMIC_LOADERS: &[&str] = &[
96    "/lib64/ld-linux-x86-64.so.2",
97    "/lib/ld-linux-aarch64.so.1",
98    "/lib/ld-linux-riscv64-lp64d.so.1",
99    "/lib/ld-musl-x86_64.so.1",
100    "/lib/ld-musl-aarch64.so.1",
101    "/lib/ld-musl-riscv64.so.1",
102];
103
104/// How to start a can's program: through the can's own ELF loader, with the can's own
105/// libraries, and nothing resolved from the host.
106#[derive(Debug, Clone, Default)]
107pub struct CanStart {
108    /// The bundled loader (`<root>/lib64/ld-linux-x86-64.so.2`); `None` for a static program.
109    pub loader: Option<PathBuf>,
110    /// Directories searched for shared libraries, in order.
111    pub library_path: Vec<PathBuf>,
112}
113
114/// Everything needed to start a cant.
115#[derive(Debug, Clone)]
116pub struct Plan {
117    /// Cant name, for messages.
118    pub cant: String,
119    /// Canonical path of the executable.
120    pub program: PathBuf,
121    /// The program the cant is about: `program` itself, except for a can, where `program` is
122    /// the can's bundled loader and this is the program it starts.
123    pub entrypoint: PathBuf,
124    /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
125    pub argv0: OsString,
126    /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
127    pub args: Vec<OsString>,
128    /// The complete environment of the program.
129    pub env: Vec<(OsString, OsString)>,
130    /// The policy to enforce (this cant's own layer).
131    pub policy: Policy,
132    /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
133    /// `cant` is not itself running inside a cant).
134    pub effective: Policy,
135    /// Whether an enclosing cant's policy was found.
136    pub nested: bool,
137    /// Shared libraries that could not be found (the loader will report them if needed).
138    pub missing_libs: Vec<String>,
139    /// The loopback port of the proxy, when the cant runs in its own network namespace with an
140    /// allow list (see [`Plan::use_proxy`]).
141    pub netns_proxy: Option<u16>,
142}
143
144/// The environment a program behind the namespace's proxy gets, whatever `[env] pass` says
145/// (docs/NETWORK-ALLOWLIST.md ยง10.3: Go and Python read the upper- or lowercase variables;
146/// Node's `fetch` needs `NODE_USE_ENV_PROXY`).
147pub fn proxy_environment(port: u16) -> Vec<(OsString, OsString)> {
148    let url = format!("http://127.0.0.1:{port}");
149    let local = "localhost,127.0.0.1,::1";
150    [
151        ("HTTPS_PROXY", url.as_str()),
152        ("https_proxy", url.as_str()),
153        ("HTTP_PROXY", url.as_str()),
154        ("http_proxy", url.as_str()),
155        ("NO_PROXY", local),
156        ("no_proxy", local),
157        ("NODE_USE_ENV_PROXY", "1"),
158    ]
159    .into_iter()
160    .map(|(k, v)| (k.into(), v.into()))
161    .collect()
162}
163
164impl Plan {
165    /// Runs the program behind the proxy listening on `port` inside its network namespace:
166    /// sets [`proxy_environment`] (replacing the user's values), and Landlock will allow TCP
167    /// connects to that port only.
168    pub fn use_proxy(&mut self, port: u16) {
169        let vars = proxy_environment(port);
170        self.env
171            .retain(|(k, _)| !vars.iter().any(|(name, _)| name == k));
172        self.env.extend(vars);
173        self.netns_proxy = Some(port);
174    }
175}
176
177/// Errors from planning or launching.
178#[derive(Debug, thiserror::Error)]
179pub enum LaunchError {
180    /// Not running on Linux.
181    #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
182    Unsupported,
183    /// The CPU architecture has no seccomp support in this build.
184    #[error("unsupported CPU architecture {0}")]
185    UnsupportedArch(&'static str),
186    /// The executable could not be analysed.
187    #[cfg(target_os = "linux")]
188    #[error(transparent)]
189    Elf(#[from] ElfError),
190    /// A can's library directories can't be passed to its loader.
191    #[error("the can's library directories can't be passed to its loader: {0}")]
192    CanLibraryPath(String),
193    /// Landlock is not available.
194    #[error(
195        "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
196    )]
197    LandlockUnavailable,
198    /// Landlock is too old to enforce the policy faithfully.
199    #[error(
200        "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
201    )]
202    LandlockTooOld {
203        /// The kernel's ABI.
204        abi: i32,
205    },
206    /// Building or applying the Landlock ruleset failed.
207    #[error("Landlock setup failed: {0}")]
208    Landlock(String),
209    /// Building or applying a seccomp filter failed.
210    #[error("seccomp setup failed: {0}")]
211    Seccomp(String),
212    /// A writable command-line file could not be created.
213    #[error("cannot create {path}: {source}")]
214    Create {
215        /// The file.
216        path: PathBuf,
217        /// Cause.
218        source: std::io::Error,
219    },
220    /// Running inside another cant that may not run this cant's program.
221    #[error(
222        "{cant} isn't available here: the enclosing cant may not run {shown} \
223         (list `{cant}` in its capabilities.cants)"
224    )]
225    ParentCannotRun {
226        /// Cant name.
227        cant: String,
228        /// The program, for display.
229        shown: String,
230    },
231    /// The enclosing cant does not allow a file named on the command line.
232    #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
233    ParentDenies {
234        /// Cant name.
235        cant: String,
236        /// "read", "write" or "execute".
237        verb: &'static str,
238        /// The path, for display.
239        shown: String,
240    },
241    /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
242    #[error("malformed {POLICY_ENV}: {0}")]
243    ParentPolicy(String),
244    /// `execve` failed.
245    #[error("cannot execute {program}: {source}")]
246    Exec {
247        /// The program.
248        program: PathBuf,
249        /// Cause.
250        source: std::io::Error,
251    },
252}
253
254/// Facts about the running kernel, for `cant check`.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct KernelSupport {
257    /// Landlock ABI, if Landlock is available.
258    pub landlock_abi: Option<i32>,
259    /// Whether this build can install seccomp filters on this architecture.
260    pub seccomp_arch: bool,
261}
262
263/// Completes `built` into a launch plan.
264///
265/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
266#[cfg(target_os = "linux")]
267pub fn plan(
268    manifest: &cant_manifest::Manifest,
269    built: cant_policy::Built,
270    user_args: &[OsString],
271    parent: Option<&Policy>,
272    home: &std::path::Path,
273    can: Option<&CanStart>,
274) -> Result<Plan, LaunchError> {
275    linux::plan(manifest, built, user_args, parent, home, can)
276}
277
278/// Completes `built` into a launch plan (unsupported on this OS).
279#[cfg(not(target_os = "linux"))]
280pub fn plan(
281    _manifest: &cant_manifest::Manifest,
282    _built: cant_policy::Built,
283    _user_args: &[OsString],
284    _parent: Option<&Policy>,
285    _home: &std::path::Path,
286    _can: Option<&CanStart>,
287) -> Result<Plan, LaunchError> {
288    Err(LaunchError::Unsupported)
289}
290
291/// Enforces `plan` and replaces the current process with the program.
292/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
293#[cfg(target_os = "linux")]
294pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
295    linux::exec(plan, warn)
296}
297
298/// Enforces `plan` and replaces the current process (unsupported on this OS).
299#[cfg(not(target_os = "linux"))]
300pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
301    LaunchError::Unsupported
302}
303
304/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
305/// process (the only way to learn the ABI through the `landlock` crate), so call it only
306/// from a process that is about to exit, such as `cant check`.
307#[cfg(target_os = "linux")]
308pub fn probe_kernel() -> KernelSupport {
309    KernelSupport {
310        landlock_abi: linux::landlock::probe_abi(),
311        seccomp_arch: cfg!(any(
312            target_arch = "x86_64",
313            target_arch = "aarch64",
314            target_arch = "riscv64"
315        )),
316    }
317}
318
319/// Probes kernel support (nothing is supported on this OS).
320#[cfg(not(target_os = "linux"))]
321pub fn probe_kernel() -> KernelSupport {
322    KernelSupport {
323        landlock_abi: None,
324        seccomp_arch: false,
325    }
326}
327
328/// Writes this process's coverage profile now. Only in coverage builds (`cargo llvm-cov`);
329/// elsewhere it does nothing. Called right before `exec` (which replaces the process without
330/// running the profiler's exit handler, so every successful `cant run` would otherwise leave no
331/// coverage) and before the supervisor dies from a signal. Never compiled into shipped binaries.
332#[cfg(coverage)]
333#[allow(unsafe_code)]
334pub fn flush_coverage() {
335    unsafe extern "C" {
336        fn __llvm_profile_write_file() -> i32;
337    }
338    // SAFETY: the profiler runtime that every coverage build links defines this function; it
339    // takes no arguments and only writes the profile file named by LLVM_PROFILE_FILE.
340    let _ = unsafe { __llvm_profile_write_file() };
341}
342
343/// Does nothing outside coverage builds.
344#[cfg(not(coverage))]
345pub fn flush_coverage() {}
346
347/// The directory the coverage profile is written to (coverage builds only): the sandbox lets
348/// `cant` write there, so that [`flush_coverage`] still works after Landlock is applied.
349#[cfg(coverage)]
350pub(crate) fn coverage_dir() -> Option<PathBuf> {
351    let file = PathBuf::from(std::env::var_os("LLVM_PROFILE_FILE")?);
352    file.parent().map(std::path::Path::to_path_buf)
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358
359    #[test]
360    fn the_proxy_environment_replaces_the_users() {
361        let mut plan = Plan {
362            cant: "x".into(),
363            program: PathBuf::from("/bin/x"),
364            entrypoint: PathBuf::from("/bin/x"),
365            argv0: "x".into(),
366            args: Vec::new(),
367            env: vec![
368                ("HTTPS_PROXY".into(), "http://corp:3128".into()),
369                ("LANG".into(), "C".into()),
370            ],
371            policy: Policy::default(),
372            effective: Policy::default(),
373            nested: false,
374            missing_libs: Vec::new(),
375            netns_proxy: None,
376        };
377        plan.use_proxy(41000);
378        assert_eq!(plan.netns_proxy, Some(41000));
379        let get = |k: &str| {
380            plan.env
381                .iter()
382                .filter(|(n, _)| n == k)
383                .map(|(_, v)| v.to_string_lossy().into_owned())
384                .collect::<Vec<_>>()
385        };
386        assert_eq!(
387            get("HTTPS_PROXY"),
388            ["http://127.0.0.1:41000"],
389            "replaced, once"
390        );
391        assert_eq!(get("http_proxy"), ["http://127.0.0.1:41000"]);
392        assert_eq!(get("no_proxy"), ["localhost,127.0.0.1,::1"]);
393        assert_eq!(get("NODE_USE_ENV_PROXY"), ["1"]);
394        assert_eq!(get("LANG"), ["C"], "the rest stays");
395        assert_eq!(proxy_environment(1).len(), 7);
396    }
397}