#![cfg(windows)]
use crate::config::ExecutionLimits;
use crate::execution::{
ExecutionError, ExecutionErrorCategory, FilesystemAccess, FilesystemGrantKind,
ResolvedFilesystemGrant,
};
use std::ffi::c_void;
use std::mem::{size_of, zeroed};
use std::ptr::{null, null_mut};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use windows_sys::Win32::Foundation::{
CloseHandle, GetLastError, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE,
SetHandleInformation, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows_sys::Win32::Security::Isolation::{
CreateAppContainerProfile, DeleteAppContainerProfile,
};
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::{
EqualSid, FreeSid, GetTokenInformation, IsValidSid, SECURITY_CAPABILITIES,
TOKEN_APPCONTAINER_INFORMATION, TOKEN_QUERY, TokenAppContainerSid, TokenIsAppContainer,
};
use windows_sys::Win32::System::IO::{CreateIoCompletionPort, GetQueuedCompletionStatus};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
JOB_OBJECT_LIMIT_JOB_MEMORY, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_ASSOCIATE_COMPLETION_PORT, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectAssociateCompletionPortInformation,
JobObjectBasicAccountingInformation, JobObjectExtendedLimitInformation,
QueryInformationJobObject, SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::SystemServices::JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO;
use windows_sys::Win32::System::Threading::{
CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList,
EXTENDED_STARTUPINFO_PRESENT, GetExitCodeProcess, InitializeProcThreadAttributeList,
OpenProcessToken, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, PROCESS_INFORMATION, ResumeThread,
STARTF_USESTDHANDLES, STARTUPINFOEXW, TerminateProcess, UpdateProcThreadAttribute,
WaitForSingleObject,
};
#[allow(dead_code)] pub(super) struct WindowsJob {
handle: HANDLE,
completion_port: HANDLE,
process_was_assigned: AtomicBool,
}
#[allow(dead_code)] impl WindowsJob {
pub(super) fn new(
limits: &ExecutionLimits,
restrict_subprocesses: bool,
) -> Result<Self, ExecutionError> {
let handle = unsafe { CreateJobObjectW(null(), null()) };
if handle == 0 {
return Err(unsupported_job("create Job Object"));
}
let mut job = Self {
handle,
completion_port: 0,
process_was_assigned: AtomicBool::new(false),
};
job.completion_port = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1) };
if job.completion_port == 0 {
return Err(unsupported_job("create Job Object completion port"));
}
let mut information: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
let mut flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let process_limit = match (limits.max_processes(), restrict_subprocesses) {
(Some(limit), true) => Some(limit.min(1)),
(Some(limit), false) => Some(limit),
(None, true) => Some(1),
(None, false) => None,
};
if let Some(limit) = process_limit {
flags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
information.BasicLimitInformation.ActiveProcessLimit = limit;
}
if let Some(limit) = limits.max_memory_bytes() {
information.JobMemoryLimit = usize::try_from(limit).map_err(|_| {
ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"Windows Job Object cannot represent the requested job-wide memory limit",
)
})?;
flags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
}
information.BasicLimitInformation.LimitFlags = flags;
let size = u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
.expect("Win32 Job Object information structure size fits u32");
let configured = unsafe {
SetInformationJobObject(
job.handle,
JobObjectExtendedLimitInformation,
(&information as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast::<c_void>(),
size,
)
};
if configured == 0 {
return Err(unsupported_job("configure Job Object limits"));
}
let association = JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
CompletionKey: job.handle as usize as *mut c_void,
CompletionPort: job.completion_port,
};
let association_size = u32::try_from(size_of::<JOBOBJECT_ASSOCIATE_COMPLETION_PORT>())
.expect("Job Object completion-port association size fits u32");
let associated = unsafe {
SetInformationJobObject(
job.handle,
JobObjectAssociateCompletionPortInformation,
(&association as *const JOBOBJECT_ASSOCIATE_COMPLETION_PORT).cast::<c_void>(),
association_size,
)
};
if associated == 0 {
return Err(unsupported_job("associate Job Object completion port"));
}
Ok(job)
}
#[allow(dead_code)]
pub(super) fn assign_suspended_process(&self, process: HANDLE) -> Result<(), ExecutionError> {
if process == 0 {
return Err(ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"cannot assign an invalid process handle to the Windows Job Object",
));
}
let assigned = unsafe { AssignProcessToJobObject(self.handle, process) };
if assigned == 0 {
return Err(unsupported_job("assign suspended child to Job Object"));
}
self.process_was_assigned.store(true, Ordering::Release);
let mut in_job = 0;
let verified = unsafe { IsProcessInJob(process, self.handle, &mut in_job) };
if verified == 0 {
return Err(unsupported_job(
"verify suspended child Job Object membership",
));
}
if in_job == 0 {
return Err(ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"Windows reported successful Job Object assignment but membership verification failed",
));
}
Ok(())
}
pub(super) fn terminate_all(&self) -> Result<(), ExecutionError> {
if unsafe { TerminateJobObject(self.handle, 1) } == 0 {
return Err(unsupported_job("terminate Windows Job Object members"));
}
Ok(())
}
pub(super) fn active_process_count(&self) -> Result<u32, ExecutionError> {
let mut information: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
let size = u32::try_from(size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>())
.expect("Job Object accounting information size fits u32");
let queried = unsafe {
QueryInformationJobObject(
self.handle,
JobObjectBasicAccountingInformation,
(&mut information as *mut JOBOBJECT_BASIC_ACCOUNTING_INFORMATION).cast::<c_void>(),
size,
null_mut(),
)
};
if queried == 0 {
return Err(unsupported_job("query active Job Object process count"));
}
Ok(information.ActiveProcesses)
}
pub(super) fn wait_until_empty(&self, timeout_ms: u32) -> Result<(), ExecutionError> {
if !self.process_was_assigned.load(Ordering::Acquire) {
return Ok(());
}
if matches!(self.active_process_count(), Ok(0)) {
return Ok(());
}
self.wait_for_active_process_zero_notification(timeout_ms)
}
fn wait_for_active_process_zero_notification(
&self,
timeout_ms: u32,
) -> Result<(), ExecutionError> {
let started = Instant::now();
loop {
let remaining_ms = if timeout_ms == u32::MAX {
u32::MAX
} else {
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
if elapsed_ms >= timeout_ms {
return Err(ExecutionError::new(
ExecutionErrorCategory::Timeout,
"timed out waiting for Windows Job Object active-process-zero notification",
));
}
timeout_ms - elapsed_ms
};
let mut bytes_transferred = 0u32;
let mut completion_key = 0usize;
let mut overlapped = null_mut();
let received = unsafe {
GetQueuedCompletionStatus(
self.completion_port,
&mut bytes_transferred,
&mut completion_key,
&mut overlapped,
remaining_ms,
)
};
if received == 0 {
let error = unsafe { GetLastError() };
if error == WAIT_TIMEOUT {
return Err(ExecutionError::new(
ExecutionErrorCategory::Timeout,
"timed out waiting for Windows Job Object active-process-zero notification",
));
}
return Err(unsupported_job(
"receive Job Object completion notification",
));
}
if completion_key == self.handle as usize
&& bytes_transferred == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO
&& overlapped.is_null()
{
return Ok(());
}
}
}
#[cfg(test)]
fn query_extended_limits(
&self,
) -> Result<JOBOBJECT_EXTENDED_LIMIT_INFORMATION, ExecutionError> {
let mut information: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
let size = u32::try_from(size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
.expect("Win32 Job Object information structure size fits u32");
let queried = unsafe {
QueryInformationJobObject(
self.handle,
JobObjectExtendedLimitInformation,
(&mut information as *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast::<c_void>(),
size,
null_mut(),
)
};
if queried == 0 {
return Err(unsupported_job("query configured Job Object limits"));
}
Ok(information)
}
}
impl Drop for WindowsJob {
fn drop(&mut self) {
if self.handle != 0 {
unsafe { CloseHandle(self.handle) };
}
if self.completion_port != 0 {
unsafe { CloseHandle(self.completion_port) };
}
}
}
static NEXT_APPCONTAINER_ID: AtomicU64 = AtomicU64::new(1);
#[allow(dead_code)]
pub(super) struct WindowsAppContainer {
name: Vec<u16>,
sid: windows_sys::Win32::Foundation::PSID,
deleted: bool,
}
#[allow(dead_code)]
impl WindowsAppContainer {
pub(super) fn create() -> Result<Self, ExecutionError> {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| {
ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"Windows AppContainer profile name could not be generated",
)
})?
.as_nanos();
let sequence = NEXT_APPCONTAINER_ID.fetch_add(1, Ordering::Relaxed);
let profile = format!("td-{:x}-{nonce:x}-{sequence:x}", std::process::id());
if profile.encode_utf16().count() > 64 {
return Err(ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"Windows AppContainer profile name exceeds the platform limit",
));
}
let name = profile
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let display = format!("Tapid {profile}")
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let description = "Ephemeral Tapid root-script execution"
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>();
let mut sid = null_mut();
let result = unsafe {
CreateAppContainerProfile(
name.as_ptr(),
display.as_ptr(),
description.as_ptr(),
null(),
0,
&mut sid,
)
};
if result < 0 {
if !sid.is_null() {
unsafe { FreeSid(sid) };
}
return Err(unsupported_hresult("create AppContainer profile", result));
}
if sid.is_null() || unsafe { IsValidSid(sid) } == 0 {
if !sid.is_null() {
unsafe { FreeSid(sid) };
}
unsafe { DeleteAppContainerProfile(name.as_ptr()) };
return Err(ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
"Windows created an AppContainer profile without a valid SID",
));
}
Ok(Self {
name,
sid,
deleted: false,
})
}
pub(super) fn sid(&self) -> windows_sys::Win32::Foundation::PSID {
self.sid
}
pub(super) fn profile_name(&self) -> &[u16] {
&self.name
}
pub(super) fn cleanup(&mut self) -> Result<(), ExecutionError> {
if !self.deleted {
let result = unsafe { DeleteAppContainerProfile(self.name.as_ptr()) };
if result < 0 {
return Err(unsupported_hresult("delete AppContainer profile", result));
}
self.deleted = true;
}
if !self.sid.is_null() {
unsafe { FreeSid(self.sid) };
self.sid = null_mut();
}
Ok(())
}
}
impl Drop for WindowsAppContainer {
fn drop(&mut self) {
if !self.deleted {
if unsafe { DeleteAppContainerProfile(self.name.as_ptr()) } >= 0 {
self.deleted = true;
}
}
if !self.sid.is_null() {
unsafe { FreeSid(self.sid) };
self.sid = null_mut();
}
}
}
#[path = "windows_filesystem.rs"]
mod filesystem;
pub(super) use filesystem::WindowsFilesystemGrants;
#[cfg(test)]
pub(super) use filesystem::WindowsPathAcl;
#[path = "windows_process.rs"]
mod process;
pub(super) use process::{
WindowsChildTermination, WindowsOutputCapture, WindowsStdioPipes, WindowsSuspendedChild,
};
fn unsupported_hresult(operation: &str, hresult: i32) -> ExecutionError {
ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
format!(
"Windows {operation} failed with HRESULT 0x{:08X}",
hresult as u32
),
)
}
fn unsupported_job(operation: &str) -> ExecutionError {
ExecutionError::new(
ExecutionErrorCategory::UnsupportedContainment,
format!(
"Windows {operation} failed: {}",
std::io::Error::last_os_error()
),
)
}
#[cfg(test)]
#[path = "windows_job_tests.rs"]
mod tests;