Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: allow same-user Windows clients to attach across elevation (#4777)

JJ Liebig331775c3e51e
diff --git a/docs/next/website/src/content/docs/windows-beta.mdx b/docs/next/website/src/content/docs/windows-beta.mdx
index 5d612e56b..095455caf 100644
--- a/docs/next/website/src/content/docs/windows-beta.mdx
+++ b/docs/next/website/src/content/docs/windows-beta.mdx
@@ -49,6 +49,8 @@ For internal testing, `HERDR_MANIFEST_URL` can point the installer at a custom m
Local persistent sessions continue running after the client detaches or its terminal window closes. Servers and pane processes launched through Windows OpenSSH also survive logout; run `herdr` again to reconnect.
+The same Windows account can attach to a session from ordinary and administrator terminals, including sessions started through SSH. The server's privileges stay as they were at startup: attaching from an ordinary terminal to an elevated server still controls administrator panes, and attaching from an administrator terminal does not elevate an ordinary server. This deliberately trusts ordinary local processes belonging to that account to control its elevated Herdr sessions; other accounts are excluded. Older elevated servers need to be stopped from an administrator terminal and restarted with the updated build before ordinary clients can attach; stopping closes their panes.
+
Windows agent process detection scans descendants of the pane shell and recognizes direct agents plus common command wrappers, including npm/Node and Git Bash process chains. It follows Git Bash-launched agents across emulated `exec` boundaries, but it is not the same as Unix foreground process-group detection.
Windows integration installation currently supports Pi, OMP, Claude Code, Codex, GitHub Copilot CLI, Devin CLI, OpenCode, Kilo Code CLI, Droid, Kimi Code CLI, Qoder CLI, and Antigravity CLI. Availability is narrower than on Unix; Herdr hides or rejects integrations whose install format is not supported on Windows.
diff --git a/src/ipc.rs b/src/ipc.rs
index eee623ef5..f740b17f6 100644
--- a/src/ipc.rs
+++ b/src/ipc.rs
@@ -66,12 +66,14 @@ pub(crate) fn bind_local_listener(path: &Path) -> io::Result<LocalListener> {
#[cfg(windows)]
{
use interprocess::local_socket::{prelude::*, GenericNamespaced, ListenerOptions};
+ use interprocess::os::windows::local_socket::ListenerOptionsExt as _;
let name = path.to_string_lossy().to_string();
let name = name.to_ns_name::<GenericNamespaced>()?;
let listener = ListenerOptions::new()
.name(name)
.reclaim_name(false)
+ .security_descriptor(crate::platform::local_server_security_descriptor()?)
.create_sync()?;
fs::write(path, windows_socket_marker())?;
Ok(listener)
diff --git a/src/platform/windows.rs b/src/platform/windows.rs
index c61d2f3f8..b82aac6cc 100644
--- a/src/platform/windows.rs
+++ b/src/platform/windows.rs
@@ -16,6 +16,76 @@ use std::{
mod clipboard_image;
mod config_backup;
+pub(crate) fn probe_local_server(path: &std::path::Path) -> std::io::Result<()> {
+ use interprocess::os::windows::named_pipe::{pipe_mode::Bytes, DuplexPipeStream};
+ use interprocess::ConnectWaitMode;
+
+ // The local-socket wrapper ignores wait_mode on Windows in interprocess
+ // 2.4.2. Its named-pipe API honors it without importing/reopening a handle.
+ let name = format!(r"\\.\pipe\{}", path.to_string_lossy());
+ DuplexPipeStream::<Bytes>::connect_by_path_with_wait_mode(
+ name.as_str(),
+ ConnectWaitMode::Timeout(Duration::from_millis(500)),
+ )
+ .map(|_| ())
+ .map_err(local_server_connection_error)
+}
+
+pub(crate) fn local_server_security_descriptor(
+) -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {
+ user_security_descriptor("GRGW")
+}
+
+fn user_security_descriptor(
+ access: &str,
+) -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {
+ use interprocess::os::windows::security_descriptor::SecurityDescriptor;
+ use widestring::{U16CStr, U16CString};
+ use windows_sys::Win32::Security::{
+ Authorization::ConvertSidToStringSidW, GetTokenInformation, TokenUser, TOKEN_QUERY,
+ TOKEN_USER,
+ };
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
+
+ let mut token = null_mut();
+ if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ let token = unsafe { OwnedHandle::from_raw_handle(token) };
+ let mut needed = 0;
+ unsafe { GetTokenInformation(token.as_raw_handle(), TokenUser, null_mut(), 0, &mut needed) };
+ if needed == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ // usize storage keeps TOKEN_USER aligned and its trailing SID alive.
+ let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
+ if unsafe {
+ GetTokenInformation(
+ token.as_raw_handle(),
+ TokenUser,
+ buffer.as_mut_ptr().cast(),
+ needed,
+ &mut needed,
+ )
+ } == 0
+ {
+ return Err(std::io::Error::last_os_error());
+ }
+ // SAFETY: GetTokenInformation initialized the aligned TOKEN_USER and SID.
+ let user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
+ let mut sid = null_mut();
+ if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid) } == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ let sid_text = unsafe { U16CStr::from_ptr_str(sid) }.to_string_lossy();
+ unsafe { LocalFree(sid.cast()) };
+ // The elevated token's default owner can be Administrators. Authorize the
+ // account instead: its ordinary clients deliberately control elevated panes.
+ let sddl = U16CString::from_str(format!("D:P(A;;GA;;;SY)(A;;{access};;;{sid_text})"))
+ .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
+ SecurityDescriptor::deserialize(&sddl)
+}
+
pub(crate) fn local_server_connection_error(error: std::io::Error) -> std::io::Error {
if error.kind() != std::io::ErrorKind::PermissionDenied {
return error;
@@ -23,8 +93,8 @@ pub(crate) fn local_server_connection_error(error: std::io::Error) -> std::io::E
std::io::Error::new(
error.kind(),
format!(
- "If this server is elevated, stop it in an admin shell; \
- reopen Herdr normally (closes panes). {error}"
+ "For an older elevated server, stop it in an admin shell and \
+ reopen Herdr (closes panes). {error}"
),
)
}
@@ -190,10 +260,7 @@ pub(crate) fn create_config_temporary(
.create_new(true)
.open(path);
}
- use interprocess::os::windows::security_descriptor::{
- AsSecurityDescriptorExt as _, SecurityDescriptor,
- };
- use widestring::U16CString;
+ use interprocess::os::windows::security_descriptor::AsSecurityDescriptorExt as _;
use windows_sys::Win32::{
Foundation::GENERIC_WRITE,
Storage::FileSystem::{
@@ -201,9 +268,7 @@ pub(crate) fn create_config_temporary(
FILE_SHARE_WRITE,
},
};
- let sddl =
- U16CString::from_str("D:P(A;;GA;;;SY)(A;;GA;;;OW)").map_err(std::io::Error::other)?;
- let descriptor = SecurityDescriptor::deserialize(&sddl)?;
+ let descriptor = user_security_descriptor("GA")?;
let mut attributes = SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: null_mut(),
@@ -3133,6 +3198,152 @@ mod tests {
AllocConsole, FreeConsole, GetConsoleProcessList, GetConsoleWindow,
};
+ #[test]
+ fn local_resources_authorize_account_without_admin_rights() {
+ use interprocess::local_socket::traits::Listener as _;
+ use std::io::{Read, Write};
+ use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
+ use windows_sys::Win32::Security::{
+ CreateRestrictedToken, GetTokenInformation, ImpersonateLoggedOnUser, RevertToSelf,
+ TokenUser, DISABLE_MAX_PRIVILEGE, LUA_TOKEN, SID_AND_ATTRIBUTES, TOKEN_DUPLICATE,
+ TOKEN_QUERY, TOKEN_USER,
+ };
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
+
+ let path =
+ std::env::temp_dir().join(format!("herdr-user-pipe-{}.sock", std::process::id()));
+ let listener = crate::ipc::bind_local_listener(&path).unwrap();
+ let mut raw_token = std::ptr::null_mut();
+ assert_ne!(
+ unsafe {
+ OpenProcessToken(
+ GetCurrentProcess(),
+ TOKEN_DUPLICATE | TOKEN_QUERY,
+ &mut raw_token,
+ )
+ },
+ 0
+ );
+ let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
+ let mut restricted = std::ptr::null_mut();
+ assert_ne!(
+ unsafe {
+ CreateRestrictedToken(
+ token.as_raw_handle(),
+ DISABLE_MAX_PRIVILEGE | LUA_TOKEN,
+ 0,
+ std::ptr::null(),
+ 0,
+ std::ptr::null(),
+ 0,
+ std::ptr::null(),
+ &mut restricted,
+ )
+ },
+ 0
+ );
+ let restricted = unsafe { OwnedHandle::from_raw_handle(restricted) };
+ let private_path = path.with_extension("private");
+ super::create_config_temporary(&private_path, true)
+ .unwrap()
+ .write_all(b"recovery")
+ .unwrap();
+ assert_ne!(
+ unsafe { ImpersonateLoggedOnUser(restricted.as_raw_handle()) },
+ 0
+ );
+ let connection = crate::ipc::connect_local_stream(&path);
+ let private_read = fs::read(&private_path);
+ let private_write = fs::write(&private_path, b"updated");
+ let reverted = unsafe { RevertToSelf() };
+ assert_ne!(reverted, 0);
+ assert_eq!(private_read.unwrap(), b"recovery");
+ private_write.unwrap();
+ let mut client = connection.expect("the account SID must work without admin membership");
+ let mut server = listener.accept().unwrap();
+ client.write_all(b"account").unwrap();
+ let mut received = [0; 7];
+ server.read_exact(&mut received).unwrap();
+ assert_eq!(&received, b"account");
+
+ // Removing the account SID must not leave access through Everyone or
+ // another ordinary group. This exercises the real DACL access check.
+ let mut size = 0;
+ unsafe {
+ GetTokenInformation(
+ token.as_raw_handle(),
+ TokenUser,
+ std::ptr::null_mut(),
+ 0,
+ &mut size,
+ )
+ };
+ let mut user = vec![0usize; (size as usize).div_ceil(std::mem::size_of::<usize>())];
+ assert_ne!(
+ unsafe {
+ GetTokenInformation(
+ token.as_raw_handle(),
+ TokenUser,
+ user.as_mut_ptr().cast(),
+ size,
+ &mut size,
+ )
+ },
+ 0
+ );
+ let user = unsafe { &*user.as_ptr().cast::<TOKEN_USER>() };
+ let disabled = SID_AND_ATTRIBUTES {
+ Sid: user.User.Sid,
+ Attributes: 0,
+ };
+ let mut without_account = std::ptr::null_mut();
+ assert_ne!(
+ unsafe {
+ CreateRestrictedToken(
+ token.as_raw_handle(),
+ DISABLE_MAX_PRIVILEGE | LUA_TOKEN,
+ 1,
+ &disabled,
+ 0,
+ std::ptr::null(),
+ 0,
+ std::ptr::null(),
+ &mut without_account,
+ )
+ },
+ 0
+ );
+ let without_account = unsafe { OwnedHandle::from_raw_handle(without_account) };
+ assert_ne!(
+ unsafe { ImpersonateLoggedOnUser(without_account.as_raw_handle()) },
+ 0
+ );
+ let denied = crate::ipc::connect_local_stream(&path);
+ let private_denied = fs::read(&private_path);
+ let reverted = unsafe { RevertToSelf() };
+ assert_ne!(reverted, 0);
+ assert_eq!(
+ denied.unwrap_err().kind(),
+ std::io::ErrorKind::PermissionDenied
+ );
+ assert_eq!(
+ private_denied.unwrap_err().kind(),
+ std::io::ErrorKind::PermissionDenied
+ );
+ assert_ne!(
+ unsafe { ImpersonateLoggedOnUser(restricted.as_raw_handle()) },
+ 0
+ );
+ let removed = fs::remove_file(private_path);
+ let reverted = unsafe { RevertToSelf() };
+ assert_ne!(reverted, 0);
+ removed.expect("the account must be able to remove its private recovery files");
+ drop(client);
+ drop(server);
+ drop(listener);
+ fs::remove_file(path).unwrap();
+ }
+
#[test]
fn clipboard_text_equals_normalizes_line_endings() {
assert!(super::clipboard_text_equals("hello", b"hello"));
diff --git a/src/remote/host.rs b/src/remote/host.rs
index 825ae10c1..41e54b6a2 100644
--- a/src/remote/host.rs
+++ b/src/remote/host.rs
@@ -39,7 +39,7 @@ pub(crate) fn run_remote_client_bridge(args: &[String]) -> io::Result<()> {
fn ensure_remote_server_running() -> io::Result<()> {
let socket_path = crate::server::socket_paths::client_socket_path();
- if crate::server::autodetect::is_server_listening() {
+ if crate::server::autodetect::is_server_listening()? {
let status = crate::api::read_runtime_status_at(
&crate::api::socket_path(),
Duration::from_millis(500),
diff --git a/src/server/autodetect.rs b/src/server/autodetect.rs
index afd8edfda..729e7890a 100644
--- a/src/server/autodetect.rs
+++ b/src/server/autodetect.rs
@@ -41,25 +41,35 @@ pub(crate) const STARTUP_CWD_ENV_VAR: &str = "HERDR_STARTUP_CWD";
/// server) are detected because connect returns `ConnectionRefused`
/// when nobody is listening.
#[allow(dead_code)] // Public API for external use and testing
-pub fn is_server_listening() -> bool {
+pub fn is_server_listening() -> io::Result<bool> {
is_server_listening_at(&client_socket_path())
}
/// Checks whether a herdr server is listening at a specific socket path.
-fn is_server_listening_at(socket_path: &Path) -> bool {
+fn is_server_listening_at(socket_path: &Path) -> io::Result<bool> {
#[cfg(windows)]
{
- let _ = socket_path;
- read_server_status().ok().flatten().is_some()
+ match crate::platform::probe_local_server(socket_path) {
+ Ok(()) => Ok(true),
+ Err(err)
+ if matches!(
+ err.kind(),
+ io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
+ ) =>
+ {
+ Ok(false)
+ }
+ Err(err) => Err(err),
+ }
}
#[cfg(not(windows))]
{
if !socket_path.exists() {
- return false;
+ return Ok(false);
}
- match crate::ipc::connect_local_stream(socket_path) {
+ Ok(match crate::ipc::connect_local_stream(socket_path) {
Ok(_) => {
// Server is listening. Close the test connection immediately.
// The server's handshake handler will time out on this connection
@@ -84,7 +94,7 @@ fn is_server_listening_at(socket_path: &Path) -> bool {
tracing::warn!(err = %err, "unexpected error checking server socket");
false
}
- }
+ })
}
}
@@ -260,7 +270,7 @@ pub fn wait_for_server_socket(socket_path: &Path, timeout: Duration) -> io::Resu
}
#[cfg(not(windows))]
- if is_server_listening_at(socket_path) {
+ if is_server_listening_at(socket_path)? {
info!(path = %socket_path.display(), "server socket ready");
return Ok(());
}
@@ -304,18 +314,20 @@ pub fn auto_detect_launch(saved_federation: bool) -> io::Result<()> {
let socket_path = client_socket_path();
info!(path = %socket_path.display(), "auto-detect launch starting");
- let startup = if is_server_listening_at(&socket_path) {
- info!("server already running, attaching as client");
- if saved_federation {
- Ok(())
+ let startup = is_server_listening().and_then(|listening| {
+ if listening {
+ info!("server already running, attaching as client");
+ if saved_federation {
+ Ok(())
+ } else {
+ validate_running_server_compatibility(false)
+ }
} else {
- validate_running_server_compatibility(false)
+ info!("no server running, spawning server daemon");
+ spawn_server_daemon()
+ .and_then(|_| wait_for_server_socket(&socket_path, SERVER_READY_TIMEOUT))
}
- } else {
- info!("no server running, spawning server daemon");
- spawn_server_daemon()
- .and_then(|_| wait_for_server_socket(&socket_path, SERVER_READY_TIMEOUT))
- };
+ });
if let Err(error) = startup {
if !saved_federation {
return Err(error);
@@ -331,6 +343,71 @@ pub fn auto_detect_launch(saved_federation: bool) -> io::Result<()> {
// Tests
// ---------------------------------------------------------------------------
+#[cfg(all(test, windows))]
+mod windows_tests {
+ use super::*;
+ use interprocess::local_socket::{prelude::*, GenericNamespaced, ListenerOptions};
+ use interprocess::os::windows::local_socket::ListenerOptionsExt as _;
+ use interprocess::os::windows::security_descriptor::SecurityDescriptor;
+
+ #[test]
+ fn reachability_distinguishes_denied_silent_busy_and_absent_pipes() {
+ let path =
+ std::env::temp_dir().join(format!("herdr-startup-probe-{}.sock", std::process::id()));
+ let name = path.to_string_lossy();
+ let denied = ListenerOptions::new()
+ .name(name.to_ns_name::<GenericNamespaced>().unwrap())
+ .security_descriptor(
+ SecurityDescriptor::deserialize(
+ &widestring::U16CString::from_str("D:P(A;;GA;;;SY)").unwrap(),
+ )
+ .unwrap(),
+ )
+ .create_sync()
+ .unwrap();
+ assert_eq!(
+ is_server_listening_at(&path).unwrap_err().kind(),
+ io::ErrorKind::PermissionDenied
+ );
+ drop(denied);
+ // A real listener that never answers the status API is still present:
+ // automatic startup must not replace it just because it is unresponsive.
+ let silent = crate::ipc::bind_local_listener(&path).unwrap();
+ assert!(is_server_listening_at(&path).unwrap());
+ drop(silent);
+ let busy = crate::ipc::bind_local_listener(&path).unwrap();
+ let occupied = crate::ipc::connect_local_stream(&path).unwrap();
+ let start_probe = || {
+ let probe_path = path.clone();
+ let (result_tx, result_rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = result_tx.send(is_server_listening_at(&probe_path));
+ });
+ result_rx
+ };
+ assert_eq!(
+ start_probe()
+ .recv_timeout(Duration::from_secs(5))
+ .expect("an occupied pipe must not block startup")
+ .unwrap_err()
+ .kind(),
+ io::ErrorKind::TimedOut
+ );
+ let retry = start_probe();
+ assert!(matches!(
+ retry.recv_timeout(Duration::from_millis(50)),
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout)
+ ));
+ let accepted = busy.accept().unwrap();
+ assert!(retry.recv_timeout(Duration::from_secs(5)).unwrap().unwrap());
+ drop(accepted);
+ drop(occupied);
+ drop(busy);
+ assert!(!is_server_listening_at(&path).unwrap());
+ std::fs::remove_file(path).unwrap();
+ }
+}
+
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -356,7 +433,7 @@ mod tests {
fn is_server_listening_returns_false_for_nonexistent_path() {
let dir = unique_test_dir("nonexistent");
let path = dir.join("s.sock");
- assert!(!is_server_listening_at(&path));
+ assert!(!is_server_listening_at(&path).unwrap());
}
#[test]
@@ -424,7 +501,7 @@ test "$sid" = "$$"
let path = dir.join("s.sock");
let _listener = UnixListener::bind(&path).unwrap();
- assert!(is_server_listening_at(&path));
+ assert!(is_server_listening_at(&path).unwrap());
let _ = std::fs::remove_dir_all(dir);
}
@@ -441,7 +518,7 @@ test "$sid" = "$$"
}
// The socket file exists but nobody is listening.
- assert!(!is_server_listening_at(&path));
+ assert!(!is_server_listening_at(&path).unwrap());
let _ = std::fs::remove_dir_all(dir);
}
@@ -455,7 +532,7 @@ test "$sid" = "$$"
drop(UnixListener::bind(&path).unwrap());
// Socket is stale — should return false.
- assert!(!is_server_listening_at(&path));
+ assert!(!is_server_listening_at(&path).unwrap());
let _ = std::fs::remove_dir_all(dir);
}