|
| 1 | +#[cfg(target_family = "windows")] |
| 2 | +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; |
| 3 | +#[cfg(target_family = "windows")] |
| 4 | +use windows_sys::Win32::Security::{ |
| 5 | + GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation, |
| 6 | +}; |
| 7 | +#[cfg(target_family = "windows")] |
| 8 | +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; |
| 9 | + |
| 10 | +#[derive(Debug, thiserror::Error)] |
| 11 | +#[error("{0}")] |
| 12 | +pub struct IsElevatedError(String); |
| 13 | + |
| 14 | +pub fn is_elevated() -> Result<bool, IsElevatedError> { |
| 15 | + #[cfg(target_family = "unix")] |
| 16 | + return Ok(nix::unistd::Uid::effective().is_root()); |
| 17 | + |
| 18 | + #[cfg(target_family = "windows")] |
| 19 | + is_elevated_windows() |
| 20 | +} |
| 21 | + |
| 22 | +#[cfg(target_family = "windows")] |
| 23 | +fn is_elevated_windows() -> Result<bool, IsElevatedError> { |
| 24 | + unsafe { |
| 25 | + let mut token_handle: HANDLE = std::ptr::null_mut(); |
| 26 | + let process = GetCurrentProcess(); |
| 27 | + |
| 28 | + // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocesstoken |
| 29 | + // An access token contains the security information for a logon session and every process |
| 30 | + // executed on behalf of the user has a copy of the token. Here we get that token. |
| 31 | + if OpenProcessToken(process, TOKEN_QUERY, &mut token_handle) == 0 { |
| 32 | + return Err(IsElevatedError("Failed to open process token.".to_string())); |
| 33 | + } |
| 34 | + |
| 35 | + let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 }; |
| 36 | + let mut return_length = 0; |
| 37 | + |
| 38 | + // https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation |
| 39 | + // GetTokenInformation requires a pointer to a buffer (elevation) the function fills with the requested information. |
| 40 | + // The second parameter is the class (TokenElevation) we want to get information from the Token. |
| 41 | + let result = GetTokenInformation( |
| 42 | + token_handle, |
| 43 | + TokenElevation, |
| 44 | + &mut elevation as *mut _ as *mut _, |
| 45 | + std::mem::size_of::<TOKEN_ELEVATION>() as u32, |
| 46 | + &mut return_length, |
| 47 | + ); |
| 48 | + |
| 49 | + CloseHandle(token_handle); |
| 50 | + |
| 51 | + if result == 0 { |
| 52 | + return Err(IsElevatedError( |
| 53 | + "Failed to get token information to check user rights.".to_string(), |
| 54 | + )); |
| 55 | + } |
| 56 | + |
| 57 | + Ok(elevation.TokenIsElevated != 0) |
| 58 | + } |
| 59 | +} |
0 commit comments