Preserve Windows runtime state and qualify native guarded adapters
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,406 @@
|
||||
//! Bounded Windows child process trees. No authorization is conferred here.
|
||||
//! The caller must commit the verified grant/attempt consumption before run.
|
||||
//! Job and handle lists are applied atomically by CreateProcessW (Windows 10+).
|
||||
use anyhow::{Result, ensure};
|
||||
use std::{
|
||||
ffi::{OsStr, OsString},
|
||||
mem::{size_of, size_of_val, zeroed},
|
||||
os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
path::Path,
|
||||
ptr,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{
|
||||
ERROR_BROKEN_PIPE, GetLastError, HANDLE, HANDLE_FLAG_INHERIT, STILL_ACTIVE,
|
||||
SetHandleInformation,
|
||||
},
|
||||
Security::SECURITY_ATTRIBUTES,
|
||||
Storage::FileSystem::ReadFile,
|
||||
System::{
|
||||
JobObjects::*,
|
||||
Pipes::{CreatePipe, PeekNamedPipe},
|
||||
Threading::*,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Output {
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub exit_code: Option<i32>,
|
||||
pub truncated: bool,
|
||||
/// A killed process can already have affected the machine: never retry it.
|
||||
pub interrupted: bool,
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
/// Windows CRT quoting, not shell escaping. PowerShell receives -File followed
|
||||
/// by individual arguments; none are evaluated as a generated command string.
|
||||
pub fn quote(arg: &OsStr) -> Result<Vec<u16>> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let input: Vec<u16> = arg.encode_wide().collect();
|
||||
ensure!(!input.contains(&0), "ARGUMENT_NUL");
|
||||
let mut out = vec![b'"' as u16];
|
||||
let mut slashes = 0;
|
||||
for ch in input {
|
||||
if ch == b'\\' as u16 {
|
||||
slashes += 1;
|
||||
continue;
|
||||
}
|
||||
out.extend(std::iter::repeat_n(
|
||||
b'\\' as u16,
|
||||
slashes * if ch == b'"' as u16 { 2 } else { 1 },
|
||||
));
|
||||
if ch == b'"' as u16 {
|
||||
out.push(b'\\' as u16);
|
||||
}
|
||||
out.push(ch);
|
||||
slashes = 0;
|
||||
}
|
||||
out.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2));
|
||||
out.push(b'"' as u16);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn owned(raw: HANDLE) -> Result<OwnedHandle> {
|
||||
ensure!(!raw.is_null() && raw != -1isize as HANDLE, "PROCESS_HANDLE");
|
||||
// SAFETY: successful creating API transfers this unique, live handle.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(raw) })
|
||||
}
|
||||
fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
|
||||
let mut read = ptr::null_mut();
|
||||
let mut write = ptr::null_mut();
|
||||
let security = SECURITY_ATTRIBUTES {
|
||||
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: ptr::null_mut(),
|
||||
bInheritHandle: 1,
|
||||
};
|
||||
// SAFETY: initialized output pointers and fixed-size security descriptor.
|
||||
ensure!(
|
||||
unsafe { CreatePipe(&mut read, &mut write, &security, 8192) } != 0,
|
||||
"PROCESS_PIPE"
|
||||
);
|
||||
let read = owned(read)?;
|
||||
let write = owned(write)?;
|
||||
ensure!(
|
||||
unsafe { SetHandleInformation(read.as_raw_handle(), HANDLE_FLAG_INHERIT, 0) } != 0,
|
||||
"PIPE_READ_NOT_INHERITED"
|
||||
);
|
||||
Ok((read, write))
|
||||
}
|
||||
|
||||
struct Attributes {
|
||||
storage: Vec<usize>,
|
||||
}
|
||||
impl Attributes {
|
||||
fn new() -> Result<Self> {
|
||||
let mut bytes = 0;
|
||||
unsafe {
|
||||
InitializeProcThreadAttributeList(ptr::null_mut(), 2, 0, &mut bytes);
|
||||
}
|
||||
ensure!(bytes > 0 && bytes < 65536, "PROCESS_ATTRIBUTES_SIZE");
|
||||
let mut storage = vec![0usize; bytes.div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe {
|
||||
InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), 2, 0, &mut bytes)
|
||||
} != 0,
|
||||
"PROCESS_ATTRIBUTES"
|
||||
);
|
||||
Ok(Self { storage })
|
||||
}
|
||||
fn pointer(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
|
||||
self.storage.as_mut_ptr().cast()
|
||||
}
|
||||
fn set(&mut self, attribute: u32, handles: &[HANDLE]) -> Result<()> {
|
||||
ensure!(
|
||||
unsafe {
|
||||
UpdateProcThreadAttribute(
|
||||
self.pointer(),
|
||||
0,
|
||||
attribute as usize,
|
||||
handles.as_ptr().cast(),
|
||||
std::mem::size_of_val(handles),
|
||||
ptr::null_mut(),
|
||||
ptr::null(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_ATTRIBUTE_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Attributes {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
DeleteProcThreadAttributeList(self.pointer());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(
|
||||
pipe: &OwnedHandle,
|
||||
output: &mut Vec<u8>,
|
||||
remaining: &mut usize,
|
||||
truncated: &mut bool,
|
||||
) -> Result<()> {
|
||||
// One bounded read per stream/iteration avoids starvation by a noisy child.
|
||||
let mut available = 0;
|
||||
if unsafe {
|
||||
PeekNamedPipe(
|
||||
pipe.as_raw_handle(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
ptr::null_mut(),
|
||||
&mut available,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
ensure!(
|
||||
unsafe { GetLastError() } == ERROR_BROKEN_PIPE,
|
||||
"PROCESS_PIPE_PEEK"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if available == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let mut buffer = [0u8; 16384];
|
||||
let mut read = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
ReadFile(
|
||||
pipe.as_raw_handle(),
|
||||
buffer.as_mut_ptr(),
|
||||
available.min(buffer.len() as u32),
|
||||
&mut read,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_PIPE_READ"
|
||||
);
|
||||
let keep = (*remaining).min(read as usize);
|
||||
output.extend_from_slice(&buffer[..keep]);
|
||||
*remaining -= keep;
|
||||
*truncated |= keep < read as usize;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run(
|
||||
executable: &Path,
|
||||
arguments: &[OsString],
|
||||
cwd: &Path,
|
||||
seconds: u32,
|
||||
max_bytes: usize,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<Output> {
|
||||
ensure!(
|
||||
executable.is_absolute() && cwd.is_absolute() && seconds > 0 && max_bytes <= 512 * 1024,
|
||||
"PROCESS_LIMITS"
|
||||
);
|
||||
let (stdout, out_write) = pipe()?;
|
||||
let (stderr, err_write) = pipe()?;
|
||||
let (stdin, in_write) = pipe()?;
|
||||
// The child reads immediate EOF. Only its read handle is inheritable.
|
||||
ensure!(
|
||||
unsafe {
|
||||
SetHandleInformation(
|
||||
stdin.as_raw_handle(),
|
||||
HANDLE_FLAG_INHERIT,
|
||||
HANDLE_FLAG_INHERIT,
|
||||
)
|
||||
} != 0,
|
||||
"STDIN_INHERITANCE"
|
||||
);
|
||||
drop(in_write);
|
||||
let job = owned(unsafe { CreateJobObjectW(ptr::null(), ptr::null()) })?;
|
||||
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
ensure!(
|
||||
unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
ptr::addr_of!(limits).cast(),
|
||||
size_of_val(&limits) as u32,
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_JOB_LIMITS"
|
||||
);
|
||||
let jobs = [job.as_raw_handle()];
|
||||
let inherited = [
|
||||
stdin.as_raw_handle(),
|
||||
out_write.as_raw_handle(),
|
||||
err_write.as_raw_handle(),
|
||||
];
|
||||
let mut attributes = Attributes::new()?;
|
||||
attributes.set(PROC_THREAD_ATTRIBUTE_JOB_LIST, &jobs)?;
|
||||
attributes.set(PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &inherited)?;
|
||||
let mut startup: STARTUPINFOEXW = unsafe { zeroed() };
|
||||
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
|
||||
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput = stdin.as_raw_handle();
|
||||
startup.StartupInfo.hStdOutput = out_write.as_raw_handle();
|
||||
startup.StartupInfo.hStdError = err_write.as_raw_handle();
|
||||
startup.lpAttributeList = attributes.pointer();
|
||||
let mut command = quote(executable.as_os_str())?;
|
||||
for arg in arguments {
|
||||
command.push(b' ' as u16);
|
||||
command.extend(quote(arg)?);
|
||||
}
|
||||
ensure!(command.len() < 32766, "PROCESS_ARGUMENT_LIMIT");
|
||||
command.push(0);
|
||||
let application = crate::native::wide(executable);
|
||||
let directory = crate::native::wide(cwd);
|
||||
let mut system_buffer = [0u16; 32768];
|
||||
let system_length = unsafe {
|
||||
windows_sys::Win32::System::SystemInformation::GetSystemWindowsDirectoryW(
|
||||
system_buffer.as_mut_ptr(),
|
||||
system_buffer.len() as u32,
|
||||
)
|
||||
} as usize;
|
||||
ensure!(
|
||||
system_length > 0 && system_length < system_buffer.len(),
|
||||
"SYSTEM_ROOT"
|
||||
);
|
||||
let system = std::path::PathBuf::from(String::from_utf16(&system_buffer[..system_length])?);
|
||||
// Minimal environment: no inherited tokens, proxy secrets, device paths,
|
||||
// PSModulePath overrides, user profile or caller-controlled executable PATH.
|
||||
let mut environment = Vec::new();
|
||||
for value in [
|
||||
format!("PATH={}\\System32;{}", system.display(), system.display()),
|
||||
format!("SystemRoot={}", system.display()),
|
||||
format!("TEMP={}", cwd.display()),
|
||||
format!("TMP={}", cwd.display()),
|
||||
format!("windir={}", system.display()),
|
||||
] {
|
||||
environment.extend(crate::native::wide(value));
|
||||
}
|
||||
environment.push(0);
|
||||
let mut process: PROCESS_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateProcessW(
|
||||
application.as_ptr(),
|
||||
command.as_mut_ptr(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
1,
|
||||
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
|
||||
environment.as_ptr().cast(),
|
||||
directory.as_ptr(),
|
||||
&startup.StartupInfo,
|
||||
&mut process,
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_CREATION_REFUSED"
|
||||
);
|
||||
let process_handle = owned(process.hProcess)?;
|
||||
let _thread = owned(process.hThread)?;
|
||||
// Handles not explicitly listed (including job, DB and keys) are never inherited.
|
||||
drop(attributes);
|
||||
drop(stdin);
|
||||
drop(out_write);
|
||||
drop(err_write);
|
||||
let mut result = Output {
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
exit_code: None,
|
||||
truncated: false,
|
||||
interrupted: false,
|
||||
cancelled: false,
|
||||
};
|
||||
let began = Instant::now();
|
||||
let mut remaining = max_bytes;
|
||||
loop {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
let mut accounting: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectBasicAccountingInformation,
|
||||
ptr::addr_of_mut!(accounting).cast(),
|
||||
size_of_val(&accounting) as u32,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} != 0,
|
||||
"PROCESS_TREE_STATE"
|
||||
);
|
||||
if accounting.ActiveProcesses == 0 {
|
||||
break;
|
||||
}
|
||||
if began.elapsed() >= Duration::from_secs(seconds.into()) || cancel.load(Ordering::SeqCst) {
|
||||
result.cancelled = cancel.load(Ordering::SeqCst);
|
||||
result.interrupted = true;
|
||||
ensure!(
|
||||
unsafe { TerminateJobObject(job.as_raw_handle(), 1) } != 0,
|
||||
"PROCESS_TREE_TERMINATION"
|
||||
);
|
||||
// This wait proves termination, not absence of effects.
|
||||
ensure!(
|
||||
unsafe { WaitForSingleObject(process_handle.as_raw_handle(), 5000) } == 0,
|
||||
"PROCESS_TERMINATION_UNCONFIRMED"
|
||||
);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
// No writer can outlive job destruction. Drain the bounded OS pipe buffers.
|
||||
drop(job);
|
||||
for _ in 0..8 {
|
||||
drain(
|
||||
&stdout,
|
||||
&mut result.stdout,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
drain(
|
||||
&stderr,
|
||||
&mut result.stderr,
|
||||
&mut remaining,
|
||||
&mut result.truncated,
|
||||
)?;
|
||||
}
|
||||
let mut code = 0;
|
||||
ensure!(
|
||||
unsafe { GetExitCodeProcess(process_handle.as_raw_handle(), &mut code) } != 0
|
||||
&& code != STILL_ACTIVE as u32,
|
||||
"PROCESS_EXIT_UNCONFIRMED"
|
||||
);
|
||||
result.exit_code = Some(code as i32);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() {
|
||||
assert_eq!(
|
||||
String::from_utf16("e(OsStr::new("a b\\")).unwrap()).unwrap(),
|
||||
"\"a b\\\\\""
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf16("e(OsStr::new("a\"b")).unwrap()).unwrap(),
|
||||
"\"a\\\"b\""
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf16("e(OsStr::new("$(Get-Content x); & y")).unwrap()).unwrap(),
|
||||
"\"$(Get-Content x); & y\""
|
||||
);
|
||||
assert!(quote(OsStr::new("a\0b")).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user