Certainly! Below is the Rust code that replicates the functionality of your PowerShell script. This Rust program performs the following tasks:
- Checks for Administrative Privileges: If the program is not running as an administrator, it restarts itself with elevated privileges.
- Manages VMware Services: It starts the specified VMware services and sets their startup type to manual if they are not already set.
- Enables VMware Network Adapters: It enables network adapters that are associated with VMware.
- Launches VMware Workstation: It starts VMware Workstation and waits for it to exit.
- Cleans Up: After VMware Workstation exits, it stops the VMware services and disables the VMware network adapters.
Rust Code:
use std::ffi::OsStr;
use std::io::{self, Error};
use std::os::windows::ffi::OsStrExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::ptr::null_mut;
use std::thread;
use std::time::Duration;
use windows::{
core::PCWSTR,
Win32::{
Foundation::{CloseHandle, ERROR_INSUFFICIENT_BUFFER, HANDLE},
NetworkManagement::NetManagement::{
NetConnectionProps, NLM_CONNECTIVITY, NLM_ENUM_NETWORK, NLM_NETWORK_CATEGORY,
NLM_NETWORK_PROPERTY_CHANGE,
},
Security::{
CheckTokenMembership, AllocateAndInitializeSid, FreeSid, WinBuiltinAdministratorsSid,
SECURITY_NT_AUTHORITY, SID_IDENTIFIER_AUTHORITY,
},
System::{
Services::{
ChangeServiceConfigW, ControlService, OpenSCManagerW, OpenServiceW,
QueryServiceConfigW, StartServiceW, ControlServiceExW, SC_MANAGER_ALL_ACCESS,
SERVICE_CONFIG_DESCRIPTION, SERVICE_CONTROL_STOP, SERVICE_NO_CHANGE,
SERVICE_QUERY_CONFIG, SERVICE_START, SERVICE_STOP, SERVICE_STATUS,
SERVICE_STATUS_PROCESS, SERVICE_STOPPED,
},
Threading::{GetCurrentProcess, WaitForSingleObject, INFINITE},
},
UI::Shell::{
ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS, SW_SHOW,
},
},
};
fn main() -> io::Result<()> {
if !is_running_as_admin()? {
elevate()?;
return Ok(());
}
let vmware_services = vec![
"VMware Authorization Service",
"VMware Autostart Service",
"VMware DHCP Service",
"VMware NAT Service",
"VMware USB Arbitration Service",
];
start_vmware_services(&vmware_services)?;
enable_vmware_adapters()?;
// Start VMware Workstation
let vmware_path = r"C:\Program Files (x86)\VMware\VMware Workstation\vmware.exe";
let mut vmware_process = Command::new(vmware_path)
.spawn()
.expect("Failed to start VMware Workstation.");
// Wait for VMware Workstation to exit
vmware_process
.wait()
.expect("Failed to wait on VMware Workstation.");
stop_vmware_services(&vmware_services)?;
disable_vmware_adapters()?;
Ok(())
}
fn is_running_as_admin() -> io::Result<bool> {
unsafe {
let mut is_admin = false;
let mut nt_authority = SID_IDENTIFIER_AUTHORITY { Value: [0, 0, 0, 0, 0, 5] };
let mut administrators_group = null_mut();
let result = AllocateAndInitializeSid(
&nt_authority,
2,
32,
544,
0,
0,
0,
0,
0,
0,
&mut administrators_group,
);
if !result.as_bool() {
return Err(Error::last_os_error());
}
let result = CheckTokenMembership(
None,
administrators_group,
&mut is_admin as *mut _ as *mut _,
);
FreeSid(administrators_group);
if !result.as_bool() {
return Err(Error::last_os_error());
}
Ok(is_admin)
}
}
fn elevate() -> io::Result<()> {
use windows::Win32::{
System::Threading::GetCurrentProcessId,
UI::WindowsAndMessaging::SW_NORMAL,
};
let exe = std::env::current_exe()?;
let exe_str: Vec<u16> = exe.as_os_str().encode_wide().chain(Some(0)).collect();
let lp_verb = to_pwstr("runas");
let mut sei = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
fMask: SEE_MASK_NOCLOSEPROCESS,
hwnd: None,
lpVerb: lp_verb,
lpFile: PCWSTR(exe_str.as_ptr()),
lpParameters: PCWSTR::null(),
lpDirectory: PCWSTR::null(),
nShow: SW_SHOW.0 as i32,
..Default::default()
};
let result = unsafe { ShellExecuteExW(&mut sei) };
if !result.as_bool() {
return Err(Error::last_os_error());
} else {
let h_process = sei.hProcess;
unsafe { WaitForSingleObject(h_process, INFINITE) };
unsafe { CloseHandle(h_process) };
std::process::exit(0);
}
}
fn to_pwstr(s: &str) -> PCWSTR {
let wide: Vec<u16> = OsStr::new(s).encode_wide().chain(Some(0)).collect();
PCWSTR(wide.as_ptr())
}
fn start_vmware_services(services: &[&str]) -> io::Result<()> {
unsafe {
let scm_handle = OpenSCManagerW(None, None, SC_MANAGER_ALL_ACCESS);
if scm_handle.0 == 0 {
return Err(Error::last_os_error());
}
for service_name in services {
let service_name_wide = to_pwstr(service_name);
let service_handle = OpenServiceW(
scm_handle,
service_name_wide,
SERVICE_QUERY_CONFIG | SERVICE_START,
);
if service_handle.0 == 0 {
eprintln!("Failed to open service: {}", service_name);
continue;
}
// Query current service configuration
let mut bytes_needed = 0;
let query_result = QueryServiceConfigW(
service_handle,
None,
0,
&mut bytes_needed,
);
if !query_result.as_bool() && Error::last_os_error().raw_os_error().unwrap() != ERROR_INSUFFICIENT_BUFFER.0 as i32 {
eprintln!("Failed to query service config: {}", service_name);
CloseServiceHandle(service_handle);
continue;
}
let mut config_buffer = vec![0u8; bytes_needed as usize];
let service_config = config_buffer.as_mut_ptr() as *mut windows::Win32::System::Services::QUERY_SERVICE_CONFIGW;
let query_result = QueryServiceConfigW(
service_handle,
Some(service_config),
bytes_needed,
&mut bytes_needed,
);
if !query_result.as_bool() {
eprintln!("Failed to query service config: {}", service_name);
CloseServiceHandle(service_handle);
continue;
}
let config = &*service_config;
// Change startup type to Manual if not already
if config.dwStartType != windows::Win32::System::Services::SERVICE_START_TYPE(SERVICE_NO_CHANGE) {
let change_result = ChangeServiceConfigW(
service_handle,
windows::Win32::System::Services::SERVICE_NO_CHANGE,
windows::Win32::System::Services::SERVICE_DEMAND_START,
windows::Win32::System::Services::SERVICE_ERROR_IGNORE,
None,
None,
None,
None,
None,
None,
None,
);
if !change_result.as_bool() {
eprintln!("Failed to change startup type for service: {}", service_name);
}
}
// Start the service
let start_result = StartServiceW(service_handle, &[]);
if !start_result.as_bool() {
eprintln!("Failed to start service: {}", service_name);
} else {
println!("Started service: {}", service_name);
}
CloseServiceHandle(service_handle);
}
CloseServiceHandle(scm_handle);
}
Ok(())
}
fn stop_vmware_services(services: &[&str]) -> io::Result<()> {
unsafe {
let scm_handle = OpenSCManagerW(None, None, SC_MANAGER_ALL_ACCESS);
if scm_handle.0 == 0 {
return Err(Error::last_os_error());
}
for service_name in services {
let service_name_wide = to_pwstr(service_name);
let service_handle = OpenServiceW(
scm_handle,
service_name_wide,
SERVICE_STOP | SERVICE_QUERY_STATUS,
);
if service_handle.0 == 0 {
eprintln!("Failed to open service: {}", service_name);
continue;
}
// Stop the service
let mut service_status = SERVICE_STATUS::default();
let stop_result = ControlService(
service_handle,
SERVICE_CONTROL_STOP,
&mut service_status,
);
if !stop_result.as_bool() {
eprintln!("Failed to stop service: {}", service_name);
} else {
println!("Stopped service: {}", service_name);
}
CloseServiceHandle(service_handle);
}
CloseServiceHandle(scm_handle);
}
Ok(())
}
fn enable_vmware_adapters() -> io::Result<()> {
// Get all network adapters and enable those with "VMware" in the description
let output = Command::new("PowerShell")
.args(&[
"-Command",
"Get-NetAdapter | Where-Object { $_.InterfaceDescription -Like '*VMware*' } | Enable-NetAdapter -Confirm:$false",
])
.stdout(Stdio::null())
.output()?;
if !output.status.success() {
eprintln!("Failed to enable VMware network adapters.");
return Err(Error::new(
io::ErrorKind::Other,
"Failed to enable VMware network adapters.",
));
} else {
println!("Enabled VMware network adapters.");
}
Ok(())
}
fn disable_vmware_adapters() -> io::Result<()> {
// Get all network adapters and disable those with "VMware" in the description
let output = Command::new("PowerShell")
.args(&[
"-Command",
"Get-NetAdapter | Where-Object { $_.InterfaceDescription -Like '*VMware*' } | Disable-NetAdapter -Confirm:$false",
])
.stdout(Stdio::null())
.output()?;
if !output.status.success() {
eprintln!("Failed to disable VMware network adapters.");
return Err(Error::new(
io::ErrorKind::Other,
"Failed to disable VMware network adapters.",
));
} else {
println!("Disabled VMware network adapters.");
}
Ok(())
}
Explanation:
-
Administrative Privilege Check and Elevation:
- The
is_running_as_admin() function checks if the current process has administrative privileges by using Windows APIs like AllocateAndInitializeSid and CheckTokenMembership.
- If not running as admin, the
elevate() function restarts the executable with elevated privileges using ShellExecuteExW with the runas verb.
-
Service Management Functions:
start_vmware_services():
- Opens the Service Control Manager with
OpenSCManagerW.
- Iterates through the list of VMware services, opens each service, queries its current configuration, and changes the startup type to manual if necessary using
ChangeServiceConfigW.
- Starts the service with
StartServiceW.
stop_vmware_services():
- Similar to the start function but sends a stop control code to each service using
ControlService.
-
Network Adapter Management:
enable_vmware_adapters() and disable_vmware_adapters():
- Executes PowerShell commands to enable or disable network adapters that have "VMware" in their interface description.
- Uses
Get-NetAdapter, filters with Where-Object, and then enables or disables using Enable-NetAdapter or Disable-NetAdapter.
-
Main Function Workflow:
- Checks for administrative rights and elevates if necessary.
- Starts VMware services and enables the adapters.
- Launches VMware Workstation and waits for it to exit.
- Stops the VMware services and disables the adapters after VMware Workstation exits.
Additional Notes:
-
Dependencies in Cargo.toml:
You need to add the following dependencies to your Cargo.toml file:
[dependencies]
windows = "0.48"
The windows crate provides bindings to Windows APIs.
-
Error Handling:
The code includes basic error handling. In a production environment, you may want to handle errors more gracefully and provide more detailed logging.
-
Safety and Unsafety:
Interacting with Windows APIs often requires unsafe blocks. Ensure you understand the implications of using unsafe code and handle pointers and handles correctly to avoid memory leaks or crashes.
-
Testing:
Test the code in a safe environment as it modifies system services and network adapters, which can affect system stability.
-
VMware Adapter Names:
The PowerShell commands in the enable_vmware_adapters() and disable_vmware_adapters() functions assume that all VMware network adapters have "VMware" in their interface description. Adjust the filter if your adapters have different naming conventions.
-
Administrative Privileges:
Running this program will prompt for administrative privileges due to the modifications to system services and network adapters.
Disclaimer:
Modifying system services and network configurations can have unintended consequences. Use this code responsibly and ensure you have backups or restore points as necessary. Always test in a controlled environment before deploying to production systems.