#![allow(unsafe_code)]
use std::cmp::Ordering;
use std::ffi::{OsStr, OsString};
use std::io;
use std::marker::PhantomData;
use std::mem::size_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};
use windows_sys::Win32::Foundation::{
DuplicateHandle, SetHandleInformation, DUPLICATE_SAME_ACCESS, ERROR_BROKEN_PIPE, HANDLE,
HANDLE_FLAG_INHERIT,
};
use windows_sys::Win32::Globalization::{
CompareStringOrdinal, CSTR_EQUAL, CSTR_GREATER_THAN, CSTR_LESS_THAN,
};
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::SECURITY_CAPABILITIES;
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, ReadFile, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::Threading::{
CreateProcessAsUserW, CreateProcessW, DeleteProcThreadAttributeList,
InitializeProcThreadAttributeList, ResumeThread, TerminateProcess, UpdateProcThreadAttribute,
CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT,
LPPROC_THREAD_ATTRIBUTE_LIST, PROCESS_INFORMATION, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
PROC_THREAD_ATTRIBUTE_JOB_LIST, PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW,
};
use crate::app_container::AppContainerProfile;
use crate::handle::{current_process, owned_from_creation};
use crate::job::Job;
use crate::process::{Process, ProcessAccess};
use crate::session::current_session_id;
use crate::token::PrimaryToken;
use crate::wide::wide_null;
const MANAGED_FLAGS: u32 =
CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT;
#[derive(Debug)]
pub struct Launch<'a> {
executable: PathBuf,
arguments: Vec<OsString>,
inherited: Vec<OwnedHandle>,
stdin: Option<BorrowedHandle<'a>>,
stdout: Option<BorrowedHandle<'a>>,
stderr: Option<BorrowedHandle<'a>>,
current_dir: Option<PathBuf>,
environment: EnvironmentPlan,
create_no_window: bool,
extra_flags: u32,
token: Option<&'a PrimaryToken>,
desktop: Option<OsString>,
app_container: Option<&'a AppContainerProfile>,
}
impl<'a> Launch<'a> {
pub fn new(executable: impl Into<PathBuf>) -> Self {
Self {
executable: executable.into(),
arguments: Vec::new(),
inherited: Vec::new(),
stdin: None,
stdout: None,
stderr: None,
current_dir: None,
environment: EnvironmentPlan::default(),
create_no_window: true,
extra_flags: 0,
token: None,
desktop: None,
app_container: None,
}
}
pub fn arg(&mut self, argument: impl AsRef<OsStr>) -> &mut Self {
self.arguments.push(argument.as_ref().to_owned());
self
}
pub fn args<I, S>(&mut self, arguments: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.arguments.extend(
arguments
.into_iter()
.map(|argument| argument.as_ref().to_owned()),
);
self
}
pub fn inherit(&mut self, handle: &impl AsHandle) -> io::Result<usize> {
let copy = duplicate(handle.as_handle(), false)?;
let value = copy.as_raw_handle() as usize;
self.inherited.push(copy);
Ok(value)
}
pub fn stdin<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
self.stdin = Some(handle.as_handle());
self
}
pub fn stdout<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
self.stdout = Some(handle.as_handle());
self
}
pub fn stderr<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
self.stderr = Some(handle.as_handle());
self
}
pub fn current_dir(&mut self, directory: impl Into<PathBuf>) -> &mut Self {
self.current_dir = Some(directory.into());
self
}
pub fn env(&mut self, name: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
self.environment
.changes
.push((name.as_ref().to_owned(), Some(value.as_ref().to_owned())));
self
}
pub fn env_remove(&mut self, name: impl AsRef<OsStr>) -> &mut Self {
self.environment
.changes
.push((name.as_ref().to_owned(), None));
self
}
pub fn env_clear(&mut self) -> &mut Self {
self.environment.clear = true;
self.environment.changes.clear();
self
}
pub fn create_no_window(&mut self, enabled: bool) -> &mut Self {
self.create_no_window = enabled;
self
}
pub fn creation_flags(&mut self, flags: u32) -> &mut Self {
self.extra_flags = flags & !MANAGED_FLAGS;
self
}
pub fn as_user(&mut self, token: &'a PrimaryToken) -> &mut Self {
self.token = Some(token);
self
}
pub fn desktop(&mut self, name: impl AsRef<OsStr>) -> &mut Self {
self.desktop = Some(name.as_ref().to_owned());
self
}
pub fn app_container(&mut self, profile: &'a AppContainerProfile) -> &mut Self {
self.app_container = Some(profile);
self
}
pub fn spawn_suspended(&mut self) -> io::Result<SuspendedChild> {
self.create_suspended(None)
}
pub fn spawn_suspended_in_job(&mut self, job: &Job) -> io::Result<SuspendedChild> {
self.create_suspended(Some(job))
}
pub fn spawn_in_job(&mut self, job: &Job) -> io::Result<Process> {
self.spawn_suspended_in_job(job)?.resume()
}
pub fn spawn(&mut self) -> io::Result<Process> {
self.spawn_suspended()?.resume()
}
fn create_suspended(&mut self, job: Option<&Job>) -> io::Result<SuspendedChild> {
if self.token.is_some() && self.app_container.is_some() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"an AppContainer launch cannot use as_user: the profile belongs to the calling user, not the token's user",
));
}
let application = wide_null(&self.executable)?;
let mut command_line = command_line(&self.executable, &self.arguments)?;
let current_dir = self.current_dir.as_ref().map(wide_null).transpose()?;
let environment = self.environment.block()?;
let mut desktop = self.desktop.as_ref().map(wide_null).transpose()?;
let standard = if self.stdin.is_some() || self.stdout.is_some() || self.stderr.is_some() {
Some([
standard_slot(self.stdin)?,
standard_slot(self.stdout)?,
standard_slot(self.stderr)?,
])
} else {
None
};
let mut handles: Vec<HANDLE> = Vec::new();
if let Some(standard) = &standard {
handles.extend(standard.iter().map(AsRawHandle::as_raw_handle));
}
handles.extend(self.inherited.iter().map(AsRawHandle::as_raw_handle));
if let Some(token) = self.token {
if !handles.is_empty() && token.session_id()? != current_session_id()? {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"a child in another session cannot inherit handles",
));
}
}
let mut attributes = if handles.is_empty() && self.app_container.is_none() && job.is_none()
{
None
} else {
Some(AttributeList::with_attributes(
&handles,
self.app_container,
job,
)?)
};
let inheritable = InheritableWindow::open(&self.inherited)?;
let mut startup = STARTUPINFOEXW::default();
let mut flags = self.extra_flags | CREATE_SUSPENDED;
if let Some(list) = attributes.as_mut() {
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
startup.lpAttributeList = list.as_mut_ptr();
flags |= EXTENDED_STARTUPINFO_PRESENT;
} else {
startup.StartupInfo.cb = size_of::<STARTUPINFOW>() as u32;
}
if let Some([input, output, error]) = &standard {
startup.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput = input.as_raw_handle();
startup.StartupInfo.hStdOutput = output.as_raw_handle();
startup.StartupInfo.hStdError = error.as_raw_handle();
}
if let Some(desktop) = desktop.as_mut() {
startup.StartupInfo.lpDesktop = desktop.as_mut_ptr();
}
if self.create_no_window {
flags |= CREATE_NO_WINDOW;
}
if environment.is_some() {
flags |= CREATE_UNICODE_ENVIRONMENT;
}
let environment_pointer = environment
.as_ref()
.map_or(null(), |block| block.as_ptr().cast());
let directory_pointer = current_dir
.as_ref()
.map_or(null(), |directory| directory.as_ptr());
let inherit_handles = i32::from(!handles.is_empty());
let mut information = PROCESS_INFORMATION::default();
let created = match self.token {
None => unsafe {
CreateProcessW(
application.as_ptr(),
command_line.as_mut_ptr(),
null(),
null(),
inherit_handles,
flags,
environment_pointer,
directory_pointer,
&startup.StartupInfo,
&mut information,
)
},
Some(token) => unsafe {
CreateProcessAsUserW(
token.as_raw_handle(),
application.as_ptr(),
command_line.as_mut_ptr(),
null(),
null(),
inherit_handles,
flags,
environment_pointer,
directory_pointer,
&startup.StartupInfo,
&mut information,
)
},
};
let failure = (created == 0).then(io::Error::last_os_error);
drop(inheritable);
drop(attributes);
drop(standard);
if let Some(error) = failure {
return Err(error);
}
let process = owned_from_creation(information.hProcess);
let thread = owned_from_creation(information.hThread);
match (process, thread) {
(Ok(process), Ok(thread)) => Ok(SuspendedChild {
process: Some(Process::from_owned(process, ProcessAccess::AsCreated)),
thread: Some(thread),
pid: information.dwProcessId,
}),
(Ok(process), Err(error)) => {
unsafe { TerminateProcess(process.as_raw_handle(), 1) };
Err(error)
}
(Err(error), _) => Err(error),
}
}
}
#[derive(Debug)]
pub struct SuspendedChild {
process: Option<Process>,
thread: Option<OwnedHandle>,
pid: u32,
}
impl SuspendedChild {
pub fn pid(&self) -> u32 {
self.pid
}
pub fn process(&self) -> &Process {
self.process.as_ref().expect("present until consumed")
}
pub fn resume(mut self) -> io::Result<Process> {
let thread = self.thread.take().expect("present until consumed");
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(self.process.take().expect("present until consumed"))
}
pub fn terminate(mut self, exit_code: u32) -> io::Result<()> {
self.process
.take()
.expect("present until consumed")
.terminate(exit_code)
}
}
impl Drop for SuspendedChild {
fn drop(&mut self) {
if let Some(process) = self.process.take() {
let _ = process.terminate(1);
}
}
}
pub fn anonymous_pipe() -> io::Result<(OwnedHandle, OwnedHandle)> {
let mut read = null_mut();
let mut write = null_mut();
if unsafe { CreatePipe(&mut read, &mut write, null(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let read = owned_from_creation(read);
let write = owned_from_creation(write);
Ok((read?, write?))
}
pub fn null_device() -> io::Result<OwnedHandle> {
open_null(false)
}
pub fn read_to_end_bounded(handle: &impl AsHandle, maximum: usize) -> io::Result<Vec<u8>> {
let raw = handle.as_handle().as_raw_handle();
let mut output = Vec::new();
let mut buffer = [0_u8; 4096];
loop {
let mut bytes_read = 0;
let read = unsafe {
ReadFile(
raw,
buffer.as_mut_ptr(),
buffer.len() as u32,
&mut bytes_read,
null_mut(),
)
};
if read == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
break;
}
return Err(error);
}
if bytes_read == 0 {
break;
}
let remaining = maximum.saturating_add(1).saturating_sub(output.len());
output.extend_from_slice(&buffer[..(bytes_read as usize).min(remaining)]);
}
Ok(output)
}
fn standard_slot(handle: Option<BorrowedHandle<'_>>) -> io::Result<OwnedHandle> {
match handle {
Some(handle) => duplicate(handle, true),
None => open_null(true),
}
}
fn duplicate(handle: BorrowedHandle<'_>, inheritable: bool) -> io::Result<OwnedHandle> {
let mut copy = null_mut();
let duplicated = unsafe {
DuplicateHandle(
current_process(),
handle.as_raw_handle(),
current_process(),
&mut copy,
0,
i32::from(inheritable),
DUPLICATE_SAME_ACCESS,
)
};
if duplicated == 0 {
return Err(io::Error::last_os_error());
}
owned_from_creation(copy)
}
fn open_null(inheritable: bool) -> io::Result<OwnedHandle> {
let security = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: null_mut(),
bInheritHandle: i32::from(inheritable),
};
let name = wide_null("NUL")?;
let handle = unsafe {
CreateFileW(
name.as_ptr(),
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
&security,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
null_mut(),
)
};
owned_from_creation(handle)
}
struct InheritableWindow<'h> {
handles: &'h [OwnedHandle],
opened: usize,
}
impl<'h> InheritableWindow<'h> {
fn open(handles: &'h [OwnedHandle]) -> io::Result<Self> {
let mut window = Self { handles, opened: 0 };
for handle in handles {
set_inheritable(handle.as_raw_handle(), true)?;
window.opened += 1;
}
Ok(window)
}
}
impl Drop for InheritableWindow<'_> {
fn drop(&mut self) {
for handle in &self.handles[..self.opened] {
let _ = set_inheritable(handle.as_raw_handle(), false);
}
}
}
fn set_inheritable(handle: RawHandle, inheritable: bool) -> io::Result<()> {
let value = if inheritable { HANDLE_FLAG_INHERIT } else { 0 };
if unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, value) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
struct AttributeList<'a> {
storage: Vec<usize>,
initialized: bool,
_handles: Vec<HANDLE>,
_job: Option<Box<HANDLE>>,
_security_capabilities: Option<Box<SECURITY_CAPABILITIES>>,
_borrows: PhantomData<(&'a AppContainerProfile, &'a Job)>,
}
impl<'a> AttributeList<'a> {
fn with_attributes(
handles: &[HANDLE],
app_container: Option<&'a AppContainerProfile>,
job: Option<&'a Job>,
) -> io::Result<Self> {
let mut count = u32::from(!handles.is_empty());
count += u32::from(app_container.is_some());
count += u32::from(job.is_some());
let mut bytes = 0_usize;
unsafe { InitializeProcThreadAttributeList(null_mut(), count, 0, &mut bytes) };
if bytes == 0 {
return Err(io::Error::last_os_error());
}
let mut list = Self {
storage: vec![0_usize; bytes.div_ceil(size_of::<usize>())],
initialized: false,
_handles: handles.to_vec(),
_job: job.map(|job| Box::new(job.as_raw_handle())),
_security_capabilities: app_container
.map(AppContainerProfile::security_capabilities)
.map(Box::new),
_borrows: PhantomData,
};
let initialized =
unsafe { InitializeProcThreadAttributeList(list.as_mut_ptr(), count, 0, &mut bytes) };
if initialized == 0 {
return Err(io::Error::last_os_error());
}
list.initialized = true;
if !list._handles.is_empty() {
let pointer = list._handles.as_ptr();
let length = std::mem::size_of_val(list._handles.as_slice());
let updated = unsafe {
UpdateProcThreadAttribute(
list.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
pointer.cast(),
length,
null_mut(),
null(),
)
};
if updated == 0 {
return Err(io::Error::last_os_error());
}
}
let job = list._job.as_deref().map(|handle| handle as *const HANDLE);
if let Some(job) = job {
let updated = unsafe {
UpdateProcThreadAttribute(
list.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_JOB_LIST as usize,
job.cast(),
size_of::<HANDLE>(),
null_mut(),
null(),
)
};
if updated == 0 {
return Err(io::Error::last_os_error());
}
}
let capabilities = list
._security_capabilities
.as_deref_mut()
.map(|value| value as *mut SECURITY_CAPABILITIES);
if let Some(capabilities) = capabilities {
let updated = unsafe {
UpdateProcThreadAttribute(
list.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES as usize,
capabilities.cast(),
size_of::<SECURITY_CAPABILITIES>(),
null_mut(),
null(),
)
};
if updated == 0 {
return Err(io::Error::last_os_error());
}
}
Ok(list)
}
fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
self.storage.as_mut_ptr().cast()
}
}
impl Drop for AttributeList<'_> {
fn drop(&mut self) {
if self.initialized {
unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
}
}
}
#[derive(Debug, Default)]
struct EnvironmentPlan {
clear: bool,
changes: Vec<(OsString, Option<OsString>)>,
}
impl EnvironmentPlan {
fn block(&self) -> io::Result<Option<Vec<u16>>> {
if !self.clear && self.changes.is_empty() {
return Ok(None);
}
let mut entries: Vec<(Vec<u16>, Vec<u16>)> = Vec::new();
if !self.clear {
for (name, value) in std::env::vars_os() {
upsert(
&mut entries,
name.encode_wide().collect(),
value.encode_wide().collect(),
);
}
}
for (name, value) in &self.changes {
let name: Vec<u16> = name.encode_wide().collect();
if name.is_empty() || name.contains(&0) || name.contains(&u16::from(b'=')) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"environment names must be non-empty and contain neither '=' nor NUL",
));
}
match value {
Some(value) => {
let value: Vec<u16> = value.encode_wide().collect();
if value.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"environment values must not contain NUL",
));
}
upsert(&mut entries, name, value);
}
None => entries.retain(|(existing, _)| {
compare_environment_names(existing, &name) != Ordering::Equal
}),
}
}
entries.sort_by(|left, right| compare_environment_names(&left.0, &right.0));
let mut block = Vec::new();
for (name, value) in entries {
block.extend(name);
block.push(u16::from(b'='));
block.extend(value);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(Some(block))
}
}
fn upsert(entries: &mut Vec<(Vec<u16>, Vec<u16>)>, name: Vec<u16>, value: Vec<u16>) {
entries.retain(|(existing, _)| compare_environment_names(existing, &name) != Ordering::Equal);
entries.push((name, value));
}
fn compare_environment_names(left: &[u16], right: &[u16]) -> Ordering {
let (Ok(left_length), Ok(right_length)) =
(i32::try_from(left.len()), i32::try_from(right.len()))
else {
return left.cmp(right);
};
let result = unsafe {
CompareStringOrdinal(left.as_ptr(), left_length, right.as_ptr(), right_length, 1)
};
match result {
CSTR_LESS_THAN => Ordering::Less,
CSTR_EQUAL => Ordering::Equal,
CSTR_GREATER_THAN => Ordering::Greater,
_ => left.cmp(right),
}
}
fn command_line(executable: &Path, arguments: &[OsString]) -> io::Result<Vec<u16>> {
let executable: Vec<u16> = executable.as_os_str().encode_wide().collect();
if executable.contains(&0) || executable.contains(&u16::from(b'"')) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"the executable path contains a NUL or a quote",
));
}
let mut line = vec![u16::from(b'"')];
line.extend(executable);
line.push(u16::from(b'"'));
for argument in arguments {
line.push(u16::from(b' '));
append_argument(&mut line, argument)?;
}
line.push(0);
Ok(line)
}
pub(crate) fn command_line_tail(arguments: &[OsString]) -> io::Result<Vec<u16>> {
let mut line = Vec::new();
for (index, argument) in arguments.iter().enumerate() {
if index != 0 {
line.push(u16::from(b' '));
}
append_argument(&mut line, argument)?;
}
line.push(0);
Ok(line)
}
fn append_argument(line: &mut Vec<u16>, argument: &OsStr) -> io::Result<()> {
let units: Vec<u16> = argument.encode_wide().collect();
if units.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"an argument contains a NUL",
));
}
let quote = u16::from(b'"');
let backslash = u16::from(b'\\');
let needs_quotes = units.is_empty()
|| units
.iter()
.any(|unit| matches!(*unit, 0x09..=0x0d | 0x20 | 0x22));
if !needs_quotes {
line.extend(units);
return Ok(());
}
line.push(quote);
let mut backslashes = 0_usize;
for unit in units {
if unit == backslash {
backslashes += 1;
} else if unit == quote {
line.extend(std::iter::repeat(backslash).take(backslashes * 2 + 1));
line.push(unit);
backslashes = 0;
} else {
line.extend(std::iter::repeat(backslash).take(backslashes));
line.push(unit);
backslashes = 0;
}
}
line.extend(std::iter::repeat(backslash).take(backslashes * 2));
line.push(quote);
Ok(())
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::fs::File;
use std::io::{Read, Write};
use std::os::windows::ffi::OsStringExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
use std::path::Path;
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{ERROR_NOT_ENOUGH_QUOTA, GENERIC_READ, GENERIC_WRITE};
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
use windows_sys::Win32::System::JobObjects::IsProcessInJob;
use super::{
anonymous_pipe, command_line, command_line_tail, null_device, read_to_end_bounded, Launch,
};
use crate::handle::WaitOutcome;
use crate::job::{Job, JobLimits};
use crate::pipe::{PipeDirection, PipeServer, PipeWait};
use crate::process::ProcessAccess;
use crate::security::{
current_user_sid_string, ObjectSecurityDescriptor, OwnedSid, SecurityDescriptor,
};
use crate::{AppContainerAccess, AppContainerProfile, PrimaryToken};
fn cmd() -> std::path::PathBuf {
let root = std::env::var_os("SystemRoot").expect("SystemRoot is set");
Path::new(&root).join("System32").join("cmd.exe")
}
struct ProfileGuard(Option<AppContainerProfile>);
impl ProfileGuard {
fn new(suffix: &str) -> Self {
let name = format!("win-custody-test-{}-{suffix}", std::process::id());
assert!(name.encode_utf16().count() <= 64);
Self(Some(
AppContainerProfile::create_or_open(
&name,
"Win Custody test",
"Win Custody AppContainer launch test",
)
.unwrap(),
))
}
fn with_capabilities(suffix: &str, capabilities: &[&str]) -> Self {
let name = format!("win-custody-test-{}-{suffix}", std::process::id());
assert!(name.encode_utf16().count() <= 64);
Self(Some(
AppContainerProfile::create_or_open_with_capabilities(
&name,
"Win Custody test",
"Win Custody AppContainer launch test",
capabilities,
)
.unwrap(),
))
}
fn profile(&self) -> &AppContainerProfile {
self.0.as_ref().expect("profile present until guard drop")
}
}
impl Drop for ProfileGuard {
fn drop(&mut self) {
if let Some(profile) = self.0.take() {
let _ = profile.delete();
}
}
}
fn rendered(arguments: &[&str]) -> String {
let arguments: Vec<OsString> = arguments.iter().map(OsString::from).collect();
let units = command_line(Path::new(r"C:\a b\x.exe"), &arguments).unwrap();
String::from_utf16(&units[..units.len() - 1]).unwrap()
}
#[test]
fn arguments_are_quoted_only_where_the_child_parser_needs_it() {
assert_eq!(rendered(&[]), r#""C:\a b\x.exe""#);
assert_eq!(rendered(&["plain"]), r#""C:\a b\x.exe" plain"#);
assert_eq!(rendered(&[""]), r#""C:\a b\x.exe" """#);
assert_eq!(rendered(&["two words"]), r#""C:\a b\x.exe" "two words""#);
assert_eq!(
rendered(&["with \"quote\""]),
r#""C:\a b\x.exe" "with \"quote\"""#
);
assert_eq!(
rendered(&[r"trailing\ x\"]),
r#""C:\a b\x.exe" "trailing\ x\\""#
);
assert_eq!(rendered(&[r"no\space\"]), r#""C:\a b\x.exe" no\space\"#);
}
#[test]
fn unpaired_surrogates_survive_quoting() {
let value = OsString::from_wide(&[0xd800, u16::from(b' '), u16::from(b'x')]);
let units = command_line_tail(&[value]).unwrap();
assert_eq!(
units,
[
u16::from(b'"'),
0xd800,
u16::from(b' '),
u16::from(b'x'),
u16::from(b'"'),
0
]
);
}
#[test]
fn nuls_and_quotes_in_the_program_name_are_rejected() {
assert!(command_line(Path::new("a\"b.exe"), &[]).is_err());
assert!(command_line(Path::new("a.exe"), &[OsString::from("a\0b")]).is_err());
}
#[test]
fn a_child_in_a_kill_on_close_job_reports_its_exit_code() {
let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "exit 7"])
.spawn_in_job(&job)
.unwrap();
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(child.exit_code().unwrap(), Some(7));
}
#[test]
fn an_appcontainer_child_is_created_in_its_job_and_keeps_captured_stdio() {
let profile = ProfileGuard::new("grant");
assert!(profile
.profile()
.sid_string()
.unwrap()
.starts_with("S-1-15-2-"));
let directory = tempfile::tempdir().unwrap();
profile
.profile()
.grant_path(directory.path(), AppContainerAccess::ReadWrite)
.unwrap();
let job = Job::create(&JobLimits::new().kill_on_close(true).active_processes(1)).unwrap();
let (read, write) = anonymous_pipe().unwrap();
let child = Launch::new(cmd())
.args([
"/d",
"/c",
"echo appcontainer-ok > marker.txt & type marker.txt",
])
.current_dir(directory.path())
.app_container(profile.profile())
.stdout(&write)
.spawn_in_job(&job)
.unwrap();
assert!(child.is_app_container().unwrap());
assert!(!child.has_capability("internetClient").unwrap());
drop(write);
let output = read_to_end_bounded(&read, 4096).unwrap();
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(String::from_utf8_lossy(&output).trim(), "appcontainer-ok");
assert_eq!(
std::fs::read_to_string(directory.path().join("marker.txt"))
.unwrap()
.trim(),
"appcontainer-ok"
);
}
#[test]
fn an_appcontainer_child_cannot_write_outside_a_granted_directory() {
let profile = ProfileGuard::new("confine");
let granted = tempfile::tempdir().unwrap();
let ungranted = tempfile::tempdir().unwrap();
profile
.profile()
.grant_path(granted.path(), AppContainerAccess::ReadWrite)
.unwrap();
let marker = ungranted.path().join("forbidden-marker.txt");
assert_eq!(granted.path().parent(), ungranted.path().parent());
let ungranted_name = ungranted
.path()
.file_name()
.and_then(|name| name.to_str())
.expect("tempfile directory names are Unicode");
assert!(!ungranted_name.chars().any(char::is_whitespace));
let command = format!(r"echo x > ..\{ungranted_name}\forbidden-marker.txt");
let control = Launch::new(cmd())
.args(["/d", "/c", &command])
.current_dir(granted.path())
.spawn()
.unwrap();
assert_eq!(
control.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(control.exit_code().unwrap(), Some(0));
assert!(marker.exists());
std::fs::remove_file(&marker).unwrap();
let contained_command = format!("echo ok > ran-marker.txt & {command}");
let child = Launch::new(cmd())
.args(["/d", "/c", &contained_command])
.current_dir(granted.path())
.app_container(profile.profile())
.spawn()
.unwrap();
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert!(granted.path().join("ran-marker.txt").exists());
assert_ne!(child.exit_code().unwrap(), Some(0));
assert!(!marker.exists());
}
#[test]
fn an_appcontainer_child_token_contains_its_configured_capability() {
let profile = ProfileGuard::with_capabilities("capability", &["internetClient"]);
let child = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.app_container(profile.profile())
.spawn_suspended()
.unwrap();
assert!(child.process().has_capability("internetClient").unwrap());
assert!(!child
.process()
.has_capability("internetClientServer")
.unwrap());
child.process().terminate(0).unwrap();
assert_eq!(
child.process().wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
}
#[test]
fn ensuring_path_access_writes_only_missing_rights() {
let profile = ProfileGuard::new("ensure");
let directory = tempfile::tempdir().unwrap();
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
assert!(!profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadWriteExecute)
.unwrap());
}
#[test]
fn all_application_packages_access_avoids_writing_the_dacl() {
let profile = ProfileGuard::new("packages-access");
let directory = tempfile::tempdir().unwrap();
let current_user = current_user_sid_string().unwrap();
let descriptor = SecurityDescriptor::from_sddl(&format!(
"D:P(A;OICI;FA;;;{current_user})(A;OICI;GRGX;;;AC)"
))
.unwrap();
descriptor.apply_to_tree(directory.path(), true).unwrap();
let current_user = OwnedSid::from_string(¤t_user).unwrap();
let packages = OwnedSid::from_string("AC").unwrap();
let before = ObjectSecurityDescriptor::query_file(directory.path()).unwrap();
let before: Vec<_> = before
.dacl()
.unwrap()
.allowed_aces()
.map(|ace| {
(
ace.flags(),
ace.mask(),
ace.trustee_matches(¤t_user),
ace.trustee_matches(&packages),
)
})
.collect();
assert!(!profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
let profile_sid = OwnedSid::from_string(&profile.profile().sid_string().unwrap()).unwrap();
let after = ObjectSecurityDescriptor::query_file(directory.path()).unwrap();
let dacl = after.dacl().unwrap();
assert!(!dacl
.allowed_aces()
.any(|ace| ace.trustee_matches(&profile_sid)));
let after: Vec<_> = dacl
.allowed_aces()
.map(|ace| {
(
ace.flags(),
ace.mask(),
ace.trustee_matches(¤t_user),
ace.trustee_matches(&packages),
)
})
.collect();
assert_eq!(after, before);
}
#[test]
fn a_profile_deny_precedes_the_package_allow() {
let profile = ProfileGuard::new("denied-execute");
let directory = tempfile::tempdir().unwrap();
let current_user = current_user_sid_string().unwrap();
let profile_sid = profile.profile().sid_string().unwrap();
let descriptor = SecurityDescriptor::from_sddl(&format!(
"D:P(A;OICI;FA;;;{current_user})(D;OICI;GX;;;{profile_sid})(A;OICI;GRGX;;;AC)"
))
.unwrap();
descriptor.apply_to_tree(directory.path(), true).unwrap();
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
}
#[test]
fn an_inherit_only_package_rule_does_not_grant_the_directory_access() {
let profile = ProfileGuard::new("inherit-only");
let directory = tempfile::tempdir().unwrap();
let current_user = current_user_sid_string().unwrap();
let descriptor = SecurityDescriptor::from_sddl(&format!(
"D:P(A;OICI;FA;;;{current_user})(A;OICIIO;GRGX;;;AC)"
))
.unwrap();
descriptor.apply_to_tree(directory.path(), true).unwrap();
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
}
#[test]
fn repeated_path_access_checks_finish_without_authz_delay() {
let profile = ProfileGuard::new("ensure-timing");
let directory = tempfile::tempdir().unwrap();
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
let started = Instant::now();
for _ in 0..20 {
assert!(!profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
}
let elapsed = started.elapsed();
eprintln!("20 repeated ensure_path_access calls took {elapsed:?}");
assert!(elapsed < Duration::from_secs(2), "elapsed: {elapsed:?}");
}
#[test]
fn read_execute_grant_includes_file_execute_rights() {
let profile = ProfileGuard::new("execute-rights");
let directory = tempfile::tempdir().unwrap();
profile
.profile()
.grant_path(directory.path(), AppContainerAccess::ReadExecute)
.unwrap();
let rights = profile
.profile()
.effective_path_rights(directory.path())
.unwrap();
assert_eq!(rights & FILE_GENERIC_EXECUTE, FILE_GENERIC_EXECUTE);
}
const APPCONTAINER_SELF_CHECK: &str = "WIN_CUSTODY_TEST_SELF_CHECK";
#[test]
#[ignore = "run by appcontainer_capability_is_visible_inside_the_child"]
fn appcontainer_process_reports_its_capability() {
if std::env::var_os(APPCONTAINER_SELF_CHECK) != Some(OsString::from("1")) {
return;
}
let process =
crate::Process::open(std::process::id(), ProcessAccess::QueryLimited).unwrap();
assert!(process.is_app_container().unwrap());
assert!(process.has_capability("internetClient").unwrap());
assert!(!process.has_capability("internetClientServer").unwrap());
}
#[test]
fn appcontainer_capability_is_visible_inside_the_child() {
let profile = ProfileGuard::with_capabilities("self-check", &["internetClient"]);
let current =
crate::Process::open(std::process::id(), ProcessAccess::QueryLimited).unwrap();
assert!(!current.has_capability("internetClient").unwrap());
let directory = tempfile::tempdir().unwrap();
let executable = directory.path().join("win-custody-self-check.exe");
std::fs::copy(std::env::current_exe().unwrap(), &executable).unwrap();
assert!(profile
.profile()
.ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
.unwrap());
let child = Launch::new(&executable)
.args([
"--exact",
"launch::tests::appcontainer_process_reports_its_capability",
"--ignored",
])
.env(APPCONTAINER_SELF_CHECK, "1")
.app_container(profile.profile())
.spawn_suspended()
.unwrap();
assert!(child.process().has_capability("internetClient").unwrap());
let child = child.resume().unwrap();
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(child.exit_code().unwrap(), Some(0));
}
#[test]
fn as_user_and_appcontainer_are_rejected_before_launch_conversion() {
let profile = ProfileGuard::new("as-user");
let token = PrimaryToken::duplicate_current_process().unwrap();
let error = Launch::new(Path::new("contains\0nul.exe"))
.as_user(&token)
.app_container(profile.profile())
.spawn()
.unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
assert_eq!(
error.to_string(),
"an AppContainer launch cannot use as_user: the profile belongs to the calling user, not the token's user"
);
}
#[test]
fn appcontainer_launch_composes_with_a_low_integrity_named_pipe() {
let profile = ProfileGuard::new("pipe");
let pipe_name = format!(r"\\.\pipe\win-custody-appcontainer-{}", std::process::id());
let descriptor = SecurityDescriptor::from_sddl(&format!(
"D:P(A;;0x{:08X};;;{})(A;;0x{:08X};;;{})S:(ML;;NW;;;LW)",
GENERIC_READ | GENERIC_WRITE,
current_user_sid_string().unwrap(),
GENERIC_READ | GENERIC_WRITE,
profile.profile().sid_string().unwrap(),
))
.unwrap();
let server = PipeServer::create(&pipe_name, PipeDirection::Inbound, &descriptor).unwrap();
let command = format!("echo appcontainer-pipe>{pipe_name}");
let child = Launch::new(cmd())
.args(["/d", "/c", &command])
.app_container(profile.profile())
.spawn()
.unwrap();
server
.connect(&PipeWait::within(Duration::from_secs(30)).with_peer(&child))
.unwrap();
assert_eq!(server.client_process_id().unwrap(), child.pid().unwrap());
let mut payload = [0_u8; 128];
let read = server
.read(
&mut payload,
&PipeWait::within(Duration::from_secs(30)).with_peer(&child),
)
.unwrap();
assert_eq!(
String::from_utf8_lossy(&payload[..read]).trim(),
"appcontainer-pipe"
);
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(child.exit_code().unwrap(), Some(0));
}
#[test]
fn closing_the_job_kills_the_child() {
let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "ping -n 60 127.0.0.1 >NUL"])
.spawn_in_job(&job)
.unwrap();
assert_eq!(
child.wait(Some(Duration::from_millis(200))).unwrap(),
WaitOutcome::TimedOut
);
drop(job);
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
}
const SUPERVISOR_REPORT: &str = "WIN_CUSTODY_TEST_SUPERVISOR_REPORT";
struct TerminateOnDrop(crate::Process);
impl Drop for TerminateOnDrop {
fn drop(&mut self) {
let _ = self.0.terminate(1);
}
}
#[test]
fn supervisor_process_for_the_killed_parent_test() {
let Some(report) = std::env::var_os(SUPERVISOR_REPORT) else {
return;
};
let report: usize = report.to_str().unwrap().parse().unwrap();
let mut report = unsafe { File::from_raw_handle(report as RawHandle) };
let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended_in_job(&job)
.unwrap();
report.write_all(&child.pid().to_le_bytes()).unwrap();
std::thread::sleep(Duration::from_secs(120));
}
fn is_in_job(process: &crate::Process, job: &Job) -> bool {
let mut member = 0;
let queried =
unsafe { IsProcessInJob(process.as_raw_handle(), job.as_raw_handle(), &mut member) };
assert_ne!(queried, 0, "{}", std::io::Error::last_os_error());
member != 0
}
#[test]
fn a_child_created_in_a_job_is_a_member_while_still_suspended() {
let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
let outside = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended()
.unwrap();
assert!(!is_in_job(outside.process(), &job));
let inside = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended_in_job(&job)
.unwrap();
assert!(is_in_job(inside.process(), &job));
}
#[test]
fn a_full_job_refuses_the_child_instead_of_letting_it_exist_outside() {
let job = Job::create(&JobLimits::new().kill_on_close(true).active_processes(1)).unwrap();
let _first = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended_in_job(&job)
.unwrap();
let error = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended_in_job(&job)
.unwrap_err();
assert_eq!(error.raw_os_error(), Some(ERROR_NOT_ENOUGH_QUOTA as i32));
}
#[test]
fn a_child_created_in_a_job_still_receives_its_standard_output() {
let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
let (read, write) = anonymous_pipe().unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "echo in-the-job"])
.stdout(&write)
.spawn_in_job(&job)
.unwrap();
drop(write);
let output = read_to_end_bounded(&read, 4096).unwrap();
assert_eq!(
child.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(String::from_utf8_lossy(&output).trim(), "in-the-job");
}
#[test]
fn a_child_created_in_a_job_dies_when_its_parent_is_killed() {
let (read, write) = anonymous_pipe().unwrap();
let input = null_device().unwrap();
let supervisor = {
let mut launch = Launch::new(std::env::current_exe().unwrap());
launch
.args([
"--exact",
"launch::tests::supervisor_process_for_the_killed_parent_test",
])
.stdin(&input);
let report = launch.inherit(&write).unwrap();
launch.env(SUPERVISOR_REPORT, report.to_string());
TerminateOnDrop(launch.spawn().unwrap())
};
drop(write);
let mut pid = [0_u8; 4];
File::from(read)
.read_exact(&mut pid)
.expect("the supervisor reports its child before it waits");
let child = TerminateOnDrop(
crate::Process::open(u32::from_le_bytes(pid), ProcessAccess::Terminate).unwrap(),
);
assert_eq!(
child.0.wait(Some(Duration::from_millis(200))).unwrap(),
WaitOutcome::TimedOut
);
supervisor.0.terminate(1).unwrap();
assert_eq!(
supervisor.0.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(
child.0.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
}
#[test]
fn standard_output_and_environment_reach_the_child() {
let (read, write) = anonymous_pipe().unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "echo %WIN_CUSTODY_PROBE%"])
.env("WIN_CUSTODY_PROBE", "custody-ok")
.stdout(&write)
.spawn()
.unwrap();
drop(write);
let output = read_to_end_bounded(&read, 4096).unwrap();
child.wait(Some(Duration::from_secs(30))).unwrap();
assert_eq!(String::from_utf8_lossy(&output).trim(), "custody-ok");
}
#[test]
fn a_removed_variable_is_absent_in_the_child() {
std::env::set_var("WIN_CUSTODY_REMOVED", "present");
let (read, write) = anonymous_pipe().unwrap();
let child = Launch::new(cmd())
.args([
"/d",
"/c",
"if defined WIN_CUSTODY_REMOVED (echo yes) else (echo no)",
])
.env_remove("win_custody_removed")
.stdout(&write)
.spawn()
.unwrap();
drop(write);
let output = read_to_end_bounded(&read, 4096).unwrap();
child.wait(Some(Duration::from_secs(30))).unwrap();
assert_eq!(String::from_utf8_lossy(&output).trim(), "no");
}
#[test]
fn a_dropped_suspended_child_is_terminated() {
let child = Launch::new(cmd())
.args(["/d", "/c", "exit 0"])
.spawn_suspended()
.unwrap();
let process = crate::process::Process::open(
child.pid(),
crate::process::ProcessAccess::QueryLimitedAndSynchronize,
)
.unwrap();
drop(child);
assert_eq!(
process.wait(Some(Duration::from_secs(30))).unwrap(),
WaitOutcome::Signaled
);
assert_eq!(process.exit_code().unwrap(), Some(1));
}
#[test]
fn output_beyond_the_bound_is_cut_at_one_extra_byte() {
let (read, write) = anonymous_pipe().unwrap();
let child = Launch::new(cmd())
.args(["/d", "/c", "echo 0123456789"])
.stdout(&write)
.spawn()
.unwrap();
drop(write);
let output = read_to_end_bounded(&read, 4).unwrap();
child.wait(Some(Duration::from_secs(30))).unwrap();
assert_eq!(output, b"01234");
}
}