#![cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;
macro_rules! note {
($($arg:tt)*) => {
crate::common::note(&format!($($arg)*))
};
}
macro_rules! skip {
($($arg:tt)*) => {
crate::common::skip(&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 => {
skip!("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();
#[cfg(feature = "alloc")]
if let Some(file) = mode.strip_prefix("nested:") {
children::helper_nested(file);
process::exit(0);
} else if mode == "no-clone3" {
children::helper_no_clone3();
process::exit(0);
}
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={}\nmonotonic={}\nboot={}\nuptime={}\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(),
oscall::time::Clock::Monotonic.now().unwrap().as_nanos(),
oscall::time::Clock::Boottime.now().unwrap().as_nanos(),
std::fs::read_to_string("/proc/uptime")
.unwrap_or_default()
.split_whitespace()
.next()
.unwrap_or_default(),
);
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 == "block" {
let mut line = String::new();
let read = std::io::stdin().read_line(&mut line).unwrap_or(0);
process::exit(if read == 0 { 1 } else { 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:?}");
skip!(
"(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, ClockOffset, CommandExt as _, ConfineExt as _, IdMap, Namespaces, TimeOffsets,
};
use oscall::process::unix::{
ChildExt as _, CommandExt as _, ExitStatusExt as _, SIGKILL, SIGTERM,
};
use oscall::process::{self, Child, Command, ExitStatus, Stdio};
use oscall::time::Clock;
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));
}
}
struct Program {
exe: std::path::PathBuf,
env: Vec<Vec<u8>>,
}
impl Program {
fn new(mode: &str) -> Self {
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());
Self {
exe: std::env::current_exe().unwrap(),
env,
}
}
fn command(&self) -> Command<'_> {
const ARGS: &[&str] = &["--exact", "--nocapture", "helper_child_process"];
Command::new(self.exe.as_os_str().as_encoded_bytes())
.args(ARGS)
.env(&self.env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
}
}
fn blocked() -> (Child, OwnedHandle) {
match Program::new("block").command().spawn_blocked() {
Ok(spawned) => spawned,
Err(error) if error.raw_os_error() == ENOEXEC => Command::new("/bin/sh")
.args(&["-c", "read line"])
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn_blocked()
.unwrap(),
Err(error) => panic!("spawn: {error:?}"),
}
}
#[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,
time_offsets: Option<TimeOffsets>,
identity: 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();
}
if let Some(offsets) = self.time_offsets {
command = command.time_offsets(offsets);
}
if self.identity {
command = command.uid(0).gid(0);
}
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 program = Program::new(mode);
match setup.apply(program.command()).spawn() {
Ok(mut child) => Some(wait(&mut child)),
Err(error) if error.raw_os_error() == ENOEXEC => {
skip!("the system cannot execute {}", program.exe.display());
None
}
Err(error) => match refusal(&error) {
Some(reason) => {
skip!("({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();
let pidfd = match linux::pidfd_open(child.id()) {
Ok(pidfd) => pidfd,
Err(error) if error.raw_os_error() == ENOSYS => {
skip!("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 wait = |events: &mut [Event], timeout| loop {
match poller.wait(events, timeout) {
Err(error)
if error.kind() == ErrorKind::Interrupted && super::common::emulated() => {}
result => break result.unwrap(),
}
};
let short = Some(Duration::from_millis(50));
assert_eq!(wait(&mut events, short), 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!(wait(&mut events, long), 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!(wait(&mut events, short), 1);
event::unix::deregister(&poller, &pidfd).unwrap();
let (child, feed) = blocked();
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_eq!(status.code(), Some(1), "{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()
},
Setup {
namespaces: Namespaces::USER | Namespaces::PID,
time_offsets: Some(TimeOffsets {
monotonic: Some(ClockOffset::new(1, 0)),
boot_time: None,
}),
..Setup::default()
},
Setup {
namespaces: Namespaces::USER | Namespaces::TIME,
time_offsets: Some(TimeOffsets::default()),
..Setup::default()
},
Setup {
namespaces: Namespaces::USER | Namespaces::TIME,
time_offsets: Some(TimeOffsets {
monotonic: None,
boot_time: Some(ClockOffset::new(0, 1_000_000_000)),
}),
..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 {
skip!("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) => skip!("{reason}: {error}"),
None => panic!("spawn: {error:?}"),
}
}
}
#[test]
fn pid_namespace_init() {
let ids = root_maps();
let setup = Setup::root(Namespaces::PID, &ids);
let program = Program::new("block");
let (mut child, feed) = match setup.apply(program.command()).spawn_blocked() {
Ok(spawned) => spawned,
Err(error) => match refusal(&error) {
Some(reason) => {
skip!("{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 {
super::common::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 clock_offsets() {
let second = Duration::from_secs(1);
assert_eq!(ClockOffset::ahead(Duration::ZERO), ClockOffset::new(0, 0));
assert_eq!(ClockOffset::behind(Duration::ZERO), ClockOffset::new(0, 0));
assert_eq!(
ClockOffset::ahead(second * 5 / 2),
ClockOffset::new(2, 500_000_000)
);
assert_eq!(ClockOffset::behind(second * 3), ClockOffset::new(-3, 0));
assert_eq!(
ClockOffset::behind(second * 9 / 4),
ClockOffset::new(-3, 750_000_000)
);
assert_eq!(
ClockOffset::behind(second / 1_000_000_000),
ClockOffset::new(-1, 999_999_999)
);
assert_eq!(
ClockOffset::ahead(Duration::MAX),
ClockOffset::new(i64::MAX, 999_999_999)
);
assert_eq!(ClockOffset::behind(Duration::MAX).seconds, i64::MIN);
assert_eq!(TimeOffsets::default().monotonic, None);
if namespace("time").is_some() {
let offsets = TimeOffsets {
monotonic: Some(ClockOffset::new(1, 0)),
boot_time: None,
};
let error = linux::write_time_offsets(process::id(), &offsets).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let error = linux::set_time_offsets(&offsets).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
}
let error = linux::write_time_offsets(process::id(), &TimeOffsets::default()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = linux::write_time_offsets(0, &TimeOffsets::default()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[test]
fn time_namespace_offsets() {
const ERANGE: i32 = 34;
if namespace("time").is_none() {
super::common::no_time_namespaces();
return;
}
let ids = root_maps();
let ahead = (
Duration::new(1_000_000, 250_000_000),
Duration::new(2_000_000, 0),
);
let offsets = TimeOffsets {
monotonic: Some(ClockOffset::ahead(ahead.0)),
boot_time: Some(ClockOffset::ahead(ahead.1)),
};
let shared = Setup {
time_offsets: Some(offsets),
..Setup::root(Namespaces::TIME, &ids)
};
let copied = Setup {
time_offsets: Some(offsets),
identity: true,
..Setup::root(Namespaces::TIME, &ids)
};
let nanos = |report: &HashMap<String, String>, name: &str| {
Duration::from_nanos(report[name].parse::<u64>().unwrap())
};
for (name, setup) in [
("process_linux_offsets", shared),
("process_linux_offsets_copy", copied),
] {
let before = (
Clock::Monotonic.now().unwrap(),
Clock::Boottime.now().unwrap(),
);
let Some(inside) = report(name, &setup) else {
if setup.identity {
continue;
}
return;
};
let after = (
Clock::Monotonic.now().unwrap(),
Clock::Boottime.now().unwrap(),
);
assert_ne!(inside["time"], namespace("time").unwrap());
let monotonic = nanos(&inside, "monotonic");
assert!(
before.0 + ahead.0 <= monotonic && monotonic <= after.0 + ahead.0,
"{name}: {monotonic:?} is not {:?} after {before:?}..{after:?}",
ahead.0
);
let boot = nanos(&inside, "boot");
assert!(
before.1 + ahead.1 <= boot && boot <= after.1 + ahead.1,
"{name}: {boot:?} is not {:?} after {before:?}..{after:?}",
ahead.1
);
let uptime = Duration::from_secs_f64(inside["uptime"].parse().unwrap());
let slack = Duration::from_millis(20);
assert!(
before.1 + ahead.1 <= uptime + slack && uptime <= after.1 + ahead.1 + slack,
"{name}: /proc/uptime says {uptime:?}"
);
}
let behind = Clock::Monotonic.now().unwrap() / 2;
let setup = Setup {
time_offsets: Some(TimeOffsets {
monotonic: Some(ClockOffset::behind(behind)),
boot_time: None,
}),
..Setup::root(Namespaces::TIME, &ids)
};
let before = (
Clock::Monotonic.now().unwrap(),
Clock::Boottime.now().unwrap(),
);
let inside = report("process_linux_offsets_behind", &setup).unwrap();
let after = (
Clock::Monotonic.now().unwrap(),
Clock::Boottime.now().unwrap(),
);
let monotonic = nanos(&inside, "monotonic");
assert!(
before.0 - behind <= monotonic && monotonic <= after.0 - behind,
"{monotonic:?} is not {behind:?} before {before:?}..{after:?}"
);
let boot = nanos(&inside, "boot");
assert!(before.1 <= boot && boot <= after.1, "{boot:?}");
let setup = Setup {
time_offsets: Some(TimeOffsets {
monotonic: None,
boot_time: Some(ClockOffset::behind(Duration::from_secs(1 << 40))),
}),
..Setup::root(Namespaces::TIME, &ids)
};
let error = setup
.apply(Program::new("block").command())
.spawn()
.unwrap_err();
assert_eq!(error.raw_os_error(), ERANGE, "{error:?}");
}
#[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());
}
}
fn has_clone3() -> bool {
let result = unsafe { oscall::raw::linux::syscall!(CLONE3, 0usize, 0usize) };
result.unwrap_err().raw_os_error() != ENOSYS
}
#[test]
fn cgroup() {
if super::common::privileged_required() {
assert!(has_clone3(), "no clone3 in a run that must cover it");
}
cgroup_checks("process_linux_cgroup");
}
#[test]
fn cgroup_without_clone3() {
if let Some(status) = helper("no-clone3", &Setup::default()) {
assert!(status.success(), "{status}");
}
}
pub(super) fn helper_no_clone3() {
use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction};
let clone3 = oscall::raw::linux::nr::CLONE3 as u32;
let program = [
Instruction::load(seccomp::DATA_NUMBER),
Instruction::jump_if_equal(clone3, 0, 1),
Instruction::ret(Action::Errno(ENOSYS as u16)),
Instruction::ret(Action::Allow),
];
let program = &program[..];
linux::set_no_new_privileges().unwrap();
if let Err(error) = seccomp::install(program, FilterFlags::empty()) {
assert!(super::common::emulated(), "install: {error:?}");
skip!("(no-clone3) qemu-user has no seccomp: {error}");
return;
}
assert!(!has_clone3());
let command = Command::new("/bin/sh").args(&["-c", "exit 0"]);
let error = command
.namespaces(Namespaces::USER | Namespaces::TIME)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
cgroup_checks("process_linux_cgroup_fallback");
}
fn cgroup_checks(name: &str) {
let dir = tmp_dir(name);
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 {
skip!("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) {
skip!("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 program = Program::new("block");
let (mut child, feed) = match program.command().cgroup(handle).spawn_blocked() {
Ok(spawned) => spawned,
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
skip!("may not move a process to the new cgroup: {error}");
return;
}
Err(error) if error.raw_os_error() == ENOEXEC => {
skip!("the system cannot execute {}", program.exe.display());
return;
}
Err(error) => panic!("spawn: {error:?}"),
};
assert_eq!(members().trim(), child.id().to_string());
note!(
"the child was put in its cgroup by {}",
if has_clone3() {
"clone3"
} else {
"itself: there is no clone3"
}
);
drop(feed);
wait(&mut child);
let setup = Setup {
cgroup: Some(handle),
..Setup::default()
};
let own = cgroup.0.file_name().unwrap().to_str().unwrap();
if let Some(inside) = report(&format!("{name}_report"), &setup) {
assert!(inside["cgroup"].ends_with(own), "{}", inside["cgroup"]);
}
let dir = tmp_dir(&format!("{name}_nested"));
let file = std::path::absolute(dir.join("report")).unwrap();
let status = helper(&format!("nested:{}", file.display()), &setup).unwrap();
assert!(status.success(), "{status}");
let text = std::fs::read_to_string(file).unwrap();
let line = text.lines().find_map(|line| line.strip_prefix("cgroup="));
assert!(line.unwrap().ends_with(own), "{text}");
}
pub(super) fn helper_nested(file: &str) {
let status = helper(&format!("report:{file}"), &Setup::default()).unwrap();
assert!(status.success(), "{status}");
}
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))
}
}
}