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