use nix::libc;
use std::{fmt, io};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Landlock {
Abi(u8),
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers {
pub landlock: Landlock,
}
impl fmt::Display for Layers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("non-dumpable, ")?;
match self.landlock {
Landlock::Abi(abi) => write!(f, "Landlock ABI v{abi}")?,
Landlock::Unavailable => f.write_str("Landlock unavailable")?,
}
f.write_str(", seccomp allow-list")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layer {
NonDumpable,
Landlock,
AllowList,
}
impl fmt::Display for Layer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Layer::NonDumpable => "non-dumpable",
Layer::Landlock => "Landlock",
Layer::AllowList => "seccomp allow-list",
})
}
}
#[derive(Debug, thiserror::Error)]
#[error("{layer}: {source}")]
pub struct ConfineError {
pub layer: Layer,
#[source]
pub source: io::Error,
}
pub fn confine() -> Result<Layers, ConfineError> {
let at = |layer| move |source| ConfineError { layer, source };
settle_malloc().map_err(at(Layer::AllowList))?;
prctl(libc::PR_SET_DUMPABLE, 0).map_err(at(Layer::NonDumpable))?;
prctl(libc::PR_SET_NO_NEW_PRIVS, 1)
.map_err(|error| io::Error::new(error.kind(), format!("no_new_privs: {error}")))
.map_err(at(Layer::AllowList))?;
let landlock = landlock().map_err(at(Layer::Landlock))?;
allow_list().map_err(at(Layer::AllowList))?;
Ok(Layers { landlock })
}
#[cfg(target_env = "gnu")]
const TRIM_THRESHOLD: usize = 128 * 1024;
#[cfg(target_env = "gnu")]
const WARM_UP_BLOCK: usize = 16 * 1024;
#[cfg(target_env = "gnu")]
fn settle_malloc() -> io::Result<()> {
let cpus = cpus_in_affinity_mask().unwrap_or_else(|| {
usize::try_from(unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }).unwrap_or(1)
});
let arenas = libc::c_int::try_from(cpus.saturating_mul(8)).unwrap_or(libc::c_int::MAX);
let trim = libc::c_int::try_from(TRIM_THRESHOLD).expect("the threshold fits");
for (option, value) in [(libc::M_ARENA_MAX, arenas), (libc::M_TRIM_THRESHOLD, trim)] {
if unsafe { libc::mallopt(option, value) } != 1 {
return Err(io::Error::other(format!("malloc refused option {option}")));
}
}
std::thread::Builder::new()
.spawn(|| {
let blocks: Vec<Vec<u8>> = (0..8 * TRIM_THRESHOLD / WARM_UP_BLOCK)
.map(|_| vec![1; WARM_UP_BLOCK])
.collect();
drop(std::hint::black_box(blocks));
})?
.join()
.map_err(|_| io::Error::other("the malloc warm-up thread panicked"))
}
#[cfg(target_env = "gnu")]
fn cpus_in_affinity_mask() -> Option<usize> {
let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() };
if unsafe { libc::sched_getaffinity(0, std::mem::size_of_val(&set), &mut set) } != 0 {
return None;
}
let count = unsafe { libc::CPU_COUNT(&set) };
usize::try_from(count).ok().filter(|&count| count > 0)
}
#[cfg(not(target_env = "gnu"))]
fn settle_malloc() -> io::Result<()> {
Ok(())
}
fn check(result: libc::c_long) -> io::Result<libc::c_long> {
if result < 0 {
Err(io::Error::last_os_error())
} else {
Ok(result)
}
}
fn prctl(option: libc::c_int, value: libc::c_ulong) -> io::Result<()> {
check(unsafe { libc::prctl(option, value, 0, 0, 0) }.into()).map(drop)
}
const LANDLOCK_ABI: u8 = 7;
#[repr(C)]
struct RulesetAttr {
handled_access_fs: u64,
handled_access_net: u64,
scoped: u64,
}
fn landlock() -> io::Result<Landlock> {
const VERSION: u32 = 1;
let abi = match check(unsafe {
libc::syscall(
libc::SYS_landlock_create_ruleset,
std::ptr::null::<RulesetAttr>(),
0usize,
VERSION,
)
}) {
Ok(abi) => abi.min(LANDLOCK_ABI.into()) as u8,
Err(error)
if matches!(
error.raw_os_error(),
Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM)
) =>
{
return Ok(Landlock::Unavailable);
}
Err(error) => return Err(error),
};
let attr = RulesetAttr {
handled_access_fs: match abi {
1 => 0x1fff,
2 => 0x3fff,
3 | 4 => 0x7fff,
_ => 0xffff,
},
handled_access_net: if abi >= 4 { 0b11 } else { 0 },
scoped: if abi >= 6 { 0b11 } else { 0 },
};
let size: usize = match abi {
..4 => 8,
4 | 5 => 16,
_ => 24,
};
let ruleset =
check(unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr, size, 0u32) })?
as libc::c_int;
let restricted =
check(unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset, 0u32) });
unsafe { libc::close(ruleset) };
restricted?;
Ok(Landlock::Abi(abi))
}
#[cfg(target_arch = "x86_64")]
const AUDIT_ARCH: u32 = 0xC000_003E;
#[cfg(target_arch = "aarch64")]
const AUDIT_ARCH: u32 = 0xC000_00B7;
const ALLOWED: &[libc::c_long] = &[
libc::SYS_recvmsg,
libc::SYS_recvfrom,
libc::SYS_read,
libc::SYS_write,
libc::SYS_writev,
libc::SYS_close,
libc::SYS_shutdown,
libc::SYS_setsockopt,
libc::SYS_epoll_create1,
libc::SYS_epoll_ctl,
libc::SYS_epoll_pwait,
#[cfg(target_arch = "x86_64")]
libc::SYS_epoll_wait,
libc::SYS_eventfd2,
libc::SYS_set_robust_list,
libc::SYS_rseq,
libc::SYS_futex,
libc::SYS_sigaltstack,
libc::SYS_rt_sigprocmask,
libc::SYS_rt_sigaction,
libc::SYS_rt_sigreturn,
libc::SYS_sched_yield,
libc::SYS_sched_getaffinity,
libc::SYS_restart_syscall,
libc::SYS_mmap,
libc::SYS_munmap,
libc::SYS_mprotect,
libc::SYS_mremap,
libc::SYS_madvise,
libc::SYS_brk,
libc::SYS_getrandom,
libc::SYS_clock_gettime,
libc::SYS_exit,
libc::SYS_exit_group,
libc::SYS_getpid,
libc::SYS_gettid,
];
const DATA_NR: u32 = 0;
const DATA_ARCH: u32 = 4;
const DATA_ARG0: u32 = 16;
const DATA_ARG1: u32 = 24;
const DATA_ARG4: u32 = 48;
enum Test<'a> {
OneOf(&'a [u32]),
Bit(u32),
}
fn allow_list() -> io::Result<()> {
const LOAD: u16 = (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16;
const EQUAL: u16 = (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16;
const BIT_SET: u16 = (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16;
const RETURN: u16 = (libc::BPF_RET | libc::BPF_K) as u16;
let op = |code, k, jt, jf| libc::sock_filter { code, jt, jf, k };
let allow = op(RETURN, libc::SECCOMP_RET_ALLOW, 0, 0);
let kill = op(RETURN, libc::SECCOMP_RET_KILL_PROCESS, 0, 0);
let number = |nr: libc::c_long| nr as u32;
let mut filter = vec![
op(LOAD, DATA_ARCH, 0, 0),
op(EQUAL, AUDIT_ARCH, 1, 0),
kill,
op(LOAD, DATA_NR, 0, 0),
];
#[cfg(target_arch = "x86_64")]
filter.extend([
op(
(libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K) as u16,
0x4000_0000,
0,
1,
),
kill,
]);
filter.extend([
op(EQUAL, number(libc::SYS_clone3), 0, 1),
op(RETURN, libc::SECCOMP_RET_ERRNO | libc::ENOSYS as u32, 0, 0),
]);
for nr in ALLOWED {
filter.extend([op(EQUAL, number(*nr), 0, 1), allow]);
}
let own_pid = [std::process::id()];
let conditional: [(libc::c_long, &[(u32, Test)]); 7] = [
(libc::SYS_kill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
(libc::SYS_tgkill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
(
libc::SYS_fcntl,
&[(
DATA_ARG1,
Test::OneOf(&[
libc::F_DUPFD_CLOEXEC as u32,
libc::F_GETFD as u32,
libc::F_GETFL as u32,
]),
)],
),
(
libc::SYS_clone,
&[(DATA_ARG0, Test::Bit(libc::CLONE_THREAD as u32))],
),
(
libc::SYS_socketpair,
&[(DATA_ARG0, Test::OneOf(&[libc::AF_UNIX as u32]))],
),
(
libc::SYS_ioctl,
&[(DATA_ARG1, Test::OneOf(&[libc::FIONBIO as u32]))],
),
(
libc::SYS_sendto,
&[
(DATA_ARG4, Test::OneOf(&[0])),
(DATA_ARG4 + 4, Test::OneOf(&[0])),
],
),
];
for (nr, tests) in conditional {
let mut block = Vec::new();
for (word, test) in tests {
block.push(op(LOAD, *word, 0, 0));
match test {
Test::OneOf(values) => {
for (tried, value) in values.iter().enumerate() {
block.push(op(EQUAL, *value, (values.len() - tried) as u8, 0));
}
}
Test::Bit(bit) => block.push(op(BIT_SET, *bit, 1, 0)),
}
block.push(kill);
}
block.push(allow);
filter.push(op(EQUAL, number(nr), 0, block.len() as u8));
filter.extend(block);
}
filter.push(kill);
let program = libc::sock_fprog {
len: filter.len() as u16,
filter: filter.as_mut_ptr(),
};
check(
unsafe {
libc::prctl(
libc::PR_SET_SECCOMP,
libc::SECCOMP_MODE_FILTER,
&program as *const libc::sock_fprog,
)
}
.into(),
)
.map(drop)
}