Skip to content

Commit 331775c

Browse files
authored
fix: allow same-user Windows clients to attach across elevation (#4777)
refs #4717
1 parent fb8b9e2 commit 331775c

5 files changed

Lines changed: 324 additions & 32 deletions

File tree

‎docs/next/website/src/content/docs/windows-beta.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ For internal testing, `HERDR_MANIFEST_URL` can point the installer at a custom m
4949

5050
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.
5151

52+
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.
53+
5254
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.
5355

5456
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.

‎src/ipc.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,14 @@ pub(crate) fn bind_local_listener(path: &Path) -> io::Result<LocalListener> {
6666
#[cfg(windows)]
6767
{
6868
use interprocess::local_socket::{prelude::*, GenericNamespaced, ListenerOptions};
69+
use interprocess::os::windows::local_socket::ListenerOptionsExt as _;
6970

7071
let name = path.to_string_lossy().to_string();
7172
let name = name.to_ns_name::<GenericNamespaced>()?;
7273
let listener = ListenerOptions::new()
7374
.name(name)
7475
.reclaim_name(false)
76+
.security_descriptor(crate::platform::local_server_security_descriptor()?)
7577
.create_sync()?;
7678
fs::write(path, windows_socket_marker())?;
7779
Ok(listener)

‎src/platform/windows.rs‎

Lines changed: 220 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,85 @@ use std::{
1616
mod clipboard_image;
1717
mod config_backup;
1818

19+
pub(crate) fn probe_local_server(path: &std::path::Path) -> std::io::Result<()> {
20+
use interprocess::os::windows::named_pipe::{pipe_mode::Bytes, DuplexPipeStream};
21+
use interprocess::ConnectWaitMode;
22+
23+
// The local-socket wrapper ignores wait_mode on Windows in interprocess
24+
// 2.4.2. Its named-pipe API honors it without importing/reopening a handle.
25+
let name = format!(r"\\.\pipe\{}", path.to_string_lossy());
26+
DuplexPipeStream::<Bytes>::connect_by_path_with_wait_mode(
27+
name.as_str(),
28+
ConnectWaitMode::Timeout(Duration::from_millis(500)),
29+
)
30+
.map(|_| ())
31+
.map_err(local_server_connection_error)
32+
}
33+
34+
pub(crate) fn local_server_security_descriptor(
35+
) -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {
36+
user_security_descriptor("GRGW")
37+
}
38+
39+
fn user_security_descriptor(
40+
access: &str,
41+
) -> std::io::Result<interprocess::os::windows::security_descriptor::SecurityDescriptor> {
42+
use interprocess::os::windows::security_descriptor::SecurityDescriptor;
43+
use widestring::{U16CStr, U16CString};
44+
use windows_sys::Win32::Security::{
45+
Authorization::ConvertSidToStringSidW, GetTokenInformation, TokenUser, TOKEN_QUERY,
46+
TOKEN_USER,
47+
};
48+
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
49+
50+
let mut token = null_mut();
51+
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
52+
return Err(std::io::Error::last_os_error());
53+
}
54+
let token = unsafe { OwnedHandle::from_raw_handle(token) };
55+
let mut needed = 0;
56+
unsafe { GetTokenInformation(token.as_raw_handle(), TokenUser, null_mut(), 0, &mut needed) };
57+
if needed == 0 {
58+
return Err(std::io::Error::last_os_error());
59+
}
60+
// usize storage keeps TOKEN_USER aligned and its trailing SID alive.
61+
let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
62+
if unsafe {
63+
GetTokenInformation(
64+
token.as_raw_handle(),
65+
TokenUser,
66+
buffer.as_mut_ptr().cast(),
67+
needed,
68+
&mut needed,
69+
)
70+
} == 0
71+
{
72+
return Err(std::io::Error::last_os_error());
73+
}
74+
// SAFETY: GetTokenInformation initialized the aligned TOKEN_USER and SID.
75+
let user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
76+
let mut sid = null_mut();
77+
if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid) } == 0 {
78+
return Err(std::io::Error::last_os_error());
79+
}
80+
let sid_text = unsafe { U16CStr::from_ptr_str(sid) }.to_string_lossy();
81+
unsafe { LocalFree(sid.cast()) };
82+
// The elevated token's default owner can be Administrators. Authorize the
83+
// account instead: its ordinary clients deliberately control elevated panes.
84+
let sddl = U16CString::from_str(format!("D:P(A;;GA;;;SY)(A;;{access};;;{sid_text})"))
85+
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
86+
SecurityDescriptor::deserialize(&sddl)
87+
}
88+
1989
pub(crate) fn local_server_connection_error(error: std::io::Error) -> std::io::Error {
2090
if error.kind() != std::io::ErrorKind::PermissionDenied {
2191
return error;
2292
}
2393
std::io::Error::new(
2494
error.kind(),
2595
format!(
26-
"If this server is elevated, stop it in an admin shell; \
27-
reopen Herdr normally (closes panes). {error}"
96+
"For an older elevated server, stop it in an admin shell and \
97+
reopen Herdr (closes panes). {error}"
2898
),
2999
)
30100
}
@@ -190,20 +260,15 @@ pub(crate) fn create_config_temporary(
190260
.create_new(true)
191261
.open(path);
192262
}
193-
use interprocess::os::windows::security_descriptor::{
194-
AsSecurityDescriptorExt as _, SecurityDescriptor,
195-
};
196-
use widestring::U16CString;
263+
use interprocess::os::windows::security_descriptor::AsSecurityDescriptorExt as _;
197264
use windows_sys::Win32::{
198265
Foundation::GENERIC_WRITE,
199266
Storage::FileSystem::{
200267
CreateFileW, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_DELETE, FILE_SHARE_READ,
201268
FILE_SHARE_WRITE,
202269
},
203270
};
204-
let sddl =
205-
U16CString::from_str("D:P(A;;GA;;;SY)(A;;GA;;;OW)").map_err(std::io::Error::other)?;
206-
let descriptor = SecurityDescriptor::deserialize(&sddl)?;
271+
let descriptor = user_security_descriptor("GA")?;
207272
let mut attributes = SECURITY_ATTRIBUTES {
208273
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
209274
lpSecurityDescriptor: null_mut(),
@@ -3133,6 +3198,152 @@ mod tests {
31333198
AllocConsole, FreeConsole, GetConsoleProcessList, GetConsoleWindow,
31343199
};
31353200

3201+
#[test]
3202+
fn local_resources_authorize_account_without_admin_rights() {
3203+
use interprocess::local_socket::traits::Listener as _;
3204+
use std::io::{Read, Write};
3205+
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
3206+
use windows_sys::Win32::Security::{
3207+
CreateRestrictedToken, GetTokenInformation, ImpersonateLoggedOnUser, RevertToSelf,
3208+
TokenUser, DISABLE_MAX_PRIVILEGE, LUA_TOKEN, SID_AND_ATTRIBUTES, TOKEN_DUPLICATE,
3209+
TOKEN_QUERY, TOKEN_USER,
3210+
};
3211+
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
3212+
3213+
let path =
3214+
std::env::temp_dir().join(format!("herdr-user-pipe-{}.sock", std::process::id()));
3215+
let listener = crate::ipc::bind_local_listener(&path).unwrap();
3216+
let mut raw_token = std::ptr::null_mut();
3217+
assert_ne!(
3218+
unsafe {
3219+
OpenProcessToken(
3220+
GetCurrentProcess(),
3221+
TOKEN_DUPLICATE | TOKEN_QUERY,
3222+
&mut raw_token,
3223+
)
3224+
},
3225+
0
3226+
);
3227+
let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
3228+
let mut restricted = std::ptr::null_mut();
3229+
assert_ne!(
3230+
unsafe {
3231+
CreateRestrictedToken(
3232+
token.as_raw_handle(),
3233+
DISABLE_MAX_PRIVILEGE | LUA_TOKEN,
3234+
0,
3235+
std::ptr::null(),
3236+
0,
3237+
std::ptr::null(),
3238+
0,
3239+
std::ptr::null(),
3240+
&mut restricted,
3241+
)
3242+
},
3243+
0
3244+
);
3245+
let restricted = unsafe { OwnedHandle::from_raw_handle(restricted) };
3246+
let private_path = path.with_extension("private");
3247+
super::create_config_temporary(&private_path, true)
3248+
.unwrap()
3249+
.write_all(b"recovery")
3250+
.unwrap();
3251+
assert_ne!(
3252+
unsafe { ImpersonateLoggedOnUser(restricted.as_raw_handle()) },
3253+
0
3254+
);
3255+
let connection = crate::ipc::connect_local_stream(&path);
3256+
let private_read = fs::read(&private_path);
3257+
let private_write = fs::write(&private_path, b"updated");
3258+
let reverted = unsafe { RevertToSelf() };
3259+
assert_ne!(reverted, 0);
3260+
assert_eq!(private_read.unwrap(), b"recovery");
3261+
private_write.unwrap();
3262+
let mut client = connection.expect("the account SID must work without admin membership");
3263+
let mut server = listener.accept().unwrap();
3264+
client.write_all(b"account").unwrap();
3265+
let mut received = [0; 7];
3266+
server.read_exact(&mut received).unwrap();
3267+
assert_eq!(&received, b"account");
3268+
3269+
// Removing the account SID must not leave access through Everyone or
3270+
// another ordinary group. This exercises the real DACL access check.
3271+
let mut size = 0;
3272+
unsafe {
3273+
GetTokenInformation(
3274+
token.as_raw_handle(),
3275+
TokenUser,
3276+
std::ptr::null_mut(),
3277+
0,
3278+
&mut size,
3279+
)
3280+
};
3281+
let mut user = vec![0usize; (size as usize).div_ceil(std::mem::size_of::<usize>())];
3282+
assert_ne!(
3283+
unsafe {
3284+
GetTokenInformation(
3285+
token.as_raw_handle(),
3286+
TokenUser,
3287+
user.as_mut_ptr().cast(),
3288+
size,
3289+
&mut size,
3290+
)
3291+
},
3292+
0
3293+
);
3294+
let user = unsafe { &*user.as_ptr().cast::<TOKEN_USER>() };
3295+
let disabled = SID_AND_ATTRIBUTES {
3296+
Sid: user.User.Sid,
3297+
Attributes: 0,
3298+
};
3299+
let mut without_account = std::ptr::null_mut();
3300+
assert_ne!(
3301+
unsafe {
3302+
CreateRestrictedToken(
3303+
token.as_raw_handle(),
3304+
DISABLE_MAX_PRIVILEGE | LUA_TOKEN,
3305+
1,
3306+
&disabled,
3307+
0,
3308+
std::ptr::null(),
3309+
0,
3310+
std::ptr::null(),
3311+
&mut without_account,
3312+
)
3313+
},
3314+
0
3315+
);
3316+
let without_account = unsafe { OwnedHandle::from_raw_handle(without_account) };
3317+
assert_ne!(
3318+
unsafe { ImpersonateLoggedOnUser(without_account.as_raw_handle()) },
3319+
0
3320+
);
3321+
let denied = crate::ipc::connect_local_stream(&path);
3322+
let private_denied = fs::read(&private_path);
3323+
let reverted = unsafe { RevertToSelf() };
3324+
assert_ne!(reverted, 0);
3325+
assert_eq!(
3326+
denied.unwrap_err().kind(),
3327+
std::io::ErrorKind::PermissionDenied
3328+
);
3329+
assert_eq!(
3330+
private_denied.unwrap_err().kind(),
3331+
std::io::ErrorKind::PermissionDenied
3332+
);
3333+
assert_ne!(
3334+
unsafe { ImpersonateLoggedOnUser(restricted.as_raw_handle()) },
3335+
0
3336+
);
3337+
let removed = fs::remove_file(private_path);
3338+
let reverted = unsafe { RevertToSelf() };
3339+
assert_ne!(reverted, 0);
3340+
removed.expect("the account must be able to remove its private recovery files");
3341+
drop(client);
3342+
drop(server);
3343+
drop(listener);
3344+
fs::remove_file(path).unwrap();
3345+
}
3346+
31363347
#[test]
31373348
fn clipboard_text_equals_normalizes_line_endings() {
31383349
assert!(super::clipboard_text_equals("hello", b"hello"));

‎src/remote/host.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pub(crate) fn run_remote_client_bridge(args: &[String]) -> io::Result<()> {
3939

4040
fn ensure_remote_server_running() -> io::Result<()> {
4141
let socket_path = crate::server::socket_paths::client_socket_path();
42-
if crate::server::autodetect::is_server_listening() {
42+
if crate::server::autodetect::is_server_listening()? {
4343
let status = crate::api::read_runtime_status_at(
4444
&crate::api::socket_path(),
4545
Duration::from_millis(500),

0 commit comments

Comments
 (0)