the runtime your coding agents live on
Rust agentagent-orchestrationaiai-agentsclaude-codeclicodexcoding-agentsdeveloper-toolsdevtoolsmultiplexerrustterminalterminal-multiplexerterminal-uitmuxtuiworkspace-manager
fix: require opt-in for cross-elevation Windows access (#4779)
JJ Liebig49848effb0d2
diff --git a/docs/next/website/src/content/docs/windows-beta.mdx b/docs/next/website/src/content/docs/windows-beta.mdxindex 095455caf..b96b503ee 100644--- a/docs/next/website/src/content/docs/windows-beta.mdx+++ b/docs/next/website/src/content/docs/windows-beta.mdx@@ -49,7 +49,18 @@ For internal testing, `HERDR_MANIFEST_URL` can point the installer at a custom mLocal 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.+Elevated Windows servers require an administrator client by default, including servers started through an elevated SSH login. Ordinary servers accept clients from ordinary and administrator terminals belonging to the same account; attaching never changes the server's privileges.++To deliberately share elevated sessions with ordinary clients, set:++```toml+[server]+allow_unelevated_clients = true+```++This Windows-only setting is off by default and applies when a new server starts, including automatic startup. Reloading config does not change a running server's access policy. You can instead enable sharing for one server process from an administrator terminal with `herdr server --allow-unelevated-clients` (or `herdr --session <name> server --allow-unelevated-clients` for a named session). The flag enables sharing even when the config setting is false.++Either option allows ordinary local processes belonging to that account to control administrator panes; other accounts remain excluded. The flag must be supplied again after a restart unless sharing is enabled in config. Existing servers retain their previous access policy until stopped and restarted with the updated build; stopping closes their panes. Config and recovery files retain their account-based permissions.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.diff --git a/docs/next/website/src/data/config-reference.json b/docs/next/website/src/data/config-reference.jsonindex eb7e08d49..f06507c14 100644--- a/docs/next/website/src/data/config-reference.json+++ b/docs/next/website/src/data/config-reference.json@@ -16,6 +16,12 @@"id": "server","title": "Server","keys": [+ {+ "key": "server.allow_unelevated_clients",+ "type": "boolean",+ "default": "false",+ "description": "Windows only: allow ordinary clients from the same account to control an elevated server and its administrator panes. Applies at server startup and requires a restart; config reload does not change access. The --allow-unelevated-clients startup flag enables sharing even when this setting is false."+ },{"key": "server.headless_cols","type": "integer",diff --git a/src/cli/server.rs b/src/cli/server.rsindex 2045f420b..657a5db8e 100644--- a/src/cli/server.rs+++ b/src/cli/server.rs@@ -1,6 +1,11 @@use crate::api::schema::{EmptyParams, Method, Request, ServerLiveHandoffParams};pub(super) fn run_server_command(args: &[String]) -> std::io::Result<Option<i32>> {+ #[cfg(windows)]+ if args == ["--allow-unelevated-clients"] {+ crate::platform::allow_unelevated_clients();+ return Ok(None);+ }let Some(subcommand) = args.first().map(|arg| arg.as_str()) else {return Ok(None);};@@ -259,6 +264,8 @@ fn parse_live_handoff_params(args: &[String]) -> Option<ServerLiveHandoffParams>fn print_server_help() {eprintln!("herdr server commands:");eprintln!(" herdr server run as headless server");+ #[cfg(windows)]+ eprintln!(" herdr server --allow-unelevated-clients allow ordinary same-account clients to control an elevated server");eprintln!(" herdr server stop stop the running server via the API socket");eprintln!(" herdr server live-handoff hand off live panes to a new local server");eprintln!(" herdr server reload-config reload config.toml in the running server");diff --git a/src/cli/spec.rs b/src/cli/spec.rsindex 1cfc2e7f7..c6bde2252 100644--- a/src/cli/spec.rs+++ b/src/cli/spec.rs@@ -157,7 +157,7 @@ fn channel_command() -> Command {}fn server_command() -> Command {- Command::new("server")+ let command = Command::new("server").about("Run or control the headless server").subcommand(Command::new("stop").about("Stop the running server")).subcommand(Command::new("reload-config").about("Reload config in the running server"))@@ -174,7 +174,13 @@ fn server_command() -> Command {.subcommand(Command::new("reload-agent-manifests").about("Reload local agent detection manifest overrides"),- )+ );+ #[cfg(windows)]+ let command = command.arg(+ flag("allow-unelevated-clients")+ .help("Allow ordinary same-account clients to control this elevated server"),+ );+ command}fn api_command() -> Command {diff --git a/src/config/model.rs b/src/config/model.rsindex 0e2e57ced..29802fd9f 100644--- a/src/config/model.rs+++ b/src/config/model.rs@@ -1039,6 +1039,9 @@ impl ImeCursorShape {#[derive(Debug, Deserialize)]#[serde(default)]pub struct ServerConfig {+ /// Windows: allow ordinary same-account clients to control an elevated server. Default: false.+ #[cfg(windows)]+ pub allow_unelevated_clients: bool,/// Virtual terminal width used when no client is attached. Default: 120.pub headless_cols: u16,/// Virtual terminal height used when no client is attached. Default: 40.@@ -1311,6 +1314,8 @@ impl<'de> Deserialize<'de> for ToastConfig {impl Default for ServerConfig {fn default() -> Self {Self {+ #[cfg(windows)]+ allow_unelevated_clients: false,headless_cols: crate::config::DEFAULT_HEADLESS_COLS,headless_rows: crate::config::DEFAULT_HEADLESS_ROWS,}diff --git a/src/main.rs b/src/main.rsindex b5c92ec1b..32ef0e76f 100644--- a/src/main.rs+++ b/src/main.rs@@ -223,6 +223,9 @@ const DEFAULT_CONFIG: &str = r##"# herdr configuration# Size of the virtual terminal used when no client is attached.# Attached clients always use their own terminal size.[server]+# Windows only: allow ordinary same-account clients to control an elevated server.+# Requires a server restart.+# allow_unelevated_clients = false# headless_cols = 120# headless_rows = 40diff --git a/src/platform/windows.rs b/src/platform/windows.rsindex c94f6a203..1e2e66197 100644--- a/src/platform/windows.rs+++ b/src/platform/windows.rs@@ -21,6 +21,12 @@ pub(crate) use notifications::{show_actionable_desktop_notification, show_desktop_notification,};+static ALLOW_UNELEVATED_CLIENTS: OnceLock<bool> = OnceLock::new();++pub(crate) fn allow_unelevated_clients() {+ let _ = ALLOW_UNELEVATED_CLIENTS.set(true);+}+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;@@ -38,11 +44,44 @@ pub(crate) fn probe_local_server(path: &std::path::Path) -> std::io::Result<()>pub(crate) fn local_server_security_descriptor() -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {- user_security_descriptor("GRGW")+ use windows_sys::Win32::Security::{+ GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY,+ };+ 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 elevation = TOKEN_ELEVATION::default();+ let mut needed = 0;+ if unsafe {+ GetTokenInformation(+ token.as_raw_handle(),+ TokenElevation,+ (&mut elevation as *mut TOKEN_ELEVATION).cast(),+ size_of::<TOKEN_ELEVATION>() as u32,+ &mut needed,+ )+ } == 0+ {+ return Err(std::io::Error::last_os_error());+ }+ let allow_unelevated = ALLOW_UNELEVATED_CLIENTS.get().copied().unwrap_or(false);+ let integrity = if elevation.TokenIsElevated != 0 && !allow_unelevated {+ "HI"+ } else {+ "ME"+ };+ // The account DACL alone cannot distinguish ordinary and elevated clients.+ // The integrity label blocks both reading and writing from lower levels.+ user_security_descriptor("GRGW", &format!("S:(ML;;NRNW;;;{integrity})"))}fn user_security_descriptor(access: &str,+ integrity_label: &str,) -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {use interprocess::os::windows::security_descriptor::SecurityDescriptor;use widestring::{U16CStr, U16CString};@@ -84,10 +123,11 @@ fn user_security_descriptor(}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))?;+ // Use the account SID rather than the elevated token's Administrators owner.+ let sddl = U16CString::from_str(format!(+ "D:P(A;;GA;;;SY)(A;;{access};;;{sid_text}){integrity_label}"+ ))+ .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;SecurityDescriptor::deserialize(&sddl)}@@ -98,8 +138,9 @@ pub(crate) fn local_server_connection_error(error: std::io::Error) -> std::io::Estd::io::Error::new(error.kind(),format!(- "For an older elevated server, stop it in an admin shell and \- reopen Herdr (closes panes). {error}"+ "For an elevated server, use an administrator terminal. Sharing with ordinary \+ clients requires stopping it there and restarting its `herdr server` command \+ with --allow-unelevated-clients (closes panes). {error}"),)}@@ -273,7 +314,7 @@ pub(crate) fn create_config_temporary(FILE_SHARE_WRITE,},};- let descriptor = user_security_descriptor("GA")?;+ let descriptor = user_security_descriptor("GA", "")?;let mut attributes = SECURITY_ATTRIBUTES {nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,lpSecurityDescriptor: null_mut(),diff --git a/src/server/headless/bootstrap.rs b/src/server/headless/bootstrap.rsindex e5ff400dc..664aa9a2a 100644--- a/src/server/headless/bootstrap.rs+++ b/src/server/headless/bootstrap.rs@@ -27,6 +27,10 @@ pub fn run_server() -> io::Result<()> {}let loaded_config = config::Config::load();+ #[cfg(windows)]+ if loaded_config.config.server.allow_unelevated_clients {+ crate::platform::allow_unelevated_clients();+ }let (api_tx, api_rx) = tokio::sync::mpsc::unbounded_channel();let event_hub = api::EventHub::default();let should_quit = Arc::new(AtomicBool::new(false));diff --git a/src/session.rs b/src/session.rsindex b2cb7a4eb..017c20dd2 100644--- a/src/session.rs+++ b/src/session.rs@@ -544,7 +544,6 @@ mod tests {let running_listener = crate::ipc::bind_local_listener(&running_path).unwrap();let error = crate::ipc::connect_local_stream(&denied_path).unwrap_err();assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);- assert!(error.to_string().contains("admin shell"));let sessions = list_sessions().unwrap();let denied = sessions@@ -552,7 +551,7 @@ mod tests {.find(|session| session.name == "denied").unwrap();assert!(!denied.running);- assert!(denied.connection_error.is_some());+ assert_eq!(denied.connection_error, Some(error.to_string()));let running = sessions.iter().find(|session| session.name == "running")diff --git a/tests/windows_server_security.rs b/tests/windows_server_security.rsnew file mode 100644index 000000000..87fe39793--- /dev/null+++ b/tests/windows_server_security.rs@@ -0,0 +1,262 @@+#![cfg(windows)]++use std::io;+use std::mem::size_of;+use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};+use std::os::windows::process::CommandExt;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::ptr::null_mut;+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};++use interprocess::os::windows::named_pipe::{pipe_mode::Bytes, DuplexPipeStream};+use interprocess::ConnectWaitMode;+use windows_sys::Win32::Foundation::LocalFree;+use windows_sys::Win32::Security::{+ Authorization::ConvertStringSidToSidW, CreateRestrictedToken, GetLengthSid, GetSidSubAuthority,+ GetSidSubAuthorityCount, GetTokenInformation, ImpersonateLoggedOnUser, RevertToSelf,+ SetTokenInformation, TokenIntegrityLevel, DISABLE_MAX_PRIVILEGE, LUA_TOKEN, SID_AND_ATTRIBUTES,+ TOKEN_ADJUST_DEFAULT, TOKEN_DUPLICATE, TOKEN_MANDATORY_LABEL, TOKEN_QUERY,+};+use windows_sys::Win32::System::Threading::{+ GetCurrentProcess, OpenProcessToken, CREATE_NO_WINDOW,+};++struct TestServer {+ child: Option<Child>,+ directory: PathBuf,+}++impl Drop for TestServer {+ fn drop(&mut self) {+ if let Some(child) = self.child.as_mut() {+ let _ = child.kill();+ let _ = child.wait();+ }+ let _ = std::fs::remove_dir_all(&self.directory);+ }+}++fn connect(path: &Path) -> io::Result<()> {+ let name = format!(r"\\.\pipe\{}", path.display());+ DuplexPipeStream::<Bytes>::connect_by_path_with_wait_mode(+ name.as_str(),+ ConnectWaitMode::Timeout(Duration::from_millis(500)),+ )+ .map(|_| ())+}++#[test]+fn server_integrity_requires_startup_consent_on_both_endpoints() {+ // Windows integrity SID RIDs and the SE_GROUP_INTEGRITY attribute.+ const LOW: u32 = 0x1000;+ const MEDIUM: u32 = 0x2000;+ const HIGH: u32 = 0x3000;++ let mut raw_token = null_mut();+ assert_ne!(+ unsafe {+ OpenProcessToken(+ GetCurrentProcess(),+ TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT,+ &mut raw_token,+ )+ },+ 0+ );+ let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };+ let mut buffer = [0usize; 64];+ let mut needed = 0;+ assert_ne!(+ unsafe {+ GetTokenInformation(+ token.as_raw_handle(),+ TokenIntegrityLevel,+ buffer.as_mut_ptr().cast(),+ std::mem::size_of_val(&buffer) as u32,+ &mut needed,+ )+ },+ 0+ );+ let label = unsafe { &*buffer.as_ptr().cast::<TOKEN_MANDATORY_LABEL>() };+ let integrity = unsafe {+ *GetSidSubAuthority(+ label.Label.Sid,+ u32::from(*GetSidSubAuthorityCount(label.Label.Sid)) - 1,+ )+ };++ let directory = std::env::temp_dir().join(format!(+ "herdr-server-integrity-{}-{}",+ std::process::id(),+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ std::fs::create_dir(&directory).unwrap();+ let mut server = TestServer {+ child: None,+ directory,+ };+ let app_dir = if cfg!(debug_assertions) {+ "herdr-dev"+ } else {+ "herdr"+ };+ let session_dir = server+ .directory+ .join(app_dir)+ .join("sessions")+ .join("integrity-test");+ let endpoints = [+ session_dir.join("herdr.sock"),+ session_dir.join("herdr-client.sock"),+ ];++ // Reuse the named session after stopping, proving consent is process-local.+ for (configured, allow_unelevated) in [+ (false, false),+ (false, true),+ (false, false),+ (true, false),+ (false, false),+ ] {+ std::fs::create_dir_all(server.directory.join(app_dir)).unwrap();+ let configuration = if configured || allow_unelevated {+ format!("[server]\nallow_unelevated_clients = {configured}\n")+ } else {+ String::new()+ };+ std::fs::write(+ server.directory.join(app_dir).join("config.toml"),+ configuration,+ )+ .unwrap();+ let mut command = Command::new(env!("CARGO_BIN_EXE_herdr"));+ command.args(["--session", "integrity-test", "server"]);+ if allow_unelevated {+ command.arg("--allow-unelevated-clients");+ }+ command+ .env("XDG_CONFIG_HOME", &server.directory)+ .env("XDG_STATE_HOME", &server.directory)+ .current_dir(&server.directory)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .creation_flags(CREATE_NO_WINDOW);+ for name in [+ "HERDR_SOCKET_PATH",+ "HERDR_CLIENT_SOCKET_PATH",+ "HERDR_CONFIG_PATH",+ "HERDR_SESSION",+ "HERDR_WORKSPACE",+ "HERDR_TAB",+ "HERDR_PANE",+ "HERDR_TERMINAL",+ "HERDR_STARTUP_CWD",+ ] {+ command.env_remove(name);+ }+ server.child = Some(command.spawn().expect("start isolated headless server"));+ let deadline = Instant::now() + Duration::from_secs(30);+ for endpoint in &endpoints {+ loop {+ let status = server.child.as_mut().unwrap().try_wait().unwrap();+ assert!(+ status.is_none(),+ "server exited before readiness: {status:?}"+ );+ match connect(endpoint) {+ Ok(()) => break,+ Err(error) => {+ assert!(+ Instant::now() < deadline,+ "{} not ready: {error}",+ endpoint.display()+ );+ std::thread::sleep(Duration::from_millis(25));+ }+ }+ }+ }++ let mut restricted = null_mut();+ assert_ne!(+ unsafe {+ CreateRestrictedToken(+ token.as_raw_handle(),+ DISABLE_MAX_PRIVILEGE | LUA_TOKEN,+ 0,+ null_mut(),+ 0,+ null_mut(),+ 0,+ null_mut(),+ &mut restricted,+ )+ },+ 0+ );+ let restricted = unsafe { OwnedHandle::from_raw_handle(restricted) };++ // Exercise high -> medium on elevated runners and medium -> low otherwise.+ // Removing administrator groups alone does not lower a token's integrity.+ for client_integrity in [MEDIUM, LOW] {+ if client_integrity >= integrity {+ continue;+ }+ let sid_text =+ widestring::U16CString::from_str(format!("S-1-16-{client_integrity}")).unwrap();+ let mut sid = null_mut();+ assert_ne!(+ unsafe { ConvertStringSidToSidW(sid_text.as_ptr(), &mut sid) },+ 0+ );+ let client_label = TOKEN_MANDATORY_LABEL {+ Label: SID_AND_ATTRIBUTES {+ Sid: sid,+ Attributes: 0x20,+ },+ };+ let set = unsafe {+ SetTokenInformation(+ restricted.as_raw_handle(),+ TokenIntegrityLevel,+ (&client_label as *const TOKEN_MANDATORY_LABEL).cast(),+ size_of::<TOKEN_MANDATORY_LABEL>() as u32 + GetLengthSid(sid),+ )+ };+ let error = io::Error::last_os_error();+ unsafe { LocalFree(sid.cast()) };+ assert_ne!(set, 0, "lower client integrity: {error}");++ for endpoint in &endpoints {+ assert_ne!(+ unsafe { ImpersonateLoggedOnUser(restricted.as_raw_handle()) },+ 0+ );+ let connection = connect(endpoint);+ assert_ne!(unsafe { RevertToSelf() }, 0);+ if integrity >= HIGH+ && (configured || allow_unelevated)+ && client_integrity == MEDIUM+ {+ connection.expect("explicit sharing must admit ordinary same-account clients");+ } else {+ assert_eq!(+ connection.unwrap_err().kind(),+ io::ErrorKind::PermissionDenied,+ "{}: config={configured}, flag={allow_unelevated}, client integrity={client_integrity}",+ endpoint.display()+ );+ }+ }+ }+ let child = server.child.as_mut().unwrap();+ child.kill().unwrap();+ child.wait().unwrap();+ server.child = None;+ }+}