#![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;
pub const POLICY_ENV: &str = "CANT_POLICY";
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",
"/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",
];
pub const NETWORK_READ: &[&str] = &[
"/etc/resolv.conf",
"/etc/hosts",
"/etc/nsswitch.conf",
"/etc/host.conf",
"/etc/gai.conf",
];
pub const RUNTIME_READ_WRITE: &[&str] = &["/dev/null", "/dev/full", "/dev/tty"];
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",
];
#[derive(Debug, Clone, Default)]
pub struct CanStart {
pub loader: Option<PathBuf>,
pub library_path: Vec<PathBuf>,
}
#[derive(Debug, Clone)]
pub struct Plan {
pub cant: String,
pub program: PathBuf,
pub entrypoint: PathBuf,
pub argv0: OsString,
pub args: Vec<OsString>,
pub env: Vec<(OsString, OsString)>,
pub policy: Policy,
pub effective: Policy,
pub nested: bool,
pub missing_libs: Vec<String>,
pub netns_proxy: Option<u16>,
pub readonly: Vec<PathBuf>,
pub readonly_lock: bool,
}
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 {
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);
}
}
#[derive(Debug, thiserror::Error)]
pub enum LaunchError {
#[error("cants run on Linux only (this is {})", std::env::consts::OS)]
Unsupported,
#[error("unsupported CPU architecture {0}")]
UnsupportedArch(&'static str),
#[cfg(target_os = "linux")]
#[error(transparent)]
Elf(#[from] ElfError),
#[error("the can's library directories can't be passed to its loader: {0}")]
CanLibraryPath(String),
#[error(
"Landlock is not available on this kernel, so cants cannot be sandboxed; refusing to run (see `cant check`)"
)]
LandlockUnavailable,
#[error(
"this kernel's Landlock ABI is {abi}; at least 3 (Linux 6.2) is required; refusing to run"
)]
LandlockTooOld {
abi: i32,
},
#[error("Landlock setup failed: {0}")]
Landlock(String),
#[error("seccomp setup failed: {0}")]
Seccomp(String),
#[error("can't mount package trees read-only: {0}")]
ReadOnly(String),
#[error("cannot create {path}: {source}")]
Create {
path: PathBuf,
source: std::io::Error,
},
#[error(
"{cant} isn't available here: the enclosing cant may not run {shown} \
(list `{cant}` in its capabilities.cants)"
)]
ParentCannotRun {
cant: String,
shown: String,
},
#[error("{cant} can't {verb} {shown} (not granted by the enclosing cant)")]
ParentDenies {
cant: String,
verb: &'static str,
shown: String,
},
#[error("malformed {POLICY_ENV}: {0}")]
ParentPolicy(String),
#[error("cannot execute {program}: {source}")]
Exec {
program: PathBuf,
source: std::io::Error,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KernelSupport {
pub landlock_abi: Option<i32>,
pub seccomp_arch: bool,
}
#[cfg(target_os = "linux")]
pub fn probe_readonly() -> Result<(), netns::Failure> {
linux::readonly::probe()
}
#[cfg(not(target_os = "linux"))]
pub fn probe_readonly() -> Result<(), netns::Failure> {
Err(netns::Failure {
step: netns::Step::Unshare,
errno: 38, })
}
#[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)
}
#[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)
}
#[cfg(target_os = "linux")]
pub fn exec(plan: Plan, warn: &mut dyn FnMut(&str)) -> LaunchError {
linux::exec(plan, warn)
}
#[cfg(not(target_os = "linux"))]
pub fn exec(_plan: Plan, _warn: &mut dyn FnMut(&str)) -> LaunchError {
LaunchError::Unsupported
}
#[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"
)),
}
}
#[cfg(not(target_os = "linux"))]
pub fn probe_kernel() -> KernelSupport {
KernelSupport {
landlock_abi: None,
seccomp_arch: false,
}
}
#[cfg(coverage)]
#[allow(unsafe_code)]
pub fn flush_coverage() {
unsafe extern "C" {
fn __llvm_profile_write_file() -> i32;
}
let _ = unsafe { __llvm_profile_write_file() };
}
#[cfg(not(coverage))]
pub fn flush_coverage() {}
#[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);
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"]);
}
}