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
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    /// The loopback port of the proxy, when the cant runs in its own network namespace with an
137    /// allow list (see [`Plan::use_proxy`]).
138    pub netns_proxy: Option<u16>,
139}
140
141/// The environment a program behind the namespace's proxy gets, whatever `[env] pass` says
142/// (docs/NETWORK-ALLOWLIST.md ยง10.3: Go and Python read the upper- or lowercase variables;
143/// Node's `fetch` needs `NODE_USE_ENV_PROXY`).
144pub fn proxy_environment(port: u16) -> Vec<(OsString, OsString)> {
145    let url = format!("http://127.0.0.1:{port}");
146    let local = "localhost,127.0.0.1,::1";
147    [
148        ("HTTPS_PROXY", url.as_str()),
149        ("https_proxy", url.as_str()),
150        ("HTTP_PROXY", url.as_str()),
151        ("http_proxy", url.as_str()),
152        ("NO_PROXY", local),
153        ("no_proxy", local),
154        ("NODE_USE_ENV_PROXY", "1"),
155    ]
156    .into_iter()
157    .map(|(k, v)| (k.into(), v.into()))
158    .collect()
159}
160
161impl Plan {
162    /// Runs the program behind the proxy listening on `port` inside its network namespace:
163    /// sets [`proxy_environment`] (replacing the user's values), and Landlock will allow TCP
164    /// connects to that port only.
165    pub fn use_proxy(&mut self, port: u16) {
166        let vars = proxy_environment(port);
167        self.env
168            .retain(|(k, _)| !vars.iter().any(|(name, _)| name == k));
169        self.env.extend(vars);
170        self.netns_proxy = Some(port);
171    }
172}
173
174/// Errors from planning or launching.
175#[derive(Debug, thiserror::Error)]
176pub enum LaunchError {
177    /// Not running on Linux.
178    #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
179    Unsupported,
180    /// The CPU architecture has no seccomp support in this build.
181    #[error("unsupported CPU architecture {0}")]
182    UnsupportedArch(&'static str),
183    /// The executable could not be analysed.
184    #[cfg(target_os = "linux")]
185    #[error(transparent)]
186    Elf(#[from] ElfError),
187    /// A can's library directories can't be passed to its loader.
188    #[error("the can's library directories can't be passed to its loader: {0}")]
189    CanLibraryPath(String),
190    /// Landlock is not available.
191    #[error(
192        "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
193    )]
194    LandlockUnavailable,
195    /// Landlock is too old to enforce the policy faithfully.
196    #[error(
197        "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
198    )]
199    LandlockTooOld {
200        /// The kernel's ABI.
201        abi: i32,
202    },
203    /// Building or applying the Landlock ruleset failed.
204    #[error("Landlock setup failed: {0}")]
205    Landlock(String),
206    /// Building or applying a seccomp filter failed.
207    #[error("seccomp setup failed: {0}")]
208    Seccomp(String),
209    /// A writable command-line file could not be created.
210    #[error("cannot create {path}: {source}")]
211    Create {
212        /// The file.
213        path: PathBuf,
214        /// Cause.
215        source: std::io::Error,
216    },
217    /// Running inside another cant that may not run this cant's program.
218    #[error(
219        "{cant} isn't available here: the enclosing cant may not run {shown} \
220         (list `{cant}` in its capabilities.cants)"
221    )]
222    ParentCannotRun {
223        /// Cant name.
224        cant: String,
225        /// The program, for display.
226        shown: String,
227    },
228    /// The enclosing cant does not allow a file named on the command line.
229    #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
230    ParentDenies {
231        /// Cant name.
232        cant: String,
233        /// "read", "write" or "execute".
234        verb: &'static str,
235        /// The path, for display.
236        shown: String,
237    },
238    /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
239    #[error("malformed {POLICY_ENV}: {0}")]
240    ParentPolicy(String),
241    /// `execve` failed.
242    #[error("cannot execute {program}: {source}")]
243    Exec {
244        /// The program.
245        program: PathBuf,
246        /// Cause.
247        source: std::io::Error,
248    },
249}
250
251/// Facts about the running kernel, for `cant check`.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct KernelSupport {
254    /// Landlock ABI, if Landlock is available.
255    pub landlock_abi: Option<i32>,
256    /// Whether this build can install seccomp filters on this architecture.
257    pub seccomp_arch: bool,
258}
259
260/// Completes `built` into a launch plan.
261///
262/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
263#[cfg(target_os = "linux")]
264pub fn plan(
265    manifest: &cant_manifest::Manifest,
266    built: cant_policy::Built,
267    user_args: &[OsString],
268    parent: Option<&Policy>,
269    home: &std::path::Path,
270    can: Option<&CanStart>,
271) -> Result<Plan, LaunchError> {
272    linux::plan(manifest, built, user_args, parent, home, can)
273}
274
275/// Completes `built` into a launch plan (unsupported on this OS).
276#[cfg(not(target_os = "linux"))]
277pub fn plan(
278    _manifest: &cant_manifest::Manifest,
279    _built: cant_policy::Built,
280    _user_args: &[OsString],
281    _parent: Option<&Policy>,
282    _home: &std::path::Path,
283    _can: Option<&CanStart>,
284) -> Result<Plan, LaunchError> {
285    Err(LaunchError::Unsupported)
286}
287
288/// Enforces `plan` and replaces the current process with the program.
289/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
290#[cfg(target_os = "linux")]
291pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
292    linux::exec(plan, warn)
293}
294
295/// Enforces `plan` and replaces the current process (unsupported on this OS).
296#[cfg(not(target_os = "linux"))]
297pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
298    LaunchError::Unsupported
299}
300
301/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
302/// process (the only way to learn the ABI through the `landlock` crate), so call it only
303/// from a process that is about to exit, such as `cant check`.
304#[cfg(target_os = "linux")]
305pub fn probe_kernel() -> KernelSupport {
306    KernelSupport {
307        landlock_abi: linux::landlock::probe_abi(),
308        seccomp_arch: cfg!(any(
309            target_arch = "x86_64",
310            target_arch = "aarch64",
311            target_arch = "riscv64"
312        )),
313    }
314}
315
316/// Probes kernel support (nothing is supported on this OS).
317#[cfg(not(target_os = "linux"))]
318pub fn probe_kernel() -> KernelSupport {
319    KernelSupport {
320        landlock_abi: None,
321        seccomp_arch: false,
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn the_proxy_environment_replaces_the_users() {
331        let mut plan = Plan {
332            cant: "x".into(),
333            program: PathBuf::from("/bin/x"),
334            entrypoint: PathBuf::from("/bin/x"),
335            argv0: "x".into(),
336            args: Vec::new(),
337            env: vec![
338                ("HTTPS_PROXY".into(), "http://corp:3128".into()),
339                ("LANG".into(), "C".into()),
340            ],
341            policy: Policy::default(),
342            effective: Policy::default(),
343            nested: false,
344            missing_libs: Vec::new(),
345            netns_proxy: None,
346        };
347        plan.use_proxy(41000);
348        assert_eq!(plan.netns_proxy, Some(41000));
349        let get = |k: &str| {
350            plan.env
351                .iter()
352                .filter(|(n, _)| n == k)
353                .map(|(_, v)| v.to_string_lossy().into_owned())
354                .collect::<Vec<_>>()
355        };
356        assert_eq!(
357            get("HTTPS_PROXY"),
358            ["http://127.0.0.1:41000"],
359            "replaced, once"
360        );
361        assert_eq!(get("http_proxy"), ["http://127.0.0.1:41000"]);
362        assert_eq!(get("no_proxy"), ["localhost,127.0.0.1,::1"]);
363        assert_eq!(get("NODE_USE_ENV_PROXY"), ["1"]);
364        assert_eq!(get("LANG"), ["C"], "the rest stays");
365        assert_eq!(proxy_environment(1).len(), 7);
366    }
367}