From 05d631c6a3477aee307b3997577bcfd5f0579de1 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Thu, 5 Nov 2026 11:42:41 -0800 Subject: [PATCH 1/4] fix(windows): protect the SSH service directory natively With the old launcher, SSH failed for every non-elevated Windows user: the spawned `orx ssh-service` re-ran a PowerShell Get-Acl/Set-Acl step and died with "The process does not possess the 'SeSecurityPrivilege' privilege", which surfaced as "Could not start the SSH monitoring service". Set-Acl rewrites the SACL as well as the DACL, and only the second run hit it, so the first launch of the directory looked healthy. Direct Win32 calls write the DACL alone and drop a powershell.exe spawn from every service start. The owner check and the protected, inherited FullControl-for-the-current-user DACL match the script. Closes #824 Assisted-by: claude-opus-5.5 --- Cargo.toml | 2 +- src/jobs/ssh/service/mod.rs | 184 +++++++++++++++++++++++------------- 2 files changed, 119 insertions(+), 67 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f1ddfff8c..6105c9544 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -102,7 +102,7 @@ raw-window-handle = "0.6" # `--version` fast path in harness detection), total RAM for the agent idle # policy, the desktop app's single instance and taskbar identity, and the # registry PATH a running orx re-reads. Already in the tree. -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_SystemServices", "Win32_System_Threading", "Win32_System_Console", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_SystemServices", "Win32_System_Threading", "Win32_System_Console", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } [target.'cfg(any(target_os = "macos", windows))'.dependencies] # Desktop app mode (src/commands/app.rs): the dashboard in its own window. tao diff --git a/src/jobs/ssh/service/mod.rs b/src/jobs/ssh/service/mod.rs index 83edd1b24..6a7f8d454 100644 --- a/src/jobs/ssh/service/mod.rs +++ b/src/jobs/ssh/service/mod.rs @@ -107,37 +107,105 @@ fn private_directory(path: &Path) -> Result<()> { std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?; } #[cfg(windows)] - { - let script = r#"$ErrorActionPreference = 'Stop' -$identity = [Security.Principal.WindowsIdentity]::GetCurrent() -$acl = Get-Acl -LiteralPath $env:ORX_PRIVATE_DIRECTORY -$owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -if ($owner -notin @($identity.User.Value, 'S-1-5-32-544', 'S-1-5-18')) { throw 'SSH service directory has a different owner' } -$acl.SetAccessRuleProtection($true, $false) -foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleAll($rule) } -$rule = [Security.AccessControl.FileSystemAccessRule]::new($identity.User, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') -$acl.SetAccessRule($rule) -Set-Acl -LiteralPath $env:ORX_PRIVATE_DIRECTORY -AclObject $acl -"#; - let status = crate::process::command("powershell.exe") - .args(["-NoProfile", "-NonInteractive", "-Command", script]) - // Windows PowerShell must not load PowerShell 7's incompatible modules. - .env_remove("PSModulePath") - .env("ORX_PRIVATE_DIRECTORY", path) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status()?; - if !status.success() { - return Err(anyhow!( - "Could not verify and protect the private SSH service directory." - )); - } + if !protect_directory(path) { + return Err(anyhow!( + "Could not verify and protect the private SSH service directory." + )); } verified.insert(path.to_owned()); Ok(()) } +/// Writes only the DACL: rewriting the SACL needs a privilege normal users lack. +#[cfg(windows)] +fn protect_directory(path: &Path) -> bool { + use std::os::windows::ffi::OsStrExt; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use std::ptr::{null, null_mut}; + use windows_sys::Win32::Foundation::{LocalFree, ERROR_SUCCESS}; + use windows_sys::Win32::Security::Authorization::{ + GetNamedSecurityInfoW, SetNamedSecurityInfoW, SE_FILE_OBJECT, + }; + use windows_sys::Win32::Security::{ + AddAccessAllowedAceEx, EqualSid, GetTokenInformation, InitializeAcl, IsWellKnownSid, + TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid, ACL_REVISION, + CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, OBJECT_INHERIT_ACE, + OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, TOKEN_QUERY, TOKEN_USER, + }; + use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + let path: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + // Sized for the longest SID, 68 bytes: a TOKEN_USER with its SID, and an ACL with one ACE. + let mut user = [0u64; 16]; + let mut acl = [0u32; 32]; + let mut token = null_mut(); + let mut owner = null_mut(); + let mut descriptor = null_mut(); + let mut written = 0; + + // SAFETY: every buffer outlives its call and its length is passed with it. `owner` points + // into `descriptor`, read before LocalFree; `sid` points into `user`. + unsafe { + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return false; + } + let token = OwnedHandle::from_raw_handle(token); + if GetTokenInformation( + token.as_raw_handle(), + TokenUser, + user.as_mut_ptr().cast(), + size_of_val(&user) as u32, + &mut written, + ) == 0 + { + return false; + } + let sid = (*user.as_ptr().cast::()).User.Sid; + + if GetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION, + &mut owner, + null_mut(), + null_mut(), + null_mut(), + &mut descriptor, + ) != ERROR_SUCCESS + { + return false; + } + let trusted_owner = EqualSid(owner, sid) != 0 + || IsWellKnownSid(owner, WinBuiltinAdministratorsSid) != 0 + || IsWellKnownSid(owner, WinLocalSystemSid) != 0; + LocalFree(descriptor); + + trusted_owner + && InitializeAcl( + acl.as_mut_ptr().cast(), + size_of_val(&acl) as u32, + ACL_REVISION, + ) != 0 + && AddAccessAllowedAceEx( + acl.as_mut_ptr().cast(), + ACL_REVISION, + CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, + FILE_ALL_ACCESS, + sid, + ) != 0 + && SetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + null_mut(), + null_mut(), + acl.as_ptr().cast(), + null(), + ) == ERROR_SUCCESS + } +} + fn endpoint() -> Result { let endpoint: Endpoint = serde_json::from_slice(&std::fs::read(state::root().join("endpoint.json"))?)?; @@ -915,46 +983,30 @@ mod tests { #[cfg(windows)] #[test] - fn private_directory_ignores_inherited_powershell_module_path() { - const CHILD_DIR: &str = "ORX_TEST_PRIVATE_DIRECTORY_MODULE_PATH"; - if let Some(path) = std::env::var_os(CHILD_DIR) { - private_directory(Path::new(&path)).unwrap(); - return; - } + fn private_directory_grants_only_the_current_user() { + let dir = crate::local::git::TemporaryDirectory::new("orx-private-directory").unwrap(); + let path = dir.path().join("ssh service"); + let aces = |path: &Path| { + let output = crate::process::command("icacls") + .arg(path) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + String::from_utf8_lossy(&output.stdout).into_owned() + }; - let dir = crate::local::git::TemporaryDirectory::new("orx-private-module-path").unwrap(); - let modules = dir.path().join("modules with spaces"); - let security = modules.join("Microsoft.PowerShell.Security"); - std::fs::create_dir_all(&security).unwrap(); - // Model an incompatible module earlier on PowerShell 7's inherited search path. - std::fs::write( - security.join("Microsoft.PowerShell.Security.psd1"), - r#"@{ -RootModule = 'Microsoft.PowerShell.Security.psm1' -ModuleVersion = '99.0' -FunctionsToExport = @('Get-Acl', 'Set-Acl') -}"#, - ) - .unwrap(); - std::fs::write( - security.join("Microsoft.PowerShell.Security.psm1"), - "throw 'incompatible module'\nfunction Get-Acl {}\nfunction Set-Acl {}\n", - ) - .unwrap(); - // Including the built-in path last preserves the inherited ordering on startup. - let system_modules = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()) - .join(r"System32\WindowsPowerShell\v1.0\Modules"); - let module_path = std::env::join_paths([modules, system_modules]).unwrap(); - let output = crate::process::command(std::env::current_exe().unwrap()) - .args([ - "--exact", - "jobs::ssh::service::tests::private_directory_ignores_inherited_powershell_module_path", - "--nocapture", - ]) - .env(CHILD_DIR, dir.path().join("ssh service")) - .env("PSModulePath", module_path) - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); + private_directory(&path).unwrap(); + // Each process protects the directory again, over the DACL the last one wrote. + assert!(protect_directory(&path)); + + let directory = aces(&path); + assert_eq!(directory.matches(":(").count(), 1, "{directory}"); + assert!(directory.contains(":(OI)(CI)(F)"), "{directory}"); + + let child = path.join("child"); + std::fs::write(&child, "").unwrap(); + let child = aces(&child); + assert_eq!(child.matches(":(").count(), 1, "{child}"); + assert!(child.contains(":(I)(F)"), "{child}"); } } From 6b00d1ae19ff50973d7bf24bb35c2fb7ba08faad Mon Sep 17 00:00:00 2001 From: clover caruso Date: Thu, 5 Nov 2026 11:44:51 -0800 Subject: [PATCH 2/4] fix(windows): hide the console askpass opens Each SSH password prompt opened a blank window titled orx.exe. The engine spawns ssh with DETACHED_PROCESS, so ssh has no console to hand on, and Windows gives its console-subsystem askpass child a new, visible one. CREATE_NO_WINDOW applies only to ssh commands that use askpass. Batch logins keep DETACHED_PROCESS on purpose: with a hidden console, a ProxyJump hop that ignores BatchMode would wait forever on input nobody can type, where today it fails. Askpass commands are safe because the hop inherits askpass too. Assisted-by: claude-opus-5.5 --- src/engine/transport/askpass.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/engine/transport/askpass.rs b/src/engine/transport/askpass.rs index 681a6aba3..52f097a2a 100644 --- a/src/engine/transport/askpass.rs +++ b/src/engine/transport/askpass.rs @@ -75,6 +75,10 @@ impl Askpass { .env("ORX_ENGINE_ASKPASS", &self.endpoint) .env("ORX_ENGINE_ASKPASS_TOKEN", &self.token) .stdin(std::process::Stdio::null()); + // Askpass is a console program: a detached ssh would open a window for it. Batch + // logins stay detached, so a ProxyJump hop fails instead of waiting on a hidden console. + #[cfg(windows)] + command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); } } From 0720c24aefea11716f8de9458d8db772088c2d94 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Thu, 5 Nov 2026 11:45:08 -0800 Subject: [PATCH 3/4] fix(ssh): offer Connect on key hosts when the old launcher needs it On Windows the old launcher logs in only through Connect, even with a key, so a key host with the new engine off failed launches with "Use Connect" while the SSH page offered only Test. The CLI was the only way out. The server reports connectRequired from the same check Connect uses, so a key host with a live old-launcher run keeps Connect after the setting is turned on. A new field keeps `class` meaning what the engine classified. Assisted-by: claude-opus-5.5 --- src/commands/up/api_v2.rs | 7 +++++++ src/commands/up/api_v2/tests.rs | 2 +- ui/src/api.ts | 2 ++ ui/src/components/SettingsPage.tsx | 4 ++-- ui/src/queries/invalidation.ts | 2 +- 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/commands/up/api_v2.rs b/src/commands/up/api_v2.rs index 2521e4b71..b7c8a01f8 100644 --- a/src/commands/up/api_v2.rs +++ b/src/commands/up/api_v2.rs @@ -460,10 +460,17 @@ pub(crate) fn host_view( ) -> Result { use crate::engine::transport::{HostClass, Status}; let class = store.engine_host_auth(alias)?.class; + let connect_required = cfg!(windows) + && crate::compute::supervised_ssh_needed( + crate::config::run_engine_settings()?.0, + &store.list_active_runs()?, + alias, + ); Ok(json!({ "alias": alias, "root": root, "status": match state.status { Status::Idle => "idle", Status::Connecting => "connecting", Status::Live => "live", Status::Backoff => "backoff", Status::NeedsAuth => "needs_auth" }, "class": class.map(|class| match class { HostClass::Key => "key", HostClass::Interactive => "interactive" }), + "connectRequired": connect_required, "sinceMs": state.since_ms, "nextRetryMs": state.next_retry_ms, "cause": state.cause, })) } diff --git a/src/commands/up/api_v2/tests.rs b/src/commands/up/api_v2/tests.rs index de539e8c5..0c7d1acb9 100644 --- a/src/commands/up/api_v2/tests.rs +++ b/src/commands/up/api_v2/tests.rs @@ -1711,7 +1711,7 @@ async fn dashboard_host_routes_report_states_and_retry_only_key_hosts() { .unwrap(); assert_eq!( serde_json::from_slice::(&bytes).unwrap(), - json!([{"alias":"lab","status":"backoff","class":"key","sinceMs":100,"nextRetryMs":200,"cause":"offline","root":"/engine"}]) + json!([{"alias":"lab","status":"backoff","class":"key","connectRequired":cfg!(windows),"sinceMs":100,"nextRetryMs":200,"cause":"offline","root":"/engine"}]) ); let request = || { Request::builder() diff --git a/ui/src/api.ts b/ui/src/api.ts index a882bccf2..d8f04054a 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -268,6 +268,8 @@ export interface EngineHost { root: string; status: HostStatus; class: "key" | "interactive" | null; + /** The old launcher on Windows logs in only through Connect, even with a key. */ + connectRequired: boolean; sinceMs: number; nextRetryMs: number | null; cause: string | null; diff --git a/ui/src/components/SettingsPage.tsx b/ui/src/components/SettingsPage.tsx index f641ac387..3ff030747 100644 --- a/ui/src/components/SettingsPage.tsx +++ b/ui/src/components/SettingsPage.tsx @@ -1236,8 +1236,8 @@ function SshSection() { // A Test run this session speaks for a connected host; trouble on the host outranks it. const engineShown = !connecting && engine !== undefined && ENGINE_HOST_SHOWN.has(engine.status) && !(engine.status === "live" && executionTest) ? engine : null; - const keyHost = engine?.class === "key"; - // Key hosts never need Connect: Retry while backing off, otherwise Test. + const keyHost = engine?.class === "key" && !engine.connectRequired; + // Key hosts need no Connect: Retry while backing off, otherwise Test. const keyAction = !keyHost || engineShown?.status === "needs_auth" ? null : engineShown?.status === "backoff" ? "retry" : "test"; const open = expandedHosts[h.host] ?? false; const hasTerminal = connecting || Boolean(connectionError); diff --git a/ui/src/queries/invalidation.ts b/ui/src/queries/invalidation.ts index 801f6135c..5161919cf 100644 --- a/ui/src/queries/invalidation.ts +++ b/ui/src/queries/invalidation.ts @@ -40,7 +40,7 @@ const settingsFamilies: Record = { "lit-sources": ["getLitSources"], projects: ["getProjectDefaults", "getProjectGitStatus"], telemetry: ["getTelemetry"], - "run-engine": ["getRunEngine"], + "run-engine": ["getRunEngine", "listEngineHosts"], }; export function createInvalidation(client: WorkspaceClient) { const { From 1da34964f9a45339515bf20809b86937b9bbe31c Mon Sep 17 00:00:00 2001 From: clover caruso Date: Thu, 5 Nov 2026 14:31:13 -0800 Subject: [PATCH 4/4] test: expect Connect only while the old launcher runs With the engine setting on, a submitting run alone does not need the old launcher, so key hosts report connectRequired false on Windows. Assisted-by: claude-opus-5.5 --- src/commands/up/api_v2/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/commands/up/api_v2/tests.rs b/src/commands/up/api_v2/tests.rs index 0c7d1acb9..c3555ea42 100644 --- a/src/commands/up/api_v2/tests.rs +++ b/src/commands/up/api_v2/tests.rs @@ -1709,9 +1709,10 @@ async fn dashboard_host_routes_report_states_and_retry_only_key_hosts() { let bytes = axum::body::to_bytes(response.into_body(), 4096) .await .unwrap(); + let connect_required = cfg!(windows) && !crate::config::run_engine_settings().unwrap().0; assert_eq!( serde_json::from_slice::(&bytes).unwrap(), - json!([{"alias":"lab","status":"backoff","class":"key","connectRequired":cfg!(windows),"sinceMs":100,"nextRetryMs":200,"cause":"offline","root":"/engine"}]) + json!([{"alias":"lab","status":"backoff","class":"key","connectRequired":connect_required,"sinceMs":100,"nextRetryMs":200,"cause":"offline","root":"/engine"}]) ); let request = || { Request::builder()