cant-launch 0.0.22

Sandbox setup (Landlock, seccomp) and exec for Cantainer capsules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Sandbox setup and exec for Cantainer.
//!
//! [`plan`] completes a policy with what the executable needs to start (its ELF interpreter,
//! shared libraries and a small runtime base), filters the environment and builds argv.
//! [`exec`] then makes the kernel enforce the plan and replaces the current process with the
//! program:
//!
//! 1. create writable command-line files that do not exist yet (so they have an inode),
//! 2. Landlock: deny by default, allow each grant (also sets `no_new_privs`),
//! 3. seccomp: baseline deny list plus the socket families the policy does not allow,
//! 4. `execve`.
//!
//! There is no supervisor process: exit status, signals and the terminal belong to the
//! program, exactly as if it had been run directly. Restrictions are inherited by everything
//! it starts and cannot be lifted.
//!
//! Linux only. On other systems every entry point returns [`LaunchError::Unsupported`], so the
//! workspace still builds on macOS for editing.

// No unsafe code, except in coverage builds (`cargo llvm-cov` sets `cfg(coverage)`): there,
// `flush_coverage` calls the profiler runtime. Shipped and normal builds forbid unsafe code.
#![cfg_attr(not(coverage), forbid(unsafe_code))]
#![cfg_attr(coverage, deny(unsafe_code))]

use std::ffi::OsString;
use std::path::PathBuf;

use cant_policy::Policy;

#[cfg(target_os = "linux")]
mod linux;

pub mod netns;
pub mod readonly;

#[cfg(target_os = "linux")]
pub use linux::elf::{
    ElfError, Resolved, in_merged_usr, resolve as resolve_libraries,
    resolve_in as resolve_libraries_in,
};
#[cfg(target_os = "linux")]
pub use linux::landlock::MIN_ABI;

/// Name of the environment variable carrying the effective policy into a cant, so that a
/// nested `cant` can explain and pre-check attenuation. It is informational: the kernel
/// enforces the real restrictions, and a forged value cannot widen them.
pub const POLICY_ENV: &str = "CANT_POLICY";

/// Files every program may need to read: the loader cache, locale, time zone, terminfo, the CA
/// trust store and a few devices.
pub const RUNTIME_READ: &[&str] = &[
    "/etc/ld.so.cache",
    "/etc/ld.so.preload",
    "/etc/localtime",
    "/usr/share/zoneinfo",
    "/usr/lib/locale",
    "/usr/share/locale",
    "/etc/locale.alias",
    "/usr/share/terminfo",
    "/usr/lib/terminfo",
    "/lib/terminfo",
    "/etc/terminfo",
    // The host's public CA trust store, for TLS (Debian/Ubuntu, Fedora/RHEL, Alpine, openSUSE).
    // Only these: never `/etc/ssl` or `/etc/pki` as a whole, which hold `private/` key
    // directories. Symlinked entries resolve into the directories listed after them.
    "/etc/ssl/certs",
    "/etc/ssl/cert.pem",
    "/etc/ssl/ca-bundle.pem",
    "/etc/pki/tls/certs",
    "/etc/pki/ca-trust/extracted",
    "/usr/share/ca-certificates",
    "/var/lib/ca-certificates",
    "/dev/zero",
    "/dev/urandom",
    "/dev/random",
];

/// What name resolution reads, granted (read-only) to every cant with `network = true`:
/// without them a program may reach the network but can't look up a host name. They hold no
/// secrets. A symlinked `/etc/resolv.conf` (systemd-resolved) resolves to its target.
pub const NETWORK_READ: &[&str] = &[
    "/etc/resolv.conf",
    "/etc/hosts",
    "/etc/nsswitch.conf",
    "/etc/host.conf",
    "/etc/gai.conf",
];

/// Devices every program may read and write.
pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];

/// The system's dynamic loaders. A cant that may execute files in a directory (cargo's build
/// scripts in `$CWD`) gets these, because the kernel needs execute access to a program's
/// loader to start it, and `cant` can't know in advance which files will run. Programs whose
/// libraries `cant` resolves get their own loader anyway.
pub const DYNAMIC_LOADERS: &[&str] = &[
    "/lib64/ld-linux-x86-64.so.2",
    "/lib/ld-linux-aarch64.so.1",
    "/lib/ld-linux-riscv64-lp64d.so.1",
    "/lib/ld-musl-x86_64.so.1",
    "/lib/ld-musl-aarch64.so.1",
    "/lib/ld-musl-riscv64.so.1",
];

