diff --git a/src/platform/windows/installer_files.rs b/src/platform/windows/installer_files.rs index a4eaaaf08..20755e41a 100644 --- a/src/platform/windows/installer_files.rs +++ b/src/platform/windows/installer_files.rs @@ -82,8 +82,8 @@ impl ProtectedInstallFile { } pub(super) fn release(&mut self) { - // cmd.exe cannot read/copy these files while a DELETE handle is open. - // The handoff gate keeps it waiting until every staged handle is closed. + // cmd.exe cannot read/copy these files while a DELETE handle is open, so every + // staged handle is closed before the elevated cmd starts. drop(self.cleanup_handle.take()); } } diff --git a/src/platform/windows/installer_handoff.rs b/src/platform/windows/installer_handoff.rs index 3fc384c2c..33424dc03 100644 --- a/src/platform/windows/installer_handoff.rs +++ b/src/platform/windows/installer_handoff.rs @@ -1,5 +1,4 @@ pub(super) mod directory; -mod gate; use super::{ installer_files::ProtectedInstallFile, @@ -10,7 +9,6 @@ use super::{ }, validate_install_app_name, ResultType, }; -use gate::InstallGate; use hbb_common::{bail, log}; use std::{fs, io, path::Path}; @@ -82,14 +80,9 @@ fn write_install_script(cmds: InstallCommands, path: &Path) -> ResultType ResultType { +fn protected_install_parameters(script: &InstallCommandScript) -> ResultType { let path = path_for_cmd_environment(script.file.path())?; - let pipe = gate.name(); - let parameters = - format!("/D /E:ON /V:OFF /C \"set /p RUSTDESK_HANDOFF=<\"{pipe}\" >nul && \"{path}\"\""); + let parameters = format!("/D /E:ON /V:OFF /C \"\"{path}\"\""); let length = parameters.encode_utf16().count(); if length >= WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS { bail!("Elevated command is too long: {length} UTF-16 characters"); @@ -103,9 +96,13 @@ pub(super) fn run_cmds(cmds: impl Into, show: bool, tip: &str) let directory = path.with_extension("bat.dir"); let mut script = write_install_script(cmds.into(), &path)?; let cmd_path = get_system_executable(CMD_RELATIVE_PATH)?; - let gate = InstallGate::new()?; - let parameters = protected_install_parameters(&script, &gate)?; + let parameters = protected_install_parameters(&script)?; directory::create(&directory)?; + // cmd cannot open the BAT or copy its inputs while a DELETE-capable handle is open, so + // close them before launching it; a cancelled UAC prompt then leaves the files behind. + // Holding them until cmd read a release signal from a named pipe made F-Secure's + // behavior detection end the elevated cmd (#16840, #16842). The DACL still protects them. + script.release_files(); let process = launch_elevated(&cmd_path, ¶meters, show).map_err(|err| { log::debug!("Failed to launch elevated installer: {err:#}"); err.context(format!( @@ -113,11 +110,6 @@ pub(super) fn run_cmds(cmds: impl Into, show: bool, tip: &str) directory.display() )) })?; - gate.wait_for_client(process.handle())?; - // Keep DELETE-capable handles through UAC cancellation, but close them before - // cmd opens the BAT or copies its inputs. The protected DACL stays unchanged. - script.release_files(); - gate.release(process.handle())?; let exit_code = process.wait()?; // Cleanup must not change the result of an installation that already ran. match fs::symlink_metadata(&directory) { @@ -152,11 +144,7 @@ fn elevated_install_failure_reason(exit_code: u32) -> &'static str { mod tests { use super::super::installer_shell::shortcut_bytes; use super::*; - use std::{ - os::windows::{io::AsRawHandle, process::CommandExt}, - process::Stdio, - }; - use windows::Win32::Foundation::HANDLE; + use std::{os::windows::process::CommandExt, process::Stdio}; #[test] fn protected_handoff_preserves_shortcuts_failures_and_cleanup() { @@ -180,10 +168,12 @@ mod tests { files: vec![shortcut], }; let mut script = write_install_script(commands, &source).unwrap(); + // The DACL, not a held handle, keeps the unelevated owner from editing the BAT. + script.release_files(); if !super::super::is_elevated(None).unwrap() { assert!(fs::write(script.file.path(), "exit /b 0\r\n").is_err()); } - let output = run_script(&mut script, true); + let output = run_script(&mut script); let copied = fs::read(&marker).unwrap(); let cleaned = !runner.exists() && !script.file.path().exists() @@ -199,54 +189,16 @@ mod tests { } } - #[test] - fn interrupted_handoff_does_not_execute_the_batch() { - let root = - std::env::temp_dir().join(format!("rustdesk-interrupted-{}", uuid::Uuid::new_v4())); - fs::create_dir(&root).unwrap(); - let source = root.join("source.bat"); - let marker = root.join("executed"); - let commands = format!("echo unexpected > \"{}\"", marker.display()); - let mut script = write_install_script(commands.into(), &source).unwrap(); - let output = run_script(&mut script, false); - assert!(!output.status.success(), "{output:?}"); - assert!(!marker.exists()); - drop(script); - assert!(!source.exists()); - fs::remove_dir(&root).unwrap(); - - // A child exiting without connecting must also retire the pending pipe I/O. - let gate = InstallGate::new().unwrap(); - let mut child = - std::process::Command::new(get_system_executable(CMD_RELATIVE_PATH).unwrap()) - .args(["/D", "/C", "exit", "0"]) - .creation_flags(::windows::Win32::System::Threading::CREATE_NO_WINDOW.0) - .spawn() - .unwrap(); - assert!(gate.wait_for_client(HANDLE(child.as_raw_handle())).is_err()); - assert!(child.wait().unwrap().success()); - } - - fn run_script(script: &mut InstallCommandScript, release: bool) -> std::process::Output { - let gate = InstallGate::new().unwrap(); - let parameters = protected_install_parameters(script, &gate).unwrap(); - let mut child = - std::process::Command::new(get_system_executable(CMD_RELATIVE_PATH).unwrap()) - .raw_arg(parameters) - .creation_flags(::windows::Win32::System::Threading::CREATE_NO_WINDOW.0) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let process = HANDLE(child.as_raw_handle()); - gate.wait_for_client(process).unwrap(); - assert!(child.try_wait().unwrap().is_none()); - if release { - script.release_files(); - gate.release(process).unwrap(); - } else { - drop(gate); - } - child.wait_with_output().unwrap() + // Mirrors run_cmds without UAC: the files are released before cmd starts and nothing + // reaches cmd's stdin. + fn run_script(script: &mut InstallCommandScript) -> std::process::Output { + let parameters = protected_install_parameters(script).unwrap(); + script.release_files(); + std::process::Command::new(get_system_executable(CMD_RELATIVE_PATH).unwrap()) + .raw_arg(parameters) + .creation_flags(::windows::Win32::System::Threading::CREATE_NO_WINDOW.0) + .stdin(Stdio::null()) + .output() + .unwrap() } } diff --git a/src/platform/windows/installer_handoff/gate.rs b/src/platform/windows/installer_handoff/gate.rs deleted file mode 100644 index 4a3cee1c7..000000000 --- a/src/platform/windows/installer_handoff/gate.rs +++ /dev/null @@ -1,135 +0,0 @@ -use super::super::wide_string; -use hbb_common::{bail, log, ResultType}; -use std::io; -use windows::{ - core::{Owned, PCWSTR}, - Win32::{ - Foundation::{ - ERROR_IO_PENDING, ERROR_NOT_FOUND, ERROR_PIPE_CONNECTED, HANDLE, WAIT_OBJECT_0, - }, - Storage::FileSystem::{ - WriteFile, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, PIPE_ACCESS_OUTBOUND, - }, - System::{ - Pipes::{ - ConnectNamedPipe, CreateNamedPipeW, GetNamedPipeClientProcessId, - PIPE_REJECT_REMOTE_CLIENTS, - }, - Threading::{CreateEventW, GetProcessId, WaitForMultipleObjects, INFINITE}, - IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}, - }, - }, -}; - -const READY: &[u8] = b"1\r\n"; -const PIPE_INSTANCES: u32 = 1; - -pub(super) struct InstallGate { - pipe: Owned, - name: String, -} - -impl InstallGate { - pub(super) fn new() -> ResultType { - let name = format!( - r"\\.\pipe\rustdesk-install-{}", - uuid::Uuid::new_v4().simple() - ); - let wide_name = wide_string(&name); - let pipe = unsafe { - CreateNamedPipeW( - PCWSTR(wide_name.as_ptr()), - PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, - PIPE_REJECT_REMOTE_CLIENTS, - PIPE_INSTANCES, - READY.len() as u32, - 0, - 0, - None, - ) - }; - if pipe.is_invalid() { - return Err(io::Error::last_os_error().into()); - } - Ok(Self { - pipe: unsafe { Owned::new(pipe) }, - name, - }) - } - - pub(super) fn name(&self) -> &str { - &self.name - } - - pub(super) fn wait_for_client(&self, process: HANDLE) -> ResultType<()> { - let event = unsafe { Owned::new(CreateEventW(None, true, false, None)?) }; - let mut overlapped = OVERLAPPED { - hEvent: *event, - ..Default::default() - }; - if let Err(error) = unsafe { ConnectNamedPipe(*self.pipe, Some(&mut overlapped)) } { - if error.code() == ERROR_IO_PENDING.to_hresult() { - self.wait_for_io(&overlapped, process)?; - } else if error.code() != ERROR_PIPE_CONNECTED.to_hresult() { - return Err(error.into()); - } - } - let mut client = 0; - unsafe { GetNamedPipeClientProcessId(*self.pipe, &mut client)? }; - if client != unsafe { GetProcessId(process) } { - bail!("Unexpected installer handoff pipe client"); - } - Ok(()) - } - - // cmd's SET /P must read a line successfully before it opens the BAT. Closing - // the pipe without this signal fails the command instead of running the BAT. - pub(super) fn release(&self, process: HANDLE) -> ResultType<()> { - let event = unsafe { Owned::new(CreateEventW(None, true, false, None)?) }; - let mut overlapped = OVERLAPPED { - hEvent: *event, - ..Default::default() - }; - // Windows 7 requires a byte-count pointer even for overlapped writes. - let mut written = 0; - if let Err(error) = unsafe { - WriteFile( - *self.pipe, - Some(READY), - Some(&mut written), - Some(&mut overlapped), - ) - } { - if error.code() != ERROR_IO_PENDING.to_hresult() { - return Err(error.into()); - } - self.wait_for_io(&overlapped, process)?; - } - // Keep the server handle alive until cmd exits so the signal stays buffered. - Ok(()) - } - - fn wait_for_io(&self, overlapped: &OVERLAPPED, process: HANDLE) -> ResultType<()> { - let wait = - unsafe { WaitForMultipleObjects(&[overlapped.hEvent, process], false, INFINITE) }; - let mut transferred = 0; - if wait == WAIT_OBJECT_0 { - unsafe { GetOverlappedResult(*self.pipe, overlapped, &mut transferred, false)? }; - return Ok(()); - } - let error = io::Error::last_os_error(); - // Retire pending I/O before the stack-allocated OVERLAPPED and event go away. - if let Err(error) = unsafe { CancelIoEx(*self.pipe, Some(overlapped)) } { - if error.code() != ERROR_NOT_FOUND.to_hresult() { - log::warn!("Failed to cancel installer handoff I/O: {error}"); - } - } - // Cancellation normally completes with ERROR_OPERATION_ABORTED; preserve - // the original wait failure after observing that completion. - let _ = unsafe { GetOverlappedResult(*self.pipe, overlapped, &mut transferred, true) }; - if wait.0 == WAIT_OBJECT_0.0 + 1 { - bail!("Elevated installer exited before the file handoff completed"); - } - bail!("Installer handoff wait failed ({}): {error}", wait.0) - } -} diff --git a/src/platform/windows/installer_shell.rs b/src/platform/windows/installer_shell.rs index 6ae389e0b..056e9977f 100644 --- a/src/platform/windows/installer_shell.rs +++ b/src/platform/windows/installer_shell.rs @@ -195,10 +195,6 @@ fn initialize_shell_com() -> ResultType> { pub(super) struct ProcessHandle(HANDLE); impl ProcessHandle { - pub(super) fn handle(&self) -> HANDLE { - self.0 - } - pub(super) fn wait(self) -> ResultType { let wait_result = unsafe { Threading::WaitForSingleObject(self.0, Threading::INFINITE) }; if wait_result == Foundation::WAIT_FAILED {