mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
feat(windows): support gpclient authentication and VPN connections
This commit is contained in:
49 files changed
+1888
-390
No files matched your search
@@ -101,10 +101,7 @@ uzers = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
file-rotate = { version = "0.8.0", optional = true }
|
||||
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation"] }
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] }
|
||||
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Console", "Win32_System_RemoteDesktop", "Win32_System_SystemServices", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
[[test]]
|
||||
name = "certificate_compatibility"
|
||||
|
||||
@@ -8,6 +8,13 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::credential::AuthCookieCredential;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "cookie_store/unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(windows)]
|
||||
#[path = "cookie_store/windows.rs"]
|
||||
mod platform;
|
||||
|
||||
const STORE_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
@@ -45,16 +52,15 @@ impl StoredCookie {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie_path(custom: Option<&str>) -> PathBuf {
|
||||
if let Some(p) = custom {
|
||||
return PathBuf::from(p);
|
||||
pub fn cookie_path(custom: Option<&str>) -> Option<PathBuf> {
|
||||
match custom {
|
||||
Some(path) => Some(PathBuf::from(path)),
|
||||
None => platform::default_path(),
|
||||
}
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
|
||||
PathBuf::from(home).join(".config/gpclient/cookie.json")
|
||||
}
|
||||
|
||||
pub fn load(path: &Path, server: &str, host_id: &str) -> Option<StoredCookie> {
|
||||
let bytes = fs::read(path).ok()?;
|
||||
let bytes = zeroize::Zeroizing::new(platform::decode(fs::read(path).ok()?).ok()?);
|
||||
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
|
||||
if stored.version != STORE_VERSION || stored.server != server || stored.host_id != host_id {
|
||||
return None;
|
||||
@@ -67,12 +73,12 @@ pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> {
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
set_private_dir_permissions(parent)?;
|
||||
platform::prepare_directory(parent)?;
|
||||
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(&serde_json::to_vec(stored)?)?;
|
||||
tmp.write_all(&platform::encode(serde_json::to_vec(stored)?)?)?;
|
||||
tmp.flush()?;
|
||||
set_private_file_permissions(tmp.path())?;
|
||||
platform::prepare_file(tmp.path())?;
|
||||
tmp.persist(path)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -81,60 +87,6 @@ pub fn clear(path: &Path) {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
|
||||
use permissions::{set_private_dir_permissions, set_private_file_permissions};
|
||||
|
||||
mod permissions {
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix {
|
||||
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
|
||||
|
||||
pub(super) fn set_private_dir(path: &Path) -> anyhow::Result<()> {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn set_private_file(path: &Path) -> anyhow::Result<()> {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn file_mode(path: &Path) -> Option<u32> {
|
||||
Some(fs::metadata(path).ok()?.permissions().mode() & 0o777)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_private_dir_permissions(path: &Path) -> anyhow::Result<()> {
|
||||
#[cfg(unix)]
|
||||
unix::set_private_dir(path)?;
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn set_private_file_permissions(path: &Path) -> anyhow::Result<()> {
|
||||
#[cfg(unix)]
|
||||
unix::set_private_file(path)?;
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn file_mode(path: &Path) -> Option<u32> {
|
||||
#[cfg(unix)]
|
||||
return unix::file_mode(path);
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -149,6 +101,24 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_cookie_cache_uses_profile_storage_and_protects_credentials() {
|
||||
let default_path = cookie_path(None).unwrap();
|
||||
assert!(default_path.starts_with(PathBuf::from(std::env::var_os("LOCALAPPDATA").unwrap())));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("cookie.json");
|
||||
save(&path, &sample()).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert!(
|
||||
!bytes
|
||||
.windows(b"prelogon-auth".len())
|
||||
.any(|part| part == b"prelogon-auth")
|
||||
);
|
||||
assert!(load(&path, "vpn.example.com", "host-1").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_and_mode_0600() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -156,8 +126,10 @@ mod tests {
|
||||
let s = sample();
|
||||
save(&path, &s).unwrap();
|
||||
|
||||
if let Some(mode) = permissions::file_mode(&path) {
|
||||
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
|
||||
let loaded = load(&path, "vpn.example.com", "host-1").unwrap();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub(super) fn default_path() -> Option<PathBuf> {
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
|
||||
Some(PathBuf::from(home).join(".config/gpclient/cookie.json"))
|
||||
}
|
||||
|
||||
pub(super) fn encode(bytes: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(super) use encode as decode;
|
||||
|
||||
pub(super) fn prepare_directory(path: &Path) -> io::Result<()> {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o700))
|
||||
}
|
||||
|
||||
pub(super) fn prepare_file(path: &Path) -> io::Result<()> {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600))
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
io,
|
||||
os::windows::ffi::OsStringExt,
|
||||
path::{Path, PathBuf},
|
||||
ptr, slice,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::Cryptography::{CRYPT_INTEGER_BLOB, CRYPTPROTECT_UI_FORBIDDEN, CryptProtectData, CryptUnprotectData},
|
||||
UI::Shell::{CSIDL_LOCAL_APPDATA, SHGetFolderPathW},
|
||||
};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
pub(super) fn default_path() -> Option<PathBuf> {
|
||||
let mut path = [0; 260];
|
||||
let result = unsafe {
|
||||
SHGetFolderPathW(
|
||||
ptr::null_mut(),
|
||||
CSIDL_LOCAL_APPDATA as i32,
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
path.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
let length = path.iter().position(|&unit| unit == 0).filter(|&length| length > 0)?;
|
||||
(result >= 0).then(|| PathBuf::from(OsString::from_wide(&path[..length])).join(r"GP Connect\gpclient\cookie.bin"))
|
||||
}
|
||||
|
||||
pub(super) fn encode(mut bytes: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
let result = transform(&mut bytes, true);
|
||||
bytes.zeroize();
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn decode(mut bytes: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
transform(&mut bytes, false)
|
||||
}
|
||||
|
||||
// DPAPI encrypts for the current Windows user, including at custom paths.
|
||||
fn transform(bytes: &mut [u8], protect: bool) -> io::Result<Vec<u8>> {
|
||||
let input = CRYPT_INTEGER_BLOB {
|
||||
cbData: u32::try_from(bytes.len()).map_err(io::Error::other)?,
|
||||
pbData: bytes.as_mut_ptr(),
|
||||
};
|
||||
let mut output = CRYPT_INTEGER_BLOB::default();
|
||||
let success = unsafe {
|
||||
if protect {
|
||||
CryptProtectData(
|
||||
&input,
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
CRYPTPROTECT_UI_FORBIDDEN,
|
||||
&mut output,
|
||||
)
|
||||
} else {
|
||||
CryptUnprotectData(
|
||||
&input,
|
||||
ptr::null_mut(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
CRYPTPROTECT_UI_FORBIDDEN,
|
||||
&mut output,
|
||||
)
|
||||
}
|
||||
};
|
||||
if success == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if output.pbData.is_null() {
|
||||
return Err(io::Error::other("Windows returned no cookie cache data"));
|
||||
}
|
||||
let buffer = unsafe { slice::from_raw_parts_mut(output.pbData, output.cbData as usize) };
|
||||
let result = buffer.to_vec();
|
||||
buffer.zeroize();
|
||||
unsafe { LocalFree(output.pbData.cast()) };
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn prepare_directory(_: &Path) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) use prepare_directory as prepare_file;
|
||||
@@ -32,6 +32,8 @@ pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
auth_executable: Option<&'a str>,
|
||||
#[cfg(windows)]
|
||||
windows_cli: bool,
|
||||
gateway: bool,
|
||||
saml_request: Option<&'a str>,
|
||||
os: Option<&'a str>,
|
||||
@@ -65,6 +67,8 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken::new(),
|
||||
server,
|
||||
auth_executable: None,
|
||||
#[cfg(windows)]
|
||||
windows_cli: false,
|
||||
gateway: false,
|
||||
saml_request: None,
|
||||
os: None,
|
||||
@@ -93,6 +97,12 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn with_windows_cli_launch(mut self) -> Self {
|
||||
self.windows_cli = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn desktop_compatibility_graphics(mut self) -> Self {
|
||||
self.desktop_compatibility_graphics = true;
|
||||
self
|
||||
@@ -297,6 +307,12 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
#[cfg(windows)]
|
||||
let program = if self.windows_cli {
|
||||
crate::windows::application_directory()?.join("gpauth.exe")
|
||||
} else {
|
||||
program
|
||||
};
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let mut command = auth_cmd.into_non_root()?.into_std();
|
||||
@@ -317,6 +333,8 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
let detect_gbm_failure = can_use_shared_memory && !use_shared_memory;
|
||||
let stdin = auth_stdin(self.browser);
|
||||
let cancellation = self.cancellation.clone();
|
||||
#[cfg(windows)]
|
||||
let windows_cli = self.windows_cli;
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(feature = "logger")]
|
||||
let stderr = crate::logger::diagnostic_writer();
|
||||
@@ -351,6 +369,8 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
},
|
||||
&mut stderr,
|
||||
stdin,
|
||||
#[cfg(windows)]
|
||||
windows_cli,
|
||||
);
|
||||
std::io::Write::flush(&mut stderr)?;
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
|
||||
@@ -39,3 +39,15 @@ pub mod rendering_recovery;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/user_process.rs"]
|
||||
pub mod user_process;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/desktop_auth.rs"]
|
||||
mod desktop_auth;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/auth_bootstrap.rs"]
|
||||
pub mod auth_bootstrap;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/console_input.rs"]
|
||||
mod console_input;
|
||||
@@ -0,0 +1,175 @@
|
||||
//! One-shot launch arguments for the installed Windows CLI authenticator.
|
||||
use std::{env, ffi::OsStr, io, os::windows::io::AsRawHandle, process::Command, time::Duration};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::windows::named_pipe::{ClientOptions, NamedPipeServer},
|
||||
time,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::{GetNamedPipeClientProcessId, GetNamedPipeServerProcessId};
|
||||
|
||||
use super::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV;
|
||||
use crate::collection::CollectionControl;
|
||||
|
||||
const FLAG: &str = "--windows-cli-bootstrap";
|
||||
const MAX_BYTES: usize = 256 * 1024;
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const RECEIVED: u8 = 1;
|
||||
|
||||
pub(super) struct AuthBootstrap {
|
||||
name: String,
|
||||
pipe: NamedPipeServer,
|
||||
request: Vec<u8>,
|
||||
}
|
||||
|
||||
impl AuthBootstrap {
|
||||
pub(super) fn prepare(command: &Command) -> io::Result<Self> {
|
||||
let args: Vec<_> = command
|
||||
.get_args()
|
||||
.map(|arg| {
|
||||
arg
|
||||
.to_str()
|
||||
.ok_or_else(|| invalid("Invalid Windows authentication argument"))
|
||||
})
|
||||
.collect::<io::Result<_>>()?;
|
||||
let request = serde_json::to_vec(&args)?;
|
||||
check_length(request.len())?;
|
||||
let name = format!(r"\\.\pipe\GPConnect.Auth.{}", uuid::Uuid::new_v4());
|
||||
let pipe = crate::windows::create_user_pipe(&name, true)?;
|
||||
Ok(Self { name, pipe, request })
|
||||
}
|
||||
|
||||
pub(super) fn arguments(&self) -> [&OsStr; 2] {
|
||||
[OsStr::new(FLAG), OsStr::new(&self.name)]
|
||||
}
|
||||
|
||||
/// Build the short command used when the CLI and authenticator share a token.
|
||||
pub(super) fn command(&self, original: &Command) -> Command {
|
||||
let mut command = Command::new(original.get_program());
|
||||
command.args(self.arguments());
|
||||
for (name, value) in original.get_envs() {
|
||||
match value {
|
||||
Some(value) => command.env(name, value),
|
||||
None => command.env_remove(name),
|
||||
};
|
||||
}
|
||||
if let Some(directory) = original.get_current_dir() {
|
||||
command.current_dir(directory);
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
pub(super) fn send_to_child(self, pid: u32, control: &dyn CollectionControl) -> io::Result<()> {
|
||||
tokio::runtime::Handle::current().block_on(self.send(pid, control))
|
||||
}
|
||||
|
||||
async fn send(mut self, expected_pid: u32, control: &dyn CollectionControl) -> io::Result<()> {
|
||||
let send = async {
|
||||
self.pipe.connect().await?;
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeClientProcessId(self.pipe.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if pid != expected_pid {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"Unexpected authentication pipe client",
|
||||
));
|
||||
}
|
||||
self.pipe.write_u32(self.request.len() as u32).await?;
|
||||
self.pipe.write_all(&self.request).await?;
|
||||
if self.pipe.read_u8().await? != RECEIVED {
|
||||
return Err(invalid("Windows authentication arguments were not accepted"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let check = async {
|
||||
loop {
|
||||
control.check()?;
|
||||
time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
};
|
||||
time::timeout(TIMEOUT, async {
|
||||
tokio::select! {
|
||||
result = send => result,
|
||||
result = check => result,
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognize the internal bootstrap before handing actual arguments to the normal parser.
|
||||
pub async fn receive_arguments() -> io::Result<Option<Vec<String>>> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
if args.next().as_deref() != Some(OsStr::new(FLAG)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = args
|
||||
.next()
|
||||
.ok_or_else(|| invalid("Missing Windows authentication pipe"))?;
|
||||
if args.next().is_some() {
|
||||
return Err(invalid("Unexpected Windows authentication bootstrap argument"));
|
||||
}
|
||||
let expected_pid: u32 = env::var(AUTH_PARENT_PROCESS_ID_ENV)
|
||||
.ok()
|
||||
.and_then(|value| value.parse().ok())
|
||||
.filter(|pid| *pid != 0)
|
||||
.ok_or_else(|| invalid("Missing Windows authentication parent process"))?;
|
||||
receive(&name, expected_pid).await.map(Some)
|
||||
}
|
||||
|
||||
async fn receive(name: &OsStr, expected_pid: u32) -> io::Result<Vec<String>> {
|
||||
time::timeout(TIMEOUT, async {
|
||||
let mut pipe = ClientOptions::new().open(name)?;
|
||||
let mut pid = 0;
|
||||
if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if pid != expected_pid {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"Unexpected authentication pipe server",
|
||||
));
|
||||
}
|
||||
let length = pipe.read_u32().await? as usize;
|
||||
check_length(length)?;
|
||||
let mut request = vec![0; length];
|
||||
pipe.read_exact(&mut request).await?;
|
||||
let args = serde_json::from_slice(&request)?;
|
||||
pipe.write_u8(RECEIVED).await?;
|
||||
Ok(args)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn check_length(length: usize) -> io::Result<()> {
|
||||
if length == 0 || length > MAX_BYTES {
|
||||
return Err(invalid("Windows authentication launch arguments exceed their limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn large_saml_request_round_trips_outside_the_os_command_line() {
|
||||
let request = format!("<html>{}</html>", "🎵".repeat(20_000));
|
||||
let mut command = Command::new("gpauth.exe");
|
||||
command.args(["portal.example.test", "--saml-request", &request]);
|
||||
let bootstrap = AuthBootstrap::prepare(&command).unwrap();
|
||||
assert!(request.encode_utf16().count() > 32_767);
|
||||
let launch = bootstrap.command(&command);
|
||||
assert_eq!(launch.get_args().collect::<Vec<_>>(), bootstrap.arguments());
|
||||
let name = bootstrap.name.clone();
|
||||
let pid = std::process::id();
|
||||
let (sent, received) = tokio::join!(bootstrap.send(pid, &|| Ok(())), receive(OsStr::new(&name), pid));
|
||||
sent.unwrap();
|
||||
assert_eq!(received.unwrap(), ["portal.example.test", "--saml-request", &request]);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
|
||||
use super::{
|
||||
auth_bootstrap::AuthBootstrap,
|
||||
console_input::{self, ConsoleInput},
|
||||
desktop_auth::DesktopChild,
|
||||
};
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
os::windows::io::AsRawHandle,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
os::windows::io::{AsRawHandle, OwnedHandle},
|
||||
process::{Child, Command, ExitStatus, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
@@ -30,45 +36,35 @@ pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl,
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
ChildInput::Null,
|
||||
false,
|
||||
)
|
||||
.map(|observed| observed.output)
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
mut command: Command,
|
||||
command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin: ChildInput<'_>,
|
||||
windows_cli_auth: bool,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
// Windows desktop processes must not open a console for each helper.
|
||||
use std::os::windows::process::CommandExt;
|
||||
if !matches!(stdin, ChildInput::Terminal) {
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
});
|
||||
command.stderr(Stdio::piped());
|
||||
command.stdin(match stdin {
|
||||
ChildInput::Terminal => Stdio::inherit(),
|
||||
ChildInput::Null => Stdio::null(),
|
||||
ChildInput::Frame(_) => Stdio::piped(),
|
||||
});
|
||||
let mut child = ControlledChild(command.spawn()?);
|
||||
let input = if let ChildInput::Frame(frame) = stdin {
|
||||
let mut pipe = child.0.stdin.take().expect("piped stdin");
|
||||
let bootstrap = windows_cli_auth.then(|| AuthBootstrap::prepare(&command)).transpose()?;
|
||||
let (mut child, mut stdout, mut stderr, input) = match bootstrap {
|
||||
Some(bootstrap) if crate::windows::is_elevated()? => {
|
||||
let (child, stdout, stderr, input) = DesktopChild::spawn(&command, bootstrap, &stdin, control)?;
|
||||
(ControlledChild::Desktop(child), Some(stdout), stderr, input)
|
||||
}
|
||||
bootstrap => spawn_command(command, &stdin, output_limit, bootstrap, control)?,
|
||||
};
|
||||
let input = if let (ChildInput::Frame(frame), Some(mut pipe)) = (stdin, input) {
|
||||
let frame = frame.to_vec();
|
||||
Some(thread::spawn(move || pipe.write_all(&frame)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut stdout = child.0.stdout.take();
|
||||
let mut stderr = child.0.stderr.take().expect("piped stderr");
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
loop {
|
||||
@@ -86,7 +82,7 @@ pub(crate) fn run_observed(
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
if let Some(status) = child.0.try_wait()? {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
// Drain the remaining buffered output after the process exits.
|
||||
if let Some(pipe) = &mut stdout {
|
||||
loop {
|
||||
@@ -126,6 +122,60 @@ pub(crate) fn run_observed(
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_command(
|
||||
command: Command,
|
||||
stdin: &ChildInput<'_>,
|
||||
output_limit: Option<usize>,
|
||||
bootstrap: Option<AuthBootstrap>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<(ControlledChild, Option<File>, File, Option<File>)> {
|
||||
let mut command = match &bootstrap {
|
||||
Some(bootstrap) => bootstrap.command(&command),
|
||||
None => command,
|
||||
};
|
||||
// Windows desktop processes must not open a console for each helper.
|
||||
use std::os::windows::process::CommandExt;
|
||||
if !matches!(stdin, ChildInput::Terminal) {
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
});
|
||||
command.stderr(Stdio::piped());
|
||||
let terminal = if bootstrap.is_some() && matches!(stdin, ChildInput::Terminal) {
|
||||
let input = console_input::terminal_input()?;
|
||||
console_input::is_console(&input).then_some(input)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
command.stdin(match stdin {
|
||||
ChildInput::Terminal if terminal.is_none() => Stdio::inherit(),
|
||||
ChildInput::Terminal => Stdio::piped(),
|
||||
ChildInput::Null => Stdio::null(),
|
||||
ChildInput::Frame(_) => Stdio::piped(),
|
||||
});
|
||||
let mut child = StandardChild {
|
||||
child: command.spawn()?,
|
||||
console_input: None,
|
||||
};
|
||||
if let Some(bootstrap) = bootstrap {
|
||||
bootstrap.send_to_child(child.child.id(), control)?;
|
||||
}
|
||||
let stdout = child
|
||||
.child
|
||||
.stdout
|
||||
.take()
|
||||
.map(|pipe| File::from(OwnedHandle::from(pipe)));
|
||||
let stderr = File::from(OwnedHandle::from(child.child.stderr.take().expect("piped stderr")));
|
||||
let mut input = child.child.stdin.take().map(|pipe| File::from(OwnedHandle::from(pipe)));
|
||||
if let Some(terminal) = terminal {
|
||||
child.console_input = Some(ConsoleInput::start(terminal, input.take().expect("piped stdin"))?);
|
||||
}
|
||||
Ok((ControlledChild::Standard(child), stdout, stderr, input))
|
||||
}
|
||||
|
||||
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let mut available = 0;
|
||||
let success = unsafe {
|
||||
@@ -152,11 +202,34 @@ fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io
|
||||
pipe.read(&mut buffer[..length])
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
impl Drop for ControlledChild {
|
||||
enum ControlledChild {
|
||||
Standard(StandardChild),
|
||||
Desktop(DesktopChild),
|
||||
}
|
||||
|
||||
impl ControlledChild {
|
||||
fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
|
||||
match self {
|
||||
Self::Standard(child) => {
|
||||
if let Some(input) = &mut child.console_input {
|
||||
input.check()?;
|
||||
}
|
||||
child.child.try_wait()
|
||||
}
|
||||
Self::Desktop(child) => child.try_wait(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct StandardChild {
|
||||
child: Child,
|
||||
console_input: Option<ConsoleInput>,
|
||||
}
|
||||
|
||||
impl Drop for StandardChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Relay a pasted browser callback from the elevated CLI's own console.
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Write},
|
||||
os::windows::io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
|
||||
ptr,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_OPERATION_ABORTED, INVALID_HANDLE_VALUE},
|
||||
System::{
|
||||
Console::{GetConsoleMode, GetStdHandle, ReadConsoleW, STD_INPUT_HANDLE},
|
||||
IO::CancelSynchronousIo,
|
||||
Threading::GetCurrentProcess,
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_CALLBACK_CHARS: usize = 64 * 1024;
|
||||
|
||||
pub(super) fn is_console(input: &OwnedHandle) -> bool {
|
||||
let mut mode = 0;
|
||||
unsafe { GetConsoleMode(input.as_raw_handle(), &mut mode) != 0 }
|
||||
}
|
||||
|
||||
pub(super) struct ConsoleInput {
|
||||
stop: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<io::Result<()>>>,
|
||||
}
|
||||
|
||||
impl ConsoleInput {
|
||||
pub(super) fn start(input: OwnedHandle, output: File) -> io::Result<Self> {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let worker_stop = stop.clone();
|
||||
let worker = thread::Builder::new().spawn(move || {
|
||||
let line = read_line(input, &worker_stop)?;
|
||||
if !worker_stop.load(Ordering::Relaxed) {
|
||||
let mut output = output;
|
||||
output.write_all(line.as_bytes())?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Self {
|
||||
stop,
|
||||
worker: Some(worker),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn check(&mut self) -> io::Result<()> {
|
||||
if self.worker.as_ref().is_some_and(JoinHandle::is_finished) {
|
||||
let worker = self.worker.take().expect("completed console reader");
|
||||
worker
|
||||
.join()
|
||||
.map_err(|_| io::Error::other("Console reader stopped unexpectedly"))??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConsoleInput {
|
||||
fn drop(&mut self) {
|
||||
if let Some(worker) = self.worker.take() {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
// Retry in case the worker was between checking stop and entering I/O.
|
||||
// Join before returning so a failed sign-in cannot consume a later prompt.
|
||||
while !worker.is_finished() {
|
||||
unsafe { CancelSynchronousIo(worker.as_raw_handle()) };
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_line(input: OwnedHandle, stop: &AtomicBool) -> io::Result<String> {
|
||||
let mut text = Vec::new();
|
||||
let mut buffer = [0u16; 4096];
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let mut count = 0;
|
||||
if unsafe {
|
||||
ReadConsoleW(
|
||||
input.as_raw_handle(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
buffer.len() as u32,
|
||||
&mut count,
|
||||
ptr::null(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(ERROR_OPERATION_ABORTED as i32) {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, error));
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
let chunk = &buffer[..count as usize];
|
||||
let newline = chunk.iter().position(|&ch| ch == b'\n' as u16);
|
||||
text.extend_from_slice(&chunk[..newline.map_or(chunk.len(), |index| index + 1)]);
|
||||
if text.len() > MAX_CALLBACK_CHARS {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Browser callback is too long",
|
||||
));
|
||||
}
|
||||
if newline.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
String::from_utf16(&text).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
|
||||
pub(super) fn terminal_input() -> io::Result<OwnedHandle> {
|
||||
let input = unsafe { GetStdHandle(STD_INPUT_HANDLE) };
|
||||
if input.is_null() || input == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::other("Manual browser sign-in requires terminal input"));
|
||||
}
|
||||
let input = unsafe { BorrowedHandle::borrow_raw(input) };
|
||||
let process = unsafe { GetCurrentProcess() };
|
||||
let mut duplicate = ptr::null_mut();
|
||||
if unsafe {
|
||||
DuplicateHandle(
|
||||
process,
|
||||
input.as_raw_handle(),
|
||||
process,
|
||||
&mut duplicate,
|
||||
0,
|
||||
1,
|
||||
DUPLICATE_SAME_ACCESS,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(duplicate) })
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Run the CLI's installed authenticator with the interactive user's standard token.
|
||||
use std::{
|
||||
env,
|
||||
fs::File,
|
||||
io,
|
||||
os::windows::{
|
||||
io::{AsHandle, AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
process::ExitStatusExt,
|
||||
},
|
||||
path::Path,
|
||||
process::{Command, ExitStatus},
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HANDLE, HANDLE_FLAG_INHERIT, SetHandleInformation, WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
Security::{
|
||||
DuplicateTokenEx, SECURITY_ATTRIBUTES, SecurityImpersonation, TOKEN_DUPLICATE, TOKEN_QUERY, TokenElevation,
|
||||
TokenPrimary, TokenSessionId,
|
||||
},
|
||||
System::{Pipes::CreatePipe, SystemServices::MAXIMUM_ALLOWED, Threading::*},
|
||||
UI::WindowsAndMessaging::{GetShellWindow, GetWindowThreadProcessId},
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_bootstrap::AuthBootstrap,
|
||||
command_runner::ChildInput,
|
||||
console_input::{self, ConsoleInput},
|
||||
user_process::{command_line, user_environment, wide},
|
||||
};
|
||||
use crate::{
|
||||
collection::CollectionControl,
|
||||
windows::{current_user_sid, token_u32, token_user_sid},
|
||||
};
|
||||
|
||||
pub(super) struct DesktopChild {
|
||||
process: OwnedHandle,
|
||||
console_input: Option<ConsoleInput>,
|
||||
}
|
||||
|
||||
impl DesktopChild {
|
||||
pub(super) fn spawn(
|
||||
command: &Command,
|
||||
bootstrap: AuthBootstrap,
|
||||
input: &ChildInput<'_>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<(Self, File, File, Option<File>)> {
|
||||
let desktop = desktop_token()?;
|
||||
let program = Path::new(command.get_program());
|
||||
if !program.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"The authenticator path must be absolute",
|
||||
));
|
||||
}
|
||||
let mut executable = wide(program.as_os_str())?;
|
||||
let mut arguments = command_line(&executable, bootstrap.arguments())?;
|
||||
executable.push(0);
|
||||
let mut environment = user_environment(
|
||||
desktop.as_handle(),
|
||||
command
|
||||
.get_envs()
|
||||
.filter_map(|(name, value)| value.map(|value| (name, value))),
|
||||
)?;
|
||||
let working_directory = match command.get_current_dir() {
|
||||
Some(directory) => directory.to_path_buf(),
|
||||
None => env::current_dir()?,
|
||||
};
|
||||
let mut directory = wide(working_directory.as_os_str())?;
|
||||
directory.push(0);
|
||||
let (stdout, child_out) = pipe(false)?;
|
||||
let (stderr, child_err) = pipe(false)?;
|
||||
let mut console = None;
|
||||
let (child_in, input_pipe) = match input {
|
||||
ChildInput::Terminal => {
|
||||
let terminal = console_input::terminal_input()?;
|
||||
if console_input::is_console(&terminal) {
|
||||
let (writer, reader) = pipe(true)?;
|
||||
console = Some((terminal, File::from(writer)));
|
||||
(reader, None)
|
||||
} else {
|
||||
(terminal, None)
|
||||
}
|
||||
}
|
||||
ChildInput::Null => {
|
||||
let (writer, reader) = pipe(true)?;
|
||||
drop(writer);
|
||||
(reader, None)
|
||||
}
|
||||
ChildInput::Frame(_) => {
|
||||
let (writer, reader) = pipe(true)?;
|
||||
(reader, Some(File::from(writer)))
|
||||
}
|
||||
};
|
||||
let startup = STARTUPINFOW {
|
||||
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
|
||||
dwFlags: STARTF_USESTDHANDLES,
|
||||
hStdInput: child_in.as_raw_handle(),
|
||||
hStdOutput: child_out.as_raw_handle(),
|
||||
hStdError: child_err.as_raw_handle(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut process = PROCESS_INFORMATION::default();
|
||||
let mut flags = CREATE_UNICODE_ENVIRONMENT;
|
||||
if !matches!(input, ChildInput::Terminal) {
|
||||
flags |= CREATE_NO_WINDOW;
|
||||
}
|
||||
if unsafe {
|
||||
CreateProcessWithTokenW(
|
||||
desktop.as_raw_handle(),
|
||||
0,
|
||||
executable.as_ptr(),
|
||||
arguments.as_mut_ptr(),
|
||||
flags,
|
||||
environment.as_mut_ptr().cast(),
|
||||
directory.as_ptr(),
|
||||
&startup,
|
||||
&mut process,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut child = Self {
|
||||
process: unsafe { OwnedHandle::from_raw_handle(process.hProcess) },
|
||||
console_input: None,
|
||||
};
|
||||
drop(unsafe { OwnedHandle::from_raw_handle(process.hThread) });
|
||||
bootstrap.send_to_child(process.dwProcessId, control)?;
|
||||
child.console_input = console
|
||||
.map(|(terminal, writer)| ConsoleInput::start(terminal, writer))
|
||||
.transpose()?;
|
||||
Ok((child, File::from(stdout), File::from(stderr), input_pipe))
|
||||
}
|
||||
|
||||
pub(super) fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
|
||||
if let Some(input) = &mut self.console_input {
|
||||
input.check()?;
|
||||
}
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
|
||||
WAIT_OBJECT_0 => {
|
||||
let mut code = 0;
|
||||
if unsafe { GetExitCodeProcess(self.process.as_raw_handle(), &mut code) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(Some(ExitStatus::from_raw(code)))
|
||||
}
|
||||
WAIT_TIMEOUT => Ok(None),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DesktopChild {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if WaitForSingleObject(self.process.as_raw_handle(), 0) == WAIT_TIMEOUT
|
||||
&& TerminateProcess(self.process.as_raw_handle(), 1) != 0
|
||||
{
|
||||
WaitForSingleObject(self.process.as_raw_handle(), INFINITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_token() -> io::Result<OwnedHandle> {
|
||||
let mut pid = 0;
|
||||
let window = unsafe { GetShellWindow() };
|
||||
if window.is_null() || unsafe { GetWindowThreadProcessId(window, &mut pid) } == 0 {
|
||||
return Err(io::Error::other("Sign-in requires an interactive Windows desktop"));
|
||||
}
|
||||
let process = owned(unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) })?;
|
||||
let mut token = ptr::null_mut();
|
||||
if unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY | TOKEN_DUPLICATE, &mut token) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let source = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
if unsafe { token_user_sid(token) }? != current_user_sid()?
|
||||
|| token_u32(source.as_handle(), TokenElevation)? != 0
|
||||
|| token_u32(source.as_handle(), TokenSessionId)? != session_id()?
|
||||
{
|
||||
return Err(io::Error::other(
|
||||
"Sign-in requires the terminal user's standard Windows desktop",
|
||||
));
|
||||
}
|
||||
let mut primary = ptr::null_mut();
|
||||
if unsafe {
|
||||
// A linked token queried without SeTcbPrivilege may only be usable for identification.
|
||||
// The shell already has the primary standard token in the interactive session.
|
||||
DuplicateTokenEx(
|
||||
token,
|
||||
MAXIMUM_ALLOWED,
|
||||
ptr::null(),
|
||||
SecurityImpersonation,
|
||||
TokenPrimary,
|
||||
&mut primary,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
owned(primary)
|
||||
}
|
||||
|
||||
fn session_id() -> io::Result<u32> {
|
||||
let mut session = 0;
|
||||
if unsafe { windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId(std::process::id(), &mut session) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn owned(handle: HANDLE) -> io::Result<OwnedHandle> {
|
||||
if handle.is_null() || handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
|
||||
/// Returns the parent's non-inheritable end, then the child's end.
|
||||
fn pipe(parent_writes: bool) -> io::Result<(OwnedHandle, OwnedHandle)> {
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
bInheritHandle: 1,
|
||||
lpSecurityDescriptor: ptr::null_mut(),
|
||||
};
|
||||
let mut read = ptr::null_mut();
|
||||
let mut write = ptr::null_mut();
|
||||
if unsafe { CreatePipe(&mut read, &mut write, &attributes, 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let read = unsafe { OwnedHandle::from_raw_handle(read) };
|
||||
let write = unsafe { OwnedHandle::from_raw_handle(write) };
|
||||
let (parent, child) = if parent_writes { (write, read) } else { (read, write) };
|
||||
if unsafe { SetHandleInformation(parent.as_raw_handle(), HANDLE_FLAG_INHERIT, 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok((parent, child))
|
||||
}
|
||||
@@ -36,7 +36,7 @@ impl Drop for Environment {
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||
}
|
||||
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
|
||||
pub(super) fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
|
||||
let value: Vec<_> = value.encode_wide().collect();
|
||||
if value.contains(&0) {
|
||||
return Err(invalid("Windows process strings cannot contain NUL"));
|
||||
@@ -63,12 +63,15 @@ fn quote(argument: &[u16], output: &mut Vec<u16>) {
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
|
||||
output.push(b'"' as u16);
|
||||
}
|
||||
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
|
||||
pub(super) fn command_line<'a>(
|
||||
program: &[u16],
|
||||
arguments: impl IntoIterator<Item = &'a OsStr>,
|
||||
) -> io::Result<Vec<u16>> {
|
||||
let mut output = Vec::new();
|
||||
quote(program, &mut output);
|
||||
for argument in arguments {
|
||||
output.push(b' ' as u16);
|
||||
quote(&wide(OsStr::new(argument))?, &mut output);
|
||||
quote(&wide(argument)?, &mut output);
|
||||
}
|
||||
output.push(0);
|
||||
if output.len() > 32767 {
|
||||
@@ -90,7 +93,10 @@ fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
|
||||
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
|
||||
.cmp(&CSTR_EQUAL)
|
||||
}
|
||||
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
|
||||
pub(super) fn user_environment<'a>(
|
||||
token: BorrowedHandle<'_>,
|
||||
variables: impl IntoIterator<Item = (&'a OsStr, &'a OsStr)>,
|
||||
) -> io::Result<Vec<u16>> {
|
||||
let mut pointer = ptr::null_mut();
|
||||
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
@@ -109,11 +115,11 @@ fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io
|
||||
}
|
||||
}
|
||||
for (name, value) in variables {
|
||||
if name.is_empty() || name.contains('=') {
|
||||
let name = wide(name)?;
|
||||
if name.is_empty() || name.contains(&(b'=' as u16)) {
|
||||
return Err(invalid("Invalid worker environment name"));
|
||||
}
|
||||
let name = wide(OsStr::new(name))?;
|
||||
let value = wide(OsStr::new(value))?;
|
||||
let value = wide(value)?;
|
||||
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
|
||||
let mut entry = name;
|
||||
entry.push(b'=' as u16);
|
||||
@@ -145,9 +151,14 @@ impl UserProcess {
|
||||
return Err(invalid("Windows worker executable must be absolute"));
|
||||
}
|
||||
let mut executable = wide(program.as_os_str())?;
|
||||
let mut command = command_line(&executable, arguments)?;
|
||||
let mut command = command_line(&executable, arguments.iter().map(OsStr::new))?;
|
||||
executable.push(0);
|
||||
let mut environment = user_environment(token, variables)?;
|
||||
let mut environment = user_environment(
|
||||
token,
|
||||
variables
|
||||
.iter()
|
||||
.map(|(name, value)| (OsStr::new(name), OsStr::new(value))),
|
||||
)?;
|
||||
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
|
||||
let mut directory = wide(directory.as_os_str())?;
|
||||
directory.push(0);
|
||||
@@ -286,7 +297,7 @@ mod tests {
|
||||
"&|<>",
|
||||
]
|
||||
.map(String::from);
|
||||
let command = command_line(&program, &arguments).unwrap();
|
||||
let command = command_line(&program, arguments.iter().map(OsStr::new)).unwrap();
|
||||
let mut count = 0;
|
||||
unsafe {
|
||||
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
|
||||
|
||||
@@ -8,6 +8,32 @@ use super::*;
|
||||
|
||||
const MAX_ADDRESSES: usize = 64;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn native_helper() -> anyhow::Result<PathBuf> {
|
||||
Ok(common::binary_paths::gpclient())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn native_helper() -> anyhow::Result<PathBuf> {
|
||||
windows_native_helper(&crate::windows::application_directory()?)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn windows_native_helper(directory: &std::path::Path) -> anyhow::Result<PathBuf> {
|
||||
let installed = directory.join(r"bin\gpclient.exe");
|
||||
if installed.is_file() {
|
||||
return Ok(installed);
|
||||
}
|
||||
// Every Windows package includes build metadata. A missing bundled helper
|
||||
// in that layout is a package error, even when a development override exists.
|
||||
ensure!(
|
||||
!directory.join("build-info.json").try_exists()?,
|
||||
"The GP Connect package is missing its resolver helper: {}",
|
||||
installed.display()
|
||||
);
|
||||
Ok(common::binary_paths::gpclient())
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Result<bool> {
|
||||
super::detection::validate_target(address, hostname)?;
|
||||
@@ -27,7 +53,7 @@ pub(in crate::session) async fn detect(
|
||||
"--hostname".into(),
|
||||
hostname.into(),
|
||||
];
|
||||
let output = run_helper(common::binary_paths::gpclient(), args, cancellation.clone()).await?;
|
||||
let output = run_helper(native_helper()?, args, cancellation.clone()).await?;
|
||||
serde_json::from_slice(&output).context("Invalid internal detection helper response")
|
||||
}
|
||||
|
||||
@@ -68,14 +94,7 @@ pub(super) async fn resolve(
|
||||
if disable_ipv6 {
|
||||
args.push("--disable-ipv6".into());
|
||||
}
|
||||
run_resolver(
|
||||
common::binary_paths::gpclient(),
|
||||
args,
|
||||
port,
|
||||
disable_ipv6,
|
||||
cancellation.clone(),
|
||||
)
|
||||
.await
|
||||
run_resolver(native_helper()?, args, port, disable_ipv6, cancellation.clone()).await
|
||||
}
|
||||
|
||||
async fn run_resolver(
|
||||
@@ -147,6 +166,26 @@ fn validate_addresses(addresses: &[SocketAddr], port: u16, disable_ipv6: bool) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn packaged_resolver_requires_the_bundled_cli() {
|
||||
let package = tempfile::tempdir().unwrap();
|
||||
let directory = package.path();
|
||||
assert_eq!(
|
||||
windows_native_helper(directory).unwrap(),
|
||||
common::binary_paths::gpclient()
|
||||
);
|
||||
|
||||
std::fs::write(directory.join("build-info.json"), "{}").unwrap();
|
||||
let helper = directory.join(r"bin\gpclient.exe");
|
||||
let error = windows_native_helper(directory).unwrap_err().to_string();
|
||||
assert!(error.contains(&helper.display().to_string()), "{error}");
|
||||
|
||||
std::fs::create_dir(directory.join("bin")).unwrap();
|
||||
std::fs::write(&helper, "").unwrap();
|
||||
assert_eq!(windows_native_helper(directory).unwrap(), helper);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_helper_output_is_validated_before_admission() {
|
||||
let addresses = run_resolver(
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Windows user identity and private local IPC.
|
||||
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
|
||||
use std::{io, ptr};
|
||||
use std::{
|
||||
env, io,
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
};
|
||||
mod pipes;
|
||||
pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe};
|
||||
use tokio::net::windows::named_pipe::NamedPipeServer;
|
||||
@@ -22,6 +26,54 @@ pub fn current_user_sid() -> io::Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Locate bundled Windows helpers relative to the installed executable.
|
||||
pub fn application_directory() -> std::io::Result<PathBuf> {
|
||||
let executable = env::current_exe()?;
|
||||
let directory = executable
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Application directory is unavailable"))?;
|
||||
if directory
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("bin"))
|
||||
&& executable
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("gpclient.exe"))
|
||||
{
|
||||
return directory
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.ok_or_else(|| std::io::Error::other("GP Connect installation directory is unavailable"));
|
||||
}
|
||||
Ok(directory.to_path_buf())
|
||||
}
|
||||
|
||||
pub fn is_elevated() -> io::Result<bool> {
|
||||
let mut token = ptr::null_mut();
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
Ok(token_u32(token.as_handle(), windows_sys::Win32::Security::TokenElevation)? != 0)
|
||||
}
|
||||
|
||||
pub(crate) fn token_u32(token: BorrowedHandle<'_>, field: i32) -> io::Result<u32> {
|
||||
let mut value = 0u32;
|
||||
let mut length = 0;
|
||||
if unsafe {
|
||||
GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
field,
|
||||
(&mut value as *mut u32).cast(),
|
||||
4,
|
||||
&mut length,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// An authenticated pipe client's primary token, retained for its user-session worker.
|
||||
/// Windows user identity is a SID and token; it is never represented as a Unix UID.
|
||||
pub struct PipeClientIdentity {
|
||||
@@ -111,7 +163,7 @@ pub fn process_user_sid(pid: u32) -> io::Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
|
||||
pub(crate) unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
|
||||
unsafe {
|
||||
let mut length = 0;
|
||||
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length);
|
||||
|
||||
Reference in new issue
Block a user