-
Notifications
You must be signed in to change notification settings - Fork 193
/
run_as_admin_snippet.rs
91 lines (75 loc) · 2.57 KB
/
run_as_admin_snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Ask the user to run the program with admin privileged.
Author @5mukx
*/
use std::process::Command;
use std::ptr::null_mut;
use winapi::um::shellapi::ShellExecuteW;
use winapi::um::winnt::{HANDLE, TOKEN_ELEVATION, TOKEN_QUERY};
use winapi::um::processthreadsapi::OpenProcessToken;
use winapi::um::securitybaseapi::GetTokenInformation;
use winapi::um::winuser::{MessageBoxW, MB_ICONERROR, MB_OK};
fn is_running_as_admin() -> bool {
unsafe {
let mut token_handle: HANDLE = null_mut();
if OpenProcessToken(
winapi::um::processthreadsapi::GetCurrentProcess(),
TOKEN_QUERY,
&mut token_handle,
) == 0
{
return false;
}
let mut elevation: TOKEN_ELEVATION = std::mem::zeroed();
let mut size = 0;
let success = GetTokenInformation(
token_handle,
winapi::um::winnt::TokenElevation,
&mut elevation as *mut _ as *mut _,
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
&mut size,
) != 0;
winapi::um::handleapi::CloseHandle(token_handle);
success && elevation.TokenIsElevated != 0
}
}
fn run_as_admin() {
unsafe {
let current_exe = std::env::current_exe().unwrap();
let current_exe_wide: Vec<u16> = current_exe
.to_string_lossy()
.encode_utf16()
.chain(Some(0))
.collect();
ShellExecuteW(
null_mut(),
"runas\0".encode_utf16().chain(Some(0)).collect::<Vec<u16>>().as_ptr(),
current_exe_wide.as_ptr(),
null_mut(),
null_mut(),
winapi::um::winuser::SW_SHOWNORMAL,
);
}
}
fn main() {
// Avoid infinite relaunches
let elevated_env_var = "RUNNING_ELEVATED";
if std::env::var(elevated_env_var).is_err() {
if !is_running_as_admin() {
println!("This program requires administrator privileges.");
unsafe {
MessageBoxW(
null_mut(),
"Please run the program as Administrator.".encode_utf16().chain(Some(0)).collect::<Vec<u16>>().as_ptr(),
"Administrator Access Required".encode_utf16().chain(Some(0)).collect::<Vec<u16>>().as_ptr(),
MB_ICONERROR | MB_OK,
);
}
std::env::set_var(elevated_env_var, "1");
run_as_admin();
std::process::exit(0);
}
}
// Your privileged operations here
println!("Running with administrator privileges!");
}