use std::mem::size_of;
use std::os::windows::io::AsRawHandle as _;
use crate::test_own_process::Completion;
use crate::test_spawn::console_flags::Console;
use crate::test_spawn::raw_spawn::{spawn_locked_raw_with, RawChild, RawOptions, RawStdio};
use windows::core::PWSTR;
use windows::Win32::Foundation::LUID;
use windows::Win32::Foundation::{CloseHandle, HANDLE, STILL_ACTIVE, WAIT_OBJECT_0};
use windows::Win32::Security::{
AddAccessAllowedAce, AdjustTokenPrivileges, GetTokenInformation, InitializeAcl, InitializeSecurityDescriptor,
LookupPrivilegeValueW, SetSecurityDescriptorDacl, TokenUser, ACL, ACL_REVISION, LUID_AND_ATTRIBUTES,
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR, SE_DEBUG_NAME, SE_PRIVILEGE_REMOVED,
TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use windows::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{
GetCurrentProcess, GetExitCodeProcess, OpenProcessToken, QueryFullProcessImageNameW, ResumeThread,
TerminateProcess, WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED, DETACHED_PROCESS, INFINITE,
PROCESS_CREATION_FLAGS, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE,
};
fn drop_se_debug_privilege(_alone: &Completion) {
let mut token = HANDLE::default();
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut token) }
.expect("OpenProcessToken(TOKEN_ADJUST_PRIVILEGES)");
let mut luid = LUID::default();
unsafe { LookupPrivilegeValueW(None, SE_DEBUG_NAME, &mut luid) }.expect("LookupPrivilegeValueW(SeDebugPrivilege)");
let privileges = TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {
Luid: luid,
Attributes: SE_PRIVILEGE_REMOVED,
}],
};
let adjusted = unsafe { AdjustTokenPrivileges(token, false, Some(&privileges), 0, None, None) };
unsafe { CloseHandle(token) }.expect("CloseHandle(process token)");
adjusted.expect("AdjustTokenPrivileges(SeDebugPrivilege, SE_PRIVILEGE_REMOVED)");
}
pub(crate) fn image_file_name(pid: u32) -> Option<String> {
use super::backend::{close, open_classified, Opened};
let handle = match open_classified(pid, PROCESS_QUERY_LIMITED_INFORMATION) {
Opened::Found(handle) => handle,
Opened::Gone => return None,
Opened::Denied(e) => panic!("fixture: the job member {pid} cannot be opened: {e}"),
};
let mut buffer = vec![0u16; 32_768];
let mut len = buffer.len() as u32;
let read = unsafe { QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, PWSTR(buffer.as_mut_ptr()), &mut len) };
let mut exit_code = 0u32;
unsafe { GetExitCodeProcess(handle, &mut exit_code) }.expect("GetExitCodeProcess on an owned handle");
close(handle);
match read {
Ok(()) => Some(String::from_utf16_lossy(&buffer[..len as usize])),
Err(e) if exit_code == STILL_ACTIVE.0 as u32 => {
panic!("fixture: the image of the live job member {pid} cannot be read: {e}")
}
Err(_) => None,
}
}
pub(crate) fn is_more_com(pid: u32) -> bool {
image_file_name(pid).is_some_and(|image| {
std::path::Path::new(&image)
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("more.com"))
})
}
const NO_ACE: u32 = u32::MAX;
pub(crate) struct RestrictedChild {
child: RawChild,
job: HANDLE,
stdin: Option<std::io::PipeWriter>,
}
impl RestrictedChild {
pub(crate) fn pid(&self) -> u32 {
self.child.id()
}
pub(crate) fn handle(&self) -> HANDLE {
HANDLE(self.child.process().as_raw_handle())
}
pub(crate) fn exit_code(&self) -> u32 {
let mut code = 0u32;
unsafe { GetExitCodeProcess(self.handle(), &mut code) }.expect("GetExitCodeProcess on an owned handle");
code
}
pub(crate) fn is_running(&self) -> bool {
self.exit_code() == STILL_ACTIVE.0 as u32
}
pub(crate) fn await_exit(&self) {
let waited = unsafe { WaitForSingleObject(self.handle(), INFINITE) };
assert_eq!(
waited,
WAIT_OBJECT_0,
"fixture: wait on pid {} returned {waited:?}",
self.pid()
);
}
pub(crate) fn wait_for_child(&self) -> u32 {
loop {
assert!(self.is_running(), "the fixture shell exited before spawning its child");
let members = crate::containment::windows::query_job_pid_list(self.job).expect("the fixture job's members");
if let Some(pid) = members
.into_iter()
.filter(|&pid| pid != self.pid())
.find(|&pid| is_more_com(pid))
{
return pid;
}
std::thread::yield_now();
}
}
pub(crate) fn terminate(&self) {
if let Err(what) = self.try_terminate() {
log::error!("{what}");
if !std::thread::panicking() {
panic!("{what}");
}
}
}
fn try_terminate(&self) -> Result<(), String> {
if let Err(e) = unsafe { TerminateProcess(self.handle(), 1) } {
if !self.is_running() {
return Ok(()); }
return Err(format!(
"fixture teardown: TerminateProcess(pid {}) failed: {e}",
self.pid()
));
}
let waited = unsafe { WaitForSingleObject(self.handle(), INFINITE) };
if waited != WAIT_OBJECT_0 {
return Err(format!(
"fixture teardown: wait on pid {} returned {waited:?}",
self.pid()
));
}
Ok(())
}
}
impl Drop for RestrictedChild {
fn drop(&mut self) {
let failure = self.try_terminate().err();
if let Err(e) = unsafe { CloseHandle(self.job) } {
log::error!(
"fixture teardown: CloseHandle(job) for pid {} failed: {report}",
self.pid(),
report = crate::error::Report(&e)
);
}
if let Some(what) = failure {
log::error!("{what}");
if let Err(e) = self.child.kill() {
if self.is_running() {
log::error!(
"fixture teardown: the second TerminateProcess(pid {}) failed: {e}",
self.pid()
);
}
}
if !std::thread::panicking() {
panic!("{what}");
}
}
}
}
pub(crate) fn spawn_restricted(alone: &Completion, granted: u32) -> RestrictedChild {
spawn_with_ace(alone, granted | PROCESS_TERMINATE.0)
}
pub(crate) fn spawn_unkillable(alone: &Completion) -> RestrictedChild {
spawn_with_ace(alone, NO_ACE)
}
pub(crate) fn spawn_query_only(alone: &Completion) -> RestrictedChild {
spawn_with_ace(alone, PROCESS_QUERY_LIMITED_INFORMATION.0)
}
pub(crate) fn spawn_query_only_without_console(alone: &Completion) -> RestrictedChild {
spawn_with_ace_running(
alone,
PROCESS_QUERY_LIMITED_INFORMATION.0,
&crate::test_child::windows_more(),
&[],
DETACHED_PROCESS,
)
}
pub(crate) fn spawn_restricted_shell(alone: &Completion, granted: u32) -> RestrictedChild {
let more = crate::test_child::windows_more();
spawn_with_ace_running(
alone,
granted | PROCESS_TERMINATE.0,
&crate::test_child::system32("cmd.exe"),
&[std::path::Path::new("/c"), &more],
CREATE_NO_WINDOW,
)
}
pub(crate) fn spawn_restricted_releasable(alone: &Completion, granted: u32) -> (RestrictedChild, std::io::PipeWriter) {
let mut child = spawn_restricted(alone, granted);
let writer = child.stdin.take().expect("the fixture holds the child's stdin");
(child, writer)
}
fn spawn_with_ace(alone: &Completion, granted: u32) -> RestrictedChild {
spawn_with_ace_running(
alone,
granted,
&crate::test_child::windows_more(),
&[],
CREATE_NO_WINDOW,
)
}
fn spawn_with_ace_running(
alone: &Completion,
granted: u32,
exe: &std::path::Path,
args: &[&std::path::Path],
console: PROCESS_CREATION_FLAGS,
) -> RestrictedChild {
use std::os::windows::io::AsHandle as _;
let (reader, writer) = std::io::pipe().expect("pipe");
let null = std::fs::OpenOptions::new().write(true).open("NUL").expect("open NUL");
drop_se_debug_privilege(alone);
let mut token = HANDLE::default();
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }.expect("OpenProcessToken");
let mut needed = 0u32;
_ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut needed) };
let mut sid_buf = vec![0u64; (needed as usize).div_ceil(8).max(1)];
let info = unsafe {
GetTokenInformation(
token,
TokenUser,
Some(sid_buf.as_mut_ptr().cast()),
(sid_buf.len() * 8) as u32,
&mut needed,
)
};
unsafe { CloseHandle(token) }.expect("CloseHandle(process token)");
info.expect("GetTokenInformation(TokenUser)");
let sid = unsafe { (*sid_buf.as_ptr().cast::<TOKEN_USER>()).User.Sid };
let mut acl_buf = vec![0u32; 256];
let acl = acl_buf.as_mut_ptr().cast::<ACL>();
unsafe { InitializeAcl(acl, (acl_buf.len() * 4) as u32, ACL_REVISION) }.expect("InitializeAcl");
if granted != NO_ACE {
unsafe { AddAccessAllowedAce(acl, ACL_REVISION, granted, sid) }.expect("AddAccessAllowedAce");
}
let mut sd = SECURITY_DESCRIPTOR::default();
let psd = PSECURITY_DESCRIPTOR(&mut sd as *mut _ as *mut _);
unsafe { InitializeSecurityDescriptor(psd, 1) }.expect("InitializeSecurityDescriptor");
unsafe { SetSecurityDescriptorDacl(psd, true, Some(acl), false) }.expect("SetSecurityDescriptorDacl");
let sa = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: psd.0,
bInheritHandle: false.into(),
};
let options = RawOptions {
quote_exe: true,
stdio: RawStdio::Given {
stdin: Some(reader.as_handle()),
output: null.as_handle(),
},
process_security: Some(&sa),
..Default::default()
};
let child = spawn_locked_raw_with(exe, args, &[], console.0 | CREATE_SUSPENDED.0, Console::Asked, options)
.expect("the restricted fixture child");
drop((reader, null));
let job = unsafe { CreateJobObjectW(None, None) }.expect("CreateJobObjectW");
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
..Default::default()
},
..Default::default()
};
unsafe {
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
&limits as *const _ as *const core::ffi::c_void,
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
}
.expect("SetInformationJobObject");
unsafe { AssignProcessToJobObject(job, HANDLE(child.process().as_raw_handle())) }
.expect("AssignProcessToJobObject");
let prev = unsafe { ResumeThread(HANDLE(child.thread().as_raw_handle())) };
assert_eq!(prev, 1, "the fixture child must resume from exactly one suspend");
let child = RestrictedChild {
child,
job,
stdin: Some(writer),
};
assert!(
child.is_running(),
"the fixture child exited immediately — the command line is wrong"
);
child
}
#[cfg(test)]
#[path = "windows_fixture_tests.rs"]
mod windows_fixture_tests;