/// How to start a can's program: through the can's own ELF loader, with the can's own
/// libraries, and nothing resolved from the host.
#[derive(Debug, Clone, Default)]
pub struct CanStart {
    /// The bundled loader (`<root>/lib64/ld-linux-x86-64.so.2`); `None` for a static program.
    pub loader: Option<PathBuf>,
    /// Directories searched for shared libraries, in order.
    pub library_path: Vec<PathBuf>,
}

/// Everything needed to start a cant.
#[derive(Debug, Clone)]
pub struct Plan {
    /// Cant name, for messages.
    pub cant: String,
    /// Canonical path of the executable.
    pub program: PathBuf,
    /// The program the cant is about: `program` itself, except for a can, where `program` is
    /// the can's bundled loader and this is the program it starts.
    pub entrypoint: PathBuf,
    /// `argv[0]` (the program's name as found, e.g. `vim` for `/usr/bin/vim.basic`).
    pub argv0: OsString,
    /// Arguments after `argv[0]`: the manifest's fixed arguments, then the user's.
    pub args: Vec<OsString>,
    /// The complete environment of the program.
    pub env: Vec<(OsString, OsString)>,
    /// The policy to enforce (this cant's own layer).
    pub policy: Policy,
    /// The policy in effect after attenuation by an enclosing cant (equal to `policy` when
    /// `cant` is not itself running inside a cant).
    pub effective: Policy,
    /// Whether an enclosing cant's policy was found.
    pub nested: bool,
    /// Shared libraries that could not be found (the loader will report them if needed).
    pub missing_libs: Vec<String>,
    /// The loopback port of the proxy, when the cant runs in its own network namespace with an
    /// allow list (see [`Plan::use_proxy`]).
    pub netns_proxy: Option<u16>,
    /// Package-manager trees to mount read-only ([`readonly::shared_trees`]); empty for a
    /// nested cant, which stays in its enclosing cant's mounts.
    pub readonly: Vec<PathBuf>,
    /// Whether to mount them: set by the caller once it knows a user + mount namespace works
    /// here (or the cant is already in its own user namespace). Otherwise the launch warns
    /// that they stay writable.
    pub readonly_lock: bool,
}

/// The environment a program behind the namespace's proxy gets, whatever `[env] pass` says
/// (docs/NETWORK-ALLOWLIST.md §10.3: Go and Python read the upper- or lowercase variables;
/// Node's `fetch` needs `NODE_USE_ENV_PROXY`).
///
/// `NO_PROXY` keeps the namespace's own loopback direct, except with `loopback` (the user added
/// `localhost` or a loopback address): then those must reach the proxy, which allows this
/// machine's loopback with `--allow-loopback` and otherwise refuses with a hint, so `NO_PROXY`
/// is empty.
pub fn proxy_environment(port: u16, loopback: bool) -> Vec<(OsString, OsString)> {
    let url = format!("http://127.0.0.1:{port}");
    let local = if loopback {
        ""
    } else {
        "localhost,127.0.0.1,::1"
    };
    [
        ("HTTPS_PROXY", url.as_str()),
        ("https_proxy", url.as_str()),
        ("HTTP_PROXY", url.as_str()),
        ("http_proxy", url.as_str()),
        ("NO_PROXY", local),
        ("no_proxy", local),
        ("NODE_USE_ENV_PROXY", "1"),
    ]
    .into_iter()
    .map(|(k, v)| (k.into(), v.into()))
    .collect()
}

impl Plan {
    /// Runs the program behind the proxy listening on `port` inside its network namespace:
    /// sets [`proxy_environment`] (replacing the user's values; loopback through the proxy
    /// when the user added a loopback host), and Landlock will allow TCP connects to that port
    /// only.
    pub fn use_proxy(&mut self, port: u16) {
        let vars = proxy_environment(port, self.effective.user_names_loopback());
        self.env
            .retain(|(k, _)| !vars.iter().any(|(name, _)| name == k));
        self.env.extend(vars);
        self.netns_proxy = Some(port);
    }
}

