use std::ffi::{CString, OsStr, OsString};
use std::os::fd::RawFd;
use std::os::unix::ffi::OsStrExt;
use std::sync::atomic::{AtomicI32, Ordering};
use super::signals::{Inherited, FAULTS, TERMINATIONS};
use crate::elevation::shim::protocol::{Errno, Frame, NotExecuted};
use crate::elevation::shim::step::ToChild;
use crate::os_process::linux::fork::{Fork, ForkFn, NewChild};
static TERMINATED: AtomicI32 = AtomicI32::new(0);
extern "C" fn record_termination(signal: libc::c_int) {
_ = TERMINATED.compare_exchange(0, signal, Ordering::Relaxed, Ordering::Relaxed);
}
extern "C" fn nothing(_: libc::c_int) {}
const LOG_AT_GATE: &[u8] = b"child: waiting at gate (handlers ready)\n";
const LOG_NO_PARENT: &[u8] = b"child: the shim is gone before exec; exit 119\n";
pub(in crate::elevation::shim) struct Prepared {
candidates: Vec<*const libc::c_char>,
argv: Vec<*const libc::c_char>,
envp: Vec<*const libc::c_char>,
sh_argvs: Vec<Vec<*const libc::c_char>>,
_strings: Vec<CString>,
max_signal: libc::c_int,
ignored: *const bool,
handleable: *const bool,
inherited: Inherited,
saved_mask: libc::sigset_t,
all_signals: libc::sigset_t,
shim_pid: libc::pid_t,
status_read: RawFd,
status_write: RawFd,
release_read: RawFd,
release_write: RawFd,
log_fd: RawFd,
gate: Option<CString>,
fault: bool,
parent_death_signal: libc::c_ulong,
}
const SH: &[u8] = b"/bin/sh\0";
impl Prepared {
#[allow(
clippy::too_many_arguments,
reason = "the child's whole world, gathered once before the clone"
)]
pub(in crate::elevation::shim) fn new(
candidates: &[OsString],
argv: &[&OsStr],
env: impl Iterator<Item = (OsString, OsString)>,
inherited: Inherited,
saved_mask: libc::sigset_t,
status: (RawFd, RawFd),
release: (RawFd, RawFd),
log_fd: Option<RawFd>,
gate: Option<&OsStr>,
fault: bool,
setup_fails: bool,
) -> Prepared {
let cstring = |s: &OsStr| CString::new(s.as_bytes()).expect("argv carries no NUL: ShimArgs::parse checked");
let candidate_c: Vec<CString> = candidates.iter().map(|c| cstring(c)).collect();
let argv_c: Vec<CString> = argv.iter().map(|a| cstring(a)).collect();
let env_c: Vec<CString> = env
.map(|(mut k, v)| {
k.push("=");
k.push(v);
cstring(&k)
})
.collect();
let sh = CString::from_vec_with_nul(SH.to_vec()).expect("a literal with its NUL");
let ptrs = |list: &[&CString]| -> Vec<*const libc::c_char> {
list.iter()
.map(|s| s.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect()
};
let argv_ptrs = ptrs(&argv_c.iter().collect::<Vec<_>>());
let envp = ptrs(&env_c.iter().collect::<Vec<_>>());
let sh_argvs = candidate_c
.iter()
.map(|candidate| {
let mut list: Vec<&CString> = vec![&sh, candidate];
list.extend(argv_c.iter().skip(1));
ptrs(&list)
})
.collect();
let candidate_ptrs = candidate_c.iter().map(|c| c.as_ptr()).collect();
let mut strings = candidate_c;
strings.extend(argv_c);
strings.extend(env_c);
strings.push(sh);
let all_signals = unsafe {
let mut all: libc::sigset_t = std::mem::zeroed();
libc::sigfillset(&mut all);
all
};
Prepared {
candidates: candidate_ptrs,
argv: argv_ptrs,
envp,
sh_argvs,
_strings: strings,
max_signal: inherited.max,
ignored: inherited.ignored_ptr(),
handleable: inherited.handleable_ptr(),
inherited,
saved_mask,
all_signals,
shim_pid: rustix::process::getpid().as_raw_nonzero().get(),
status_read: status.0,
status_write: status.1,
release_read: release.0,
release_write: release.1,
log_fd: log_fd.unwrap_or(-1),
gate: gate.map(cstring),
fault,
parent_death_signal: if setup_fails {
1000
} else {
libc::SIGKILL as libc::c_ulong
},
}
}
}
pub(in crate::elevation::shim) fn spawn(prepared: &Prepared, fork: ForkFn) -> Result<NewChild, i32> {
match unsafe { fork() }? {
Fork::Child => unsafe { child_body(prepared) },
Fork::Parent(child) => Ok(child),
}
}
const KIND_EXEC: u16 = 2;
const KIND_SETUP: u16 = 3;
const KIND_TERMINATED: u16 = 4;
fn status_value(kind: u16, value: i32) -> i32 {
i32::from(kind) << 16 | value & 0xffff
}
pub(in crate::elevation::shim) fn decode_report(value: i32) -> NotExecuted {
let mut bytes = vec![b'F'];
bytes.extend_from_slice(&value.to_le_bytes());
match crate::elevation::shim::protocol::decode_frame(&bytes) {
Ok(Frame::NotExecuted(report)) => report,
other => {
debug_assert!(false, "the child wrote a value no F frame has: {other:?}");
NotExecuted::ExecFailed(Errno(libc::EIO))
}
}
}
unsafe fn fail_setup(p: &Prepared, errno: libc::c_int) -> ! {
let value = status_value(KIND_SETUP, errno);
unsafe {
libc::write(p.status_write, (&value as *const i32).cast(), 4);
libc::_exit(crate::elevation::shim::codes::NOT_EXECUTED)
}
}
fn tries_the_next(errno: libc::c_int) -> bool {
matches!(
errno,
libc::ENOENT | libc::ENOTDIR | libc::ESTALE | libc::ENODEV | libc::ETIMEDOUT | libc::EACCES
)
}
unsafe fn child_body(p: &Prepared) -> ! {
unsafe {
libc::close(p.status_read);
libc::close(p.release_write);
let mut record: libc::sigaction = std::mem::zeroed();
record.sa_sigaction = record_termination as *const () as usize;
record.sa_flags = libc::SA_RESTART;
libc::sigfillset(&mut record.sa_mask);
let mut noop: libc::sigaction = std::mem::zeroed();
noop.sa_sigaction = nothing as *const () as usize;
noop.sa_flags = libc::SA_RESTART;
let mut default: libc::sigaction = std::mem::zeroed();
default.sa_sigaction = libc::SIG_DFL;
for signal in 1..=p.max_signal {
if signal == libc::SIGKILL || signal == libc::SIGSTOP || !*p.handleable.add(signal as usize) {
continue;
}
if is_in(&FAULTS, signal) {
if libc::sigaction(signal, &default, std::ptr::null_mut()) != 0 {
fail_setup(p, *libc::__errno_location());
}
continue;
}
if *p.ignored.add(signal as usize) && signal != libc::SIGPIPE {
continue;
}
let action = if is_in(&TERMINATIONS, signal) { &record } else { &noop };
if libc::sigaction(signal, action, std::ptr::null_mut()) != 0 {
fail_setup(p, *libc::__errno_location());
}
}
let unblocked = libc::pthread_sigmask(libc::SIG_SETMASK, &p.saved_mask, std::ptr::null_mut());
if unblocked != 0 {
fail_setup(p, unblocked);
}
let mut byte = 0u8;
loop {
let n = libc::read(p.release_read, (&mut byte as *mut u8).cast(), 1);
if n >= 0 {
break;
}
let errno = *libc::__errno_location();
if errno != libc::EINTR {
fail_setup(p, errno);
}
}
libc::close(p.release_read);
if let Some(gate) = &p.gate {
write_log(p.log_fd, LOG_AT_GATE);
let fd = libc::open(gate.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC);
if fd >= 0 {
let mut byte = 0u8;
libc::read(fd, (&mut byte as *mut u8).cast(), 1);
libc::close(fd);
}
}
if p.fault {
std::ptr::write_volatile(8 as *mut i32, 0);
}
if libc::prctl(libc::PR_SET_PDEATHSIG, p.parent_death_signal) != 0 {
fail_setup(p, *libc::__errno_location());
}
if libc::getppid() != p.shim_pid {
write_log(p.log_fd, LOG_NO_PARENT);
libc::_exit(crate::elevation::shim::codes::NO_PARENT);
}
let blocked = libc::pthread_sigmask(libc::SIG_BLOCK, &p.all_signals, std::ptr::null_mut());
if blocked != 0 {
fail_setup(p, blocked);
}
let terminated = TERMINATED.load(Ordering::Relaxed);
if terminated != 0 {
let value = status_value(KIND_TERMINATED, terminated);
libc::write(p.status_write, (&value as *const i32).cast(), 4);
libc::_exit(crate::elevation::shim::codes::NOT_EXECUTED);
}
for signal in TERMINATIONS {
if !*p.ignored.add(signal as usize) && libc::sigaction(signal, &default, std::ptr::null_mut()) != 0 {
fail_setup(p, *libc::__errno_location());
}
}
let unblocked = libc::pthread_sigmask(libc::SIG_SETMASK, &p.saved_mask, std::ptr::null_mut());
if unblocked != 0 {
fail_setup(p, unblocked);
}
let mut errno = libc::ENOENT;
let mut denied = false;
let mut stopped = false;
for (&candidate, sh_argv) in p.candidates.iter().zip(&p.sh_argvs) {
libc::execve(candidate, p.argv.as_ptr(), p.envp.as_ptr());
errno = *libc::__errno_location();
if errno == libc::ENOEXEC {
libc::execve(SH.as_ptr().cast(), sh_argv.as_ptr(), p.envp.as_ptr());
errno = *libc::__errno_location();
}
if !tries_the_next(errno) {
stopped = true;
break;
}
denied |= errno == libc::EACCES;
}
if denied && !stopped {
errno = libc::EACCES;
}
let value = status_value(KIND_EXEC, errno);
libc::write(p.status_write, (&value as *const i32).cast(), 4);
libc::_exit(127)
}
}
fn is_in(list: &[libc::c_int], signal: libc::c_int) -> bool {
list.contains(&signal)
}
unsafe fn write_log(fd: RawFd, bytes: &[u8]) {
if fd >= 0 {
unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };
}
}
pub(in crate::elevation::shim) fn rustix_signal(to: ToChild) -> rustix::process::Signal {
match to {
ToChild::Kill => rustix::process::Signal::KILL,
ToChild::Term => rustix::process::Signal::TERM,
}
}
pub(in crate::elevation::shim) fn signal(child: &NewChild, to: ToChild) -> Result<(), rustix::io::Errno> {
rustix::process::pidfd_send_signal(&child.pidfd, rustix_signal(to))
}