#![cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;
macro_rules! note {
($($arg:tt)*) => {
crate::common::note(&format!($($arg)*))
};
}
#[cfg(feature = "alloc")]
use oscall::Error;
use oscall::process::linux::{self, IdMap, Namespaces};
use oscall::{ErrorKind, process};
const EPERM: i32 = 1;
#[cfg(feature = "alloc")]
const ECHILD: i32 = 10;
#[cfg(feature = "alloc")]
const EACCES: i32 = 13;
const EINVAL: i32 = 22;
#[cfg(feature = "alloc")]
const ENOSPC: i32 = 28;
const ENOSYS: i32 = 38;
#[cfg(feature = "alloc")]
fn refusal(error: &Error) -> Option<&'static str> {
match error.raw_os_error() {
EPERM | EACCES => Some(
"not permitted here (user namespaces restricted, or a container's system call filter)",
),
ENOSPC => Some("no user namespace may be created (user.max_user_namespaces)"),
ENOSYS => Some("the system call is missing (an emulator, a system call filter)"),
EINVAL if common::emulated() => {
Some("qemu-user does not create a process in new namespaces")
}
_ => None,
}
}
fn status_field(name: &str, index: usize) -> String {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
let line = status
.lines()
.find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
.unwrap();
line.split_whitespace().nth(index).unwrap().to_owned()
}
fn effective_ids() -> (u32, u32) {
(
status_field("Uid", 1).parse().unwrap(),
status_field("Gid", 1).parse().unwrap(),
)
}
fn host_name() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname")
.unwrap()
.trim()
.to_owned()
}
fn id_map(name: &str) -> String {
let text = std::fs::read_to_string(format!("/proc/self/{name}")).unwrap_or_default();
let ranges: Vec<String> = text
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.collect();
ranges.join(";")
}
fn namespace(kind: &str) -> Option<String> {
let link = std::fs::read_link(format!("/proc/self/ns/{kind}")).ok()?;
Some(link.to_string_lossy().into_owned())
}
#[test]
fn namespaces_flags() {
let all = [
Namespaces::MOUNT,
Namespaces::UTS,
Namespaces::IPC,
Namespaces::USER,
Namespaces::PID,
Namespaces::NETWORK,
Namespaces::CGROUP,
Namespaces::TIME,
];
let mut union = Namespaces::empty();
for (i, &namespace) in all.iter().enumerate() {
assert!(!namespace.is_empty());
assert!(!union.intersects(namespace), "{i}");
union |= namespace;
}
assert!(union.contains(Namespaces::USER | Namespaces::PID));
assert_eq!(
format!("{:?}", Namespaces::USER | Namespaces::PID),
"Namespaces(USER | PID)"
);
assert_eq!(Namespaces::default(), Namespaces::empty());
}
#[test]
fn pidfd_of_processes() {
let me = match linux::pidfd_open(process::id()) {
Ok(pidfd) => pidfd,
Err(error) if error.raw_os_error() == ENOSYS => {
note!("skipped: the emulator has no pidfd_open");
return;
}
Err(error) => panic!("pidfd_open: {error}"),
};
linux::pidfd_send_signal(&me, 0).unwrap();
let error = linux::pidfd_send_signal(&me, 1000).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let file = std::fs::File::open("/proc/self/status").unwrap();
let error = linux::pidfd_send_signal(&common::handle_of(&file), 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
#[cfg(feature = "alloc")]
{
let error = linux::pidfd_try_wait(&me).unwrap_err();
assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
let error = linux::pidfd_wait(&me).unwrap_err();
assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
}
let error = linux::pidfd_open(i32::MAX as u32).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
for pid in [0, i32::MAX as u32 + 1, u32::MAX] {
let error = linux::pidfd_open(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
}
#[test]
fn id_map_errors() {
let map = [IdMap {
inside: 0,
outside: 0,
count: 1,
}];
for pid in [0, u32::MAX] {
for result in [
linux::write_uid_map(pid, &map),
linux::write_gid_map(pid, &map),
linux::allow_setgroups(pid, true),
] {
assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidInput);
}
}
let me = process::id();
let error = linux::write_uid_map(me, &[]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let long: Vec<IdMap> = (0..400)
.map(|i| IdMap {
inside: 4_000_000_000 + i,
outside: 4_000_000_000 + i,
count: 1_000_000_000,
})
.collect();
let error = linux::write_gid_map(me, &long).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
if std::path::Path::new("/proc/self").exists() {
let error = linux::write_uid_map(i32::MAX as u32, &map).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let error = linux::write_uid_map(me, &map).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let error = linux::write_gid_map(me, &map).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
#[test]
fn set_host_name_refused() {
let before = host_name();
if status_field("CapEff", 0).trim_start_matches('0').is_empty() {
let error = linux::set_host_name(b"oscall-test").unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
} else {
note!("skipped: the process may have the capability to rename the machine");
}
assert_eq!(host_name(), before);
}
#[test]
fn helper_child_process() {
let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
return;
};
let mode = mode.into_string().unwrap();
if let Some(file) = mode.strip_prefix("report:") {
let (uid, gid) = effective_ids();
let report = format!(
"pid={}\nppid={}\nuid={uid}\ngid={gid}\nnnp={}\nuser={}\npidns={}\nuts={}\ntime={}\ncaps={}\nuidmap={}\ngidmap={}\ncgroup={}\n",
process::id(),
process::parent_id(),
linux::no_new_privileges().unwrap(),
namespace("user").unwrap_or_default(),
namespace("pid").unwrap_or_default(),
namespace("uts").unwrap_or_default(),
namespace("time").unwrap_or_default(),
status_field("CapEff", 0),
id_map("uid_map"),
id_map("gid_map"),
std::fs::read_to_string("/proc/self/cgroup")
.unwrap_or_default()
.trim(),
);
std::fs::write(file, report).unwrap();
process::exit(0);
} else if mode == "uts" {
helper_uts();
process::exit(0);
} else if mode == "prctl" {
helper_prctl();
process::exit(0);
} else if mode == "threads" {
let error = linux::unshare(Namespaces::USER).unwrap_err();
assert!(
matches!(error.raw_os_error(), EINVAL | EPERM),
"unshare: {error:?}"
);
let me = std::fs::File::open("/proc/self/ns/user").unwrap();
let error = linux::setns(&common::handle_of(&me), Namespaces::USER).unwrap_err();
assert!(
matches!(error.raw_os_error(), EINVAL | EPERM),
"setns: {error:?}"
);
if status_field("CapEff", 0).trim_start_matches('0').is_empty() {
for namespaces in [Namespaces::UTS, Namespaces::NETWORK | Namespaces::IPC] {
let error = linux::unshare(namespaces).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
}
let file = std::fs::File::open("/proc/self/status").unwrap();
let error = linux::setns(&common::handle_of(&file), Namespaces::empty()).unwrap_err();
assert!(
matches!(error.raw_os_error(), EINVAL | EPERM),
"setns: {error:?}"
);
process::exit(0);
}
panic!("unknown helper mode {mode}");
}
fn helper_uts() {
let thread_uts = || std::fs::read_link("/proc/thread-self/ns/uts").unwrap();
let started = thread_uts();
if let Err(error) = linux::set_host_name(b"oscall-one") {
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
note!(
"skipped (uts): no use of capabilities in the user namespace ({})",
common::confinement()
);
return;
}
assert_eq!(host_name(), "oscall-one");
let error = linux::set_host_name(&[b'x'; 65]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let first = std::fs::File::open("/proc/thread-self/ns/uts").unwrap();
let (go, wait) = std::sync::mpsc::channel::<()>();
let elsewhere = std::thread::spawn(move || {
let _ = wait.recv();
host_name()
});
linux::unshare(Namespaces::UTS).unwrap();
assert_ne!(thread_uts(), started);
assert_eq!(host_name(), "oscall-one");
linux::set_host_name(b"oscall-two").unwrap();
assert_eq!(host_name(), "oscall-two");
drop(go);
assert_eq!(elsewhere.join().unwrap(), "oscall-one");
let here = std::thread::spawn(host_name).join().unwrap();
assert_eq!(here, "oscall-two");
let handle = common::handle_of(&first);
let error = linux::setns(&handle, Namespaces::NETWORK).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
assert_eq!(host_name(), "oscall-two");
linux::setns(&handle, Namespaces::UTS).unwrap();
assert_eq!(host_name(), "oscall-one");
linux::unshare(Namespaces::UTS | Namespaces::IPC).unwrap();
linux::set_host_name(b"oscall-three").unwrap();
linux::setns(&handle, Namespaces::empty()).unwrap();
assert_eq!(host_name(), "oscall-one");
linux::unshare(Namespaces::UTS).unwrap();
linux::set_host_name(b"oscall-four").unwrap();
let me = linux::pidfd_open(process::id()).unwrap();
let error = linux::setns(&me, Namespaces::empty()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
linux::setns(&me, Namespaces::UTS).unwrap();
assert_eq!(host_name(), "oscall-one");
assert_eq!(thread_uts(), started);
}
fn helper_prctl() {
assert!(!linux::is_child_subreaper().unwrap());
linux::set_child_subreaper(true).unwrap();
assert!(linux::is_child_subreaper().unwrap());
linux::set_child_subreaper(false).unwrap();
assert!(!linux::is_child_subreaper().unwrap());
assert!(linux::is_dumpable().unwrap());
linux::set_dumpable(false).unwrap();
assert!(!linux::is_dumpable().unwrap());
linux::set_dumpable(true).unwrap();
assert!(linux::is_dumpable().unwrap());
if linux::no_new_privileges().unwrap() {
note!("skipped: whoever started the tests may gain no privileges already");
return;
}
let before = std::thread::spawn(|| {
std::thread::park();
linux::no_new_privileges().unwrap()
});
linux::set_no_new_privileges().unwrap();
assert!(linux::no_new_privileges().unwrap());
linux::set_no_new_privileges().unwrap();
let after = std::thread::spawn(|| linux::no_new_privileges().unwrap());
assert!(after.join().unwrap());
before.thread().unpark();
assert!(!before.join().unwrap());
}
#[cfg(feature = "alloc")]
mod children {
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant};
use oscall::event::{self, Event, Interest, Mode, Poller};
use oscall::process::linux::{self, CommandExt as _, IdMap, Namespaces};
use oscall::process::unix::{ChildExt as _, ExitStatusExt as _, SIGKILL, SIGTERM};
use oscall::process::{self, Child, Command, ExitStatus, Stdio};
use oscall::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, io};
use super::common::{handle_of, tmp_dir};
use super::{ECHILD, ENOSYS, effective_ids, namespace, refusal};
const ENOEXEC: i32 = 8;
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 blocked(configure: impl FnOnce(Command<'_>) -> Command<'_>) -> (Child, OwnedHandle) {
let (input, feed) = io::pipe().unwrap();
let command = Command::new("/bin/sh")
.args(&["-c", "read line"])
.stdin(Stdio::Handle(input.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null);
(configure(command).spawn().unwrap(), feed)
}
#[derive(Default)]
struct Setup<'a> {
namespaces: Namespaces,
uid_map: Option<&'a [IdMap]>,
gid_map: Option<&'a [IdMap]>,
deny_setgroups: bool,
cgroup: Option<BorrowedHandle<'a>>,
no_new_privileges: bool,
}
impl<'a> Setup<'a> {
fn root(namespaces: Namespaces, ids: &'a ([IdMap; 1], [IdMap; 1])) -> Self {
Self {
namespaces: Namespaces::USER | namespaces,
uid_map: Some(&ids.0),
gid_map: Some(&ids.1),
deny_setgroups: true,
..Self::default()
}
}
fn apply(&self, mut command: Command<'a>) -> Command<'a> {
command = command.namespaces(self.namespaces);
if let Some(map) = self.uid_map {
command = command.uid_map(map);
}
if let Some(map) = self.gid_map {
command = command.gid_map(map);
}
if self.deny_setgroups {
command = command.deny_setgroups();
}
if let Some(cgroup) = self.cgroup {
command = command.cgroup(cgroup);
}
if self.no_new_privileges {
command = command.no_new_privileges();
}
command
}
}
fn root_maps() -> ([IdMap; 1], [IdMap; 1]) {
let (uid, gid) = effective_ids();
let map = |outside| {
[IdMap {
inside: 0,
outside,
count: 1,
}]
};
(map(uid), map(gid))
}
fn helper(mode: &str, setup: &Setup<'_>) -> Option<ExitStatus> {
let exe = std::env::current_exe().unwrap();
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());
let args = ["--exact", "--nocapture", "helper_child_process"];
let command = Command::new(exe.as_os_str().as_encoded_bytes())
.args(&args)
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null);
match setup.apply(command).spawn() {
Ok(mut child) => Some(wait(&mut child)),
Err(error) if error.raw_os_error() == ENOEXEC => {
note!("skipped: the system cannot execute {}", exe.display());
None
}
Err(error) => match refusal(&error) {
Some(reason) => {
note!("skipped ({mode}): {reason}: {error}");
None
}
None => panic!("cannot run the helper {mode}: {error:?}"),
},
}
}
fn report(name: &str, setup: &Setup<'_>) -> Option<HashMap<String, String>> {
let dir = tmp_dir(name);
let file = std::path::absolute(dir.join("report")).unwrap();
let status = helper(&format!("report:{}", file.display()), setup)?;
assert!(status.success(), "{status}");
let text = std::fs::read_to_string(file).unwrap();
Some(
text.lines()
.map(|line| {
let (name, value) = line.split_once('=').unwrap();
(name.to_owned(), value.to_owned())
})
.collect(),
)
}
#[test]
fn pidfd_of_a_child() {
let (mut child, feed) = blocked(|command| command);
let pidfd = match linux::pidfd_open(child.id()) {
Ok(pidfd) => pidfd,
Err(error) if error.raw_os_error() == ENOSYS => {
note!("skipped: the emulator has no pidfd_open");
drop(feed);
wait(&mut child);
return;
}
Err(error) => panic!("pidfd_open: {error}"),
};
assert!(!io::is_inheritable(&pidfd).unwrap());
let poller = Poller::new().unwrap();
event::unix::register(&poller, &pidfd, 7, Interest::READABLE, Mode::LEVEL).unwrap();
let mut events = [Event::EMPTY; 4];
let short = Some(Duration::from_millis(50));
assert_eq!(poller.wait(&mut events, short).unwrap(), 0);
assert_eq!(linux::pidfd_try_wait(&pidfd).unwrap(), None);
linux::pidfd_send_signal(&pidfd, 0).unwrap();
linux::pidfd_send_signal(&pidfd, SIGTERM).unwrap();
let long = Some(Duration::from_secs(60));
assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
assert_eq!(events[0].token(), 7);
assert!(events[0].readiness().is_readable(), "{:?}", events[0]);
linux::pidfd_send_signal(&pidfd, SIGKILL).unwrap();
let status = linux::pidfd_wait(&pidfd).unwrap();
assert_eq!(status.signal(), Some(SIGTERM), "{status}");
assert_eq!(status.code(), None);
let error = linux::pidfd_send_signal(&pidfd, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
let error = linux::pidfd_wait(&pidfd).unwrap_err();
assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
let error = child.try_wait().unwrap_err();
assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
assert_eq!(poller.wait(&mut events, short).unwrap(), 1);
event::unix::deregister(&poller, &pidfd).unwrap();
let (child, feed) = blocked(|command| command);
assert_eq!(linux::pidfd_try_wait(&child).unwrap(), None);
linux::pidfd_send_signal(&child, 0).unwrap();
drop(feed);
let status = linux::pidfd_wait(&child).unwrap();
assert!(!status.success() && status.signal().is_none(), "{status}");
let error = child.send_signal(0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
}
#[test]
fn spawn_checks() {
let ids = root_maps();
let empty: &[IdMap] = &[];
let long: Vec<IdMap> = (0..400)
.map(|i| IdMap {
inside: 4_000_000_000 + i,
outside: 4_000_000_000 + i,
count: 1_000_000_000,
})
.collect();
let cases = [
Setup {
uid_map: Some(&ids.0),
..Setup::default()
},
Setup {
namespaces: Namespaces::PID | Namespaces::UTS,
gid_map: Some(&ids.1),
..Setup::default()
},
Setup {
deny_setgroups: true,
..Setup::default()
},
Setup {
namespaces: Namespaces::USER,
uid_map: Some(empty),
..Setup::default()
},
Setup {
namespaces: Namespaces::USER,
gid_map: Some(&long),
..Setup::default()
},
];
for setup in cases {
let error = setup.apply(Command::new("/bin/sh")).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
}
#[test]
fn user_and_pid_namespaces() {
let ids = root_maps();
let setup = Setup::root(Namespaces::PID, &ids);
let Some(inside) = report("process_linux_user_pid", &setup) else {
return;
};
assert_eq!(inside["pid"], "1");
assert_eq!(inside["ppid"], "0");
assert_eq!(inside["uid"], "0");
assert_eq!(inside["gid"], "0");
assert_ne!(inside["user"], namespace("user").unwrap());
assert_ne!(inside["pidns"], namespace("pid").unwrap());
assert_eq!(inside["uts"], namespace("uts").unwrap());
assert_ne!(inside["caps"].trim_start_matches('0'), "");
assert_eq!(inside["uidmap"], format!("0 {} 1", ids.0[0].outside));
assert_eq!(inside["gidmap"], format!("0 {} 1", ids.1[0].outside));
}
#[test]
fn maps_of_several_ranges() {
let (uid, _) = effective_ids();
if uid != 0 {
note!("skipped: only root may map identifiers that are not its own");
return;
}
let range = |inside, outside, count| IdMap {
inside,
outside,
count,
};
let users = [range(0, 0, 1), range(1, 100_000, 1000)];
let groups = [
range(0, 0, 1),
range(5, 200_000, 10),
range(100, 300_000, 1),
];
let setup = Setup {
namespaces: Namespaces::USER,
uid_map: Some(&users),
gid_map: Some(&groups),
..Setup::default()
};
let Some(inside) = report("process_linux_ranges", &setup) else {
return;
};
assert_eq!(inside["uid"], "0");
assert_eq!(inside["gid"], "0");
assert_eq!(inside["uidmap"], "0 0 1;1 100000 1000");
assert_eq!(inside["gidmap"], "0 0 1;5 200000 10;100 300000 1");
}
#[test]
fn user_namespace_without_maps() {
let setup = Setup {
namespaces: Namespaces::USER,
..Setup::default()
};
let Some(inside) = report("process_linux_user_unmapped", &setup) else {
return;
};
let overflow = |name: &str| {
let text = std::fs::read_to_string(format!("/proc/sys/kernel/{name}")).unwrap();
text.trim().to_owned()
};
assert_eq!(inside["uid"], overflow("overflowuid"));
assert_eq!(inside["gid"], overflow("overflowgid"));
assert_ne!(inside["user"], namespace("user").unwrap());
assert_eq!(inside["pidns"], namespace("pid").unwrap());
assert_eq!(inside["caps"].trim_start_matches('0'), "");
assert_ne!(inside["pid"], "1");
assert_eq!(inside["ppid"], process::id().to_string());
}
#[test]
fn map_refused() {
let (uid, _) = effective_ids();
if uid == 0 {
note!("skipped: root may write any map");
return;
}
let other = [IdMap {
inside: 0,
outside: uid + 1,
count: 1,
}];
let setup = Setup {
namespaces: Namespaces::USER,
uid_map: Some(&other),
..Setup::default()
};
let error = setup
.apply(Command::new("/bin/sh").args(&["-c", "exit 0"]))
.spawn()
.unwrap_err();
if error.kind() != ErrorKind::PermissionDenied {
match refusal(&error) {
Some(reason) => note!("skipped: {reason}: {error}"),
None => panic!("spawn: {error:?}"),
}
}
}
#[test]
fn pid_namespace_init() {
let ids = root_maps();
let setup = Setup::root(Namespaces::PID, &ids);
let (input, feed) = io::pipe().unwrap();
let command = Command::new("/bin/sh")
.args(&["-c", "read line"])
.stdin(Stdio::Handle(input.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null);
let mut child = match setup.apply(command).spawn() {
Ok(child) => child,
Err(error) => match refusal(&error) {
Some(reason) => {
note!("skipped: {reason}: {error}");
return;
}
None => panic!("spawn: {error:?}"),
},
};
child.send_signal(SIGTERM).unwrap();
std::thread::sleep(Duration::from_millis(100));
assert_eq!(child.try_wait().unwrap(), None);
child.kill().unwrap();
let status = wait(&mut child);
assert_eq!(status.signal(), Some(SIGKILL), "{status}");
drop(feed);
}
#[test]
fn uts_namespace() {
let before = super::host_name();
let ids = root_maps();
let setup = Setup::root(Namespaces::UTS, &ids);
if let Some(status) = helper("uts", &setup) {
assert!(status.success(), "{status}");
}
assert_eq!(super::host_name(), before);
}
#[test]
fn unshare_refused() {
if let Some(status) = helper("threads", &Setup::default()) {
assert!(status.success(), "{status}");
}
}
#[test]
fn time_namespace() {
let Some(outside) = namespace("time") else {
note!("skipped: the kernel has no time namespaces");
return;
};
let ids = root_maps();
let waiting = Setup::root(Namespaces::TIME, &ids);
let direct = Setup {
namespaces: Namespaces::USER | Namespaces::TIME,
..Setup::default()
};
for (name, setup) in [
("process_linux_time_maps", waiting),
("process_linux_time", direct),
] {
let mapped = setup.uid_map.is_some();
let Some(inside) = report(name, &setup) else {
return;
};
assert_ne!(inside["time"], outside);
assert_ne!(inside["user"], namespace("user").unwrap());
assert_eq!(inside["uid"] == "0", mapped);
}
}
#[test]
fn no_new_privileges() {
let setup = Setup {
no_new_privileges: true,
..Setup::default()
};
let Some(inside) = report("process_linux_nnp", &setup) else {
return;
};
assert_eq!(inside["nnp"], "true");
let here = linux::no_new_privileges().unwrap();
if here {
note!("whoever started the tests may gain no privileges already");
}
let inside = report("process_linux_nnp_default", &Setup::default()).unwrap();
assert_eq!(inside["nnp"], here.to_string());
}
#[test]
fn prctl() {
if let Some(status) = helper("prctl", &Setup::default()) {
assert!(status.success(), "{status}");
}
}
fn own_cgroup() -> Option<std::path::PathBuf> {
let text = std::fs::read_to_string("/proc/self/cgroup").ok()?;
let path = text.lines().find_map(|line| line.strip_prefix("0::"))?;
let dir = Path::new("/sys/fs/cgroup").join(path.trim_start_matches('/'));
dir.join("cgroup.procs").exists().then_some(dir)
}
struct Cgroup(std::path::PathBuf);
impl Drop for Cgroup {
fn drop(&mut self) {
for _ in 0..500 {
if std::fs::remove_dir(&self.0).is_ok() {
return;
}
std::thread::sleep(Duration::from_millis(10));
}
note!("could not remove {}", self.0.display());
}
}
#[test]
fn cgroup() {
let dir = tmp_dir("process_linux_cgroup");
let not_cgroup = std::fs::File::open(&dir).unwrap();
let error = Command::new("/bin/sh")
.args(&["-c", "exit 0"])
.cgroup(handle_of(¬_cgroup))
.spawn()
.unwrap_err();
assert!(
matches!(error.kind(), ErrorKind::BadHandle | ErrorKind::NotFound),
"{error:?}"
);
let Some(parent) = own_cgroup() else {
note!("skipped: no cgroup file system (version 2) at /sys/fs/cgroup");
return;
};
let path = parent.join(format!("oscall-test-{}", process::id()));
if let Err(error) = std::fs::create_dir(&path) {
note!(
"skipped: cannot create a cgroup in {}: {error}",
parent.display()
);
return;
}
let cgroup = Cgroup(path);
let directory = std::fs::File::open(&cgroup.0).unwrap();
let handle = handle_of(&directory);
let members = || std::fs::read_to_string(cgroup.0.join("cgroup.procs")).unwrap();
assert_eq!(members(), "");
let (mut child, feed) = match Command::new("/bin/sh")
.args(&["-c", "read line"])
.stdout(Stdio::Null)
.cgroup(handle)
.spawn_blocked()
{
Ok(spawned) => spawned,
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
note!("skipped: may not move a process to the new cgroup: {error}");
return;
}
Err(error) => panic!("spawn: {error:?}"),
};
assert_eq!(members().trim(), child.id().to_string());
drop(feed);
wait(&mut child);
let setup = Setup {
cgroup: Some(handle),
..Setup::default()
};
if let Some(inside) = report("process_linux_cgroup_report", &setup) {
let name = cgroup.0.file_name().unwrap().to_str().unwrap();
assert!(inside["cgroup"].ends_with(name), "{}", inside["cgroup"]);
}
let (output, write) = io::pipe().unwrap();
let mut child = Command::new("/bin/sh")
.args(&["-c", "/bin/sh -c 'cat /proc/self/cgroup'"])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.cgroup(handle)
.spawn()
.unwrap();
drop(write);
let mut text = Vec::new();
let mut buf = [0u8; 256];
loop {
match io::read(&output, &mut buf).unwrap() {
0 => break,
n => text.extend_from_slice(&buf[..n]),
}
}
assert!(wait(&mut child).success());
let text = String::from_utf8(text).unwrap();
let name = cgroup.0.file_name().unwrap().to_str().unwrap();
assert!(text.trim().ends_with(name), "{text}");
}
trait SpawnBlocked {
fn spawn_blocked(self) -> Result<(Child, OwnedHandle), Error>;
}
impl SpawnBlocked for Command<'_> {
fn spawn_blocked(self) -> Result<(Child, OwnedHandle), Error> {
let (input, feed) = io::pipe()?;
let child = self.stdin(Stdio::Handle(input.as_handle())).spawn()?;
Ok((child, feed))
}
}
}