use windows::Win32::Foundation::HANDLE;
use windows::Win32::Security::{
GetSidSubAuthority, GetSidSubAuthorityCount, GetTokenInformation, TokenElevation, TokenIntegrityLevel,
TOKEN_ELEVATION, TOKEN_MANDATORY_LABEL, TOKEN_QUERY,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
use super::plan::{BackendSet, Host, Os};
struct OwnedToken(HANDLE);
impl Drop for OwnedToken {
fn drop(&mut self) {
if !self.0.is_invalid() {
if let Err(e) = unsafe { windows::Win32::Foundation::CloseHandle(self.0) } {
log::warn!(
"CloseHandle of an owned token failed: {report}",
report = crate::error::Report(&e)
);
debug_assert!(
false,
"CloseHandle of an owned token should not fail: {}",
crate::error::Report(&e)
);
}
}
}
}
fn open_process_token() -> Option<OwnedToken> {
unsafe {
let mut token = HANDLE::default();
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).ok()?;
Some(OwnedToken(token))
}
}
pub(super) fn is_elevated() -> bool {
let Some(token) = open_process_token() else {
log::warn!("could not open the process token to query elevation; assuming not elevated");
return false;
};
unsafe {
let mut e = TOKEN_ELEVATION::default();
let mut ret = 0u32;
let ok = GetTokenInformation(
token.0,
TokenElevation,
Some(&mut e as *mut _ as *mut core::ffi::c_void),
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
&mut ret,
)
.is_ok();
if !ok {
log::warn!("TokenElevation query failed; assuming not elevated");
return false;
}
e.TokenIsElevated != 0
}
}
pub(super) fn integrity_level() -> Option<u32> {
let token = open_process_token()?;
unsafe {
let mut ret = 0u32;
_ = GetTokenInformation(token.0, TokenIntegrityLevel, None, 0, &mut ret);
if ret == 0 {
log::debug!("could not size the integrity-level token info; integrity unknown");
return None;
}
let words = (ret as usize).div_ceil(8);
let mut buf = vec![0u64; words];
let cap = (words * 8) as u32;
if let Err(e) = GetTokenInformation(
token.0,
TokenIntegrityLevel,
Some(buf.as_mut_ptr() as *mut core::ffi::c_void),
cap,
&mut ret,
) {
log::debug!(
"TokenIntegrityLevel query failed: {report}; integrity unknown",
report = crate::error::Report(&e)
);
return None;
}
let label_ptr = buf.as_ptr() as *const TOKEN_MANDATORY_LABEL;
let sid = std::ptr::read_unaligned(std::ptr::addr_of!((*label_ptr).Label.Sid));
let count_ptr = GetSidSubAuthorityCount(sid);
if count_ptr.is_null() || *count_ptr == 0 {
log::debug!("integrity SID has no sub-authorities; integrity unknown");
return None;
}
let last = (*count_ptr as u32) - 1;
Some(*GetSidSubAuthority(sid, last))
}
}
pub(super) fn detect(elevated: bool) -> Host {
if let Some(rid) = integrity_level() {
log::debug!("current process integrity RID = 0x{rid:04x}");
}
Host {
elevated,
has_tty: false, available: BackendSet::default(),
os: Os::Windows,
arg_max: None,
pkexec_version: crate::elevation::pkexec::PkexecVersion::NotProbed,
pkexec_pin: None,
}
}
use crate::command::Command;
use crate::error::Error;
use crate::stdio::ResolvedStdio;
pub(crate) fn reject_unsupported_config(cmd: &Command) -> Result<(), Error> {
let unsupported = |op: &str, detail: &str| {
Err(Error::Unsupported {
op: op.into(),
platform: "windows",
detail: detail.into(),
source: None,
})
};
for (&slot, resolved) in cmd.fds() {
if slot.raw() >= 3 {
return unsupported(
"fd >= 3 on an elevated Windows child",
"runas exposes no descriptor-passing mechanism; fd >= 3 needs the (deferred) broker",
);
}
if !matches!(resolved, ResolvedStdio::Inherit) {
return unsupported(
"captured/redirected stdio on an elevated Windows child",
"runas exposes no stdio-handle mechanism; capture/redirect needs the (deferred) broker. \
Use inherit(), or elevate on POSIX.",
);
}
}
if !cmd.env_ops().is_empty() {
return unsupported(
"env forwarding to an elevated Windows child",
"runas provides no environment mechanism; forwarding needs the (deferred) broker",
);
}
if cmd.contain_request().mode.is_some() {
return unsupported(
".contain() + elevate on Windows",
"a Job Object cannot span the integrity boundary of a runas child (deferred)",
);
}
let flags = cmd.flags_request();
if flags.detached {
return unsupported(
"detached() + elevate on Windows",
"the runas launch takes a show-command and no creation flags, so DETACHED_PROCESS \
cannot be expressed. Elevate without it, or spawn unelevated.",
);
}
if flags.breakaway_from_job {
return unsupported(
"breakaway_from_job() + elevate on Windows",
"the runas launch takes a show-command and no creation flags, so \
CREATE_BREAKAWAY_FROM_JOB cannot be expressed — and the runas child is created by a \
system service, not by this process's job.",
);
}
if flags.raw != 0 {
return unsupported(
"creation_flags() + elevate on Windows",
"the runas launch takes a show-command and no creation flags, so an arbitrary \
dwCreationFlags word cannot be expressed. no_window() is the one flag intent that \
survives here, lowered to the launch's show-command.",
);
}
Ok(())
}
#[cfg(windows)]
pub(crate) fn runas_show_command(
flags: &crate::command::flags::FlagsRequest,
) -> windows::Win32::UI::WindowsAndMessaging::SHOW_WINDOW_CMD {
use windows::Win32::UI::WindowsAndMessaging::{SW_HIDE, SW_SHOWNORMAL};
if flags.no_window {
SW_HIDE
} else {
SW_SHOWNORMAL
}
}
use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use windows::core::PCWSTR;
use windows::Win32::Foundation::{RPC_E_CHANGED_MODE, S_FALSE, S_OK};
use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE};
use windows::Win32::System::Threading::GetProcessId;
use windows::Win32::UI::Shell::{
ShellExecuteExW, SEE_MASK_CLASSNAME, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
};
use crate::child::drop_teardown::Torn;
use crate::child::owned::teardown::{Disposition, Past};
use crate::child::owned::OwnedChild;
use crate::child::spawn::held_teardown::tear_down_failed_spawn;
use crate::child::spawn::policy::SpawnPolicy;
use crate::child::spawn::windows_raw::resolve::ensure_no_nul_wide;
use crate::child::spawn::{Classify, Diagnosis, SpawnFailure};
use crate::containment::Attachment;
use crate::elevation::plan::Transition;
use crate::elevation::shell_file;
use crate::elevation::{ElevatedStdio, ElevatedVia, ElevationReport, Privilege};
use crate::error::ChildFate;
use crate::error::ElevationErrorKind;
use crate::identity::ProcessId;
use crate::os_process::windows::WindowsProcess;
fn hresult_cause(code: windows::core::HRESULT) -> std::sync::Arc<Error> {
let io = crate::error::win32_io_error(windows::core::Error::from_hresult(code));
let hr = code.0 as u32;
Error::io_cause(if hr & 0xFFFF_0000 == 0x8007_0000 {
io
} else {
crate::error::io_context(format!("HRESULT {hr:#010x}"), io)
})
}
pub(crate) fn shell_execute_failure(code: windows::core::HRESULT, inst_app: isize) -> SpawnFailure {
use super::runas_failure::{classify, RunasFailure};
let failed = || Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "ShellExecuteEx(runas) failed".into(),
source: Some(hresult_cause(code)),
};
match classify(code.0, inst_app) {
RunasFailure::Declined => SpawnFailure::NotStarted(Error::Elevation {
kind: ElevationErrorKind::AuthDeclined,
detail: "the UAC elevation prompt was declined".into(),
source: None,
}),
RunasFailure::BeforeLaunch => SpawnFailure::NotStarted(failed()),
RunasFailure::MayHaveLaunched => SpawnFailure::started(failed(), ChildFate::Unknown, None),
}
}
fn wide_nul(what: &str, s: &OsStr) -> Result<Vec<u16>, Error> {
ensure_no_nul_wide(what, s)?;
Ok(s.encode_wide().chain(std::iter::once(0)).collect())
}
pub(crate) enum RunasOutcome {
AlreadyElevated,
Launched {
owned: OwnedChild,
id: ProcessId,
report: ElevationReport,
},
}
struct ComInit {
uninit: bool,
}
impl ComInit {
fn init() -> Result<ComInit, Error> {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) };
if hr == S_OK || hr == S_FALSE {
Ok(ComInit { uninit: true })
} else if hr == RPC_E_CHANGED_MODE {
Ok(ComInit { uninit: false })
} else {
Err(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "CoInitializeEx failed before ShellExecuteEx".into(),
source: Some(hresult_cause(hr)),
})
}
}
}
impl Drop for ComInit {
fn drop(&mut self) {
if self.uninit {
unsafe { CoUninitialize() };
}
}
}
fn elevated_argv(cmd: &Command) -> Result<&[OsString], Error> {
super::elevation_argv(cmd, &ARGV_REFUSALS)
}
pub(crate) const ARGV_REFUSALS: super::ArgvRefusals = super::ArgvRefusals {
platform: "windows",
op_prefix: "elevation",
commandline: "runas elevation requires an argv command (set .args([...]))",
setter: super::SETTER_REFUSAL,
};
fn elevated_params(argv: &[OsString]) -> Result<OsString, Error> {
let mut tail_wide: Vec<Vec<u16>> = Vec::with_capacity(argv.len() - 1);
for (i, a) in argv.iter().enumerate().skip(1) {
ensure_no_nul_wide(&format!("argument {i}"), a)?;
tail_wide.push(a.encode_wide().collect());
}
let tail_refs: Vec<&[u16]> = tail_wide.iter().map(|v| v.as_slice()).collect();
Ok(OsString::from_wide(&crate::quote::windows::join_wide(&tail_refs)))
}
pub(crate) fn launch_runas(
cmd: &Command,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> Result<RunasOutcome, SpawnFailure> {
let request = cmd.elevation_request();
launch_runas_with_host(
cmd,
&Host::detect(request.backend, &request.auth, None, is_elevated()),
policy,
kernel,
)
}
pub(crate) struct RunasLaunch {
file_w: Vec<u16>,
class_w: Vec<u16>,
params_w: Vec<u16>,
dir_w: Option<Vec<u16>>,
verb_w: Vec<u16>,
show: windows::Win32::UI::WindowsAndMessaging::SHOW_WINDOW_CMD,
}
pub(crate) enum RunasStep {
AlreadyElevated,
Launch(Box<RunasLaunch>),
}
pub(crate) fn plan_runas(cmd: &Command, host: &Host) -> Result<RunasStep, Error> {
let req = cmd.elevation_request();
let (backend, auth) = (req.backend, req.auth.clone());
reject_unsupported_config(cmd)?;
let argv = elevated_argv(cmd)?; let program = &argv[0];
let file_w = wide_nul("program path", program.as_os_str())?;
let params = elevated_params(argv)?;
let dir = cmd
.cwd()
.map(|d| wide_nul("working directory", d.as_os_str()))
.transpose()?;
let params_w = wide_nul("argument line", params.as_os_str())?;
let verb_w = wide_nul("verb", OsStr::new("runas"))?;
let program_path = std::path::Path::new(program);
crate::child::spawn::reject_batch_path(program_path)?;
shell_file::reject_elevated_program(program_path)?;
if let Some(dir) = cmd.cwd() {
shell_file::reject_percent_in_directory(dir)?;
}
match host.plan(Privilege::Elevated, backend, auth) {
Transition::RunAsIs => return Ok(RunasStep::AlreadyElevated),
Transition::Reject { error } => return Err(error),
Transition::ElevatePosix { .. } => unreachable!("planner never yields ElevatePosix on a windows host"),
Transition::ElevateMacosGui { .. } => {
unreachable!("planner never yields ElevateMacosGui on a windows host")
}
Transition::ElevateWindows { .. } => {}
}
Ok(RunasStep::Launch(Box::new(RunasLaunch {
file_w,
class_w: wide_nul("class", OsStr::new("exefile"))?,
params_w,
dir_w: dir,
verb_w,
show: runas_show_command(cmd.flags_request()),
})))
}
pub(crate) type Unread = Result<(u32, windows::core::Error), windows::core::Error>;
pub(crate) fn end_untracked(owned: OwnedChild, unread: Unread, policy: SpawnPolicy) -> SpawnFailure {
let torn = tear_down_failed_spawn(
owned,
None,
Past::Clean,
Disposition::HandBack,
policy,
&mut Diagnosis::default(),
);
untracked_failure(unread, torn)
}
fn untracked_failure(unread: Unread, torn: Torn) -> SpawnFailure {
let (who, why, read_failure) = match unread {
Ok((pid, e)) => (
format!("the elevated child (pid {pid})"),
"its identity could not be resolved".to_string(),
e,
),
Err(e) => (
"the elevated child".to_string(),
"its pid could not be read (GetProcessId)".to_string(),
e,
),
};
let Torn {
fate,
unreaped,
cleanup,
} = torn;
let done = match fate {
ChildFate::Reaped => "; it was terminated or had exited, and its exit was collected",
ChildFate::Killed => "; it was terminated or exited, and its exit could not be collected",
ChildFate::Running { .. } => " and could not be terminated; it may still be running",
ChildFate::Gone | ChildFate::Unknown => "; what became of it could not be determined",
};
SpawnFailure::started(
Error::Elevation {
kind: ElevationErrorKind::Untracked,
detail: format!("{who} launched but {why}{done}"),
source: Some(Error::io_cause(crate::error::win32_io_error(read_failure))),
},
fate,
unreaped,
)
.with_cleanup(cleanup)
}
pub(crate) fn launch_runas_with_host(
cmd: &Command,
host: &Host,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> Result<RunasOutcome, SpawnFailure> {
let launch = match plan_runas(cmd, host).not_started()? {
RunasStep::AlreadyElevated => return Ok(RunasOutcome::AlreadyElevated),
RunasStep::Launch(launch) => launch,
};
let RunasLaunch {
file_w,
class_w,
params_w,
dir_w,
verb_w,
show,
} = *launch;
let com = ComInit::init().not_started()?;
let proc: OwnedHandle = unsafe {
let mut info = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC | SEE_MASK_CLASSNAME,
lpVerb: PCWSTR(verb_w.as_ptr()),
lpFile: PCWSTR(file_w.as_ptr()),
lpParameters: PCWSTR(params_w.as_ptr()),
lpDirectory: dir_w.as_ref().map_or(PCWSTR::null(), |d| PCWSTR(d.as_ptr())),
nShow: show.0,
lpClass: PCWSTR(class_w.as_ptr()),
..Default::default()
};
if let Err(e) = ShellExecuteExW(&mut info) {
return Err(shell_execute_failure(e.code(), info.hInstApp.0 as isize));
}
if info.hProcess.is_invalid() {
return Err(SpawnFailure::started(
Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "ShellExecuteEx(runas) returned no process handle".into(),
source: None,
},
ChildFate::Unknown,
None,
));
}
OwnedHandle::from_raw_handle(info.hProcess.0 as std::os::windows::io::RawHandle)
};
drop(com);
let pid = match unsafe { GetProcessId(HANDLE(proc.as_raw_handle())) } {
0 => Err(windows::core::Error::from_thread()),
pid => Ok(pid),
};
let report = ElevationReport {
via: ElevatedVia::WindowsUac,
stripped_env: Vec::new(),
stdio: ElevatedStdio::OwnConsole,
};
let owned = OwnedChild::new(
Box::new(WindowsProcess::for_uac(kernel, proc, pid.as_ref().ok().copied())),
report.tracked(),
);
let handle = HANDLE(owned.os_handle().as_raw_handle());
let tracked = match pid {
Ok(pid) => crate::identity::windows_identity_from_handle_result(handle, pid)
.map(|id| (pid, id))
.map_err(|e| Ok((pid, e))),
Err(e) => Err(Err(e)),
};
let id = match tracked {
Ok((_, id)) => id,
Err(unread) => {
return Err(end_untracked(owned, unread, policy));
}
};
Ok(RunasOutcome::Launched { owned, id, report })
}
pub(crate) fn spawn_elevated(
cmd: &mut Command,
kill_on_drop: bool,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> Result<crate::child::Child, SpawnFailure> {
match launch_runas(&*cmd, policy, std::sync::Arc::clone(&kernel))? {
RunasOutcome::AlreadyElevated => spawn_already_elevated(cmd, kill_on_drop, policy, kernel),
RunasOutcome::Launched { owned, id, report } => Ok(crate::child::Child::from_parts(
owned,
Some(id),
BTreeMap::new(),
kill_on_drop,
Attachment::uac_elevated(),
Some(report),
policy,
)),
}
}
fn spawn_already_elevated(
cmd: &mut Command,
kill_on_drop: bool,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> Result<crate::child::Child, SpawnFailure> {
let (input, env_ops) = (cmd.input().clone(), cmd.env_ops().to_vec());
let mut derived = cmd.derive_for_elevation(
input,
env_ops,
crate::elevation::already_elevated_report(ElevatedStdio::Passthrough),
);
crate::child::spawn::spawn_unelevated(&mut derived, kill_on_drop, policy, kernel)
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;