feat(windows): support gpclient authentication and VPN connections

This commit is contained in:
Kevin Yue committed 2026-11-19 18:31:38 +08:00
1 parent dc1376dbac
commit 6f468131c9
49 files changed
+1888 -390

No files matched your search

+2
View File
@@ -19,3 +19,5 @@ result
# Packages & test assets
*.ipa
__pycache__
+14
View File
@@ -270,7 +270,21 @@ fn init_logger(cli: &Cli) {
}
pub async fn run() {
#[cfg(not(windows))]
let cli = Cli::parse();
#[cfg(windows)]
let cli = match gpapi::process::auth_bootstrap::receive_arguments().await {
Ok(Some(args)) => Cli::parse_from(
std::env::args_os()
.take(1)
.chain(args.into_iter().map(std::ffi::OsString::from)),
),
Ok(None) => Cli::parse(),
Err(error) => {
eprintln!("Could not read Windows authentication launch arguments: {error}");
std::process::exit(1);
}
};
#[cfg(any(windows, target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
+10 -8
View File
@@ -18,25 +18,27 @@ clap.workspace = true
env_logger.workspace = true
inquire = "0.9"
log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
serde.workspace = true
serde_json.workspace = true
compile-time.workspace = true
[target.'cfg(unix)'.dependencies]
directories.workspace = true
nix = { version = "0.31", features = ["fs", "signal", "process", "poll", "term"] }
ratatui = { version = "=0.30.2", default-features = false, features = ["crossterm", "unstable-rendered-line-info"] }
crossterm = { version = "0.29", features = ["use-dev-tty"] }
strip-ansi-escapes = "0.2"
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true
whoami.workspace = true
directories.workspace = true
compile-time.workspace = true
uzers.workspace = true
whoami.workspace = true
[features]
default = ["webview-auth"]
webview-auth = ["gpapi/webview-auth"]
[target.'cfg(target_os = "macos")'.dependencies]
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
gpvpnc = { path = "../../crates/gpvpnc" }
[dev-dependencies]
+109 -41
View File
@@ -1,8 +1,10 @@
#[cfg(unix)]
use std::{
path::{Path, PathBuf},
str::FromStr,
};
#[cfg(unix)]
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
@@ -10,17 +12,22 @@ use gpapi::{
log_format::{LogFormat, write_json_record},
};
use log::info;
#[cfg(unix)]
use sysinfo::{Pid, System};
#[cfg(unix)]
use tokio::fs;
#[cfg(unix)]
use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler},
diagnostics::DiagnosticsArgs,
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
use crate::{
connect::{ConnectArgs, ConnectHandler},
hip::{HipArgs, HipHandler},
};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
@@ -33,7 +40,10 @@ const VERSION: &str = concat!(
pub(crate) struct SharedArgs<'a> {
pub(crate) ignore_tls_errors: bool,
#[cfg(unix)]
pub(crate) lock_file: &'a Path,
#[cfg(windows)]
pub(crate) system_tunnel: std::cell::RefCell<Option<gpvpnc::windows::SystemTunnel>>,
pub(crate) verbose: &'a InfoLevelVerbosity,
pub(crate) log_format: LogFormat,
}
@@ -42,12 +52,15 @@ pub(crate) struct SharedArgs<'a> {
enum CliCommand {
#[command(about = "Connect to a portal server")]
Connect(Box<ConnectArgs>),
#[cfg(unix)]
#[command(about = "Disconnect from the server")]
Disconnect(DisconnectArgs),
#[cfg(unix)]
#[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
#[cfg(unix)]
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
Diagnostics(DiagnosticsArgs),
#[command(hide = true)]
@@ -89,11 +102,12 @@ struct Cli {
#[command(subcommand)]
command: CliCommand,
#[cfg(not(target_os = "macos"))]
#[cfg(all(unix, not(target_os = "macos")))]
#[arg(long, hide = true)]
fix_openssl: bool,
#[arg(long, help = "Ignore the TLS errors")]
ignore_tls_errors: bool,
#[cfg(unix)]
#[arg(
long,
global = true,
@@ -102,6 +116,7 @@ struct Cli {
)]
lock_file: PathBuf,
#[cfg(unix)]
#[arg(long, hide = true, global = true)]
background_worker_fd: Option<i32>,
@@ -128,6 +143,7 @@ impl Args for Cli {
}
impl Cli {
#[cfg(unix)]
fn can_run_alongside_client(&self) -> bool {
match &self.command {
CliCommand::Connect(_) => false,
@@ -136,6 +152,7 @@ impl Cli {
}
}
#[cfg(unix)]
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
return false;
@@ -156,50 +173,67 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
#[cfg(not(target_os = "macos"))]
#[cfg(all(unix, not(target_os = "macos")))]
if self.fix_openssl
&& !(matches!(&self.command, CliCommand::Connect(args) if args.background) && self.background_worker_fd.is_none())
{
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
}
if let CliCommand::Connect(args) = &self.command {
if args.dashboard {
crate::dashboard::validate(self.log_format)?;
#[cfg(unix)]
let background_worker = {
if let CliCommand::Connect(args) = &self.command {
if args.dashboard {
crate::dashboard::validate(self.log_format)?;
}
}
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
bail!("Background worker requires connect --background");
}
if let CliCommand::Diagnostics(args) = &self.command {
return args.run(VERSION).await;
}
}
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
bail!("Background worker requires connect --background");
}
if let CliCommand::Diagnostics(args) = &self.command {
return args.run(VERSION).await;
}
// check if an instance is running
if !self.can_run_alongside_client() && self.is_running().await {
bail!("Another instance of the client is already running");
}
// check if an instance is running
if !self.can_run_alongside_client() && self.is_running().await {
bail!("Another instance of the client is already running");
}
let background_worker = if let CliCommand::Connect(args) = &self.command {
if args.background {
let log_file = args
.log_file
.as_deref()
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
match self.background_worker_fd {
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
None => return crate::background::start(log_file, self.log_format).await,
if let CliCommand::Connect(args) = &self.command {
if args.background {
let log_file = args
.log_file
.as_deref()
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
match self.background_worker_fd {
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
None => return crate::background::start(log_file, self.log_format).await,
}
} else {
None
}
} else {
None
}
} else {
None
};
#[cfg(windows)]
let system_tunnel = match &self.command {
CliCommand::Connect(args) if !args.cookie_only => {
anyhow::ensure!(
gpapi::windows::is_elevated()?,
"Run gpclient connect from an administrator terminal"
);
Some(gpvpnc::windows::SystemTunnel::acquire()?)
}
_ => None,
};
let shared_args = SharedArgs {
ignore_tls_errors: self.ignore_tls_errors,
#[cfg(unix)]
lock_file: &self.lock_file,
#[cfg(windows)]
system_tunnel: system_tunnel.into(),
verbose: &self.verbose,
log_format: self.log_format,
};
@@ -210,14 +244,17 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => {
ConnectHandler::new(args, &shared_args)
.with_background(background_worker)
.handle()
.await
let handler = ConnectHandler::new(args, &shared_args);
#[cfg(unix)]
let handler = handler.with_background(background_worker);
handler.handle().await
}
#[cfg(unix)]
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
#[cfg(unix)]
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
#[cfg(unix)]
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
CliCommand::DetectInternalHost { address, hostname } => {
let internal = gpapi::session::desktop::network::native::detect_in_helper(*address, hostname)?;
@@ -250,17 +287,20 @@ fn build_logger(cli: &Cli) -> env_logger::Builder {
builder
}
pub(crate) async fn run() {
let cli = Cli::parse();
fn initialize_logger(cli: &Cli) {
#[cfg(unix)]
if matches!(&cli.command, CliCommand::Connect(args) if args.dashboard) {
let logger = build_logger(&cli).build();
let logger = build_logger(cli).build();
log::set_max_level(logger.filter());
log::set_boxed_logger(Box::new(crate::dashboard::NoticeLogger::new(logger))).expect("failed to initialize logger");
} else {
build_logger(&cli).init();
return;
}
build_logger(cli).init();
}
pub(crate) async fn run() {
let cli = Cli::parse();
initialize_logger(&cli);
info!("gpclient started: {}", VERSION);
if let Err(err) = cli.run().await {
@@ -269,7 +309,7 @@ pub(crate) async fn run() {
}
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests {
use std::{
io::Write,
@@ -360,7 +400,7 @@ mod tests {
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
let cli = Cli::try_parse_from([
"gpclient",
#[cfg(not(target_os = "macos"))]
#[cfg(all(unix, not(target_os = "macos")))]
"--fix-openssl",
"diagnostics",
"--json",
@@ -593,3 +633,31 @@ mod tests {
);
}
}
#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
#[test]
fn terminal_auth_and_generated_hip_are_available() {
assert!(Cli::try_parse_from(["gpclient", "connect", "vpn.example.com", "--cookie-only", "--hip"]).is_ok());
}
#[test]
fn unix_only_workflows_are_unavailable() {
for flag in [
"--background",
"--dashboard",
"--lock-file",
"--script",
"--hip-user",
"--script-tun",
] {
assert!(
Cli::try_parse_from(["gpclient", "connect", "vpn.example.com", flag]).is_err(),
"{flag}"
);
}
assert!(Cli::try_parse_from(["gpclient", "disconnect"]).is_err());
}
}
+18 -3
View File
@@ -13,6 +13,7 @@ pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[cfg(unix)]
#[arg(
long,
conflicts_with = "cookie_only",
@@ -20,6 +21,7 @@ pub(crate) struct ConnectArgs {
)]
pub(crate) background: bool,
#[cfg(unix)]
#[arg(
long,
conflicts_with_all = ["background", "cookie_only"],
@@ -27,6 +29,7 @@ pub(crate) struct ConnectArgs {
)]
pub(crate) dashboard: bool,
#[cfg(unix)]
#[arg(
long,
requires = "background",
@@ -61,18 +64,21 @@ pub(crate) struct ConnectArgs {
)]
pub(super) cookie_cache: Option<String>,
#[cfg(unix)]
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[cfg(unix)]
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[cfg(unix)]
#[arg(
long,
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
@@ -81,6 +87,11 @@ pub(crate) struct ConnectArgs {
)]
pub(super) hip: Option<String>,
#[cfg(windows)]
#[arg(long, help = "Generate a HIP (Host Information Profile) report")]
pub(super) hip: bool,
#[cfg(unix)]
#[arg(
long,
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
@@ -100,9 +111,11 @@ pub(crate) struct ConnectArgs {
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[cfg(unix)]
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[cfg(unix)]
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
@@ -188,7 +201,7 @@ pub(crate) struct ConnectArgs {
VPN tunnel. Outputs two lines: COOKIE='<value>' and HOST='<gateway>'. Combine with \
--cookie-cache to avoid re-authenticating when the portal session is still valid."
)]
pub(super) cookie_only: bool,
pub(crate) cookie_only: bool,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
@@ -207,17 +220,19 @@ pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
args.cookie_cache.as_deref().and_then(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
#[cfg(unix)]
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
#[cfg(unix)]
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
@@ -231,7 +246,7 @@ pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
}
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests {
use super::*;
+2
View File
@@ -178,6 +178,8 @@ impl ConnectHandler<'_> {
}
}
#[cfg(windows)]
let auth_launcher = auth_launcher.with_windows_cli_launch();
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
self.check_cancelled()?;
Ok(cred)
+65 -66
View File
@@ -1,12 +1,12 @@
use std::{
fs,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
};
#[cfg(unix)]
use std::{fs, path::Path};
#[cfg(unix)]
use gpapi::process::users::get_user_by_name;
use gpapi::{
clap::report,
cookie_store,
@@ -15,19 +15,22 @@ use gpapi::{
gp_params::GpParams,
os_profile::OsProfile,
portal::{PortalConfig, prelogin},
process::users::get_user_by_name,
session::{GatewayAuthentication, SessionMode},
};
use inquire::Text;
use log::{Level, info, warn};
use openconnect::{HipScript, HipSource, VpnBuilder};
#[cfg(unix)]
use openconnect::HipScript;
use openconnect::{HipSource, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::session::{
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
};
use super::{ConnectHandler, args::cookie_cache_path, vpn_script};
#[cfg(unix)]
use super::tunnel_output::TunnelOutput;
use super::{ConnectHandler, args::cookie_cache_path};
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
@@ -452,7 +455,10 @@ impl ConnectHandler<'_> {
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn_builder = vpn_script::builder(gateway, cookie, self.args)
let vpn_builder = self
.vpn_builder(gateway, cookie)
.map_err(GatewayConnectError::before_establishment)?;
let vpn_builder = vpn_builder
.interface(self.args.interface.clone())
.certificate(certificate)
.sslkey(sslkey)
@@ -487,21 +493,8 @@ impl ConnectHandler<'_> {
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
let cancellation = self.cancellation.clone();
let mut background_stdio = self
.background
.as_ref()
.map(|background| background.redirect_stdio())
.transpose()
.map_err(GatewayConnectError::before_establishment)?;
let mut dashboard = if self.args.dashboard {
Some(
crate::dashboard::Dashboard::prepare(gateway.to_owned(), self.cancellation.clone())
.map_err(GatewayConnectError::before_establishment)?,
)
} else {
None
};
#[cfg(unix)]
let mut output = TunnelOutput::prepare(self, gateway).map_err(GatewayConnectError::before_establishment)?;
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
let disconnect_task = tokio::spawn(async move {
@@ -511,7 +504,9 @@ impl ConnectHandler<'_> {
vpn_clone.disconnect();
});
#[cfg(unix)]
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
#[cfg(unix)]
let pid_written = self.pid_written.clone();
let log_format = self.shared_args.log_format;
let session_cancellation = self.cancellation.clone();
@@ -523,6 +518,7 @@ impl ConnectHandler<'_> {
return;
}
tunnel_established_on_connect.store(true, Ordering::SeqCst);
#[cfg(unix)]
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
let _ = established_tx.send(());
@@ -536,7 +532,6 @@ impl ConnectHandler<'_> {
session_task_on_connect.lock().unwrap().replace(task);
})
});
let mut output_error = None;
let connect_result = tokio::select! {
result = &mut worker => result,
established = established_rx => {
@@ -550,23 +545,8 @@ impl ConnectHandler<'_> {
self.logout_gateway(&server).await;
}
}, || {
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.start_tunnel(monitor.clone()) {
self.cancellation.cancel();
output_error = Some(error);
}
}
if let (Some(background), Some(stdio)) = (&self.background, &mut background_stdio) {
let detach = if self.pid_written.load(Ordering::SeqCst) {
background.detach(stdio)
} else {
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
};
if let Err(error) = detach {
self.cancellation.cancel();
output_error = Some(error);
}
}
#[cfg(unix)]
output.ready(monitor.clone());
}).await
} else {
(&mut worker).await
@@ -574,11 +554,8 @@ impl ConnectHandler<'_> {
}
};
monitor.stop().await;
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.finish() {
output_error = Some(error);
}
}
#[cfg(unix)]
let output_result = output.finish();
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
disconnect_task.abort();
let _ = disconnect_task.await;
@@ -589,15 +566,15 @@ impl ConnectHandler<'_> {
let _ = task.await;
}
if let Some(error) = output_error {
return Err(GatewayConnectError::after_establishment(error));
}
#[cfg(unix)]
output_result.map_err(GatewayConnectError::after_establishment)?;
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
#[cfg(unix)]
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
let user = self.determine_hip_user();
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
@@ -605,19 +582,7 @@ impl ConnectHandler<'_> {
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
Some(_) => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
})))
Ok(generated_hip(profile))
}
None => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
@@ -626,6 +591,16 @@ impl ConnectHandler<'_> {
}
}
#[cfg(windows)]
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
Ok(if self.args.hip {
generated_hip(profile)
} else {
HipSource::Disabled
})
}
#[cfg(unix)]
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
@@ -635,6 +610,22 @@ impl ConnectHandler<'_> {
}
}
fn generated_hip(profile: OsProfile) -> HipSource {
HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
}))
}
async fn wait_for_tunnel_exit(
worker: &mut JoinHandle<i32>,
cleanup: impl std::future::Future<Output = ()>,
@@ -678,10 +669,17 @@ fn classify_openconnect_result(
}
}
#[cfg(unix)]
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
#[cfg(windows)]
fn direct_gateway_command(gateway: &str) -> String {
format!("gpclient.exe connect {gateway} --as-gateway")
}
#[cfg(unix)]
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
let pid = std::process::id();
@@ -694,6 +692,7 @@ pub(super) fn write_pid_file(lock_file: &Path) -> bool {
}
}
#[cfg(unix)]
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
user
.as_ref()
@@ -710,7 +709,7 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests {
use super::*;
+52 -55
View File
@@ -14,7 +14,7 @@ use gpapi::{
};
use log::{info, warn};
use super::ConnectHandler;
use super::{ConnectHandler, internal_output::InternalOutput};
impl ConnectHandler<'_> {
pub(super) async fn connect_internal_gateways(
@@ -26,6 +26,7 @@ impl ConnectHandler<'_> {
first_session: super::gateway::GatewayLoginSession,
remaining: &[&Gateway],
) -> anyhow::Result<()> {
#[cfg(unix)]
ensure!(
self.background.is_none(),
"--background requires a VPN tunnel; internal non-tunnel sessions must run in the foreground"
@@ -70,11 +71,18 @@ impl ConnectHandler<'_> {
}
self.check_cancelled()?;
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
self.enter_non_tunnel_mode(modes)?;
self.run_internal_session(config, &authenticated).await
}
fn enter_non_tunnel_mode(&self, modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<()> {
ensure!(
internal_session_mode(modes)? == SessionMode::NonTunnel,
"Expected non-tunnel authentication"
);
self.run_internal_session(config, &authenticated).await
#[cfg(windows)]
drop(self.shared_args.system_tunnel.take());
Ok(())
}
async fn run_internal_session(
@@ -112,18 +120,7 @@ impl ConnectHandler<'_> {
let source = Arc::new(source);
let validate_network = network.clone();
let validate_detection = detection.clone();
let members = crate::dashboard::InternalMembers::default();
let dashboard_members = members.clone();
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
let established_tx = std::sync::Mutex::new(Some(established_tx));
let mut dashboard = if self.args.dashboard {
Some(crate::dashboard::Dashboard::prepare(
authenticated[0].0.server().to_owned(),
cancellation.clone(),
)?)
} else {
None
};
let (output, observe_status) = InternalOutput::prepare(self, authenticated[0].0.server())?;
let callbacks = SessionCallbacks {
produce_report: Arc::new(move |request, control| {
control.check()?;
@@ -165,16 +162,10 @@ impl ConnectHandler<'_> {
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
member.gateway, member.client_ip, member.client_ipv6
);
if let Some(established) = established_tx.lock().unwrap().take() {
let _ = established.send(());
}
}
state => info!("Internal gateway {}: {state:?}", member.gateway),
}
members.lock().unwrap().insert(
member.gateway.server().to_owned(),
format!("{}: {:?}", member.gateway, member.maintenance),
);
observe_status(&member);
}),
validate_network: Arc::new(move |cancellation| {
let network = validate_network.clone();
@@ -204,43 +195,20 @@ impl ConnectHandler<'_> {
// The PID spans maintenance and cleanup, including initialization before the
// first successful HIP exchange. The outer handler owns final session logout.
#[cfg(unix)]
self.pid_written.store(
super::gateway::write_pid_file(self.shared_args.lock_file),
std::sync::atomic::Ordering::SeqCst,
);
let mut sessions = self.sessions.take();
let mut dashboard_error = None;
let result = {
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
});
tokio::pin!(maintenance);
tokio::select! {
result = &mut maintenance => result,
established = established_rx => {
if established.is_ok() {
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.start_internal(dashboard_members) {
self.cancellation.cancel();
dashboard_error = Some(error);
}
}
}
maintenance.await
}
}
};
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.finish() {
dashboard_error = Some(error);
}
}
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
});
let (result, output_result) = output.run(maintenance).await;
self.sessions.replace(sessions);
monitor_cancel.cancel();
monitor.await.context("Internal network monitor failed")?;
if let Some(error) = dashboard_error {
return Err(error);
}
output_result?;
match result? {
SessionExit::Disconnected => Ok(()),
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
@@ -254,8 +222,7 @@ impl ConnectHandler<'_> {
}
}
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
let mut modes = modes;
fn internal_session_mode(mut modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
let mode = modes.next().context("No internal gateway authenticated successfully")?;
ensure!(
modes.all(|candidate| candidate == mode),
@@ -276,9 +243,39 @@ mod tests {
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
SessionMode::NonTunnel
);
assert_eq!(
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
SessionMode::Tunnel
}
#[cfg(windows)]
#[test]
#[ignore = "requires the installed Windows machine tunnel directory and administrator privileges"]
fn internal_maintenance_releases_the_machine_tunnel() {
use crate::{cli::SharedArgs, connect::ConnectArgs};
use clap::Parser;
use gpvpnc::windows::SystemTunnel;
#[derive(Parser)]
struct TestArgs {
#[command(flatten)]
connect: ConnectArgs,
}
let args = TestArgs::parse_from(["test", "portal.example.com"]);
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: false,
system_tunnel: Some(SystemTunnel::acquire().unwrap()).into(),
verbose: &verbose,
log_format: gpapi::log_format::LogFormat::Text,
};
let handler = ConnectHandler::new(&args.connect, &shared);
assert!(
handler
.enter_non_tunnel_mode([SessionMode::Tunnel].into_iter())
.is_err()
);
assert!(SystemTunnel::try_acquire().unwrap().is_none());
handler
.enter_non_tunnel_mode([SessionMode::NonTunnel].into_iter())
.unwrap();
assert!(SystemTunnel::try_acquire().unwrap().is_some());
}
}
@@ -0,0 +1,73 @@
use std::{future::Future, sync::Mutex};
use gpapi::session::{GatewaySessionSummary, MaintenanceState};
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use crate::dashboard::{Dashboard, InternalMembers};
use super::ConnectHandler;
pub(super) struct InternalOutput(Option<DashboardState>);
struct DashboardState {
dashboard: Dashboard,
members: InternalMembers,
established: oneshot::Receiver<()>,
cancellation: CancellationToken,
}
impl InternalOutput {
pub(super) fn prepare(
handler: &ConnectHandler<'_>,
gateway: &str,
) -> anyhow::Result<(Self, impl Fn(&GatewaySessionSummary) + Send + Sync + 'static + use<>)> {
let (sender, established) = oneshot::channel();
let established_sender = Mutex::new(Some(sender));
let members = InternalMembers::default();
let dashboard_members = members.clone();
let output = if handler.args.dashboard {
Some(DashboardState {
dashboard: Dashboard::prepare(gateway.to_owned(), handler.cancellation.clone())?,
members,
established,
cancellation: handler.cancellation.clone(),
})
} else {
None
};
let observe = move |member: &GatewaySessionSummary| {
if member.maintenance == MaintenanceState::Healthy
&& let Some(ready) = established_sender.lock().unwrap().take()
{
let _ = ready.send(());
}
dashboard_members.lock().unwrap().insert(
member.gateway.server().to_owned(),
format!("{}: {:?}", member.gateway, member.maintenance),
);
};
Ok((Self(output), observe))
}
pub(super) async fn run<T>(self, maintenance: impl Future<Output = T>) -> (T, anyhow::Result<()>) {
let Some(mut output) = self.0 else {
return (maintenance.await, Ok(()));
};
let mut start = Ok(());
tokio::pin!(maintenance);
let result = tokio::select! {
result = &mut maintenance => result,
established = &mut output.established => {
if established.is_ok() {
start = output.dashboard.start_internal(output.members);
if start.is_err() {
output.cancellation.cancel();
}
}
maintenance.await
}
};
(result, output.dashboard.finish().and(start))
}
}
@@ -0,0 +1,20 @@
use std::future::Future;
use gpapi::session::GatewaySessionSummary;
use super::ConnectHandler;
pub(super) struct InternalOutput;
impl InternalOutput {
pub(super) fn prepare(
_: &ConnectHandler<'_>,
_: &str,
) -> anyhow::Result<(Self, impl Fn(&GatewaySessionSummary) + Send + Sync + 'static + use<>)> {
Ok((Self, |_: &GatewaySessionSummary| {}))
}
pub(super) async fn run<T>(self, maintenance: impl Future<Output = T>) -> (T, anyhow::Result<()>) {
(maintenance.await, Ok(()))
}
}
+16 -1
View File
@@ -1,12 +1,21 @@
mod args;
mod credential;
#[cfg(test)]
#[cfg(all(test, unix))]
mod flow_tests;
mod gateway;
mod internal;
#[cfg(unix)]
#[path = "internal_output/unix.rs"]
mod internal_output;
#[cfg(windows)]
#[path = "internal_output/windows.rs"]
mod internal_output;
#[cfg(unix)]
mod tunnel_output;
mod vpn_script;
use std::cell::RefCell;
#[cfg(unix)]
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -46,7 +55,9 @@ pub(crate) struct ConnectHandler<'a> {
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
sessions: RefCell<GatewaySessions>,
#[cfg(unix)]
pid_written: Arc<AtomicBool>,
#[cfg(unix)]
background: Option<crate::background::BackgroundWorker>,
}
@@ -72,11 +83,14 @@ impl<'a> ConnectHandler<'a> {
auth_attempt_fixture: Default::default(),
auth_recovery: RefCell::default(),
sessions: RefCell::default(),
#[cfg(unix)]
pid_written: Arc::default(),
#[cfg(unix)]
background: None,
}
}
#[cfg(unix)]
pub(crate) fn with_background(mut self, background: Option<crate::background::BackgroundWorker>) -> Self {
self.background = background;
self
@@ -134,6 +148,7 @@ impl<'a> ConnectHandler<'a> {
} else {
sessions.logout().await;
}
#[cfg(unix)]
if self.pid_written.load(Ordering::SeqCst) {
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
warn!("Failed to remove PID file: {error}");
@@ -0,0 +1,74 @@
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use gptunnel::TunnelMonitor;
use tokio_util::sync::CancellationToken;
use crate::{
background::{BackgroundStdio, BackgroundWorker},
dashboard::Dashboard,
};
use super::ConnectHandler;
pub(super) struct TunnelOutput<'a> {
background: Option<(&'a BackgroundWorker, BackgroundStdio)>,
dashboard: Option<Dashboard>,
pid_written: &'a AtomicBool,
cancellation: &'a CancellationToken,
error: Option<anyhow::Error>,
}
impl<'a> TunnelOutput<'a> {
pub(super) fn prepare(handler: &'a ConnectHandler<'_>, gateway: &str) -> anyhow::Result<Self> {
let background = handler
.background
.as_ref()
.map(|worker| worker.redirect_stdio().map(|stdio| (worker, stdio)))
.transpose()?;
let dashboard = handler
.args
.dashboard
.then(|| Dashboard::prepare(gateway.to_owned(), handler.cancellation.clone()))
.transpose()?;
Ok(Self {
background,
dashboard,
pid_written: &handler.pid_written,
cancellation: &handler.cancellation,
error: None,
})
}
pub(super) fn ready(&mut self, monitor: Arc<TunnelMonitor>) {
if let Some(dashboard) = &mut self.dashboard
&& let Err(error) = dashboard.start_tunnel(monitor)
{
self.cancellation.cancel();
self.error = Some(error);
}
if let Some((worker, stdio)) = &mut self.background {
let detach = if self.pid_written.load(Ordering::SeqCst) {
worker.detach(stdio)
} else {
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
};
if let Err(error) = detach {
self.cancellation.cancel();
self.error = Some(error);
}
}
}
pub(super) fn finish(&mut self) -> anyhow::Result<()> {
if let Some(dashboard) = &mut self.dashboard {
dashboard.finish()?;
}
match self.error.take() {
Some(error) => Err(error),
None => Ok(()),
}
}
}
@@ -1,9 +1,13 @@
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectArgs;
use crate::connect::ConnectHandler;
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
Vpn::builder(server, cookie)
.script(args.script.clone())
.script_tun(args.script_tun)
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
Ok(
Vpn::builder(server, cookie)
.script(self.args.script.clone())
.script_tun(self.args.script_tun),
)
}
}
+11 -4
View File
@@ -2,11 +2,18 @@ use std::ffi::OsStr;
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectArgs;
use crate::connect::{ConnectArgs, ConnectHandler};
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
configure_builder(server, cookie, args, configured_script.as_deref())
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
Ok(configure_builder(
server,
cookie,
self.args,
configured_script.as_deref(),
))
}
}
fn configure_builder(server: &str, cookie: &str, args: &ConnectArgs, configured_script: Option<&OsStr>) -> VpnBuilder {
+4 -2
View File
@@ -1,8 +1,10 @@
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
#[cfg(not(target_os = "macos"))]
#[cfg(all(unix, not(target_os = "macos")))]
#[path = "default.rs"]
mod platform;
pub(super) use platform::builder;
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
@@ -0,0 +1,23 @@
use std::sync::Mutex;
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectHandler;
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
let owner = self.shared_args.system_tunnel.borrow();
let tunnel = owner
.as_ref()
.ok_or_else(|| anyhow::anyhow!("System tunnel ownership is unavailable"))?;
let network = Mutex::new(tunnel.configurator()?);
Ok(
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
network
.lock()
.map_err(|_| std::io::Error::other("Windows network state is unavailable"))?
.configure(&configuration.reason, &configuration.environment)
}),
)
}
}
+6
View File
@@ -1,13 +1,19 @@
#[cfg(unix)]
mod background;
mod cli;
mod connect;
#[cfg(unix)]
mod dashboard;
#[cfg(unix)]
mod diagnostics;
#[cfg(unix)]
mod disconnect;
mod hip;
#[cfg(unix)]
mod launch_gui;
mod session;
#[cfg(unix)]
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
#[tokio::main]
+54 -4
View File
@@ -75,8 +75,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
tokio::time::sleep(schedule.delay).await;
crate::dashboard::session_notice(Level::Warn, &schedule.message);
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
report_session_notice(log_format, Level::Warn, &schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
@@ -91,8 +90,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
return;
};
crate::dashboard::session_notice(Level::Info, "Session extended.");
report(log_format, Level::Info, "Session extended.");
report_session_notice(log_format, Level::Info, "Session extended.");
session_info = next_session_info;
}
Err(err) => {
@@ -108,6 +106,16 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
}
}
fn report_session_notice(log_format: LogFormat, level: Level, message: &str) {
#[cfg(unix)]
crate::dashboard::session_notice(level, message);
if level == Level::Warn {
report(log_format, level, &format!("\nWARNING: {message}"));
} else {
report(log_format, level, message);
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
@@ -149,6 +157,48 @@ mod tests {
}
}
#[cfg(windows)]
#[test]
fn expiry_warning_is_reported_once() {
const CHILD: &str = "GP_TEST_SESSION_WARNING_CHILD";
const WARNING: &str = "Session expires soon";
if std::env::var_os(CHILD).is_some() {
env_logger::builder()
.filter_level(log::LevelFilter::Info)
.format(gpapi::log_format::write_json_record)
.init();
let context = SessionContext::new(
"vpn.example.test".to_owned(),
"vpn.example.test".to_owned(),
SessionRequestArgs::new("synthetic".to_owned()),
);
let session = sample_session_info(Some(unix_timestamp() + 30), false);
tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap()
.block_on(run_session_runtime(context, session, LogFormat::Json));
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"session::tests::expiry_warning_is_reported_once",
"--nocapture",
])
.env(CHILD, "1")
.output()
.unwrap();
assert!(output.status.success());
let stderr = String::from_utf8(output.stderr).unwrap();
assert_eq!(
stderr.lines().filter(|line| line.contains(WARNING)).count(),
1,
"{stderr}"
);
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
+1 -1
View File
@@ -1,4 +1,4 @@
#![cfg(not(target_os = "macos"))]
#![cfg(all(unix, not(target_os = "macos")))]
use std::process::Command;
+2
View File
@@ -1,3 +1,5 @@
#![cfg(unix)]
use std::{os::unix::fs::PermissionsExt, process::Stdio, time::Duration};
use tokio::process::Command;
+2 -2
View File
@@ -23,8 +23,6 @@ serde_json.workspace = true
env_logger.workspace = true
log.workspace = true
compile-time.workspace = true
xz2 = "0.1"
tar = "0.4"
thiserror.workspace = true
uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true
@@ -33,6 +31,8 @@ getrandom = "0.4"
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] }
tar = "0.4"
xz2 = "0.1"
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
mac_address = "1.2.1"
+4 -4
View File
@@ -1,10 +1,10 @@
use gpapi::service::request::ConnectArgs;
use gpvpnc::windows::SystemTunnel;
use openconnect::{Vpn, VpnBuilder};
use std::sync::Mutex;
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
pub(crate) fn recover_network() -> std::io::Result<()> {
gpvpnc::windows::recover(RECOVERY_KEY)
let _tunnel = SystemTunnel::try_acquire()?;
Ok(())
}
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
@@ -12,7 +12,7 @@ pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow:
args.vpnc_script().is_none(),
"Windows does not support custom VPN scripts"
);
let network = Mutex::new(gpvpnc::windows::NetworkConfigurator::new(RECOVERY_KEY)?);
let network = Mutex::new(SystemTunnel::acquire()?.configurator()?);
Ok(
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
network
+1 -4
View File
@@ -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"
+37 -65
View File
@@ -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();
+24
View File
@@ -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))
}
+87
View File
@@ -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;
+20
View 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() {
+12
View File
@@ -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(
+54 -2
View File
@@ -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);
+1 -5
View File
@@ -4,11 +4,7 @@ use gpapi::{collection::CollectionControl, process::collection::CollectorCommand
use std::io;
pub(super) fn collect(commands: &CollectorCommands<'_>, control: &dyn CollectionControl) -> io::Result<WindowsReport> {
let executable = std::env::current_exe()?;
let helper = executable
.parent()
.ok_or_else(|| io::Error::other("Application directory is unavailable"))?
.join("gp-posture.exe");
let helper = gpapi::windows::application_directory()?.join("gp-posture.exe");
let output = commands
.run_executable(&helper, &[])?
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Windows posture helper is not installed"))?;
+37 -6
View File
@@ -284,7 +284,7 @@ impl Observation {
/// One native tunnel's negotiated state and optional sampler. The connection
/// owner must join `Vpn::connect` before calling `stop`.
pub struct TunnelMonitor {
vpn: Arc<Vpn>,
vpn: Mutex<Option<Arc<Vpn>>>,
observation: Mutex<Observation>,
updates: watch::Sender<TunnelUpdate>,
wake: Arc<Notify>,
@@ -302,14 +302,14 @@ impl TunnelMonitor {
let observation = Observation::new();
let (updates, _) = watch::channel(observation.project(Instant::now()));
let monitor = Arc::new(Self {
vpn,
vpn: Mutex::new(Some(vpn.clone())),
observation: Mutex::new(observation),
updates,
wake: Arc::new(Notify::new()),
worker: Mutex::new(None),
});
let observer = Arc::downgrade(&monitor);
monitor.vpn.set_tunnel_observer(move |event| {
vpn.set_tunnel_observer(move |event| {
on_event(&event);
if let Some(monitor) = observer.upgrade() {
monitor.observe(event);
@@ -347,7 +347,9 @@ impl TunnelMonitor {
observation.finish(Instant::now());
self.publish(&observation);
drop(observation);
self.vpn.clear_tunnel_observer();
if let Some(vpn) = self.vpn.lock().unwrap().take() {
vpn.clear_tunnel_observer();
}
self.wake.notify_one();
}
@@ -405,7 +407,11 @@ impl TunnelMonitor {
}
return true;
}
match self.vpn.request_statistics() {
let vpn = self.vpn.lock().unwrap();
let Some(vpn) = vpn.as_ref() else {
return false;
};
match vpn.request_statistics() {
Ok(true) => {
observation.pending = Some(RequestStamp {
generation: observation.generation,
@@ -431,7 +437,9 @@ impl TunnelMonitor {
impl Drop for TunnelMonitor {
fn drop(&mut self) {
self.vpn.clear_tunnel_observer();
if let Some(vpn) = self.vpn.get_mut().unwrap().take() {
vpn.clear_tunnel_observer();
}
if let Some(worker) = self.worker.get_mut().unwrap().take() {
worker.abort();
}
@@ -468,6 +476,29 @@ fn millis(duration: Duration) -> u64 {
mod tests {
use super::*;
#[tokio::test]
async fn finished_monitor_keeps_telemetry_without_owning_native_resources() {
let owner = Arc::new(());
let lease = Arc::downgrade(&owner);
let vpn = Arc::new(
Vpn::builder("vpn.example.com", "cookie")
.network_configuration_handler(move |_| {
let _owner = &owner;
Ok(())
})
.build()
.unwrap(),
);
let monitor = TunnelMonitor::attach(vpn.clone());
monitor.stop().await;
drop(vpn);
assert!(
lease.upgrade().is_none(),
"finished telemetry retained the network owner"
);
let _ = monitor.subscribe();
}
fn connected(now: Instant) -> Observation {
let mut observation = Observation::new();
observation.apply(Event::Established, now);
+1 -1
View File
@@ -15,7 +15,7 @@ serde_json.workspace = true
serde.workspace = true
winreg = "0.56"
uuid = { workspace = true, features = ["v4"] }
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Threading", "Win32_UI_Shell"] }
[dev-dependencies]
ipnet = "2"
+29 -8
View File
@@ -1,5 +1,5 @@
//! Adapter DNS settings and Windows name-resolution policy scoped to this connection.
use super::configuration::Configuration;
use super::{SystemTunnel, configuration::Configuration};
use base64::Engine;
use serde_json::json;
use std::{
@@ -23,6 +23,7 @@ pub(super) struct Installed {
guid: GUID,
snapshot: Option<Snapshot>,
tag: Option<String>,
tunnel: Option<SystemTunnel>,
}
fn check(status: u32) -> io::Result<()> {
if status == 0 {
@@ -77,7 +78,7 @@ impl Snapshot {
}
}
impl Installed {
pub fn apply(configuration: &Configuration) -> io::Result<Self> {
pub fn apply(configuration: &Configuration, recovery_key: &str, tunnel: Option<&SystemTunnel>) -> io::Result<Self> {
let mut luid = NET_LUID_LH::default();
let mut guid = GUID::default();
check(unsafe { ConvertInterfaceIndexToLuid(configuration.interface, &mut luid) })?;
@@ -86,6 +87,7 @@ impl Installed {
guid,
snapshot: Some(Snapshot::capture(guid)?),
tag: None,
tunnel: tunnel.cloned(),
};
Snapshot {
domain: configuration.domains.first().cloned().unwrap_or_default(),
@@ -105,9 +107,13 @@ impl Installed {
.map(|domain| format!(".{}", domain.trim_matches('.')))
.collect()
};
let tag = format!("GPConnect:{}", uuid::Uuid::new_v4());
let tag = match tunnel {
Some(_) => format!("GPConnect:{}", uuid::Uuid::new_v4()),
None => journal_tag(recovery_key),
};
installed.tag = Some(tag.clone());
policy(
tunnel,
json!({"operation":"add", "tag":tag, "namespaces":namespaces, "servers":configuration.servers.iter().map(ToString::to_string).collect::<Vec<_>>()}),
)?;
}
@@ -116,7 +122,7 @@ impl Installed {
pub fn restore(&mut self) -> io::Result<()> {
let mut failure = None;
if let Some(tag) = self.tag.take() {
if let Err(error) = policy(json!({"operation":"remove", "tag":tag})) {
if let Err(error) = policy(self.tunnel.as_ref(), json!({"operation":"remove", "tag":tag})) {
log::warn!("Could not remove VPN DNS policy: {error}");
failure = Some(error);
}
@@ -140,21 +146,36 @@ impl Drop for Installed {
/// A crashed service cannot run Drop. Remove only GP Connect's tagged policies
/// before accepting a new connection; adapter rows disappear with Wintun itself.
pub(super) fn clear_stale_policies() -> io::Result<()> {
policy(json!({"operation":"clear-stale"}))
pub(super) fn clear_stale_policies(tunnel: &SystemTunnel) -> io::Result<()> {
policy(Some(tunnel), json!({"operation":"clear-stale"}))
}
fn policy(request: serde_json::Value) -> io::Result<()> {
// Keep isolated journals outside the GPConnect:* namespace used by system recovery.
fn journal_tag(recovery_key: &str) -> String {
format!("GPConnectJournal:{recovery_key}")
}
pub(super) fn remove_journal_policy(recovery_key: &str) -> io::Result<()> {
policy(None, json!({"operation":"remove", "tag":journal_tag(recovery_key)}))
}
fn policy(tunnel: Option<&SystemTunnel>, request: serde_json::Value) -> io::Result<()> {
const SCRIPT: &str = include_str!("dns-policy.ps1");
let encoded = base64::engine::general_purpose::STANDARD
.encode(SCRIPT.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<_>>());
let root =
std::env::var_os("SystemRoot").ok_or_else(|| io::Error::other("Windows system directory is unavailable"))?;
let executable = std::path::PathBuf::from(root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
// The script produces no standard output. Use that handle to give the worker
// a copy of the lease so it keeps ownership if the tunnel process dies.
let stdout = match tunnel {
Some(tunnel) => Stdio::from(tunnel.duplicate_lock()?),
None => Stdio::null(),
};
let mut child = Command::new(executable)
.args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded])
.creation_flags(CREATE_NO_WINDOW)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stdout(stdout)
.stderr(Stdio::piped())
.spawn()?;
let input = child
+17 -4
View File
@@ -3,24 +3,32 @@ mod configuration;
mod dns;
mod ip_helper;
mod recovery;
mod system_tunnel;
use configuration::Configuration;
use std::io;
pub use system_tunnel::SystemTunnel;
pub struct NetworkConfigurator {
connection: Option<Connection>,
recovery_key: String,
system_tunnel: Option<SystemTunnel>,
}
struct Connection {
dns: dns::Installed,
network: ip_helper::Installed,
}
impl NetworkConfigurator {
/// The owner supplies an HKLM key under its administrator-controlled namespace.
/// Use a separate HKLM journal and DNS tag for an isolated network configuration.
pub fn new(recovery_key: &str) -> io::Result<Self> {
Self::with_owner(recovery_key, None)
}
fn with_owner(recovery_key: &str, system_tunnel: Option<SystemTunnel>) -> io::Result<Self> {
recovery::Journal::begin(recovery_key)?;
Ok(Self {
connection: None,
recovery_key: recovery_key.into(),
system_tunnel,
})
}
pub fn configure(&mut self, reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
@@ -30,7 +38,7 @@ impl NetworkConfigurator {
let configuration = Configuration::parse(environment)?;
self.disconnect()?;
let network = ip_helper::Installed::apply(&configuration, &self.recovery_key)?;
let dns = dns::Installed::apply(&configuration)?;
let dns = dns::Installed::apply(&configuration, &self.recovery_key, self.system_tunnel.as_ref())?;
self.connection = Some(Connection { dns, network });
Ok(())
}
@@ -52,13 +60,18 @@ impl NetworkConfigurator {
}
}
/// Restore process-owned physical routes and DNS policy before service admission.
/// Recover an isolated journal and only the DNS rules recorded under its name.
pub fn recover(recovery_key: &str) -> io::Result<()> {
recover_routes(recovery_key)?;
dns::remove_journal_policy(recovery_key)
}
fn recover_routes(recovery_key: &str) -> io::Result<()> {
if let Some(journal) = recovery::Journal::open(recovery_key)? {
for (name, route) in journal.routes()? {
ip_helper::recover_route(&route)?;
journal.forget(&name)?;
}
}
dns::clear_stale_policies()
Ok(())
}
@@ -0,0 +1,85 @@
use super::NetworkConfigurator;
use std::{
ffi::OsString,
fs::{File, OpenOptions},
io,
os::windows::{ffi::OsStringExt, fs::OpenOptionsExt},
path::PathBuf,
ptr,
sync::Arc,
};
use windows_sys::Win32::{
Foundation::ERROR_SHARING_VIOLATION,
UI::Shell::{CSIDL_COMMON_APPDATA, SHGetFolderPathW},
};
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
/// Exclusive ownership of the installed Windows system tunnel, including recovery.
#[derive(Clone)]
pub struct SystemTunnel {
lock: Arc<File>,
}
impl SystemTunnel {
pub fn try_acquire() -> io::Result<Option<Self>> {
let path = machine_data()?.join(r"GP Connect\Private\system-tunnel.lock");
let file = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.share_mode(0)
.open(path)
{
Ok(file) => file,
Err(error) if error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => return Ok(None),
Err(error) => return Err(error),
};
let tunnel = Self { lock: Arc::new(file) };
super::recover_routes(RECOVERY_KEY)?;
super::dns::clear_stale_policies(&tunnel)?;
Ok(Some(tunnel))
}
pub fn acquire() -> io::Result<Self> {
Self::try_acquire()?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::WouldBlock,
"Another GP Connect system tunnel or installer is active. Disconnect the tunnel or wait for setup to finish.",
)
})
}
pub fn configurator(&self) -> io::Result<NetworkConfigurator> {
NetworkConfigurator::with_owner(RECOVERY_KEY, Some(self.clone()))
}
pub(super) fn duplicate_lock(&self) -> io::Result<File> {
self.lock.try_clone()
}
}
fn machine_data() -> io::Result<PathBuf> {
let mut path = [0; 260];
let result = unsafe {
SHGetFolderPathW(
ptr::null_mut(),
CSIDL_COMMON_APPDATA as i32,
ptr::null_mut(),
0,
path.as_mut_ptr(),
)
};
if result < 0 {
return Err(io::Error::other(format!(
"Windows ProgramData lookup failed ({result:#x})"
)));
}
let length = path
.iter()
.position(|&c| c == 0)
.filter(|&n| n > 0)
.ok_or_else(|| io::Error::other("Windows ProgramData path is unavailable"))?;
Ok(PathBuf::from(OsString::from_wide(&path[..length])))
}
+48 -8
View File
@@ -235,12 +235,18 @@ fn assert_dns_policy(active: bool) {
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$expected = [int]$env:GP_TEST_EXPECTED_DNS_POLICIES
$configured = @(Get-DnsClientNrptRule | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' })
$effective = @(Get-DnsClientNrptPolicy | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' })
if ($configured.Count -ne $expected -or $effective.Count -ne $expected) { throw 'Unexpected configured or effective VPN DNS policy' }
if ($expected) {
$servers = @($configured[0].NameServers)
if ($servers -notcontains '198.18.0.53' -or $servers -notcontains 'fd42:1235::53') { throw 'VPN DNS server families are missing' }
$configured = @(Get-DnsClientNrptRule)
$effective = @(Get-DnsClientNrptPolicy)
foreach ($namespace in '.gp-connect-test.invalid', '.second-gp-connect-test.invalid') {
$rules = @($configured | Where-Object { $_.Namespace -contains $namespace })
$policies = @($effective | Where-Object { $_.Namespace -contains $namespace })
if ($rules.Count -ne $expected -or $policies.Count -ne $expected) {
throw "Unexpected configured or effective VPN DNS policy for $namespace"
}
if ($expected) {
$servers = @($rules[0].NameServers)
if ($servers -notcontains '198.18.0.53' -or $servers -notcontains 'fd42:1235::53') { throw "VPN DNS server families are missing for $namespace" }
}
}
"#;
let powershell =
@@ -253,6 +259,22 @@ if ($expected) {
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
}
fn global_search_list() -> Vec<u8> {
let powershell =
PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/WindowsPowerShell/v1.0/powershell.exe");
let output = std::process::Command::new(powershell)
.args([
"-NoProfile",
"-NonInteractive",
"-Command",
"$ErrorActionPreference = 'Stop'; (Get-DnsClientGlobalSetting).SuffixSearchList | ConvertTo-Json -Compress",
])
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
output.stdout
}
#[test]
#[ignore = "requires administrator privileges and GP_TEST_WINTUN_DLL"]
fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn std::error::Error>> {
@@ -274,10 +296,17 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
let recovery_key = format!(r"SOFTWARE\GP Connect\Tests\Network{}", uuid::Uuid::new_v4().simple());
assert_dns_policy(false);
let before = state(index);
let original_search_list = global_search_list();
{
let mut network = NetworkConfigurator::new(&recovery_key)?;
network.configure("connect", &environment)?;
let during = state(index);
assert!(during.iter().any(|row| row == "dns-domain gp-connect-test.invalid"));
assert!(
during
.iter()
.any(|row| row == "dns-search gp-connect-test.invalid,second-gp-connect-test.invalid")
);
assert!(during.iter().any(|row| row == "address 192.0.2.2/24"));
assert!(during.iter().any(|row| row == "address fd42:1234::2/64"));
assert!(
@@ -298,10 +327,14 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
assert_ne!(best_route("198.51.100.1").InterfaceIndex, index);
println!("PASS: IPv4/IPv6 addresses, split routes, resolver routes and MTU installed");
assert_dns_policy(true);
gpvpnc::windows::recover(&format!(r"{recovery_key}-other"))?;
assert_dns_policy(true);
assert_eq!(global_search_list(), original_search_list);
network.configure("disconnect", &[])?;
}
assert_eq!(before, state(index), "Network state was not restored");
assert_dns_policy(false);
assert_eq!(global_search_list(), original_search_list);
println!("PASS: disconnect restored addresses, routes and interface settings");
{
let mut network = NetworkConfigurator::new(&recovery_key)?;
@@ -324,6 +357,7 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
println!("PASS: partial setup failure rolled back its physical gateway route");
drop(adapter);
assert_crash_recovery(&recovery_key)?;
assert_eq!(global_search_list(), original_search_list);
winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE).delete_subkey(&recovery_key)?;
Ok(())
}
@@ -347,8 +381,14 @@ fn environment(index: u32) -> Vec<(String, Option<String>)> {
("CISCO_IPV6_SPLIT_INC_0_ADDR", "2001:db8:1234::".into()),
("CISCO_IPV6_SPLIT_INC_0_MASKLEN", "64".into()),
("INTERNAL_IP4_DNS", "198.18.0.53 fd42:1235::53".into()),
("CISCO_DEF_DOMAIN", "gp-connect-test.invalid".into()),
("CISCO_SPLIT_DNS", "gp-connect-test.invalid".into()),
(
"CISCO_DEF_DOMAIN",
"gp-connect-test.invalid,second-gp-connect-test.invalid".into(),
),
(
"CISCO_SPLIT_DNS",
"gp-connect-test.invalid,second-gp-connect-test.invalid".into(),
),
];
pairs
.into_iter()
+16 -2
View File
@@ -9,7 +9,10 @@
`TARGET_ARCH` is `x64` or `arm64` and must match every executable and DLL in
the payload. Each installer accepts only its native Windows architecture. ARM64
requires Windows 11; x64 requires Windows 10 build 19041 or newer.
requires Windows 11. x64 requires Windows 10 version 1809 (build 17763) or
later, or Windows Server 2019 or later with Desktop Experience.
On Windows N, install the [Media Feature Pack for your Windows version](https://support.microsoft.com/en-us/windows/experience/platform-variants/media-feature-pack-list-for-windows-n-editions)
before running setup.
The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'`
(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option;
@@ -20,7 +23,8 @@ selected type. The gateway-based connection name is unchanged.
match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release
identity, including the snapshot build when applicable. The payload must contain matching
`gpgui.exe`, `gpauth.exe`, `gpservice.exe`, their DLL dependency closure, the
vendor-signed `wintun.dll`, `licenses`, and `build-info.json`. The NSIS compiler
vendor-signed `wintun.dll`, `licenses`, and `build-info.json`. The `bin` folder
contains `gpclient.exe` and its application-local DLLs. The NSIS compiler
adds the generated uninstaller; it is not a separately built executable.
The installer, extraction progress and uninstaller use the shared Windows icon
@@ -97,3 +101,13 @@ cannot host a Windows service. The latter must fail service startup, restore A's
files and uninstall metadata, and leave A's service running. Also check held
runtime files, active GUI/auth windows, Wintun-signature failure, and concurrent
installer attempts. Do not run failure fixtures against a live company VPN.
The installer includes `GP Connect\bin\gpclient.exe`. From an administrator
PowerShell, connect to your portal and press Ctrl+C to disconnect.
```powershell
& "$env:ProgramFiles\GP Connect\bin\gpclient.exe" connect vpn.example.com
```
Embedded SAML sign-in from an elevated terminal requires an interactive Windows
desktop under the same account with UAC enabled and the WebView2 Runtime.
+63 -13
View File
@@ -14,10 +14,13 @@ if ($PSVersionTable.PSEdition -eq 'Desktop') {
}
if (![Environment]::Is64BitProcess) { throw 'Run the GP Connect installer with 64-bit PowerShell.' }
$destination = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'GP Connect'
$state = Join-Path $env:ProgramData 'GP Connect'
$programData = [Environment]::GetFolderPath('CommonApplicationData')
$state = Join-Path $programData 'GP Connect'
$private = Join-Path $state 'Private'
$tunnelLock = $null
$serviceName = 'GPConnect'
$serviceBinary = Join-Path $destination 'gpservice.exe'
$shortcutPath = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
$shortcutPath = Join-Path $programData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
$uninstallKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect'
$recoveryKey = 'HKLM:\SOFTWARE\GP Connect\NetworkRecovery'
$publicAcl = 'O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFX;;;BU)'
@@ -52,8 +55,13 @@ function Set-DirectoryAcl([string]$Path, [string]$Descriptor) {
function Wait-ForApplications {
$deadline = [DateTime]::UtcNow.AddSeconds(30)
do {
$running = @(Get-CimInstance Win32_Process -Filter "Name='gpgui.exe' OR Name='gpauth.exe'" |
Where-Object { $_.ExecutablePath -in @((Join-Path $destination 'gpgui.exe'), (Join-Path $destination 'gpauth.exe')) })
$clientPath = Join-Path $destination 'bin\gpclient.exe'
$guiPaths = @((Join-Path $destination 'gpgui.exe'), (Join-Path $destination 'gpauth.exe'))
$running = @(Get-CimInstance Win32_Process -Filter "Name='gpgui.exe' OR Name='gpauth.exe' OR Name='gpclient.exe'")
if ($running.ExecutablePath -contains $clientPath) {
throw 'Close gpclient.exe before installing or removing GP Connect.'
}
$running = @($running | Where-Object { $_.ExecutablePath -in $guiPaths })
if (!$running.Count) { return }
if ([DateTime]::UtcNow -ge $deadline) {
throw 'Quit GP Connect and finish or cancel sign-in in all Windows sessions, then try again.'
@@ -91,7 +99,8 @@ function Wait-ForRuntimeRelease {
$deadline = [DateTime]::UtcNow.AddSeconds(30)
do {
$locked = $false
foreach ($file in Get-ChildItem -LiteralPath $destination -File | Where-Object { $_.Extension -in @('.exe', '.dll') }) {
$directories = @($destination, (Join-Path $destination 'bin')) | Where-Object { Test-Path -LiteralPath $_ -PathType Container }
foreach ($file in Get-ChildItem -LiteralPath $directories -File | Where-Object { $_.Extension -in @('.exe', '.dll') }) {
try {
$stream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$stream.Dispose()
@@ -103,12 +112,24 @@ function Wait-ForRuntimeRelease {
} while ($true)
}
function Open-TunnelLock {
Set-DirectoryAcl $private $privateAcl
$path = Join-Path $private 'system-tunnel.lock'
try { return [IO.File]::Open($path, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) }
catch [IO.IOException] {
if (($_.Exception.GetBaseException().HResult -band 0xffff) -eq 32) {
throw 'A GP Connect system tunnel is active. Disconnect it before running setup.'
}
throw
}
}
function Assert-NetworkClean {
$records = @()
if (Test-Path $recoveryKey) { $records = @((Get-Item $recoveryKey).GetValueNames() | Where-Object { $_ -like 'Route-*' }) }
$policies = @(Get-DnsClientNrptRule | Where-Object { $_.Comment -like 'GPConnect:*' })
if ($records.Count -or $policies.Count) {
throw 'VPN network cleanup is incomplete. Restart GP Connect before trying again.'
throw 'VPN network cleanup is incomplete. Start or restart the GPConnect service before trying again.'
}
}
@@ -119,7 +140,7 @@ function Invoke-ServiceCommand([string[]]$Arguments) {
function Set-MachineState {
Set-DirectoryAcl $state $publicAcl
Set-DirectoryAcl (Join-Path $state 'Private') $privateAcl
Set-DirectoryAcl $private $privateAcl
foreach ($name in @('gpservice.lock', 'gpservice.log')) {
$path = Join-Path $state $name
if (Test-Path -LiteralPath $path) {
@@ -281,7 +302,7 @@ try {
if ($source -eq $destination -or $source.StartsWith($destination + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw 'Install from an extracted package outside the application folder.'
}
foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) {
foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json', 'bin\gpclient.exe', 'bin\libopenconnect-5.dll', 'bin\wintun.dll')) {
if (!(Test-Path -LiteralPath (Join-Path $source $name) -PathType Leaf)) { throw "Missing Windows package file: $name" }
}
$info = Get-Content -LiteralPath (Join-Path $source 'build-info.json') -Raw | ConvertFrom-Json
@@ -294,14 +315,30 @@ try {
if ($info.product -ne 'GP Connect' -or $info.architecture -notin @('x64','arm64') -or $info.architecture -ne $architecture -or !$Version -or $info.version -ne $Version) {
throw 'The package version or architecture does not match this installer.'
}
if (![Environment]::Is64BitProcess -or [Environment]::OSVersion.Version.Build -lt 19041) {
throw 'GP Connect requires Windows 10 build 19041 or newer.'
}
if ($architecture -eq 'arm64' -and [Environment]::OSVersion.Version.Build -lt 22000) {
$build = [Environment]::OSVersion.Version.Build
if ($architecture -eq 'arm64' -and $build -lt 22000) {
throw 'GP Connect for ARM64 requires Windows 11.'
}
if ($architecture -eq 'x64' -and $build -lt 17763) {
throw 'GP Connect for x64 requires Windows 10 version 1809 or later.'
}
if ((Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name InstallationType) -eq 'Server Core') {
throw 'GP Connect requires Windows Server with Desktop Experience.'
}
foreach ($library in @('mfplat.dll', 'mfreadwrite.dll')) {
if (!(Test-Path -LiteralPath (Join-Path ([Environment]::SystemDirectory) $library) -PathType Leaf)) {
throw 'GP Connect requires Media Foundation. On Windows N, install the Media Feature Pack, then run setup again.'
}
}
$cliBin = Join-Path $source 'bin'
Assert-RegularDirectory $cliBin
foreach ($item in Get-ChildItem -LiteralPath $cliBin -Force) {
if ($item.PSIsContainer -or ($item.Name -ne 'gpclient.exe' -and $item.Extension -ne '.dll')) {
throw "Unexpected Windows CLI runtime file: $($item.Name)"
}
}
$payload = @(Get-ChildItem -LiteralPath $source -Force | Where-Object {
($_.PSIsContainer -and $_.Name -eq 'licenses') -or
($_.PSIsContainer -and $_.Name -in @('licenses', 'bin')) -or
(!$_.PSIsContainer -and ($_.Extension -eq '.dll' -or
$_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'uninstall.exe', 'build-info.json')))
})
@@ -356,6 +393,12 @@ try {
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'WireGuard LLC') {
throw 'The package requires the vendor-signed Wintun driver DLL.'
}
foreach ($dll in Get-ChildItem (Join-Path $stage 'bin') -File -Filter '*.dll') {
$shared = Join-Path $stage $dll.Name
if ((Test-Path -LiteralPath $shared) -and (Get-FileHash $shared).Hash -ne (Get-FileHash $dll.FullName).Hash) {
throw "The shared Windows runtime file differs in bin: $($dll.Name)"
}
}
if ((Test-Path -LiteralPath $destination) -and !$existing) { throw 'The service is not registered. Repair the existing installation before updating.' }
if ($existing -and !(Test-Path -LiteralPath $destination)) { throw 'The registered installation is missing. Restore its files before updating.' }
if (Test-Path $uninstallKey) {
@@ -368,6 +411,9 @@ try {
if ($existing) {
$serviceStopped = $true
Stop-InstalledService
}
$tunnelLock = Open-TunnelLock
if ($existing) {
Assert-NetworkClean
Wait-ForRuntimeRelease
}
@@ -382,6 +428,7 @@ try {
} else { Set-Service -Name $serviceName -StartupType Automatic }
Invoke-ServiceCommand @('failure', $serviceName, 'reset=', '86400', 'actions=', 'restart/3000/restart/10000/none/0')
Set-InstallationMetadata $Version
$tunnelLock.Dispose(); $tunnelLock = $null
Start-InstalledService
$committed = $true
if ($oldMoved) { Remove-Item -LiteralPath $backup -Recurse -Force; $oldMoved = $false }
@@ -395,6 +442,7 @@ try {
Wait-ForApplications
$serviceStopped = $true
Stop-InstalledService
$tunnelLock = Open-TunnelLock
Assert-NetworkClean
Wait-ForRuntimeRelease
# Move first: a locked runtime aborts while its registration and files are intact.
@@ -418,6 +466,7 @@ try {
if ($oldMoved) { Move-Item -LiteralPath $backup -Destination $destination; $oldMoved = $false }
if ($createdService) { Invoke-ServiceCommand @('delete', $serviceName) }
if ($newMoved) { Restore-InstallationMetadata }
if ($tunnelLock) { $tunnelLock.Dispose(); $tunnelLock = $null }
if ($existing -and $serviceStopped -and $wasRunning) { Start-InstalledService }
} catch {
Write-Host "Could not restore GP Connect: $($_.Exception.Message)"
@@ -428,6 +477,7 @@ try {
Write-Host "Details: $(Join-Path $state 'installer.log')"
throw $failure
} finally {
if ($tunnelLock) { $tunnelLock.Dispose() }
if ($stage -and (Test-Path -LiteralPath $stage)) {
try { Remove-Item -LiteralPath $stage -Recurse -Force } catch { Write-Warning "Could not remove temporary files: $stage" }
}
+16 -3
View File
@@ -22,7 +22,7 @@ $info = Get-Content (Join-Path $destination 'build-info.json') -Raw | ConvertFro
if ($info.architecture -ne $Architecture -or [string]$info.build_version -ne $Build) { throw 'The installed package identity does not match.' }
if ($env:WINDOWS_SIGNING_PUBLISHER) {
$signed = @($Installer)
foreach ($name in @('gpgui.exe', 'gpauth.exe', 'gpservice.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'uninstall.exe')) {
foreach ($name in @('gpgui.exe', 'gpauth.exe', 'gpservice.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'uninstall.exe', 'bin\gpclient.exe', 'bin\libopenconnect-5.dll')) {
$signed += Join-Path $destination $name
}
& (Join-Path $PSScriptRoot 'test-windows-signature.ps1') -Files $signed -Publisher $env:WINDOWS_SIGNING_PUBLISHER
@@ -41,6 +41,18 @@ foreach ($name in @('gpgui.exe', 'gpauth.exe')) {
$process = Start-Process (Join-Path $destination $name) -ArgumentList '--version' -PassThru -Wait
if ($process.ExitCode -ne 0) { throw "The installed $name cannot start." }
}
$cli = Join-Path $destination 'bin\gpclient.exe'
Push-Location $env:TEMP
try {
$version = & $cli --version
if ($LASTEXITCODE -ne 0 -or $version -notmatch "^gpclient $([regex]::Escape($info.version))\s") {
throw 'The installed CLI failed its version check.'
}
$help = & $cli connect --help | Out-String
if ($LASTEXITCODE -ne 0 -or $help -notmatch '--cookie-only' -or $help -match '--background') {
throw 'The installed Windows CLI failed its connect help check.'
}
} finally { Pop-Location }
$helper = Join-Path $destination 'gp-posture.exe'
$output = Join-Path $env:TEMP 'gp-posture-install-test.json'
$process = Start-Process $helper -PassThru -Wait -RedirectStandardOutput $output
@@ -52,7 +64,8 @@ $state = Join-Path $env:LOCALAPPDATA 'GP Connect\config\protected-state'
New-Item -ItemType Directory -Force $state | Out-Null
$marker = Join-Path $state 'ci-install-retention'
[IO.File]::WriteAllText($marker, 'retain user settings')
$process = Start-Process (Join-Path $destination 'uninstall.exe') -ArgumentList '/S' -PassThru -Wait
# Start-Process otherwise uses the executable's directory, which the uninstaller must move.
$process = Start-Process (Join-Path $destination 'uninstall.exe') -WorkingDirectory (Split-Path $destination) -ArgumentList '/S' -PassThru -Wait
if ($process.ExitCode -ne 0) { throw 'The uninstaller failed.' }
if ((Get-Service GPConnect -ErrorAction SilentlyContinue) -or (Test-Path $destination) -or (Test-Path ($destination + '.previous'))) {
throw 'The uninstaller left service registration or runtime files.'
@@ -62,4 +75,4 @@ if ((Test-Path $shortcut) -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\Curre
}
if ([IO.File]::ReadAllText($marker) -ne 'retain user settings') { throw 'The uninstaller changed user state.' }
Remove-Item $marker
Write-Host "Installed $Architecture runtime and service, launched both applications, and uninstalled successfully."
Write-Host "Installed $Architecture runtime and service, launched the desktop, authenticator and CLI, and uninstalled successfully."
+20 -13
View File
@@ -130,24 +130,31 @@ class OBSTests(unittest.TestCase):
class CoprTests(unittest.TestCase):
def test_migrated_repository_matches_exact_build_manifest(self):
def test_public_repository_must_match_the_selected_builds_signed_rpm(self):
checker = publication.Copr(arguments(build_id=42))
build = {"ownername": "yuezk", "projectname": "globalprotect-openconnect",
"state": "succeeded", "source_package": {"name": "globalprotect-openconnect", "version": "3.0.1-1"},
"chroots": ["fedora-44-x86_64"], "repo_url": "https://repo"}
status = {"state": "succeeded", "result_url": "https://results/42/"}
package = {"name": "globalprotect-openconnect", "version": "3.0.1", "release": "1.fc44", "arch": "x86_64"}
primary = ET.fromstring('''<metadata xmlns="http://linux.duke.edu/metadata/common"><package>
<name>globalprotect-openconnect</name><arch>x86_64</arch><version ver="3.0.1" rel="1.fc44"/>
<location href="Packages/g/globalprotect-openconnect-3.0.1-1.fc44.x86_64.rpm"/></package></metadata>''')
with patch.object(publication, "api", side_effect=[build, status, {"packages": [package]}]), \
patch.object(publication, "rpm_packages", return_value=primary):
self.assertIn("1 targets built and published", checker.check())
package["release"] = "1.fc45"
with patch.object(publication, "api", side_effect=[build, status, {"packages": [package]}]), \
patch.object(publication, "rpm_packages", return_value=primary):
with self.assertRaisesRegex(publication.Pending, "Waiting for Copr build 42"):
checker.check()
digest = "a" * 64
artifacts = {"count": 1, "results": [{"release": "1.fc44", "sha256": digest}]}
for release, published_digest, matches in [
("1.fc44", digest, True),
("1.fc44", "b" * 64, False),
("1.fc45", digest, False)]:
with self.subTest(release=release, published_digest=published_digest):
primary = ET.fromstring(f'''<metadata xmlns="http://linux.duke.edu/metadata/common"><package>
<name>globalprotect-openconnect</name><arch>x86_64</arch><version ver="3.0.1" rel="{release}"/>
<checksum type="sha256">{published_digest}</checksum>
<location href="Packages/g/globalprotect-openconnect-3.0.1-1.fc44.x86_64.rpm"/></package></metadata>''')
with patch.object(publication, "api", side_effect=[build, status, artifacts]) as api, \
patch.object(publication, "rpm_packages", return_value=primary):
if matches:
self.assertIn("1 targets built and published", checker.check())
else:
with self.assertRaisesRegex(publication.Pending, "Waiting for Copr build 42"):
checker.check()
self.assertEqual(api.call_args.kwargs["pulp_label_select"], "build_id=42,chroot=fedora-44-x86_64")
def test_unselected_chroot_cannot_be_hidden_by_verification(self):
checker = publication.Copr(arguments(build_id=42, chroots=["fedora-44-x86_64"]))
+1 -1
View File
@@ -66,7 +66,7 @@ class WindowsFeedTests(unittest.TestCase):
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}os"), f"windows-{payload.architecture}")
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}installerArguments"), "/UPDATE")
self.assertEqual(enclosure.get(f"{{{feed.SPARKLE}}}version"), "3.4.0")
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.19041"
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.17763"
self.assertEqual(item.findtext(f"{{{feed.SPARKLE}}}minimumSystemVersion"), minimum)
self.assertEqual(json.loads((args.output / "latest.json").read_text())["stable"]["platforms"], ["windows"])
+21 -10
View File
@@ -84,7 +84,7 @@ def rpm_packages(base_url):
return ET.fromstring(unpack(content, location))
def rpm_present(base_url, package, version, arch, release_matches):
def rpm_present(base_url, package, version, arch, release_matches, *, sha256=None):
namespace = {"rpm": "http://linux.duke.edu/metadata/common"}
for entry in rpm_packages(base_url).findall("rpm:package", namespace):
info = entry.find("rpm:version", namespace)
@@ -92,6 +92,10 @@ def rpm_present(base_url, package, version, arch, release_matches):
entry.findtext("rpm:arch", namespaces=namespace) != arch or
info.get("ver") != version or not release_matches(info.get("rel", ""))):
continue
if sha256 is not None:
digest = entry.find("rpm:checksum[@type='sha256']", namespace)
if digest is None or digest.text != sha256:
continue
return True
return False
@@ -251,16 +255,23 @@ class Copr:
raise Pending(f"Copr {chroot}: {status['state']}; {link}")
base = build["repo_url"].rstrip("/") + "/" + chroot
arch = chroot.rsplit("-", 1)[1]
packages = api(urljoin(status["result_url"], "results.json"))["packages"]
package = next((item for item in packages
if item["name"] == args.package and item["version"] == args.version
and item["arch"] == arch
and (item["release"] == args.revision
or item["release"].startswith(args.revision + "."))), None)
if package is None:
raise Failed(f"Copr build {args.build_id} has no requested package for {chroot}")
# Pulp labels the signed RPM with the producing build and chroot.
artifacts = api("https://packages.redhat.com/api/pulp/public-copr/api/v3/content/rpm/packages/",
pulp_label_select=f"build_id={args.build_id},chroot={chroot}",
name=args.package, version=args.version, arch=arch, fields="release,sha256")
if not artifacts["count"]:
raise Pending(f"Waiting for the signed RPM from Copr build {args.build_id} for {chroot}")
if artifacts["count"] != 1:
raise Failed(f"Ambiguous RPMs from Copr build {args.build_id} for {chroot}")
artifact = artifacts["results"][0]
release = artifact["release"]
if release != args.revision and not release.startswith(args.revision + "."):
raise Failed(f"Copr build {args.build_id} has an unexpected RPM revision for {chroot}")
digest = artifact["sha256"]
if not digest or not re.fullmatch(r"[0-9a-f]{64}", digest):
raise Failed(f"Missing signed RPM checksum for Copr build {args.build_id} for {chroot}")
if not rpm_present(base, args.package, args.version, arch,
lambda release: release == package["release"]):
lambda value: value == release, sha256=digest):
raise Pending(f"Waiting for Copr build {args.build_id} in {base}")
return f"Copr build {args.build_id}: {len(build['chroots'])} targets built and published; {link}"
+1 -1
View File
@@ -96,7 +96,7 @@ def generate(args: argparse.Namespace) -> None:
item = ET.SubElement(channel, "item")
ET.SubElement(item, "title").text = f"GP Connect {display_version}"
ET.SubElement(item, "description").text = "\n".join(release["highlights"])
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.19041"
minimum = "10.0.22000" if payload.architecture == "arm64" else "10.0.17763"
ET.SubElement(item, f"{{{SPARKLE}}}minimumSystemVersion").text = minimum
ET.SubElement(item, "enclosure", {
"url": payload.installer_url, "length": str(length), "type": "application/octet-stream",