Skip to main content

win_custody/
process.rs

1//! Process handles with a fixed rights set, and elevation.
2#![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/// The rights a [`Process`] handle carries.
35///
36/// Each variant is a fixed rights set. [`Process::open`] cannot request
37/// [`ProcessAccess::AsCreated`]: full access is only available on a process
38/// this one created, so a reused PID can never be reopened with it.
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40#[non_exhaustive]
41pub enum ProcessAccess {
42    /// `PROCESS_QUERY_LIMITED_INFORMATION`: identity and exit-code queries.
43    QueryLimited,
44    /// `SYNCHRONIZE`: waiting for exit.
45    Synchronize,
46    /// Identity queries and waiting for exit.
47    QueryLimitedAndSynchronize,
48    /// Identity queries, waiting for exit, and `PROCESS_TERMINATE`.
49    Terminate,
50    /// The rights the creating call granted: everything.
51    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/// An open process handle with a fixed rights set.
67///
68/// The handle names one process object for its whole life, so unlike a PID
69/// it cannot start pointing at an unrelated process after the original exits.
70#[derive(Debug)]
71pub struct Process {
72    handle: OwnedHandle,
73    access: ProcessAccess,
74}
75
76impl Process {
77    /// Opens `pid` with exactly `access`. The error carries the Win32 code; a
78    /// PID that has left the process table reports `ERROR_INVALID_PARAMETER`.
79    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        // SAFETY: OpenProcess takes plain integers and returns a new handle or
87        // null; no memory is shared with the callee.
88        let handle = unsafe { OpenProcess(access.rights(), 0, pid) };
89        Ok(Self {
90            handle: owned_from_creation(handle)?,
91            access,
92        })
93    }
94
95    /// Duplicates the handle `std` holds for `child`. The result keeps every
96    /// right `CreateProcess` granted (job assignment and termination among
97    /// them, which a reopen by PID would not get).
98    pub fn from_child(child: &std::process::Child) -> io::Result<Self> {
99        let mut duplicate = ptr::null_mut();
100        // SAFETY: the source handle is the live one `child` owns for the
101        // duration of this call, both process arguments are the current
102        // process pseudo-handle, and `duplicate` is a local out value.
103        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    /// Starts `executable` through the shell's `runas` verb, which shows the
124    /// elevation prompt, and returns the process the shell created.
125    ///
126    /// Each argument is quoted the way `CommandLineToArgvW` parses it, so it
127    /// reaches the child unchanged. The child's window starts hidden. A user
128    /// who declines the prompt makes this fail with `ERROR_CANCELLED` (1223)
129    /// as the Win32 code.
130    ///
131    /// The shell may need COM: call this from a thread that has initialized
132    /// COM if the target is not a plain executable.
133    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        // SAFETY: `info` is fully initialised; its string pointers address
155        // NUL-terminated buffers that outlive the call, and the shell writes
156        // only `hProcess` and `hInstApp` back into it.
157        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    /// The rights this handle carries.
176    pub fn access(&self) -> ProcessAccess {
177        self.access
178    }
179
180    /// The process identifier behind the handle.
181    pub fn pid(&self) -> io::Result<u32> {
182        // SAFETY: the handle is live; the call takes no pointers.
183        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    /// The creation time as a 64-bit `FILETIME` value. Together with the PID it
191    /// identifies a process across its whole lifetime, which a PID alone does
192    /// not, since Windows reuses PIDs.
193    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        // SAFETY: the handle is live and every out pointer refers to a local
199        // `FILETIME` that outlives the call.
200        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    /// The exit code, or `None` while the process is still running.
210    ///
211    /// A process may itself exit with code 259 (`STILL_ACTIVE`). When the
212    /// handle carries `SYNCHRONIZE`, a zero-length wait tells that case apart
213    /// from a running process; without it, 259 is reported as running.
214    pub fn exit_code(&self) -> io::Result<Option<u32>> {
215        let mut exit_code = 0_u32;
216        // SAFETY: the handle is live; the out pointer is a local `u32`.
217        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    /// Whether this process token is an AppContainer token.
230    pub fn is_app_container(&self) -> io::Result<bool> {
231        let mut token = ptr::null_mut();
232        // SAFETY: `self` owns a live process handle and `token` is a local
233        // output pointer. The returned token handle is owned below.
234        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        // SAFETY: `token` is live and both output pointers name initialized
241        // local storage of the documented sizes.
242        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    /// The full Win32 path of the process image.
264    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        // SAFETY: the handle is live; `buffer` is writable for `length` units,
268        // and the API updates `length` with the number of units written.
269        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    /// The Terminal Services session the process runs in.
291    pub fn session_id(&self) -> io::Result<u32> {
292        crate::session::process_session_id(self.pid()?)
293    }
294
295    /// Terminates the process with `exit_code`.
296    pub fn terminate(&self, exit_code: u32) -> io::Result<()> {
297        // SAFETY: the handle is live; the call takes no pointers.
298        if unsafe { TerminateProcess(self.raw(), exit_code) } == 0 {
299            return Err(io::Error::last_os_error());
300        }
301        Ok(())
302    }
303
304    /// Waits for the process to exit. `None` waits forever.
305    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
332/// Whether the calling process runs with an elevated (full administrator)
333/// token.
334pub fn is_elevated() -> io::Result<bool> {
335    let mut token = ptr::null_mut();
336    // SAFETY: the process pseudo-handle is always valid and `token` is a local
337    // out pointer whose handle is owned immediately below.
338    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
345/// Reads `TokenElevation` from a token opened with `TOKEN_QUERY`.
346pub(crate) fn token_is_elevated(token: RawHandle) -> io::Result<bool> {
347    let mut elevation = TOKEN_ELEVATION::default();
348    let mut returned = 0_u32;
349    // SAFETY: the caller lends a live token handle; the buffer pointer and
350    // length describe exactly the local TOKEN_ELEVATION value.
351    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        // PIDs are multiples of four; an odd value is never assigned.
396        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}