1#![allow(unsafe_code)]
3
4use std::ffi::{OsStr, OsString};
5use std::io;
6use std::mem::size_of;
7use std::os::windows::ffi::OsStringExt;
8use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
9use std::path::{Path, PathBuf};
10use std::ptr;
11use std::time::Duration;
12
13use windows_sys::Win32::Foundation::{
14 DuplicateHandle, DUPLICATE_SAME_ACCESS, FILETIME, STILL_ACTIVE,
15};
16use windows_sys::Win32::Security::{
17 GetTokenInformation, TokenElevation, TokenIsAppContainer, TOKEN_ELEVATION, TOKEN_QUERY,
18};
19use windows_sys::Win32::Storage::FileSystem::SYNCHRONIZE;
20use windows_sys::Win32::System::Threading::{
21 GetExitCodeProcess, GetProcessId, GetProcessTimes, OpenProcess, OpenProcessToken,
22 QueryFullProcessImageNameW, TerminateProcess, PROCESS_NAME_WIN32,
23 PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE,
24};
25use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW};
26use windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE;
27
28use crate::handle::{current_process, owned_from_creation, wait, WaitOutcome};
29use crate::launch::command_line_tail;
30use crate::wide::wide_null;
31
32const MAX_IMAGE_PATH_UNITS: usize = 32_768;
33
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub enum ProcessAccess {
42 QueryLimited,
44 Synchronize,
46 QueryLimitedAndSynchronize,
48 Terminate,
50 AsCreated,
52}
53
54impl ProcessAccess {
55 fn rights(self) -> u32 {
56 match self {
57 Self::QueryLimited => PROCESS_QUERY_LIMITED_INFORMATION,
58 Self::Synchronize => SYNCHRONIZE,
59 Self::QueryLimitedAndSynchronize => PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
60 Self::Terminate => PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE | PROCESS_TERMINATE,
61 Self::AsCreated => 0,
62 }
63 }
64}
65
66#[derive(Debug)]
71pub struct Process {
72 handle: OwnedHandle,
73 access: ProcessAccess,
74}
75
76impl Process {
77 pub fn open(pid: u32, access: ProcessAccess) -> io::Result<Self> {
80 if access == ProcessAccess::AsCreated {
81 return Err(io::Error::new(
82 io::ErrorKind::InvalidInput,
83 "full access is only available on a process this one created",
84 ));
85 }
86 let handle = unsafe { OpenProcess(access.rights(), 0, pid) };
89 Ok(Self {
90 handle: owned_from_creation(handle)?,
91 access,
92 })
93 }
94
95 pub fn from_child(child: &std::process::Child) -> io::Result<Self> {
99 let mut duplicate = ptr::null_mut();
100 let duplicated = unsafe {
104 DuplicateHandle(
105 current_process(),
106 child.as_raw_handle(),
107 current_process(),
108 &mut duplicate,
109 0,
110 0,
111 DUPLICATE_SAME_ACCESS,
112 )
113 };
114 if duplicated == 0 {
115 return Err(io::Error::last_os_error());
116 }
117 Ok(Self {
118 handle: owned_from_creation(duplicate)?,
119 access: ProcessAccess::AsCreated,
120 })
121 }
122
123 pub fn launch_elevated<I, S>(executable: &Path, arguments: I) -> io::Result<Self>
134 where
135 I: IntoIterator<Item = S>,
136 S: AsRef<OsStr>,
137 {
138 let arguments: Vec<OsString> = arguments
139 .into_iter()
140 .map(|argument| argument.as_ref().to_owned())
141 .collect();
142 let verb = wide_null("runas")?;
143 let file = wide_null(executable)?;
144 let parameters = command_line_tail(&arguments)?;
145 let mut info = SHELLEXECUTEINFOW {
146 cbSize: size_of::<SHELLEXECUTEINFOW>() as u32,
147 fMask: SEE_MASK_NOCLOSEPROCESS,
148 lpVerb: verb.as_ptr(),
149 lpFile: file.as_ptr(),
150 lpParameters: parameters.as_ptr(),
151 nShow: SW_HIDE,
152 ..Default::default()
153 };
154 if unsafe { ShellExecuteExW(&mut info) } == 0 {
158 return Err(io::Error::last_os_error());
159 }
160 if info.hProcess.is_null() {
161 return Err(io::Error::other(
162 "the shell started the target without returning a process handle",
163 ));
164 }
165 Ok(Self {
166 handle: owned_from_creation(info.hProcess)?,
167 access: ProcessAccess::AsCreated,
168 })
169 }
170
171 pub(crate) fn from_owned(handle: OwnedHandle, access: ProcessAccess) -> Self {
172 Self { handle, access }
173 }
174
175 pub fn access(&self) -> ProcessAccess {
177 self.access
178 }
179
180 pub fn pid(&self) -> io::Result<u32> {
182 let pid = unsafe { GetProcessId(self.raw()) };
184 if pid == 0 {
185 return Err(io::Error::last_os_error());
186 }
187 Ok(pid)
188 }
189
190 pub fn creation_time(&self) -> io::Result<u64> {
194 let mut creation = FILETIME::default();
195 let mut exit = FILETIME::default();
196 let mut kernel = FILETIME::default();
197 let mut user = FILETIME::default();
198 let queried = unsafe {
201 GetProcessTimes(self.raw(), &mut creation, &mut exit, &mut kernel, &mut user)
202 };
203 if queried == 0 {
204 return Err(io::Error::last_os_error());
205 }
206 Ok((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
207 }
208
209 pub fn exit_code(&self) -> io::Result<Option<u32>> {
215 let mut exit_code = 0_u32;
216 if unsafe { GetExitCodeProcess(self.raw(), &mut exit_code) } == 0 {
218 return Err(io::Error::last_os_error());
219 }
220 if exit_code == STILL_ACTIVE as u32 {
221 match wait(self, Some(Duration::ZERO)) {
222 Ok(WaitOutcome::Signaled | WaitOutcome::Abandoned) => {}
223 Ok(WaitOutcome::TimedOut) | Err(_) => return Ok(None),
224 }
225 }
226 Ok(Some(exit_code))
227 }
228
229 pub fn is_app_container(&self) -> io::Result<bool> {
231 let mut token = ptr::null_mut();
232 if unsafe { OpenProcessToken(self.handle.as_raw_handle(), TOKEN_QUERY, &mut token) } == 0 {
235 return Err(io::Error::last_os_error());
236 }
237 let token = owned_from_creation(token)?;
238 let mut is_app_container = 0_u32;
239 let mut returned = 0_u32;
240 if unsafe {
243 GetTokenInformation(
244 token.as_raw_handle(),
245 TokenIsAppContainer,
246 (&mut is_app_container as *mut u32).cast(),
247 size_of::<u32>() as u32,
248 &mut returned,
249 )
250 } == 0
251 {
252 return Err(io::Error::last_os_error());
253 }
254 if returned as usize != size_of::<u32>() {
255 return Err(io::Error::new(
256 io::ErrorKind::InvalidData,
257 "Windows returned a truncated AppContainer token flag",
258 ));
259 }
260 Ok(is_app_container != 0)
261 }
262
263 pub fn image_path(&self) -> io::Result<PathBuf> {
265 let mut buffer = vec![0_u16; MAX_IMAGE_PATH_UNITS];
266 let mut length = buffer.len() as u32;
267 let queried = unsafe {
270 QueryFullProcessImageNameW(
271 self.raw(),
272 PROCESS_NAME_WIN32,
273 buffer.as_mut_ptr(),
274 &mut length,
275 )
276 };
277 if queried == 0 {
278 return Err(io::Error::last_os_error());
279 }
280 if length == 0 || length as usize >= buffer.len() {
281 return Err(io::Error::new(
282 io::ErrorKind::InvalidData,
283 "process image path length is out of range",
284 ));
285 }
286 buffer.truncate(length as usize);
287 Ok(PathBuf::from(OsString::from_wide(&buffer)))
288 }
289
290 pub fn session_id(&self) -> io::Result<u32> {
292 crate::session::process_session_id(self.pid()?)
293 }
294
295 pub fn terminate(&self, exit_code: u32) -> io::Result<()> {
297 if unsafe { TerminateProcess(self.raw(), exit_code) } == 0 {
299 return Err(io::Error::last_os_error());
300 }
301 Ok(())
302 }
303
304 pub fn wait(&self, timeout: Option<Duration>) -> io::Result<WaitOutcome> {
306 wait(self, timeout)
307 }
308
309 fn raw(&self) -> RawHandle {
310 self.handle.as_raw_handle()
311 }
312}
313
314impl AsHandle for Process {
315 fn as_handle(&self) -> BorrowedHandle<'_> {
316 self.handle.as_handle()
317 }
318}
319
320impl AsRawHandle for Process {
321 fn as_raw_handle(&self) -> RawHandle {
322 self.raw()
323 }
324}
325
326impl From<Process> for OwnedHandle {
327 fn from(process: Process) -> Self {
328 process.handle
329 }
330}
331
332pub fn is_elevated() -> io::Result<bool> {
335 let mut token = ptr::null_mut();
336 if unsafe { OpenProcessToken(current_process(), TOKEN_QUERY, &mut token) } == 0 {
339 return Err(io::Error::last_os_error());
340 }
341 let token = owned_from_creation(token)?;
342 token_is_elevated(token.as_raw_handle())
343}
344
345pub(crate) fn token_is_elevated(token: RawHandle) -> io::Result<bool> {
347 let mut elevation = TOKEN_ELEVATION::default();
348 let mut returned = 0_u32;
349 let queried = unsafe {
352 GetTokenInformation(
353 token,
354 TokenElevation,
355 (&mut elevation as *mut TOKEN_ELEVATION).cast(),
356 size_of::<TOKEN_ELEVATION>() as u32,
357 &mut returned,
358 )
359 };
360 if queried == 0 {
361 return Err(io::Error::last_os_error());
362 }
363 Ok(elevation.TokenIsElevated != 0)
364}
365
366#[cfg(test)]
367mod tests {
368 use std::time::Duration;
369
370 use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
371
372 use super::{is_elevated, Process, ProcessAccess};
373 use crate::handle::WaitOutcome;
374
375 #[test]
376 fn the_current_process_opens_and_reports_its_identity() {
377 let process = Process::open(std::process::id(), ProcessAccess::QueryLimited).unwrap();
378 assert_eq!(process.pid().unwrap(), std::process::id());
379 assert_eq!(process.exit_code().unwrap(), None);
380 assert!(process.creation_time().unwrap() > 0);
381 assert_eq!(
382 process.image_path().unwrap(),
383 std::env::current_exe().unwrap()
384 );
385 }
386
387 #[test]
388 fn full_access_cannot_be_requested_by_pid() {
389 let error = Process::open(std::process::id(), ProcessAccess::AsCreated).unwrap_err();
390 assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
391 }
392
393 #[test]
394 fn a_vanished_pid_reports_invalid_parameter() {
395 let error = Process::open(u32::MAX - 2, ProcessAccess::QueryLimited).unwrap_err();
397 assert_eq!(error.raw_os_error(), Some(ERROR_INVALID_PARAMETER as i32));
398 }
399
400 #[test]
401 fn a_std_child_is_adopted_with_its_creation_rights() {
402 let mut child = std::process::Command::new("cmd")
403 .args(["/d", "/c", "exit 5"])
404 .spawn()
405 .unwrap();
406 let process = Process::from_child(&child).unwrap();
407 assert_eq!(process.access(), ProcessAccess::AsCreated);
408 assert_eq!(
409 process.wait(Some(Duration::from_secs(30))).unwrap(),
410 WaitOutcome::Signaled
411 );
412 assert_eq!(process.exit_code().unwrap(), Some(5));
413 child.wait().unwrap();
414 }
415
416 #[test]
417 fn elevation_is_readable() {
418 is_elevated().unwrap();
419 }
420}