#![cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;
macro_rules! skip {
($($arg:tt)*) => {
crate::common::skip(&format!($($arg)*))
};
}
use common::{status_capabilities, status_field};
use oscall::ErrorKind;
use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction};
use oscall::process::linux::{
self, Capabilities, Capability, CapabilitySet, FileCapabilities, SecureBits,
};
use oscall::raw::linux::nr;
#[cfg(feature = "alloc")]
const EPERM: i32 = 1;
const EINVAL: i32 = 22;
#[cfg(feature = "alloc")]
const ENOSYS: i32 = 38;
const FIRST: u16 = 77;
#[cfg(feature = "alloc")]
const SECOND: u16 = 78;
#[test]
fn capability_sets() {
assert_eq!(Capability::Chown.number(), 0);
assert_eq!(Capability::SysAdmin.number(), 21);
assert_eq!(Capability::Setfcap.number(), 31);
assert_eq!(Capability::MacOverride.number(), 32);
assert_eq!(Capability::CheckpointRestore.number(), 40);
for (number, capability) in Capability::ALL.into_iter().enumerate() {
assert_eq!(capability.number() as usize, number);
assert_eq!(Capability::from_number(number as u32), Some(capability));
}
assert_eq!(Capability::from_number(41), None);
assert_eq!(Capability::from_number(u32::MAX), None);
let set = CapabilitySet::of(&[Capability::NetBindService, Capability::Chown]);
assert_eq!(set.bits(), 1 << 10 | 1);
assert!(set.contains(Capability::Chown) && !set.contains(Capability::Kill));
assert!(!set.is_empty() && CapabilitySet::empty().is_empty());
assert_eq!(CapabilitySet::default(), CapabilitySet::EMPTY);
assert_eq!(
set.with(Capability::Kill).without(Capability::Chown).bits(),
1 << 10 | 1 << 5
);
assert_eq!(set | Capability::Bpf, set.with(Capability::Bpf));
let other = CapabilitySet::from(Capability::Chown) | CapabilitySet::from(Capability::Kill);
assert_eq!((set & other).bits(), 1);
assert_eq!((set - other).bits(), 1 << 10);
assert_eq!(set.union(other).bits(), 1 << 10 | 1 << 5 | 1);
assert!(set.is_superset(CapabilitySet::from(Capability::Chown)) && !set.is_superset(other));
let mut changed = set;
changed.insert(Capability::SysAdmin);
changed.remove(Capability::Chown);
assert_eq!(changed.bits(), 1 << 21 | 1 << 10);
assert_eq!(
set.iter().collect::<Vec<_>>(),
[Capability::Chown, Capability::NetBindService]
);
assert_eq!(set.iter().collect::<CapabilitySet>(), set);
let newer = CapabilitySet::from_bits(1 << 63 | 1 << 40 | 1 << 1);
assert_eq!(newer.bits(), 1 << 63 | 1 << 40 | 1 << 1);
assert_eq!(format!("{newer:?}"), "{DacOverride, CheckpointRestore, 63}");
assert_eq!(format!("{:?}", CapabilitySet::empty()), "{}");
let three = Capabilities::all_three(set);
assert_eq!(
(three.effective, three.permitted, three.inheritable),
(set, set, set)
);
assert_eq!(Capabilities::default().permitted, CapabilitySet::EMPTY);
}
#[test]
fn file_capability_values() {
let low = CapabilitySet::of(&[Capability::NetBindService, Capability::Chown]);
let high = CapabilitySet::of(&[Capability::CheckpointRestore, Capability::Setfcap]);
let none = CapabilitySet::EMPTY;
assert_eq!(FileCapabilities::MAX_LEN, 24);
assert_eq!(
FileCapabilities::default(),
FileCapabilities::new(none, none, false)
);
let mut buf = [0xffu8; FileCapabilities::MAX_LEN];
let capabilities = FileCapabilities::new(low | high, low, true);
assert_eq!(capabilities.root_id, None);
let value = capabilities.to_bytes(&mut buf);
#[rustfmt::skip]
assert_eq!(value, [
0x01, 0, 0, 0x02,
0x01, 0x04, 0, 0x80, 0x01, 0x04, 0, 0,
0, 0x01, 0, 0, 0, 0, 0, 0,
]);
assert_eq!(FileCapabilities::from_bytes(value), Ok(capabilities));
#[rustfmt::skip]
let ping = [
0, 0, 0, 0x02,
0, 0x20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
];
let parsed = FileCapabilities::from_bytes(&ping).unwrap();
let raw = CapabilitySet::of(&[Capability::NetRaw]);
assert_eq!(parsed, FileCapabilities::new(raw, none, false));
assert_eq!(parsed.to_bytes(&mut buf), ping);
let rooted = FileCapabilities::new(high, none, false).with_root_id(0x0102_0304);
assert_eq!(rooted.root_id, Some(0x0102_0304));
let value = rooted.to_bytes(&mut buf);
#[rustfmt::skip]
assert_eq!(value, [
0, 0, 0, 0x03,
0, 0, 0, 0x80, 0, 0, 0, 0,
0, 0x01, 0, 0, 0, 0, 0, 0,
0x04, 0x03, 0x02, 0x01,
]);
assert_eq!(FileCapabilities::from_bytes(value), Ok(rooted));
let zero = FileCapabilities::new(low, low, true).with_root_id(0);
let value = zero.to_bytes(&mut buf);
assert_eq!(value.len(), 24);
assert_eq!(FileCapabilities::from_bytes(value), Ok(zero));
#[rustfmt::skip]
let old = [
0x01, 0, 0, 0x01,
0x01, 0x04, 0, 0x80, 0x01, 0, 0, 0,
];
let parsed = FileCapabilities::from_bytes(&old).unwrap();
let chown = CapabilitySet::of(&[Capability::Chown]);
assert_eq!(
parsed,
FileCapabilities::new(low.with(Capability::Setfcap), chown, true)
);
let mut unknown = ping;
unknown[3] = 0x04;
let wrong: [&[u8]; 8] = [
&[],
&[0, 0, 0],
&[0, 0, 0, 0x02],
&ping[..19],
&old[..8],
&unknown,
&[0u8, 0, 0, 0x02, 0, 0, 0, 0, 0, 0, 0, 0],
&[0u8; 24],
];
for value in wrong {
let error = FileCapabilities::from_bytes(value).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{value:?}");
}
let mut long = [0u8; 28];
long[3] = 0x03;
assert!(FileCapabilities::from_bytes(&long).is_err());
assert!(FileCapabilities::from_bytes(&long[..24]).is_ok());
let exe = std::env::current_exe().unwrap();
match linux::file_capabilities(exe.to_str().unwrap()) {
Ok(found) => assert_eq!(found, None),
Err(error) => assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}"),
}
let error = linux::file_capabilities("/proc/self/status").unwrap_err();
assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
let error = linux::file_capabilities("/oscall/no/such/file").unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let error = linux::remove_file_capabilities("/oscall/no/such/file").unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}
#[test]
fn capabilities_of_the_thread() {
let capabilities = linux::capabilities().unwrap();
assert_eq!(capabilities.effective.bits(), status_capabilities("CapEff"));
assert_eq!(capabilities.permitted.bits(), status_capabilities("CapPrm"));
assert_eq!(
capabilities.inheritable.bits(),
status_capabilities("CapInh")
);
assert!(capabilities.permitted.is_superset(capabilities.effective));
assert_eq!(
linux::bounding_set().unwrap().bits(),
status_capabilities("CapBnd")
);
assert_eq!(
linux::ambient_set().unwrap().bits(),
status_capabilities("CapAmb")
);
let keep = linux::keep_capabilities().unwrap();
let bits = linux::secure_bits().unwrap();
assert_eq!(bits.contains(SecureBits::KEEP_CAPS), keep);
assert!(format!("{bits:?}").starts_with("SecureBits("));
}
fn status_numbers(name: &str) -> Vec<u32> {
(0..)
.map(|index| status_field(name, index))
.take_while(|field| !field.is_empty())
.map(|field| field.parse().unwrap())
.collect()
}
#[test]
fn identity() {
let users = status_numbers("Uid");
let groups = status_numbers("Gid");
assert_eq!(linux::user_id(), users[0]);
assert_eq!(linux::effective_user_id(), users[1]);
assert_eq!(linux::group_id(), groups[0]);
assert_eq!(linux::effective_group_id(), groups[1]);
let mut expected = status_numbers("Groups");
expected.sort_unstable();
let count = linux::groups(&mut []).unwrap();
assert_eq!(count, expected.len());
let mut buf = vec![u32::MAX; count + 4];
let written = linux::groups(&mut buf).unwrap();
assert_eq!(written, count);
buf.truncate(written);
buf.sort_unstable();
assert_eq!(buf, expected);
if count > 1 {
let error = linux::groups(&mut buf[..count - 1]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[cfg(feature = "alloc")]
{
let mut all = linux::groups_vec().unwrap();
all.sort_unstable();
assert_eq!(all, expected);
}
linux::set_user_ids(None, None, None).unwrap();
linux::set_group_ids(None, None, None).unwrap();
for ids in [
[Some(u32::MAX), None, None],
[None, Some(u32::MAX), None],
[None, None, Some(u32::MAX)],
] {
let error = linux::set_user_ids(ids[0], ids[1], ids[2]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = linux::set_group_ids(ids[0], ids[1], ids[2]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let effective = linux::capabilities().unwrap().effective;
if !effective.contains(Capability::Setuid) {
let other = users[0].wrapping_add(1) % 60000;
if !users.contains(&other) {
let error = linux::set_user_ids(Some(other), None, None).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
if !effective.contains(Capability::Setgid) {
let other = groups[0].wrapping_add(1) % 60000;
if !groups.contains(&other) {
let error = linux::set_group_ids(None, Some(other), None).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
let error = linux::set_groups(&[]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
assert_eq!(status_numbers("Uid"), users);
assert_eq!(status_numbers("Gid"), groups);
}
#[test]
fn system_name() {
let read = |name: &str| {
let text = std::fs::read_to_string(format!("/proc/sys/kernel/{name}")).unwrap();
text.trim_end_matches('\n').to_owned()
};
let name = linux::system_name().unwrap();
assert_eq!(name.system(), b"Linux");
assert_eq!(name.host_name(), read("hostname").as_bytes());
assert_eq!(name.domain_name(), read("domainname").as_bytes());
assert!(!name.machine().is_empty() && !name.version().is_empty());
if !common::emulated() {
assert_eq!(name.release(), read("osrelease").as_bytes());
assert_eq!(name.version(), read("version").as_bytes());
let machine = String::from_utf8(name.machine().to_vec()).unwrap();
let family: &[&str] = match std::env::consts::ARCH {
"x86_64" => &["x86_64"],
"x86" => &["x86_64", "i686", "i586", "i486", "i386"],
"aarch64" => &["aarch64"],
"arm" => &["aarch64", "armv8l", "armv7l", "armv6l"],
"riscv64" => &["riscv64"],
"riscv32" => &["riscv32"],
other => panic!("unknown architecture {other}"),
};
assert!(family.contains(&machine.as_str()), "{machine}");
}
let debug = format!("{name:?}");
assert!(
debug.starts_with("SystemName { system: \"Linux\", host_name: \""),
"{debug}"
);
assert_eq!(name, linux::system_name().unwrap());
}
#[test]
fn seccomp_programs() {
assert_eq!(Action::Allow.value(), 0x7fff_0000);
assert_eq!(Action::Log.value(), 0x7ffc_0000);
assert_eq!(Action::Errno(38).value(), 0x0005_0026);
assert_eq!(Action::Trap.value(), 0x0003_0000);
assert_eq!(Action::KillThread.value(), 0);
assert_eq!(Action::KillProcess.value(), 0x8000_0000);
assert_eq!(seccomp::AUDIT_ARCH_X86_64, 0xc000_003e);
assert_eq!(seccomp::AUDIT_ARCH_X86, 0x4000_0003);
assert_eq!(seccomp::AUDIT_ARCH_AARCH64, 0xc000_00b7);
assert_eq!(seccomp::AUDIT_ARCH_ARM, 0x4000_0028);
assert_eq!(seccomp::AUDIT_ARCH_RISCV64, 0xc000_00f3);
assert_eq!(seccomp::AUDIT_ARCH_RISCV32, 0x4000_00f3);
let own = match std::env::consts::ARCH {
"x86_64" => seccomp::AUDIT_ARCH_X86_64,
"x86" => seccomp::AUDIT_ARCH_X86,
"aarch64" => seccomp::AUDIT_ARCH_AARCH64,
"arm" => seccomp::AUDIT_ARCH_ARM,
"riscv64" => seccomp::AUDIT_ARCH_RISCV64,
"riscv32" => seccomp::AUDIT_ARCH_RISCV32,
other => panic!("unknown architecture {other}"),
};
assert_eq!(seccomp::AUDIT_ARCH, own);
assert_eq!(size_of::<Instruction>(), 8);
assert_eq!(Instruction::load(4), Instruction::new(0x20, 0, 0, 4));
assert_eq!(
Instruction::jump_if_equal(9, 1, 2),
Instruction::new(0x15, 1, 2, 9)
);
assert_eq!(
Instruction::jump_if_at_least(9, 1, 2),
Instruction::new(0x35, 1, 2, 9)
);
assert_eq!(
Instruction::ret(Action::Errno(5)),
Instruction::new(0x06, 0, 0, 0x0005_0005)
);
assert_eq!(
(
seccomp::DATA_NUMBER,
seccomp::DATA_ARCH,
seccomp::DATA_INSTRUCTION_POINTER,
seccomp::DATA_ARGS
),
(0, 4, 8, 16)
);
let x32 = cfg!(target_arch = "x86_64");
let preamble = if x32 { 6 } else { 4 };
assert_eq!(seccomp::len_for(0), preamble + 1);
assert_eq!(seccomp::len_for(3), preamble + 7);
let mut buf = [Instruction::default(); 64];
let rules = [
(nr::GETPPID, Action::Errno(FIRST)),
(nr::GETSID, Action::KillProcess),
];
let program = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
assert_eq!(program.len(), seccomp::len_for(2));
let kill = Instruction::ret(Action::KillProcess);
assert_eq!(program[0], Instruction::load(seccomp::DATA_ARCH));
assert_eq!(program[1], Instruction::jump_if_equal(own, 1, 0));
assert_eq!(program[2], kill);
assert_eq!(program[3], Instruction::load(seccomp::DATA_NUMBER));
if x32 {
assert_eq!(program[4], Instruction::jump_if_at_least(0x4000_0000, 0, 1));
assert_eq!(program[5], kill);
}
let rest = &program[preamble..];
assert_eq!(
rest,
[
Instruction::jump_if_equal(nr::GETPPID as u32, 0, 1),
Instruction::ret(Action::Errno(FIRST)),
Instruction::jump_if_equal(nr::GETSID as u32, 0, 1),
kill,
Instruction::ret(Action::Allow),
]
);
let mut other = [Instruction::default(); 64];
let allow = seccomp::allow_list(&mut other, &[nr::READ, nr::WRITE], Action::Trap).unwrap();
let mut expected = [Instruction::default(); 64];
let rules = [(nr::READ, Action::Allow), (nr::WRITE, Action::Allow)];
assert_eq!(
allow,
seccomp::build(&mut expected, &rules, Action::Trap).unwrap()
);
let deny = seccomp::deny_list(&mut other, &[nr::READ], Action::Errno(1)).unwrap();
let rules = [(nr::READ, Action::Errno(1))];
assert_eq!(
deny,
seccomp::build(&mut expected, &rules, Action::Allow).unwrap()
);
let mut exact = [Instruction::default(); seccomp::len_for(1)];
assert_eq!(
seccomp::deny_list(&mut exact, &[nr::READ], Action::Trap)
.unwrap()
.len(),
exact.len()
);
let error = seccomp::deny_list(&mut exact, &[nr::READ, nr::WRITE], Action::Trap).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
let error = seccomp::build(&mut [], &[], Action::Allow).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
let mut large = vec![Instruction::default(); 5000];
let many = vec![nr::READ; (4096 - preamble - 1) / 2];
assert_eq!(
seccomp::allow_list(&mut large, &many, Action::Trap)
.unwrap()
.len(),
seccomp::len_for(many.len())
);
assert!(seccomp::len_for(many.len()) <= 4096);
let many = vec![nr::READ; many.len() + 1];
let error = seccomp::allow_list(&mut large, &many, Action::Trap).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
#[cfg(target_pointer_width = "64")]
{
let error = seccomp::deny_list(&mut large, &[1 << 32], Action::Trap).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let error = seccomp::install(&[], FilterFlags::empty()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = seccomp::install(&large[..4097], FilterFlags::ALL_THREADS).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
assert_eq!(
format!("{:?}", FilterFlags::ALL_THREADS | FilterFlags::LOG),
"FilterFlags(ALL_THREADS | LOG)"
);
}
#[test]
fn seccomp_notification_values() {
use seccomp::{Notification, Response, SyscallData};
assert_eq!(Action::UserNotify.value(), 0x7fc0_0000);
assert_eq!(size_of::<SyscallData>(), 64);
assert_eq!(size_of::<Notification>(), 80);
assert_eq!(size_of::<Response>(), 24);
let empty = Notification::default();
assert_eq!((empty.id, empty.pid, empty.flags), (0, 0, 0));
assert_eq!(empty.data, SyscallData::default());
assert_eq!(empty.data.args, [0; 6]);
assert_eq!(
std::mem::offset_of!(SyscallData, number),
seccomp::DATA_NUMBER as usize
);
assert_eq!(
std::mem::offset_of!(SyscallData, arch),
seccomp::DATA_ARCH as usize
);
assert_eq!(
std::mem::offset_of!(SyscallData, instruction_pointer),
seccomp::DATA_INSTRUCTION_POINTER as usize
);
assert_eq!(
std::mem::offset_of!(SyscallData, args),
seccomp::DATA_ARGS as usize
);
let debug = |response: Response| format!("{response:?}");
assert_eq!(
debug(Response::success(7, -3)),
"Response { id: 7, val: -3, error: 0, flags: 0 }"
);
assert_eq!(
debug(Response::error(7, 13)),
"Response { id: 7, val: 0, error: -13, flags: 0 }"
);
assert_eq!(
debug(Response::continue_syscall(9)),
"Response { id: 9, val: 0, error: 0, flags: 1 }"
);
assert_ne!(Response::success(1, 0), Response::continue_syscall(1));
assert!(!seccomp::AddHandleFlags::CLOSE_ON_EXEC.intersects(seccomp::AddHandleFlags::RESPOND));
assert!(
!FilterFlags::WAIT_KILLABLE.intersects(
FilterFlags::ALL_THREADS | FilterFlags::LOG | FilterFlags::ALLOW_SPECULATION
)
);
match seccomp::notification_sizes() {
Ok(sizes) => {
assert_eq!(
(sizes.notification, sizes.response, sizes.data),
(80, 24, 64),
"{sizes:?}"
);
}
Err(error) if common::emulated() && error.raw_os_error() == 38 => {
skip!("qemu-user has no seccomp: {error}");
}
Err(error) => assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}"),
}
let file = std::fs::File::open("/proc/self/status").unwrap();
let file = common::handle_of(&file);
match seccomp::receive(&file) {
Err(error) if error.raw_os_error() == 25 => {}
Err(error) if common::emulated() => {
assert!(
matches!(error.raw_os_error(), 38 | 25 | EINVAL),
"{error:?}"
);
}
other => panic!("receive: {other:?}"),
}
let error = seccomp::respond(&file, &Response::success(1, 0)).unwrap_err();
assert_eq!(error.raw_os_error(), 25, "{error:?}");
let error = seccomp::is_valid(&file, 1).unwrap_err();
assert_eq!(error.raw_os_error(), 25, "{error:?}");
}
#[test]
fn seccomp_mode() {
let mode = match linux::seccomp::mode() {
Ok(mode) => mode,
Err(error) if common::emulated() && error.raw_os_error() == EINVAL => {
skip!("qemu-user has no seccomp: {error}");
return;
}
Err(error) => panic!("mode: {error:?}"),
};
let expected = match status_field("Seccomp", 0).as_str() {
"0" => seccomp::Mode::Disabled,
"2" => seccomp::Mode::Filter,
other => panic!("Seccomp: {other}"),
};
assert_eq!(mode, expected);
}
#[test]
fn helper_child_process() {
let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
return;
};
let mode = mode.into_string().unwrap();
#[cfg(feature = "alloc")]
children::helper_main(&mode);
panic!("unknown helper mode {mode}");
}
#[cfg(feature = "alloc")]
mod children {
use std::collections::HashMap;
use std::time::{Duration, Instant};
use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction, Mode};
use oscall::process::linux::{
self, Capabilities, Capability, CapabilitySet, CommandExt as _, ConfineExt as _,
FileCapabilities, IdMap, Namespaces, SecureBits,
};
use oscall::process::unix::{self, CommandExt as _, ExitStatusExt as _, Fork, SIGKILL};
use oscall::process::{self, Child, Command, ExitStatus, Stdio};
use oscall::raw::linux::{nr, syscall};
use oscall::{Error, ErrorKind, io};
use super::common::{self, status_capabilities, status_field, tmp_dir};
use super::{EINVAL, ENOSYS, EPERM, FIRST, SECOND};
const ENOEXEC: i32 = 8;
const EACCES: i32 = 13;
const SIGILL: i32 = 4;
const SIGSYS: i32 = 31;
fn wait(child: &mut Child) -> ExitStatus {
let start = Instant::now();
loop {
if let Some(status) = child.try_wait().unwrap() {
return status;
}
if start.elapsed() > Duration::from_secs(60) {
child.kill().unwrap();
panic!("the child did not exit");
}
std::thread::sleep(Duration::from_millis(2));
}
}
fn read_all(pipe: &oscall::OwnedHandle) -> Vec<u8> {
let mut data = Vec::new();
let mut buf = [0u8; 64];
loop {
match io::read(pipe, &mut buf).unwrap() {
0 => return data,
n => data.extend_from_slice(&buf[..n]),
}
}
}
fn no_seccomp(error: &Error) -> bool {
common::emulated() && matches!(error.raw_os_error(), ENOSYS | EINVAL)
}
fn root_maps() -> ([IdMap; 1], [IdMap; 1]) {
let map = |outside| {
[IdMap {
inside: 0,
outside,
count: 1,
}]
};
(
map(linux::effective_user_id()),
map(linux::effective_group_id()),
)
}
fn helper_env(mode: &str) -> Vec<Vec<u8>> {
let mut env: Vec<Vec<u8>> = std::env::vars_os()
.filter(|(name, _)| name != "OSCALL_TEST_HELPER")
.map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
.collect();
env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
env
}
#[derive(Clone, Copy, PartialEq)]
enum Place {
Here,
UserNamespace,
}
struct Helper {
mode: String,
exe: std::path::PathBuf,
env: Vec<Vec<u8>>,
ids: ([IdMap; 1], [IdMap; 1]),
}
impl Helper {
fn new(mode: &str) -> Self {
Self {
mode: mode.to_owned(),
exe: std::env::current_exe().unwrap(),
env: helper_env(mode),
ids: root_maps(),
}
}
fn run<'a>(
&'a self,
place: Place,
configure: impl FnOnce(Command<'a>) -> Command<'a>,
) -> Option<Result<ExitStatus, Error>> {
const ARGS: &[&str] = &["--exact", "--nocapture", "helper_child_process"];
let mut command = Command::new(self.exe.as_os_str().as_encoded_bytes())
.args(ARGS)
.env(&self.env)
.stdin(Stdio::Null)
.stdout(Stdio::Null);
if place == Place::UserNamespace {
command = command
.namespaces(Namespaces::USER)
.uid_map(&self.ids.0)
.gid_map(&self.ids.1)
.deny_setgroups();
}
match configure(command).spawn() {
Ok(mut child) => Some(Ok(wait(&mut child))),
Err(error) if error.raw_os_error() == ENOEXEC => {
skip!("the system cannot execute {}", self.exe.display());
None
}
Err(error) => match common::namespace_refusal(&error) {
Some(reason) if place == Place::UserNamespace => {
skip!("({}) {reason}: {error}", self.mode);
None
}
_ => Some(Err(error)),
},
}
}
fn refused<'a>(
&'a self,
configure: impl FnOnce(Command<'a>) -> Command<'a>,
) -> Option<Error> {
Some(self.run(Place::Here, configure)?.unwrap_err())
}
}
fn helper(mode: &str) {
if let Some(result) = Helper::new(mode).run(Place::Here, |command| command) {
let status = result.unwrap();
assert!(status.success(), "{mode}: {status}");
}
}
struct Report {
helper: Helper,
file: std::path::PathBuf,
}
impl Report {
fn new(name: &str) -> Self {
let dir = tmp_dir(name);
std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o777))
.unwrap();
let file = std::path::absolute(dir.join("report")).unwrap();
Self {
helper: Helper::new(&format!("report:{}", file.display())),
file,
}
}
fn run<'a>(
&'a self,
place: Place,
configure: impl FnOnce(Command<'a>) -> Command<'a>,
) -> Option<Result<HashMap<String, String>, Error>> {
let status = match self.helper.run(place, configure)? {
Ok(status) => status,
Err(error) => return Some(Err(error)),
};
assert!(status.success(), "{status}");
let text = std::fs::read_to_string(&self.file).unwrap();
Some(Ok(text
.lines()
.map(|line| {
let (name, value) = line.split_once('=').unwrap();
(name.to_owned(), value.to_owned())
})
.collect()))
}
}
fn unwanted() -> Helper {
Helper::new("report:/dev/null")
}
fn set_of(report: &HashMap<String, String>, name: &str) -> CapabilitySet {
CapabilitySet::from_bits(u64::from_str_radix(&report[name], 16).unwrap())
}
pub(super) fn helper_main(mode: &str) {
if let Some(file) = mode.strip_prefix("report:") {
let mut report = String::new();
for name in ["CapEff", "CapPrm", "CapInh", "CapBnd", "CapAmb"] {
report += &format!("{name}={:x}\n", status_capabilities(name));
}
report += &format!(
"uid={}\ngid={}\nnnp={}\nseccomp={}\nkeep={}\n",
linux::effective_user_id(),
linux::effective_group_id(),
linux::no_new_privileges().unwrap(),
status_field("Seccomp", 0),
linux::keep_capabilities().unwrap(),
);
std::fs::write(file, report).unwrap();
process::exit(0);
}
match mode {
"capabilities" => helper_capabilities(),
mode if mode.starts_with("filecaps:") => {
helper_file_capabilities(std::path::Path::new(&mode["filecaps:".len()..]));
}
"identity" => helper_identity(),
"filtered" => helper_filtered(),
"killed" => {
let _ = unix::session(process::id());
process::exit(1)
}
"inherited" => {
let error = unix::session(process::id()).unwrap_err();
assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
}
"unanswered" => {
let error = unix::session(process::id()).unwrap_err();
assert_eq!(error.raw_os_error(), ENOSYS, "{error:?}");
}
"threads" => helper_threads(),
"strict" => helper_strict(),
"allow" => helper_allow(),
"notify" => helper_notify(),
mode if mode.starts_with("notified:") => helper_notified(&mode["notified:".len()..]),
_ => return,
}
process::exit(0);
}
struct Worker<T> {
ask: std::sync::mpsc::Sender<()>,
answer: std::sync::mpsc::Receiver<T>,
}
impl<T: Send + 'static> Worker<T> {
fn new(f: impl Fn() -> T + Send + 'static) -> Self {
let (ask, asked) = std::sync::mpsc::channel::<()>();
let (reply, answer) = std::sync::mpsc::channel();
std::thread::spawn(move || {
reply.send(f()).unwrap();
while asked.recv().is_ok() {
reply.send(f()).unwrap();
}
});
let worker = Self { ask, answer };
worker.answer.recv().unwrap();
worker
}
fn ask(&self) -> T {
self.ask.send(()).unwrap();
self.answer.recv().unwrap()
}
}
fn helper_capabilities() {
let before = linux::capabilities().unwrap();
let bounding = linux::bounding_set().unwrap();
let held = status_capabilities("CapEff");
if before.effective.bits() != held {
skip!(
"(capabilities) capget says {:x} where the credentials hold {held:x}: no use of \
capabilities in the user namespace ({})",
before.effective.bits(),
common::confinement()
);
return;
}
let earlier = Worker::new(|| {
(
linux::capabilities().unwrap(),
linux::bounding_set().unwrap(),
linux::keep_capabilities().unwrap(),
)
});
assert_eq!(earlier.ask(), (before, bounding, false));
assert!(!linux::keep_capabilities().unwrap());
linux::set_keep_capabilities(true).unwrap();
assert!(linux::keep_capabilities().unwrap());
assert!(
linux::secure_bits()
.unwrap()
.contains(SecureBits::KEEP_CAPS)
);
assert!(!earlier.ask().2);
linux::set_keep_capabilities(false).unwrap();
assert!(
!linux::secure_bits()
.unwrap()
.contains(SecureBits::KEEP_CAPS)
);
assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);
linux::lower_ambient(Capability::Chown).unwrap();
linux::clear_ambient().unwrap();
if !before.inheritable.contains(Capability::Chown) {
let error = linux::raise_ambient(Capability::Chown).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
let privileged = before.effective.contains(Capability::Setpcap)
&& before.permitted.contains(Capability::Chown)
&& bounding.contains(Capability::AuditWrite);
if privileged {
if let Err(error) = linux::drop_bounding(Capability::AuditWrite) {
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
skip!(
"(capabilities) no use of capabilities in the user namespace ({})",
common::confinement()
);
return;
}
let now = linux::bounding_set().unwrap();
assert_eq!(now, bounding.without(Capability::AuditWrite));
assert_eq!(now.bits(), status_capabilities("CapBnd"));
assert_eq!(linux::capabilities().unwrap(), before);
assert_eq!(earlier.ask().1, bounding);
linux::drop_bounding(Capability::AuditWrite).unwrap();
let chown = CapabilitySet::from(Capability::Chown);
let mut wanted = before;
wanted.inheritable = before.inheritable | chown | Capability::Kill;
linux::set_capabilities(&wanted).unwrap();
assert_eq!(linux::capabilities().unwrap(), wanted);
linux::raise_ambient(Capability::Chown).unwrap();
linux::raise_ambient(Capability::Kill).unwrap();
assert_eq!(linux::ambient_set().unwrap(), chown | Capability::Kill);
assert_eq!(status_capabilities("CapAmb"), 1 << 5 | 1);
linux::lower_ambient(Capability::Kill).unwrap();
assert_eq!(linux::ambient_set().unwrap(), chown);
wanted.inheritable = before.inheritable;
linux::set_capabilities(&wanted).unwrap();
assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);
wanted.inheritable = before.inheritable | chown;
linux::set_capabilities(&wanted).unwrap();
linux::raise_ambient(Capability::Chown).unwrap();
linux::clear_ambient().unwrap();
assert_eq!(linux::ambient_set().unwrap(), CapabilitySet::EMPTY);
let bits = linux::secure_bits().unwrap();
let locked = SecureBits::NO_CAP_AMBIENT_RAISE | SecureBits::NO_CAP_AMBIENT_RAISE_LOCKED;
linux::set_secure_bits(bits | locked).unwrap();
assert_eq!(linux::secure_bits().unwrap(), bits | locked);
let error = linux::raise_ambient(Capability::Chown).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let error = linux::set_secure_bits(bits).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
} else {
if !before.effective.contains(Capability::Setpcap) {
let error = linux::drop_bounding(Capability::AuditWrite).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let bits = linux::secure_bits().unwrap();
let error = linux::set_secure_bits(bits | SecureBits::NO_ROOT).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
skip!("(capabilities) this process has no capability to drop or pass on");
}
let mut less = linux::capabilities().unwrap();
less.effective = CapabilitySet::EMPTY;
linux::set_capabilities(&less).unwrap();
assert_eq!(linux::capabilities().unwrap(), less);
less.effective = less.permitted;
linux::set_capabilities(&less).unwrap();
let none = Capabilities::default();
linux::set_capabilities(&none).unwrap();
assert_eq!(linux::capabilities().unwrap(), none);
assert_eq!(status_capabilities("CapEff"), 0);
assert_eq!(status_capabilities("CapPrm"), 0);
if !before.permitted.is_empty() {
let error = linux::set_capabilities(&before).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
let error = linux::set_capabilities(&Capabilities::all_three(
CapabilitySet::EMPTY.with(Capability::SysAdmin),
))
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
assert_eq!(earlier.ask().0, before);
let later = std::thread::spawn(|| linux::capabilities().unwrap());
assert_eq!(later.join().unwrap(), none);
}
#[test]
fn capabilities() {
helper("capabilities");
if linux::capabilities().unwrap().effective.is_empty()
&& let Some(result) =
Helper::new("capabilities").run(Place::UserNamespace, |command| command)
{
let status = result.unwrap();
assert!(status.success(), "{status}");
}
}
fn real_root() -> bool {
let effective = linux::capabilities().unwrap().effective;
linux::effective_user_id() == 0
&& std::fs::read_to_string("/proc/self/uid_map")
.is_ok_and(|map| map.split_whitespace().eq(["0", "0", "4294967295"]))
&& effective.is_superset(CapabilitySet::of(&[
Capability::Setfcap,
Capability::Setuid,
Capability::Setgid,
]))
}
fn helper_file_capabilities(dir: &std::path::Path) {
let path = |name: &str| dir.join(name).into_os_string().into_string().unwrap();
let skipped = |reason: String| {
std::fs::write(dir.join("skipped"), &reason).unwrap();
skip!("(filecaps) {reason}");
};
let file = path("program");
std::fs::write(&file, b"#!/bin/true\n").unwrap();
assert_eq!(linux::file_capabilities(&file), Ok(None));
let wide = CapabilitySet::of(&[Capability::NetBindService, Capability::CheckpointRestore]);
let chown = CapabilitySet::of(&[Capability::Chown]);
let first = FileCapabilities::new(wide, chown, true);
match linux::set_file_capabilities(&file, &first) {
Ok(()) => {}
Err(error) if error.kind() == ErrorKind::Unsupported => {
return skipped(format!(
"the filesystem of the tests has no such attribute: {error}"
));
}
Err(error) if error.raw_os_error() == EPERM && !real_root() => {
return skipped(format!(
"no use of capabilities in the user namespace ({})",
common::confinement()
));
}
Err(error) => panic!("set_file_capabilities: {error:?}"),
}
assert_eq!(linux::file_capabilities(&file), Ok(Some(first)));
let bare = path("bare");
std::fs::write(&bare, b"").unwrap();
assert_eq!(linux::remove_file_capabilities(&bare), Ok(false));
let mut raw = [0u8; 64];
let len = oscall::fs::unix::get_xattr(&file, "security.capability", &mut raw)
.unwrap()
.unwrap();
assert_eq!(FileCapabilities::from_bytes(&raw[..len]), Ok(first));
let mut buf = [0u8; FileCapabilities::MAX_LEN];
assert_eq!(&raw[..len], first.to_bytes(&mut buf));
let handle = std::fs::File::open(&file).unwrap();
let handle = common::handle_of(&handle);
assert_eq!(linux::handle_file_capabilities(handle), Ok(Some(first)));
let second = FileCapabilities::new(chown, CapabilitySet::EMPTY, false);
linux::set_handle_file_capabilities(handle, &second).unwrap();
assert_eq!(linux::file_capabilities(&file), Ok(Some(second)));
assert_eq!(linux::remove_handle_file_capabilities(handle), Ok(true));
assert_eq!(linux::remove_handle_file_capabilities(handle), Ok(false));
assert_eq!(linux::handle_file_capabilities(handle), Ok(None));
linux::set_file_capabilities(&file, &first).unwrap();
std::os::unix::fs::symlink("program", dir.join("link")).unwrap();
assert_eq!(linux::file_capabilities(&path("link")), Ok(Some(first)));
assert_eq!(linux::remove_file_capabilities(&path("link")), Ok(true));
assert_eq!(linux::file_capabilities(&file), Ok(None));
linux::set_file_capabilities(&file, &first).unwrap();
std::fs::OpenOptions::new()
.append(true)
.open(&file)
.unwrap()
.set_len(4)
.unwrap();
std::fs::write(&file, b"changed").unwrap();
assert_eq!(linux::file_capabilities(&file), Ok(None));
if real_root() {
let other = first.with_root_id(100_000);
linux::set_file_capabilities(&file, &other).unwrap();
assert_eq!(linux::file_capabilities(&file), Ok(Some(other)));
linux::set_file_capabilities(&file, &first.with_root_id(0)).unwrap();
assert_eq!(linux::file_capabilities(&file), Ok(Some(first)));
}
let kept = path("kept");
std::fs::write(&kept, b"").unwrap();
linux::set_file_capabilities(&kept, &first).unwrap();
}
#[test]
fn file_capabilities() {
let dir = tmp_dir("process_linux_filecaps");
let dir = std::path::absolute(dir).unwrap();
let place = if real_root() {
Place::Here
} else {
Place::UserNamespace
};
if !linux::capabilities()
.unwrap()
.effective
.contains(Capability::Setfcap)
{
let file = dir.join("refused");
std::fs::write(&file, b"").unwrap();
let file = file.to_str().unwrap();
let capabilities = FileCapabilities::new(
CapabilitySet::of(&Capability::ALL),
CapabilitySet::EMPTY,
true,
);
match linux::set_file_capabilities(file, &capabilities) {
Err(error) if error.kind() == ErrorKind::Unsupported => {}
result => {
let error = result.unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
assert_eq!(linux::file_capabilities(file), Ok(None));
let error = linux::remove_file_capabilities(file).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
}
let helper = Helper::new(&format!("filecaps:{}", dir.display()));
let Some(result) = helper.run(place, |command| command) else {
return;
};
let status = result.unwrap();
assert!(status.success(), "{status}");
if dir.join("skipped").exists() {
return;
}
let kept = dir.join("kept");
let read = linux::file_capabilities(kept.to_str().unwrap())
.unwrap()
.unwrap();
let wide = CapabilitySet::of(&[Capability::NetBindService, Capability::CheckpointRestore]);
let chown = CapabilitySet::of(&[Capability::Chown]);
let written = FileCapabilities::new(wide, chown, true);
if place == Place::Here {
assert_eq!(read, written);
} else {
assert_eq!(read, written.with_root_id(linux::effective_user_id()));
}
}
fn mount_options(path: &std::path::Path) -> Vec<String> {
let text = std::fs::read_to_string("/proc/self/mountinfo").unwrap();
let mut best: Option<(usize, &str)> = None;
for line in text.lines() {
let fields: Vec<&str> = line.split(' ').collect();
let point = std::path::Path::new(fields[4]);
if path.starts_with(point) && best.is_none_or(|(len, _)| fields[4].len() >= len) {
best = Some((fields[4].len(), fields[5]));
}
}
best.unwrap().1.split(',').map(str::to_owned).collect()
}
#[test]
fn file_capabilities_of_a_program() {
if !real_root() {
common::note("skipped: only root can run a program as a user without capabilities");
return;
}
let mut report = Report::new("process_linux_filecaps_run");
let dir = report.file.parent().unwrap().to_owned();
if mount_options(&dir).iter().any(|option| option == "nosuid") {
skip!(
"the tests are on a filesystem mounted nosuid, where file capabilities are ignored"
);
return;
}
let program = dir.join("program");
std::fs::copy(&report.helper.exe, &program).unwrap();
std::fs::set_permissions(
&program,
std::os::unix::fs::PermissionsExt::from_mode(0o755),
)
.unwrap();
report.helper.exe = program.clone();
let program = program.to_str().unwrap();
let start = Instant::now();
loop {
let probe = Command::new(program)
.args(&["--exact", "--list", "no-such-test"])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.spawn();
match probe {
Ok(mut child) => {
wait(&mut child);
break;
}
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
assert!(start.elapsed() < Duration::from_secs(30), "{error:?}");
std::thread::sleep(Duration::from_millis(5));
}
Err(error) if error.raw_os_error() == ENOEXEC => break,
Err(error) => panic!("spawn: {error:?}"),
}
}
let Some(inside) = report.run(Place::Here, |command| command.uid(54321).gid(54321)) else {
return;
};
let inside = inside.unwrap();
assert_eq!(inside["uid"], "54321");
assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
let bind = CapabilitySet::of(&[Capability::NetBindService]);
let both = bind.with(Capability::Chown);
let capabilities = FileCapabilities::new(both, CapabilitySet::EMPTY, true);
match linux::set_file_capabilities(program, &capabilities) {
Ok(()) => {}
Err(error) if error.kind() == ErrorKind::Unsupported => {
skip!("the filesystem of the tests has no such attribute: {error}");
return;
}
Err(error) => panic!("set_file_capabilities: {error:?}"),
}
let run = |report: &Report| {
report
.run(Place::Here, |command| command.uid(54321).gid(54321))
.unwrap()
.unwrap()
};
let inside = run(&report);
assert_eq!(inside["uid"], "54321");
assert_eq!(set_of(&inside, "CapPrm"), both);
assert_eq!(set_of(&inside, "CapEff"), both);
assert_eq!(set_of(&inside, "CapInh"), CapabilitySet::EMPTY);
let capabilities = FileCapabilities::new(bind, CapabilitySet::EMPTY, false);
linux::set_file_capabilities(program, &capabilities).unwrap();
let inside = run(&report);
assert_eq!(set_of(&inside, "CapPrm"), bind);
assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
let capabilities = FileCapabilities::new(both, CapabilitySet::EMPTY, true);
linux::set_file_capabilities(program, &capabilities).unwrap();
let keep = CapabilitySet::of(&[Capability::Setuid, Capability::Setgid, Capability::Chown]);
let error = report
.run(Place::Here, |command| {
command.uid(54321).gid(54321).bounding_set(keep)
})
.unwrap()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let inside = report
.run(Place::Here, |command| {
command.uid(54321).gid(54321).no_new_privileges()
})
.unwrap()
.unwrap();
assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
linux::set_file_capabilities(program, &capabilities.with_root_id(100_000)).unwrap();
let inside = run(&report);
assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
assert_eq!(linux::remove_file_capabilities(program), Ok(true));
}
fn helper_identity() {
let ids = || {
(
linux::user_id(),
linux::effective_user_id(),
linux::group_id(),
linux::effective_group_id(),
)
};
assert_eq!(ids(), (0, 0, 0, 0));
let earlier = Worker::new(move || (ids(), linux::groups_vec().unwrap()));
let before = earlier.ask();
linux::set_groups(&[7, 5]).unwrap();
let mut groups = linux::groups_vec().unwrap();
groups.sort_unstable();
assert_eq!(groups, [5, 7]);
linux::set_groups(&[]).unwrap();
assert_eq!(linux::groups(&mut []).unwrap(), 0);
assert_eq!(linux::groups_vec().unwrap(), []);
linux::set_group_ids(None, Some(12), None).unwrap();
assert_eq!((linux::group_id(), linux::effective_group_id()), (0, 12));
linux::set_user_ids(None, Some(11), None).unwrap();
assert_eq!((linux::user_id(), linux::effective_user_id()), (0, 11));
assert_eq!(status_capabilities("CapEff"), 0);
let error = linux::set_groups(&[1]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let error = linux::set_user_ids(Some(13), None, None).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
linux::set_user_ids(None, Some(0), None).unwrap();
linux::set_group_ids(None, Some(0), None).unwrap();
assert_eq!(ids(), (0, 0, 0, 0));
linux::set_group_ids(Some(22), Some(22), Some(22)).unwrap();
linux::set_user_ids(Some(21), Some(21), Some(21)).unwrap();
assert_eq!(ids(), (21, 21, 22, 22));
assert_eq!(linux::capabilities().unwrap(), Capabilities::default());
let error = linux::set_user_ids(None, Some(0), None).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
linux::set_user_ids(Some(21), None, Some(21)).unwrap();
assert_eq!(earlier.ask(), before);
let later = std::thread::spawn(ids);
assert_eq!(later.join().unwrap(), (21, 21, 22, 22));
}
#[test]
fn identity_of_a_thread() {
if linux::effective_user_id() != 0
|| linux::user_id() != 0
|| !linux::capabilities()
.unwrap()
.effective
.is_superset(CapabilitySet::of(&[Capability::Setuid, Capability::Setgid]))
{
skip!("only root may change its identity");
return;
}
helper("identity");
}
#[test]
fn child_bounding_set() {
let here = linux::capabilities().unwrap().effective;
let keep = CapabilitySet::of(&[Capability::Chown, Capability::Kill, Capability::Setuid]);
if !here.contains(Capability::Setpcap) {
if let Some(error) = unwanted().refused(|command| command.bounding_set(keep)) {
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
let place = if here.contains(Capability::Setpcap) && linux::effective_user_id() == 0 {
Place::Here
} else {
Place::UserNamespace
};
let dumpable = linux::is_dumpable().unwrap();
let report = Report::new("process_linux_bounding");
let inside = match report.run(place, |command| command.bounding_set(keep)) {
None => return,
Some(Ok(inside)) => inside,
Some(Err(error)) if error.raw_os_error() == EPERM && place == Place::UserNamespace => {
skip!(
"no use of capabilities in the user namespace ({})",
common::confinement()
);
return;
}
Some(Err(error)) => panic!("spawn: {error:?}"),
};
assert_eq!(inside["uid"], "0");
assert_eq!(set_of(&inside, "CapBnd"), keep);
assert_eq!(set_of(&inside, "CapPrm"), keep);
assert_eq!(set_of(&inside, "CapEff"), keep);
assert_eq!(linux::capabilities().unwrap().effective, here);
assert_eq!(linux::is_dumpable().unwrap(), dumpable);
let inside = Report::new("process_linux_bounding_none")
.run(place, |command| command.bounding_set(CapabilitySet::EMPTY))
.unwrap()
.unwrap();
assert_eq!(set_of(&inside, "CapBnd"), CapabilitySet::EMPTY);
assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
}
#[test]
fn child_capabilities() {
let here = linux::capabilities().unwrap();
let inside = Report::new("process_linux_caps_none").run(Place::Here, |command| {
command.capabilities(Capabilities::default())
});
let Some(inside) = inside else { return };
let inside = inside.unwrap();
assert_eq!(set_of(&inside, "CapInh"), CapabilitySet::EMPTY);
if linux::effective_user_id() != 0 {
assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
}
if !here.permitted.contains(Capability::SysAdmin) {
let error = unwanted()
.refused(|command| {
command.capabilities(Capabilities::all_three(Capability::SysAdmin.into()))
})
.unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let error = unwanted()
.refused(|command| command.ambient_capabilities(Capability::SysAdmin.into()))
.unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
assert_eq!(linux::capabilities().unwrap(), here);
let place = if here.effective.contains(Capability::Setpcap) {
Place::Here
} else {
Place::UserNamespace
};
let set = CapabilitySet::of(&[Capability::Chown, Capability::NetBindService]);
let Some(inside) = Report::new("process_linux_caps").run(place, |command| {
command.capabilities(Capabilities::all_three(set))
}) else {
return;
};
let inside = inside.unwrap();
assert_eq!(set_of(&inside, "CapInh"), set);
if inside["uid"] == "0" {
assert_eq!(set_of(&inside, "CapEff"), set_of(&inside, "CapBnd"));
}
}
#[test]
fn child_ambient_capabilities() {
let here = linux::capabilities().unwrap().effective;
let needed =
CapabilitySet::of(&[Capability::Setuid, Capability::Setgid, Capability::Setpcap]);
if linux::effective_user_id() != 0 || !here.is_superset(needed) {
skip!("only root may start a child as another user");
return;
}
let set = CapabilitySet::of(&[Capability::NetBindService, Capability::Kill])
.intersection(linux::capabilities().unwrap().permitted);
assert!(!set.is_empty());
fn someone(command: Command<'_>) -> Command<'_> {
command.uid(4321).gid(1234).groups(&[])
}
let Some(inside) = Report::new("process_linux_ambient").run(Place::Here, |command| {
someone(command)
.capabilities(Capabilities::all_three(set))
.ambient_capabilities(set)
}) else {
return;
};
let inside = inside.unwrap();
assert_eq!(
(inside["uid"].as_str(), inside["gid"].as_str()),
("4321", "1234")
);
for name in ["CapEff", "CapPrm", "CapInh", "CapAmb"] {
assert_eq!(set_of(&inside, name), set, "{name}");
}
assert_eq!(inside["keep"], "false");
let inside = Report::new("process_linux_ambient_none")
.run(Place::Here, |command| {
someone(command).capabilities(Capabilities::all_three(set))
})
.unwrap()
.unwrap();
assert_eq!(set_of(&inside, "CapInh"), set);
assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
assert_eq!(set_of(&inside, "CapPrm"), CapabilitySet::EMPTY);
let inside = Report::new("process_linux_ambient_plain")
.run(Place::Here, someone)
.unwrap()
.unwrap();
assert_eq!(set_of(&inside, "CapEff"), CapabilitySet::EMPTY);
assert_eq!(set_of(&inside, "CapAmb"), CapabilitySet::EMPTY);
let error = unwanted()
.refused(|command| someone(command).ambient_capabilities(set))
.unwrap();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
fn helper_filtered() {
let me = process::id();
let error = unix::session(me).unwrap_err();
assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
let error = unix::process_group(me).unwrap_err();
assert_eq!(error.raw_os_error(), i32::from(SECOND), "{error:?}");
assert_ne!(process::parent_id(), 0);
assert_eq!(linux::seccomp::mode().unwrap(), Mode::Filter);
assert_eq!(status_field("Seccomp", 0), "2");
assert!(linux::no_new_privileges().unwrap());
helper("inherited");
}
#[test]
fn child_filter() {
let mut buf = [Instruction::default(); seccomp::len_for(2)];
let rules = [
(nr::GETSID, Action::Errno(FIRST)),
(nr::GETPGID, Action::Errno(SECOND)),
];
let errors = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
let flags = FilterFlags::empty();
let filtered = Helper::new("filtered");
let Some(result) = filtered.run(Place::Here, |command| {
command.no_new_privileges().seccomp(errors, flags)
}) else {
return;
};
let status = match result {
Ok(status) => status,
Err(error) if no_seccomp(&error) => {
skip!("qemu-user has no seccomp: {error}");
return;
}
Err(error) => panic!("spawn: {error:?}"),
};
assert!(status.success(), "{status}");
unix::session(process::id()).unwrap();
if !linux::capabilities()
.unwrap()
.effective
.contains(Capability::SysAdmin)
&& !linux::no_new_privileges().unwrap()
{
let error = filtered
.refused(|command| command.seccomp(errors, flags))
.unwrap();
assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
assert_eq!(error.kind(), ErrorKind::PermissionDenied);
}
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let kills = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::KillProcess).unwrap();
let status = Helper::new("killed")
.run(Place::Here, |command| {
command
.no_new_privileges()
.seccomp(kills, FilterFlags::LOG)
.stderr(Stdio::Null)
})
.unwrap()
.unwrap();
assert_eq!(status.signal(), Some(SIGSYS), "{status}");
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let no_exec = seccomp::deny_list(&mut buf, &[nr::EXECVE], Action::Errno(FIRST)).unwrap();
let error = filtered
.refused(|command| command.no_new_privileges().seccomp(no_exec, flags))
.unwrap();
assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let nothing = seccomp::allow_list(&mut buf, &[nr::READ], Action::Errno(FIRST)).unwrap();
let no_core = [(
unix::Resource::CoreSize,
unix::Limit {
soft: Some(0),
hard: Some(0),
},
)];
let status = filtered
.run(Place::Here, |command| {
command
.limits(&no_core)
.no_new_privileges()
.seccomp(nothing, flags)
})
.unwrap()
.unwrap();
assert_eq!(status.signal(), Some(SIGILL), "{status}");
let error = filtered
.refused(|command| command.seccomp(&[], flags))
.unwrap();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
fn helper_threads() {
let me = process::id();
let probe = move || {
let code = |result: oscall::Result<u32>| result.err().map(|error| error.raw_os_error());
(code(unix::session(me)), code(unix::process_group(me)))
};
let earlier = Worker::new(probe);
assert_eq!(earlier.ask(), (None, None));
let before = match linux::seccomp::mode() {
Ok(mode) => mode,
Err(error) if no_seccomp(&error) => {
skip!("(threads) qemu-user has no seccomp: {error}");
return;
}
Err(error) => panic!("mode: {error:?}"),
};
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let first = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Errno(FIRST)).unwrap();
let privileged = linux::capabilities()
.unwrap()
.effective
.contains(Capability::SysAdmin);
if !privileged && !linux::no_new_privileges().unwrap() {
let error = seccomp::install(first, FilterFlags::empty()).unwrap_err();
assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
assert_eq!(linux::seccomp::mode().unwrap(), before);
}
linux::set_no_new_privileges().unwrap();
if let Err(error) = seccomp::install(first, FilterFlags::empty()) {
assert!(no_seccomp(&error), "install: {error:?}");
skip!("(threads) qemu-user has no seccomp: {error}");
return;
}
assert_eq!(linux::seccomp::mode().unwrap(), Mode::Filter);
let first = Some(i32::from(FIRST));
let second = Some(i32::from(SECOND));
assert_eq!(probe(), (first, None));
assert_eq!(earlier.ask(), (None, None));
assert_eq!(std::thread::spawn(probe).join().unwrap(), (first, None));
let error = seccomp::set_strict().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let more = seccomp::deny_list(&mut buf, &[nr::GETPGID], Action::Errno(SECOND)).unwrap();
seccomp::install(more, FilterFlags::ALL_THREADS).unwrap();
assert_eq!(probe(), (first, second));
assert_eq!(earlier.ask(), (first, second));
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let softer = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Log).unwrap();
seccomp::install(softer, FilterFlags::empty()).unwrap();
assert_eq!(probe(), (first, second));
}
#[test]
fn filter_of_a_thread() {
helper("threads");
}
fn forked(f: impl FnOnce(&oscall::OwnedHandle)) -> (Vec<u8>, ExitStatus) {
let (read, write) = io::pipe().unwrap();
match unsafe { unix::fork() }.unwrap() {
Fork::Child => {
f(&write);
process::exit(100)
}
Fork::Parent(mut child) => {
drop(write);
let said = read_all(&read);
(said, wait(&mut child))
}
}
}
fn exit_thread(code: i32) -> ! {
loop {
let _ = unsafe { syscall!(EXIT, code) };
}
}
fn say_error(pipe: &oscall::OwnedHandle, error: Error) -> ! {
let _ = io::write(pipe, &error.raw_os_error().to_ne_bytes());
process::exit(101)
}
fn helper_strict() {
let filtered = match linux::seccomp::mode() {
Ok(mode) => mode == Mode::Filter,
Err(error) if no_seccomp(&error) => {
skip!("(strict) qemu-user has no seccomp: {error}");
return;
}
Err(error) => panic!("mode: {error:?}"),
};
let (said, status) = forked(|pipe| {
if let Err(error) = seccomp::set_strict() {
say_error(pipe, error);
}
let _ = io::write(pipe, b"strict");
exit_thread(7)
});
if status.code() == Some(101) {
let error = Error::from_raw_os_error(i32::from_ne_bytes(said[..4].try_into().unwrap()));
if filtered && error.kind() == ErrorKind::InvalidInput {
skip!("(strict) the process has a filter already, as in a container: {error}");
return;
}
assert!(no_seccomp(&error), "set_strict: {error:?}");
skip!("(strict) qemu-user has no seccomp: {error}");
return;
}
assert_eq!(said, b"strict");
assert_eq!(status.code(), Some(7), "{status}");
let (said, status) = forked(|pipe| {
if let Err(error) = seccomp::set_strict() {
say_error(pipe, error);
}
let _ = io::write(pipe, b"strict");
let _ = process::parent_id();
let _ = io::write(pipe, b"alive");
exit_thread(8)
});
assert_eq!(said, b"strict");
assert_eq!(status.signal(), Some(SIGKILL), "{status}");
let (_, status) = forked(|pipe| {
if let Err(error) = seccomp::set_strict() {
say_error(pipe, error);
}
process::exit(9)
});
assert_eq!(status.signal(), Some(SIGKILL), "{status}");
}
#[test]
fn strict_mode() {
helper("strict");
}
fn helper_allow() {
let mut buf = [Instruction::default(); seccomp::len_for(3)];
let allowed = [nr::WRITE, nr::EXIT_GROUP, nr::GETPPID];
let program = seccomp::allow_list(&mut buf, &allowed, Action::Errno(FIRST)).unwrap();
let me = process::id();
let (said, status) = forked(|pipe| {
if let Err(error) = linux::set_no_new_privileges() {
say_error(pipe, error);
}
if let Err(error) = seccomp::install(program, FilterFlags::empty()) {
say_error(pipe, error);
}
let parent = process::parent_id();
let refused = match unix::session(me) {
Err(error) => error.raw_os_error(),
Ok(_) => 0,
};
let _ = io::write(pipe, &parent.to_ne_bytes());
let _ = io::write(pipe, &refused.to_ne_bytes());
process::exit(9)
});
if status.code() == Some(101) {
let error = Error::from_raw_os_error(i32::from_ne_bytes(said[..4].try_into().unwrap()));
assert!(no_seccomp(&error), "install: {error:?}");
skip!("(allow) qemu-user has no seccomp: {error}");
return;
}
assert_eq!(status.code(), Some(9), "{status}");
assert_eq!(said[..4], me.to_ne_bytes());
assert_eq!(said[4..], i32::from(FIRST).to_ne_bytes());
}
#[test]
fn allow_list() {
helper("allow");
}
fn next_call(
poller: &oscall::event::Poller,
listener: &oscall::OwnedHandle,
) -> seccomp::Notification {
let mut events = [oscall::event::Event::EMPTY; 4];
let long = Some(Duration::from_secs(60));
assert_eq!(poller.wait(&mut events, long).unwrap(), 1, "no call came");
assert_eq!(events[0].token(), 7);
assert!(events[0].readiness().is_readable(), "{:?}", events[0]);
seccomp::receive(listener).unwrap()
}
fn listener_poller(listener: &oscall::OwnedHandle) -> oscall::event::Poller {
use oscall::event::{self, Interest, Mode, Poller};
let poller = Poller::new().unwrap();
event::unix::register(&poller, listener, 7, Interest::READABLE, Mode::LEVEL).unwrap();
poller
}
fn is_thread_of(tid: u32, pid: u32) -> bool {
std::path::Path::new(&format!("/proc/{pid}/task/{tid}")).exists()
}
fn notifying() -> Vec<Instruction> {
let mut buf = [Instruction::default(); seccomp::len_for(2)];
let rules = [
(nr::GETSID, Action::UserNotify),
(nr::GETPGID, Action::UserNotify),
];
seccomp::build(&mut buf, &rules, Action::Allow)
.unwrap()
.to_vec()
}
fn answer_with_pipe(
listener: &oscall::OwnedHandle,
call: &seccomp::Notification,
) -> oscall::OwnedHandle {
use seccomp::{AddHandleFlags, Response};
let (read, write) = io::pipe().unwrap();
let at = seccomp::add_handle(
listener,
call.id,
&write,
Some(700),
AddHandleFlags::empty(),
);
assert_eq!(at, Ok(700));
assert!(seccomp::is_valid(listener, call.id).unwrap());
let closed = unsafe { oscall::BorrowedHandle::borrow_raw(999_999) };
let flags = AddHandleFlags::CLOSE_ON_EXEC;
let error = seccomp::add_handle(listener, call.id, &closed, None, flags).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
let error = seccomp::add_handle(listener, !call.id, &write, None, flags).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let flags = AddHandleFlags::CLOSE_ON_EXEC | AddHandleFlags::RESPOND;
match seccomp::add_handle(listener, call.id, &write, None, flags) {
Ok(number) => assert!(number > 2 && number != 700, "{number}"),
Err(error) if error.kind() == ErrorKind::InvalidInput => {
common::note(&format!(
"no answer with a handle in one step here: {error}"
));
let number =
seccomp::add_handle(listener, call.id, &write, None, AddHandleFlags::empty())
.unwrap();
let response = Response::success(call.id, i64::from(number));
seccomp::respond(listener, &response).unwrap();
}
Err(error) => panic!("add_handle: {error:?}"),
}
assert!(!seccomp::is_valid(listener, call.id).unwrap());
read
}
fn helper_notify() {
use seccomp::Response;
use std::sync::mpsc;
let me = process::id();
let program = notifying();
let (send, installed) = mpsc::channel();
let (said, results) = mpsc::channel();
let filtered = std::thread::spawn(move || {
let tid = oscall::thread::id();
if let Err(error) = linux::set_no_new_privileges() {
send.send(Err(error)).unwrap();
return;
}
let plain = seccomp::install(&program, FilterFlags::WAIT_KILLABLE).unwrap_err();
let listener = match seccomp::install_listener(&program, FilterFlags::empty()) {
Ok(listener) => listener,
Err(error) => {
send.send(Err(error)).unwrap();
return;
}
};
let second = seccomp::install_listener(&program, FilterFlags::empty()).unwrap_err();
send.send(Ok((listener, tid, plain, second))).unwrap();
let code = |result: oscall::Result<u32>| match result {
Ok(value) => i64::from(value),
Err(error) => -i64::from(error.raw_os_error()),
};
for _ in 0..3 {
said.send(code(unix::session(me))).unwrap();
}
let pipe = code(unix::process_group(me));
for (fd, text) in [(pipe, b"via"), (700, b"700")] {
let _ = unsafe { syscall!(WRITE, fd as usize, text.as_ptr(), 3usize) };
}
said.send(pipe).unwrap();
});
let (listener, tid, plain, second) = match installed.recv().unwrap() {
Ok(installed) => installed,
Err(error) => {
assert!(no_seccomp(&error), "install_listener: {error:?}");
skip!("(notify) qemu-user has no seccomp: {error}");
filtered.join().unwrap();
return;
}
};
assert_eq!(plain.kind(), ErrorKind::InvalidInput, "{plain:?}");
assert_eq!(second.kind(), ErrorKind::ResourceBusy, "{second:?}");
assert!(!io::is_inheritable(&listener).unwrap());
let poller = listener_poller(&listener);
let call = next_call(&poller, &listener);
assert_eq!(u64::from(call.pid), tid);
assert_eq!(call.data.number as usize, nr::GETSID);
assert_eq!(call.data.arch, seccomp::AUDIT_ARCH);
assert_eq!(call.data.args[0], u64::from(me));
assert_ne!(call.data.instruction_pointer, 0);
assert_eq!(call.flags, 0);
assert!(seccomp::is_valid(&listener, call.id).unwrap());
assert!(!seccomp::is_valid(&listener, !call.id).unwrap());
assert!(results.try_recv().is_err());
let error = seccomp::respond(&listener, &Response::success(!call.id, 1)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
seccomp::respond(&listener, &Response::success(call.id, 4242)).unwrap();
assert_eq!(results.recv().unwrap(), 4242);
assert!(!seccomp::is_valid(&listener, call.id).unwrap());
let error = seccomp::respond(&listener, &Response::success(call.id, 1)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let second = next_call(&poller, &listener);
assert_ne!(second.id, call.id);
seccomp::respond(&listener, &Response::error(second.id, i32::from(FIRST))).unwrap();
assert_eq!(results.recv().unwrap(), -i64::from(FIRST));
let third = next_call(&poller, &listener);
seccomp::respond(&listener, &Response::continue_syscall(third.id)).unwrap();
let session = results.recv().unwrap();
assert_eq!(session, i64::from(unix::session(me).unwrap()));
let fourth = next_call(&poller, &listener);
assert_eq!(fourth.data.number as usize, nr::GETPGID);
let pipe = answer_with_pipe(&listener, &fourth);
let number = results.recv().unwrap();
assert!(number > 2, "{number}");
let mut text = [0u8; 6];
let mut len = 0;
while len < text.len() {
len += io::read(&pipe, &mut text[len..]).unwrap();
}
assert_eq!(&text, b"via700");
match seccomp::set_listener_flags(&listener, seccomp::ListenerFlags::SYNC_WAKE_UP) {
Ok(()) => {
seccomp::set_listener_flags(&listener, seccomp::ListenerFlags::empty()).unwrap()
}
Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}"),
}
filtered.join().unwrap();
let mut events = [oscall::event::Event::EMPTY; 4];
let long = Some(Duration::from_secs(60));
assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
let readiness = events[0].readiness();
assert!(
readiness.contains(oscall::event::Readiness::HANGUP),
"{readiness:?}"
);
assert_eq!(unix::session(me).map(i64::from), Ok(session));
}
#[test]
fn notifications_of_a_thread() {
helper("notify");
}
fn helper_notified(file: &str) {
let me = process::id();
let session = unix::session(me).unwrap();
let pipe = unix::process_group(me).unwrap();
let written = unsafe { syscall!(WRITE, pipe as usize, b"through".as_ptr(), 7usize) };
assert_eq!(written, Ok(7));
let other = unix::session(me).unwrap_err();
std::fs::write(
file,
format!(
"session={session}\nother={}\npid={me}\n",
other.raw_os_error()
),
)
.unwrap();
}
#[test]
fn child_listener() {
use linux::ChildExt as _;
use seccomp::Response;
let program = notifying();
let flags = FilterFlags::empty();
let report = Report::new("process_linux_notified");
let helper = Helper::new(&format!("notified:{}", report.file.display()));
fn command(helper: &Helper) -> Command<'_> {
Command::new(helper.exe.as_os_str().as_encoded_bytes())
.args(&["--exact", "--nocapture", "helper_child_process"])
.env(&helper.env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
}
let spawned = command(&helper)
.no_new_privileges()
.seccomp_listener(&program, flags)
.spawn();
let mut child = match spawned {
Ok(child) => child,
Err(error) if error.raw_os_error() == ENOEXEC => {
skip!("the system cannot execute {}", helper.exe.display());
return;
}
Err(error) if no_seccomp(&error) => {
skip!("qemu-user has no seccomp: {error}");
return;
}
Err(error) => panic!("spawn: {error:?}"),
};
let listener = child.take_seccomp_listener().unwrap();
assert!(child.take_seccomp_listener().is_none());
assert!(!io::is_inheritable(&listener).unwrap());
let poller = listener_poller(&listener);
let call = next_call(&poller, &listener);
assert!(is_thread_of(call.pid, child.id()), "{call:?}");
assert_eq!(call.data.number as usize, nr::GETSID);
assert_eq!(call.data.args[0], u64::from(child.id()));
seccomp::respond(&listener, &Response::success(call.id, 777)).unwrap();
let call = next_call(&poller, &listener);
assert_eq!(call.data.number as usize, nr::GETPGID);
let pipe = answer_with_pipe(&listener, &call);
let mut text = [0u8; 7];
let mut len = 0;
while len < text.len() {
match io::read(&pipe, &mut text[len..]).unwrap() {
0 => panic!("the child wrote {:?}", &text[..len]),
n => len += n,
}
}
assert_eq!(&text, b"through");
let call = next_call(&poller, &listener);
seccomp::respond(&listener, &Response::error(call.id, i32::from(SECOND))).unwrap();
let status = wait(&mut child);
assert!(status.success(), "{status}");
let said = std::fs::read_to_string(&report.file).unwrap();
assert_eq!(
said,
format!("session=777\nother={SECOND}\npid={}\n", child.id())
);
let mut events = [oscall::event::Event::EMPTY; 4];
let long = Some(Duration::from_secs(60));
assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
assert!(
events[0]
.readiness()
.contains(oscall::event::Readiness::HANGUP)
);
unix::session(process::id()).unwrap();
let mut plain = command(&Helper::new("report:/dev/null")).spawn().unwrap();
assert!(plain.take_seccomp_listener().is_none());
assert!(wait(&mut plain).success());
let mut buf = [Instruction::default(); seccomp::len_for(1)];
let errors = seccomp::deny_list(&mut buf, &[nr::GETSID], Action::Errno(FIRST)).unwrap();
let mut filtered = command(&Helper::new("inherited"))
.no_new_privileges()
.seccomp(errors, flags)
.spawn()
.unwrap();
assert!(filtered.take_seccomp_listener().is_none());
assert!(wait(&mut filtered).success());
let report = Report::new("process_linux_notified_closed");
let helper = Helper::new(&format!("report:{}", report.file.display()));
let mut child = command(&helper)
.no_new_privileges()
.seccomp_listener(&program, FilterFlags::LOG)
.spawn()
.unwrap();
assert!(wait(&mut child).success());
drop(child);
let mut child = command(&Helper::new("unanswered"))
.no_new_privileges()
.seccomp_listener(&program, flags)
.stdin(Stdio::Null)
.spawn()
.unwrap();
drop(child.take_seccomp_listener());
let status = wait(&mut child);
assert!(status.success(), "{status}");
let error = command(&helper)
.no_new_privileges()
.seccomp_listener(&[], flags)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
if !linux::capabilities()
.unwrap()
.effective
.contains(Capability::SysAdmin)
&& !linux::no_new_privileges().unwrap()
{
let error = command(&helper)
.seccomp_listener(&program, flags)
.spawn()
.unwrap_err();
assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
}
let mut buf = [Instruction::default(); seccomp::len_for(2)];
let rules = [
(nr::EXECVE, Action::Errno(FIRST)),
(nr::GETSID, Action::UserNotify),
];
let no_exec = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
let error = command(&helper)
.no_new_privileges()
.seccomp_listener(no_exec, flags)
.spawn()
.unwrap_err();
assert_eq!(error.raw_os_error(), i32::from(FIRST), "{error:?}");
let ids = root_maps();
let report = Report::new("process_linux_notified_namespaces");
let helper = Helper::new(&format!("notified:{}", report.file.display()));
let spawned = command(&helper)
.namespaces(Namespaces::USER | Namespaces::PID)
.uid_map(&ids.0)
.gid_map(&ids.1)
.deny_setgroups()
.no_new_privileges()
.seccomp_listener(&program, flags)
.spawn();
let mut child = match spawned {
Ok(child) => child,
Err(error) => match common::namespace_refusal(&error) {
Some(reason) => {
skip!("(notified) {reason}: {error}");
return;
}
None => panic!("spawn: {error:?}"),
},
};
let listener = child.take_seccomp_listener().unwrap();
let poller = listener_poller(&listener);
let call = next_call(&poller, &listener);
assert!(is_thread_of(call.pid, child.id()), "{call:?}");
assert_eq!(call.data.args[0], 1);
seccomp::respond(&listener, &Response::success(call.id, 778)).unwrap();
let call = next_call(&poller, &listener);
let pipe = answer_with_pipe(&listener, &call);
let call = next_call(&poller, &listener);
let mut text = [0u8; 7];
assert_eq!(io::read(&pipe, &mut text), Ok(7));
assert_eq!(&text, b"through");
seccomp::respond(&listener, &Response::error(call.id, i32::from(SECOND))).unwrap();
let status = wait(&mut child);
assert!(status.success(), "{status}");
let said = std::fs::read_to_string(&report.file).unwrap();
assert_eq!(said, format!("session=778\nother={SECOND}\npid=1\n"));
}
}