/// Errors from planning or launching.
#[derive(Debug, thiserror::Error)]
pub enum LaunchError {
    /// Not running on Linux.
    #[error("cants run on Linux only (this is {})", std::env::consts::OS)]
    Unsupported,
    /// The CPU architecture has no seccomp support in this build.
    #[error("unsupported CPU architecture {0}")]
    UnsupportedArch(&'static str),
    /// The executable could not be analysed.
    #[cfg(target_os = "linux")]
    #[error(transparent)]
    Elf(#[from] ElfError),
    /// A can's library directories can't be passed to its loader.
    #[error("the can's library directories can't be passed to its loader: {0}")]
    CanLibraryPath(String),
    /// Landlock is not available.
    #[error(
        "Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
    )]
    LandlockUnavailable,
    /// Landlock is too old to enforce the policy faithfully.
    #[error(
        "this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
    )]
    LandlockTooOld {
        /// The kernel's ABI.
        abi: i32,
    },
    /// Building or applying the Landlock ruleset failed.
    #[error("Landlock setup failed: {0}")]
    Landlock(String),
    /// Building or applying a seccomp filter failed.
    #[error("seccomp setup failed: {0}")]
    Seccomp(String),

    /// Mounting package-manager trees read-only failed after the probe said it works.
    #[error("can't mount package trees read-only: {0}")]
    ReadOnly(String),
    /// A writable command-line file could not be created.
    #[error("cannot create {path}: {source}")]
    Create {
        /// The file.
        path: PathBuf,
        /// Cause.
        source: std::io::Error,
    },
    /// Running inside another cant that may not run this cant's program.
    #[error(
        "{cant} isn't available here: the enclosing cant may not run {shown} \
         (list `{cant}` in its capabilities.cants)"
    )]
    ParentCannotRun {
        /// Cant name.
        cant: String,
        /// The program, for display.
        shown: String,
    },
    /// The enclosing cant does not allow a file named on the command line.
    #[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
    ParentDenies {
        /// Cant name.
        cant: String,
        /// "read", "write" or "execute".
        verb: &'static str,
        /// The path, for display.
        shown: String,
    },
    /// The enclosing cant's policy (in `CANT_POLICY`) is malformed.
    #[error("malformed {POLICY_ENV}: {0}")]
    ParentPolicy(String),
    /// `execve` failed.
    #[error("cannot execute {program}: {source}")]
    Exec {
        /// The program.
        program: PathBuf,
        /// Cause.
        source: std::io::Error,
    },
}

/// Facts about the running kernel, for `cant check`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelSupport {
    /// Landlock ABI, if Landlock is available.
    pub landlock_abi: Option<i32>,
    /// Whether this build can install seccomp filters on this architecture.
    pub seccomp_arch: bool,
}

/// Whether package-manager trees can be mounted read-only here ([`readonly`]): enters a user +
/// mount namespace and mounts a directory read-only. Changes the calling process for good, so
/// it runs in a short-lived child (`cant __probe-readonly`).
#[cfg(target_os = "linux")]
pub fn probe_readonly() -> Result<(), netns::Failure> {
    linux::readonly::probe()
}

/// No namespaces off Linux.
#[cfg(not(target_os = "linux"))]
pub fn probe_readonly() -> Result<(), netns::Failure> {
    Err(netns::Failure {
        step: netns::Step::Unshare,
        errno: 38, // ENOSYS
    })
}

/// Completes `built` into a launch plan.
///
/// `parent` is the policy of an enclosing cant (from [`POLICY_ENV`]), if any.
#[cfg(target_os = "linux")]
pub fn plan(
    manifest: &cant_manifest::Manifest,
    built: cant_policy::Built,
    user_args: &[OsString],
    parent: Option<&Policy>,
    home: &std::path::Path,
    can: Option<&CanStart>,
) -> Result<Plan, LaunchError> {
    linux::plan(manifest, built, user_args, parent, home, can)
}

/// Completes `built` into a launch plan (unsupported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn plan(
    _manifest: &cant_manifest::Manifest,
    _built: cant_policy::Built,
    _user_args: &[OsString],
    _parent: Option<&Policy>,
    _home: &std::path::Path,
    _can: Option<&CanStart>,
) -> Result<Plan, LaunchError> {
    Err(LaunchError::Unsupported)
}

