fix(windows): drop the named-pipe handoff that F-Secure blocks

Since #16562 the elevated cmd.exe waited on
`set /p RUSTDESK_HANDOFF=<"\\.\pipe\rustdesk-install-<uuid>"` until the
unelevated parent released the staged files' DELETE handles. F-Secure's
behavior detection closes that cmd's end of the pipe, so installation and
Stop service fail with "The pipe is being closed. (0x800700E8)"
(ERROR_NO_DATA) and the BAT never runs (#16840, #16842).

The handles exist only to delete the staged files when UAC is cancelled.
Tampering is prevented by the DACL set at creation, which grants the
unelevated owner read/execute only, and that is unchanged. Release the
handles before launching cmd and run the BAT directly. A cancelled UAC
prompt now leaves the staged BAT and shortcut in the protected directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAxkkiaGp2k8okvs4MpCUq
This commit is contained in:
rustdeskandClaude Opus 5.5 committed 2026-11-06 11:12:05 +08:00
1 parent fdffc37bb0
commit a36faed936
4 files changed
+25 -212

No files matched your search

+2 -2
View File
@@ -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());
}
}
+23 -71
View File
@@ -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<Instal
})
}
fn protected_install_parameters(
script: &InstallCommandScript,
gate: &InstallGate,
) -> ResultType<String> {
fn protected_install_parameters(script: &InstallCommandScript) -> ResultType<String> {
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<InstallCommands>, 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, &parameters, 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<InstallCommands>, 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()
}
}
@@ -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<HANDLE>,
name: String,
}
impl InstallGate {
pub(super) fn new() -> ResultType<Self> {
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)
}
}
-4
View File
@@ -195,10 +195,6 @@ fn initialize_shell_com() -> ResultType<Option<ShellComGuard>> {
pub(super) struct ProcessHandle(HANDLE);
impl ProcessHandle {
pub(super) fn handle(&self) -> HANDLE {
self.0
}
pub(super) fn wait(self) -> ResultType<u32> {
let wait_result = unsafe { Threading::WaitForSingleObject(self.0, Threading::INFINITE) };
if wait_result == Foundation::WAIT_FAILED {