#![allow(dead_code)]
use std::mem::size_of;
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::{
CreateProcessW, GetCurrentProcess, GetExitCodeProcess, OpenProcessToken, ResumeThread, TerminateProcess,
WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED, INFINITE, PROCESS_INFORMATION,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, STARTUPINFOW,
};
static SE_DEBUG_DROPPED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
fn drop_se_debug_privilege() {
SE_DEBUG_DROPPED.get_or_init(|| {
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)");
});
}
const NO_ACE: u32 = u32::MAX;
pub(crate) struct RestrictedChild {
handle: HANDLE,
thread: HANDLE,
job: HANDLE,
pid: u32,
}
impl RestrictedChild {
pub(crate) fn pid(&self) -> u32 {
self.pid
}
pub(crate) fn handle(&self) -> HANDLE {
self.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 {
let me = crate::identity::windows_identity_from_handle(self.handle, self.pid)
.expect("the owned handle always yields an identity");
loop {
assert!(self.is_running(), "the fixture shell exited before spawning its child");
let parents = crate::containment::enumerate::process_parents();
if let Some(kid) = crate::containment::treewalk::children_of(me, &parents).first() {
return kid.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();
for (h, what) in [(self.thread, "thread"), (self.handle, "process"), (self.job, "job")] {
if let Err(e) = unsafe { CloseHandle(h) } {
log::error!("fixture teardown: CloseHandle({what}) for pid {} failed: {e}", self.pid);
}
}
if let Some(what) = failure {
log::error!("{what}");
if !std::thread::panicking() {
panic!("{what}");
}
}
}
}
pub(crate) fn spawn_restricted(granted: u32) -> RestrictedChild {
spawn_with_ace(granted | PROCESS_TERMINATE.0)
}
pub(crate) fn spawn_unkillable() -> RestrictedChild {
spawn_with_ace(NO_ACE)
}
pub(crate) fn spawn_query_only() -> RestrictedChild {
spawn_with_ace(PROCESS_QUERY_LIMITED_INFORMATION.0)
}
pub(crate) fn spawn_restricted_shell(granted: u32) -> RestrictedChild {
spawn_with_ace_cmdline(
granted | PROCESS_TERMINATE.0,
"C:\\Windows\\System32\\cmd.exe /c ping.exe -n 3600 127.0.0.1",
)
}
fn spawn_with_ace(granted: u32) -> RestrictedChild {
spawn_with_ace_cmdline(granted, "C:\\Windows\\System32\\ping.exe -n 3600 127.0.0.1")
}
fn spawn_with_ace_cmdline(granted: u32, cmdline: &str) -> RestrictedChild {
drop_se_debug_privilege();
let mut token = HANDLE::default();
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }.expect("OpenProcessToken");
let mut needed = 0u32;
let _ = 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 mut cmdline: Vec<u16> = cmdline.encode_utf16().chain(std::iter::once(0)).collect();
let si = STARTUPINFOW {
cb: size_of::<STARTUPINFOW>() as u32,
..Default::default()
};
let mut pi = PROCESS_INFORMATION::default();
unsafe {
CreateProcessW(
None,
Some(PWSTR(cmdline.as_mut_ptr())),
Some(&sa),
None,
false,
CREATE_NO_WINDOW | CREATE_SUSPENDED,
None,
None,
&si,
&mut pi,
)
}
.expect("CreateProcessW for the restricted fixture child");
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, pi.hProcess) }.expect("AssignProcessToJobObject");
let prev = unsafe { ResumeThread(pi.hThread) };
assert_eq!(prev, 1, "the fixture child must resume from exactly one suspend");
let child = RestrictedChild {
handle: pi.hProcess,
thread: pi.hThread,
job,
pid: pi.dwProcessId,
};
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;