/// Enforces `plan` and replaces the current process with the program.
/// Returns only on failure. `warn` receives non-fatal notices (printed by the CLI).
#[cfg(target_os = "linux")]
pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
    linux::exec(plan, warn)
}

/// Enforces `plan` and replaces the current process (unsupported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
    LaunchError::Unsupported
}

/// Probes kernel support. On Linux this applies a no-op Landlock ruleset to the calling
/// process (the only way to learn the ABI through the `landlock` crate), so call it only
/// from a process that is about to exit, such as `cant check`.
#[cfg(target_os = "linux")]
pub fn probe_kernel() -> KernelSupport {
    KernelSupport {
        landlock_abi: linux::landlock::probe_abi(),
        seccomp_arch: cfg!(any(
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "riscv64"
        )),
    }
}

/// Probes kernel support (nothing is supported on this OS).
#[cfg(not(target_os = "linux"))]
pub fn probe_kernel() -> KernelSupport {
    KernelSupport {
        landlock_abi: None,
        seccomp_arch: false,
    }
}

/// Writes this process's coverage profile now. Only in coverage builds (`cargo llvm-cov`);
/// elsewhere it does nothing. Called right before `exec` (which replaces the process without
/// running the profiler's exit handler, so every successful `cant run` would otherwise leave no
/// coverage) and before the supervisor dies from a signal. Never compiled into shipped binaries.
#[cfg(coverage)]
#[allow(unsafe_code)]
pub fn flush_coverage() {
    unsafe extern "C" {
        fn __llvm_profile_write_file() -> i32;
    }
    // SAFETY: the profiler runtime that every coverage build links defines this function; it
    // takes no arguments and only writes the profile file named by LLVM_PROFILE_FILE.
    let _ = unsafe { __llvm_profile_write_file() };
}

/// Does nothing outside coverage builds.
#[cfg(not(coverage))]
pub fn flush_coverage() {}

/// The directory the coverage profile is written to (coverage builds only): the sandbox lets
/// `cant` write there, so that [`flush_coverage`] still works after Landlock is applied.
#[cfg(coverage)]
pub(crate) fn coverage_dir() -> Option<PathBuf> {
    let file = PathBuf::from(std::env::var_os("LLVM_PROFILE_FILE")?);
    file.parent().map(std::path::Path::to_path_buf)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_proxy_environment_replaces_the_users() {
        let mut plan = Plan {
            cant: "x".into(),
            program: PathBuf::from("/bin/x"),
            entrypoint: PathBuf::from("/bin/x"),
            argv0: "x".into(),
            args: Vec::new(),
            env: vec![
                ("HTTPS_PROXY".into(), "http://corp:3128".into()),
                ("LANG".into(), "C".into()),
            ],
            policy: Policy::default(),
            effective: Policy::default(),
            nested: false,
            missing_libs: Vec::new(),
            netns_proxy: None,
            readonly: Vec::new(),
            readonly_lock: false,
        };
        plan.use_proxy(41000);
        assert_eq!(plan.netns_proxy, Some(41000));
        fn values(plan: &Plan, k: &str) -> Vec<String> {
            plan.env
                .iter()
                .filter(|(n, _)| n == k)
                .map(|(_, v)| v.to_string_lossy().into_owned())
                .collect()
        }
        let get = |k: &str| values(&plan, k);
        assert_eq!(
            get("HTTPS_PROXY"),
            ["http://127.0.0.1:41000"],
            "replaced, once"
        );
        assert_eq!(get("http_proxy"), ["http://127.0.0.1:41000"]);
        assert_eq!(get("no_proxy"), ["localhost,127.0.0.1,::1"]);
        assert_eq!(get("NODE_USE_ENV_PROXY"), ["1"]);
        assert_eq!(get("LANG"), ["C"], "the rest stays");
        assert_eq!(proxy_environment(1, false).len(), 7);
        // A loopback host the user added: localhost goes to the proxy too.
        plan.effective.net_user = vec![cant_policy::UserHostGrant {
            host: cant_manifest::net::UserHost::parse("localhost:3000").expect("host"),
            from: "--allow-host".into(),
        }];
        plan.use_proxy(41001);
        assert_eq!(values(&plan, "NO_PROXY"), [""]);
        assert_eq!(values(&plan, "no_proxy"), [""]);
        assert_eq!(values(&plan, "HTTPS_PROXY"), ["http://127.0.0.1:41001"]);
    }
}