#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux {
use super::common::emulated;
use oscall::process::linux::{self, IdMap, Namespaces};
use oscall::{ErrorKind, process};
const EPERM: i32 = 1;
const EACCES: i32 = 13;
const ENOSPC: i32 = 28;
const ENOSYS: i32 = 38;
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 namespace(kind: &str) -> String {
let link = std::fs::read_link(format!("/proc/self/ns/{kind}")).unwrap();
link.to_string_lossy().into_owned()
}
fn refused(error: &oscall::Error) -> bool {
matches!(error.raw_os_error(), EPERM | EACCES | ENOSPC | ENOSYS)
}
pub fn main() {
if !emulated() {
assert_eq!(status_field("Threads", 0), "1");
}
let (uid, gid) = effective_ids();
let outside_host = host_name();
let outside_user = namespace("user");
let outside_uts = namespace("uts");
let nobody: u32 = std::fs::read_to_string("/proc/sys/kernel/overflowuid")
.unwrap()
.trim()
.parse()
.unwrap();
if let Err(error) = linux::unshare(Namespaces::USER) {
if error.kind() == ErrorKind::InvalidInput && emulated() {
println!("skipped: the emulator is a process with several threads: {error}");
return;
}
assert!(refused(&error), "unshare: {error:?}");
println!("skipped: no user namespace for this process: {error}");
return;
}
assert_ne!(namespace("user"), outside_user);
assert_eq!(effective_ids(), (nobody, nobody));
let me = process::id();
let map = |outside| {
[IdMap {
inside: 0,
outside,
count: 1,
}]
};
let error = linux::write_gid_map(me, &map(gid)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
if let Err(error) = linux::allow_setgroups(me, false) {
assert!(refused(&error), "setgroups: {error:?}");
println!(
"skipped: no use of capabilities in the user namespace ({})",
super::common::confinement()
);
return;
}
let error = linux::allow_setgroups(me, true).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
linux::write_gid_map(me, &map(gid)).unwrap();
linux::write_uid_map(me, &map(uid)).unwrap();
assert_eq!(effective_ids(), (0, 0));
let error = linux::write_uid_map(me, &map(uid)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
if let Err(error) = linux::unshare(Namespaces::UTS | Namespaces::IPC | Namespaces::NETWORK)
{
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
println!(
"skipped: no use of capabilities in the user namespace ({})",
super::common::confinement()
);
return;
}
assert_ne!(namespace("uts"), outside_uts);
assert_eq!(host_name(), outside_host);
linux::set_host_name(b"oscall-single").unwrap();
assert_eq!(host_name(), "oscall-single");
linux::unshare(Namespaces::MOUNT | Namespaces::CGROUP).unwrap();
#[cfg(feature = "alloc")]
children();
println!("ok");
}
#[cfg(feature = "alloc")]
fn children() {
use oscall::process::{Command, Stdio};
use oscall::{AsHandle, io};
fn run(script: &str) -> oscall::Result<String> {
let (output, write) = io::pipe().unwrap();
let mut child = Command::new("/bin/sh")
.args(&["-c", script])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()?;
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!(child.wait().unwrap().success());
Ok(String::from_utf8(text).unwrap().trim().to_owned())
}
assert_eq!(
run("cat /proc/sys/kernel/hostname").unwrap(),
"oscall-single"
);
if std::path::Path::new("/proc/self/ns/time").exists() {
let before = namespace("time");
linux::unshare(Namespaces::TIME).unwrap();
assert_eq!(namespace("time"), before);
let number = |link: String| link.split_once(':').unwrap().1.to_owned();
assert_ne!(
number(namespace("time_for_children")),
number(before.clone())
);
assert_ne!(run("readlink /proc/self/ns/time").unwrap(), before);
} else {
println!("skipped: the kernel has no time namespaces");
}
let pid = process::id();
linux::unshare(Namespaces::PID).unwrap();
assert_eq!(process::id(), pid);
assert_eq!(run("echo $$").unwrap(), "1");
let error = run("echo $$").unwrap_err();
assert_eq!(error.kind(), ErrorKind::OutOfMemory, "{error:?}");
}
}
const NAME: &str = "single_thread";
#[cfg(not(any(target_os = "linux", target_os = "fullrust")))]
mod linux {
pub fn main() {}
}
fn main() {
let mut filters = std::env::args().skip(1).filter(|arg| !arg.starts_with('-'));
let selected = match filters.next() {
None => true,
Some(first) => NAME.contains(&first) || filters.any(|filter| NAME.contains(&filter)),
};
let list = std::env::args().any(|arg| arg == "--list");
if selected && !list {
linux::main();
}
}