release: publish verified 3.2.0 sources

This commit is contained in:
Kevin Yue committed 2026-10-23 00:47:07 +08:00
commit 6040ced26b
32 files changed
+1635 -67

No files matched your search

Generated
+12 -12
View File
@@ -253,7 +253,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]] [[package]]
name = "auth" name = "auth"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"block2", "block2",
@@ -508,7 +508,7 @@ dependencies = [
[[package]] [[package]]
name = "browser-launcher" name = "browser-launcher"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"log", "log",
@@ -860,7 +860,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"tempfile", "tempfile",
] ]
@@ -2050,7 +2050,7 @@ dependencies = [
[[package]] [[package]]
name = "gpapi" name = "gpapi"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.23.1", "base64 0.23.1",
@@ -2104,7 +2104,7 @@ dependencies = [
[[package]] [[package]]
name = "gpauth" name = "gpauth"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"auth", "auth",
@@ -2123,7 +2123,7 @@ dependencies = [
[[package]] [[package]]
name = "gpclient" name = "gpclient"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2155,7 +2155,7 @@ dependencies = [
[[package]] [[package]]
name = "gpgui-helper" name = "gpgui-helper"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap", "clap",
@@ -2176,7 +2176,7 @@ dependencies = [
[[package]] [[package]]
name = "gphip" name = "gphip"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"askama", "askama",
@@ -2193,7 +2193,7 @@ dependencies = [
[[package]] [[package]]
name = "gpservice" name = "gpservice"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
@@ -2228,7 +2228,7 @@ dependencies = [
[[package]] [[package]]
name = "gptunnel" name = "gptunnel"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"gpapi", "gpapi",
"log", "log",
@@ -2240,7 +2240,7 @@ dependencies = [
[[package]] [[package]]
name = "gpvpnc" name = "gpvpnc"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"log", "log",
] ]
@@ -3727,7 +3727,7 @@ dependencies = [
[[package]] [[package]]
name = "openconnect" name = "openconnect"
version = "3.1.0" version = "3.2.0"
dependencies = [ dependencies = [
"autotools", "autotools",
"cc", "cc",
+1 -1
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package] [workspace.package]
rust-version = "1.91" rust-version = "1.91"
version = "3.1.0" version = "3.2.0"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2024"
+33 -1
View File
@@ -112,7 +112,15 @@ pub(crate) struct ConnectArgs {
#[arg(short, long, help = "Request MTU from server (legacy servers only)")] #[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>, pub(super) mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")] #[arg(
long,
value_enum,
default_value = "auto",
help = "Choose which IP version to try first when connecting to the gateway"
)]
pub(super) ip_preference: gpapi::gateway::GatewayIpPreference,
#[arg(long, help = "Use only IPv4 for traffic inside the VPN tunnel")]
pub(super) disable_ipv6: bool, pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)] #[arg(long = "user-agent", hide = true)]
@@ -469,4 +477,28 @@ mod tests {
assert!(!cli.args.cookie_only); assert!(!cli.args.cookie_only);
} }
#[test]
fn ip_preference_parses_independently_of_tunnel_ipv6() {
use clap::Parser;
use gpapi::gateway::GatewayIpPreference;
let default = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).unwrap();
assert_eq!(default.args.ip_preference, GatewayIpPreference::Auto);
for (value, expected) in [
("auto", GatewayIpPreference::Auto),
("ipv4", GatewayIpPreference::Ipv4),
("ipv6", GatewayIpPreference::Ipv6),
] {
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--ip-preference",
value,
"--disable-ipv6",
])
.unwrap();
assert_eq!(cli.args.ip_preference, expected);
assert!(cli.args.disable_ipv6);
}
}
} }
+5
View File
@@ -452,6 +452,11 @@ impl ConnectHandler<'_> {
.reconnect_timeout(self.args.reconnect_timeout) .reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu) .mtu(mtu)
.disable_ipv6(self.args.disable_ipv6) .disable_ipv6(self.args.disable_ipv6)
.gateway_ip_preference(match self.args.ip_preference {
gpapi::gateway::GatewayIpPreference::Auto => openconnect::GatewayIpPreference::Auto,
gpapi::gateway::GatewayIpPreference::Ipv4 => openconnect::GatewayIpPreference::Ipv4,
gpapi::gateway::GatewayIpPreference::Ipv6 => openconnect::GatewayIpPreference::Ipv6,
})
.no_dtls(self.args.no_dtls) .no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone()) .local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0)) .dpd_interval(self.args.dpd_interval.unwrap_or(0))
+9 -2
View File
@@ -3,6 +3,7 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use anyhow::{Context, bail}; use anyhow::{Context, bail};
use log::{info, warn}; use log::{info, warn};
@@ -43,14 +44,20 @@ impl CredentialServer {
tokio::select! { tokio::select! {
_ = cancel.cancelled() => break, _ = cancel.cancelled() => break,
accepted = listener.accept() => { accepted = listener.accept() => {
let (stream, _) = accepted?; let (mut stream, _) = accepted?;
if peer_uid(&stream)? != 0 { if peer_uid(&stream)? != 0 {
warn!("Rejected non-root broker credential client"); warn!("Rejected non-root broker credential client");
continue; continue;
} }
let registry = Arc::clone(&self.registry); let registry = Arc::clone(&self.registry);
tokio::spawn(async move { tokio::spawn(async move {
if let Err(err) = credential_lease::serve(stream, registry, None).await { let identity = tokio::time::timeout(std::time::Duration::from_secs(5), stream.read_u32()).await;
let uid = match identity {
Ok(Ok(0)) => { let _ = stream.write_u8(1).await; return; }
Ok(Ok(uid)) => uid,
_ => { warn!("Invalid desktop identity from broker"); return; }
};
if let Err(err) = credential_lease::serve(stream, registry, Some(uid)).await {
warn!("Broker credential lease ended: {err}"); warn!("Broker credential lease ended: {err}");
} }
}); });
+28 -1
View File
@@ -138,7 +138,9 @@ impl RequestDispatcher {
authority authority
.registry .registry
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || { .reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
self.lifecycle.reserve_connect() self
.lifecycle
.reserve_connect(request.restart_of().map(|attempt| (attempt, authority.session_id)))
})?; })?;
let preparation = ConnectionPreparation { let preparation = ConnectionPreparation {
authority, authority,
@@ -599,4 +601,29 @@ mod tests {
Err("macOS does not support custom HIP scripts") Err("macOS does not support custom HIP scripts")
); );
} }
#[test]
#[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"]
fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() {
let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap();
let archive = compressed_gui_archive(&binary);
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
let temporary = tempfile::tempdir().unwrap();
let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| temporary.path().to_owned());
std::fs::create_dir_all(&output).unwrap();
std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap();
let target = output.join("gpclient/gpgui");
for upgrade in [false, true] {
if upgrade {
std::fs::write(&target, b"old GUI").unwrap();
}
install_gui_at(archive.path(), &checksum, &target).unwrap();
assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1);
assert_eq!(std::fs::read(&target).unwrap(), binary);
let result = std::process::Command::new(&target).arg("--version").output().unwrap();
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION")));
}
}
} }
+18 -7
View File
@@ -190,6 +190,10 @@ impl SessionRegistry {
Ok(None) Ok(None)
} }
pub fn service_instance_id(&self) -> Uuid {
self.service_instance_id
}
pub fn new(service_instance_id: Uuid) -> Self { pub fn new(service_instance_id: Uuid) -> Self {
Self { Self {
service_instance_id, service_instance_id,
@@ -425,6 +429,13 @@ impl SessionRegistry {
} }
} }
pub fn has_session(&self, session_id: Uuid) -> bool {
self
.sessions
.lock()
.is_ok_and(|sessions| sessions.contains_key(&session_id))
}
pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool { pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool {
let Ok(sessions) = self.sessions.lock() else { let Ok(sessions) = self.sessions.lock() else {
return false; return false;
@@ -653,7 +664,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected); let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone()); let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let reservation = registry let reservation = registry
.reserve_connection(session, 1, true, || lifecycle.reserve_connect()) .reserve_connection(session, 1, true, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
let drain = reservation.drain(); let drain = reservation.drain();
let cancel = reservation.cancellation(); let cancel = reservation.cancellation();
@@ -669,7 +680,7 @@ mod tests {
assert!(!drain.is_complete()); assert!(!drain.is_complete());
assert!( assert!(
registry registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect()) .reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.is_err() .is_err()
); );
assert!(matches!( assert!(matches!(
@@ -680,7 +691,7 @@ mod tests {
drain.wait().await; drain.wait().await;
let next_reservation = registry let next_reservation = registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect()) .reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
assert!( assert!(
registry registry
@@ -710,7 +721,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected); let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone()); let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let reservation = registry let reservation = registry
.reserve_connection(session, 1, true, || lifecycle.reserve_connect()) .reserve_connection(session, 1, true, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap(); let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
assert!(reservation.cancellation().is_cancelled()); assert!(reservation.cancellation().is_cancelled());
@@ -728,7 +739,7 @@ mod tests {
); );
assert!( assert!(
registry registry
.reserve_connection(session, 1, false, || lifecycle.reserve_connect()) .reserve_connection(session, 1, false, || lifecycle.reserve_connect(None))
.is_ok() .is_ok()
); );
} }
@@ -748,7 +759,7 @@ mod tests {
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected); let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone()); let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
let tunnel = registry let tunnel = registry
.reserve_connection(session, 1, false, || lifecycle.reserve_connect()) .reserve_connection(session, 1, false, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
registry.disconnect_if_current(session, 1); registry.disconnect_if_current(session, 1);
assert!(!tunnel.cancellation().is_cancelled()); assert!(!tunnel.cancellation().is_cancelled());
@@ -765,7 +776,7 @@ mod tests {
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0) .commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
.unwrap(); .unwrap();
let session_work = registry let session_work = registry
.reserve_connection(session, 2, true, || lifecycle.reserve_connect()) .reserve_connection(session, 2, true, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
registry.revoke(session); registry.revoke(session);
assert!(session_work.cancellation().is_cancelled()); assert!(session_work.cancellation().is_cancelled());
+98 -10
View File
@@ -27,12 +27,14 @@ mod non_tunnel;
mod preparation; mod preparation;
pub(crate) use preparation::{PreparedConnection, prepare_connection}; pub(crate) use preparation::{PreparedConnection, prepare_connection};
mod runtime; mod runtime;
mod script_tun;
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct LifecycleHandle { pub(crate) struct LifecycleHandle {
events: mpsc::Sender<LifecycleEvent>, events: mpsc::Sender<LifecycleEvent>,
admissions: Arc<Mutex<Admissions>>, admissions: Arc<Mutex<Admissions>>,
tunnel: watch::Sender<TunnelBinding>, tunnel: watch::Sender<TunnelBinding>,
state: watch::Sender<VpnState>,
} }
#[derive(Clone, Default)] #[derive(Clone, Default)]
@@ -46,7 +48,7 @@ impl LifecycleHandle {
pub fn subscribe_tunnel(&self) -> watch::Receiver<TunnelBinding> { pub fn subscribe_tunnel(&self) -> watch::Receiver<TunnelBinding> {
self.tunnel.subscribe() self.tunnel.subscribe()
} }
pub fn reserve_connect(&self) -> Result<ConnectReservation, ServiceResult> { pub fn reserve_connect(&self, restart: Option<(u64, Uuid)>) -> Result<ConnectReservation, ServiceResult> {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned"); let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
if admissions.closed { if admissions.closed {
return Err(ServiceResult::rejected( return Err(ServiceResult::rejected(
@@ -60,6 +62,13 @@ impl LifecycleHandle {
"A VPN connection is already in progress", "A VPN connection is already in progress",
)); ));
} }
if restart.is_some() && admissions.restart != restart {
return Err(ServiceResult::rejected(
ServiceErrorCode::InvalidRequest,
"Reconnect request is no longer current",
));
}
admissions.restart = None;
let attempt = admissions.next_attempt; let attempt = admissions.next_attempt;
admissions.next_attempt += 1; admissions.next_attempt += 1;
let cancellation = CancellationToken::new(); let cancellation = CancellationToken::new();
@@ -86,7 +95,7 @@ impl LifecycleHandle {
edited_report: Option<Arc<str>>, edited_report: Option<Arc<str>>,
session_id: Option<Uuid>, session_id: Option<Uuid>,
) -> ServiceResult { ) -> ServiceResult {
match self.reserve_connect() { match self.reserve_connect(None) {
Ok(reservation) => reservation.commit( Ok(reservation) => reservation.commit(
PreparedConnection::lifecycle_fixture(request), PreparedConnection::lifecycle_fixture(request),
desktop_uid, desktop_uid,
@@ -99,7 +108,9 @@ impl LifecycleHandle {
pub fn request_disconnect(&self) -> ServiceResult { pub fn request_disconnect(&self) -> ServiceResult {
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned"); let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
admissions.restart = None;
let Some(admission) = admissions.current.as_mut() else { let Some(admission) = admissions.current.as_mut() else {
self.state.send_replace(VpnState::Disconnected);
return ServiceResult::Accepted; return ServiceResult::Accepted;
}; };
if admission.stop_requested { if admission.stop_requested {
@@ -355,6 +366,7 @@ struct Admissions {
closed: bool, closed: bool,
next_attempt: u64, next_attempt: u64,
current: Option<Admission>, current: Option<Admission>,
restart: Option<(u64, Uuid)>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -395,6 +407,12 @@ enum LifecycleEvent {
Stop { Stop {
attempt: u64, attempt: u64,
}, },
ScriptTunSuspended {
attempt: u64,
},
ReconnectRequired {
attempt: u64,
},
Established { Established {
attempt: u64, attempt: u64,
session: VpnSessionInfo, session: VpnSessionInfo,
@@ -422,6 +440,7 @@ struct ActiveAttempt {
cancellation: CancellationToken, cancellation: CancellationToken,
task: tokio::task::JoinHandle<()>, task: tokio::task::JoinHandle<()>,
failure: Option<String>, failure: Option<String>,
reconnect_required: bool,
} }
pub(crate) struct VpnTask { pub(crate) struct VpnTask {
@@ -445,6 +464,7 @@ impl VpnTask {
events: events_tx, events: events_tx,
admissions: Arc::new(Mutex::new(Admissions::default())), admissions: Arc::new(Mutex::new(Admissions::default())),
tunnel: watch::channel(TunnelBinding::default()).0, tunnel: watch::channel(TunnelBinding::default()).0,
state: vpn_state_tx.clone(),
}; };
let task = Self { let task = Self {
events, events,
@@ -539,6 +559,21 @@ impl VpnTask {
active.failure = Some(reason); active.failure = Some(reason);
} }
} }
LifecycleEvent::ScriptTunSuspended { attempt } => {
if let Some(active) = self
.active
.as_mut()
.filter(|a| a.attempt == attempt && !a.cancellation.is_cancelled())
{
let info = active.info.clone();
self.send_state(VpnState::Connecting(Box::new(info)));
}
}
LifecycleEvent::ReconnectRequired { attempt } => {
if let Some(active) = self.active.as_mut().filter(|a| a.attempt == attempt) {
active.reconnect_required = true;
}
}
LifecycleEvent::PreparationReleased => {} LifecycleEvent::PreparationReleased => {}
} }
} }
@@ -562,7 +597,14 @@ impl VpnTask {
.iter() .iter()
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel), .all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel),
}); });
let info = connection.request.info().clone(); let mut info = connection.request.info().clone();
if let gpapi::script_tun::PacketDelivery::ScriptTun(request) = connection.request.args().packet_delivery() {
info.set_script_tun_identity(gpapi::script_tun::Identity {
service_instance: self.registry.service_instance_id(),
attempt,
launch_id: request.launch_id,
});
}
let allow_extend_session = connection.request.args().allow_extend_session(); let allow_extend_session = connection.request.args().allow_extend_session();
let cancellation = self.lifecycle.attempt_cancellation(attempt); let cancellation = self.lifecycle.attempt_cancellation(attempt);
if !activated { if !activated {
@@ -590,6 +632,7 @@ impl VpnTask {
cancellation, cancellation,
task, task,
failure: None, failure: None,
reconnect_required: false,
}); });
if activated { if activated {
self.send_state(VpnState::Connecting(Box::new(info))); self.send_state(VpnState::Connecting(Box::new(info)));
@@ -703,7 +746,33 @@ impl VpnTask {
..Default::default() ..Default::default()
}); });
} }
if let Some(reason) = active.failure { if active.reconnect_required
&& !active.cancellation.is_cancelled()
&& active.session_id.is_some_and(|id| self.registry.has_session(id))
{
let mut admissions = self
.lifecycle
.admissions
.lock()
.expect("VPN lifecycle admissions mutex poisoned");
if let Some(admission) = admissions.current.take() {
if !admission.cancellation.is_cancelled() && !admission.stop_requested {
let owner = active.session_id.unwrap();
admissions.restart = Some((attempt, owner));
self.send_state(VpnState::ReconnectRequired(Box::new(
gpapi::service::vpn_state::ReconnectRequest {
attempt,
owner,
info: active.info,
},
)));
} else {
self.send_state(VpnState::Disconnected);
}
admission.completion.completed.store(true, Ordering::Release);
admission.completion.notify.notify_waiters();
}
} else if let Some(reason) = active.failure {
self.send_state(VpnState::Failed(reason)); self.send_state(VpnState::Failed(reason));
self.lifecycle.clear_attempt(attempt); self.lifecycle.clear_attempt(attempt);
} else { } else {
@@ -918,12 +987,12 @@ mod tests {
fn shutdown_cancels_preparation_despite_a_full_queue_and_rejects_commit() { fn shutdown_cancels_preparation_despite_a_full_queue_and_rejects_commit() {
let (state, _state_rx) = watch::channel(VpnState::Disconnected); let (state, _state_rx) = watch::channel(VpnState::Disconnected);
let (_task, lifecycle) = VpnTask::new(state, false, registry()); let (_task, lifecycle) = VpnTask::new(state, false, registry());
let reservation = lifecycle.reserve_connect().unwrap(); let reservation = lifecycle.reserve_connect(None).unwrap();
let cancellation = reservation.cancellation(); let cancellation = reservation.cancellation();
while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {} while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {}
lifecycle.close_admission(); lifecycle.close_admission();
assert!(cancellation.is_cancelled()); assert!(cancellation.is_cancelled());
assert!(lifecycle.reserve_connect().is_err()); assert!(lifecycle.reserve_connect(None).is_err());
let request = test_connect_request(ConnectInfo::new( let request = test_connect_request(ConnectInfo::new(
"portal.example.com".into(), "portal.example.com".into(),
gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into()), gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into()),
@@ -934,19 +1003,35 @@ mod tests {
ServiceResult::Rejected(..) ServiceResult::Rejected(..)
)); ));
assert!(!lifecycle.has_attempt(0)); assert!(!lifecycle.has_attempt(0));
assert!(lifecycle.reserve_connect().is_err()); assert!(lifecycle.reserve_connect(None).is_err());
} }
#[test] #[test]
fn disconnect_cancels_preparation_even_when_stop_notification_queue_is_full() { fn disconnect_cancels_preparation_even_when_stop_notification_queue_is_full() {
let (state, _state_rx) = watch::channel(VpnState::Disconnected); let (state, _state_rx) = watch::channel(VpnState::Disconnected);
let (_task, lifecycle) = VpnTask::new(state, false, registry()); let (_task, lifecycle) = VpnTask::new(state, false, registry());
let reservation = lifecycle.reserve_connect().unwrap(); let reservation = lifecycle.reserve_connect(None).unwrap();
while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {} while lifecycle.events.try_send(LifecycleEvent::PreparationReleased).is_ok() {}
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted); assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
assert!(reservation.cancellation().is_cancelled()); assert!(reservation.cancellation().is_cancelled());
assert!(!reservation.drain().is_complete()); assert!(!reservation.drain().is_complete());
assert!(lifecycle.reserve_connect().is_err()); assert!(lifecycle.reserve_connect(None).is_err());
}
#[test]
fn reconnect_admission_is_owned_single_use_and_cancelled_by_disconnect() {
let lifecycle = LifecycleHandle::for_tests();
let owner = Uuid::new_v4();
lifecycle.admissions.lock().unwrap().restart = Some((42, owner));
assert!(lifecycle.reserve_connect(Some((42, Uuid::new_v4()))).is_err());
assert!(lifecycle.reserve_connect(Some((41, owner))).is_err());
let reservation = lifecycle.reserve_connect(Some((42, owner))).unwrap();
drop(reservation);
assert!(lifecycle.reserve_connect(Some((42, owner))).is_err());
lifecycle.admissions.lock().unwrap().restart = Some((43, owner));
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
assert!(lifecycle.reserve_connect(Some((43, owner))).is_err());
assert!(lifecycle.reserve_connect(None).is_ok());
} }
#[tokio::test] #[tokio::test]
@@ -955,7 +1040,7 @@ mod tests {
let (mut task, lifecycle) = VpnTask::new(state, false, registry()); let (mut task, lifecycle) = VpnTask::new(state, false, registry());
let gateway = gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into()); let gateway = gpapi::gateway::Gateway::new("vpn".into(), "vpn.example.com".into());
let info = ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]); let info = ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]);
let reservation = lifecycle.reserve_connect().unwrap(); let reservation = lifecycle.reserve_connect(None).unwrap();
let cancellation = reservation.cancellation(); let cancellation = reservation.cancellation();
assert_eq!( assert_eq!(
reservation.commit( reservation.commit(
@@ -976,6 +1061,7 @@ mod tests {
cancellation, cancellation,
task: tokio::spawn(async {}), task: tokio::spawn(async {}),
failure: None, failure: None,
reconnect_required: false,
}); });
task.send_state(VpnState::Connecting(Box::new(info))); task.send_state(VpnState::Connecting(Box::new(info)));
let mut member = gpapi::session::GatewaySessionSummary { let mut member = gpapi::session::GatewaySessionSummary {
@@ -1030,6 +1116,7 @@ mod tests {
cancellation: cancellation.clone(), cancellation: cancellation.clone(),
task: worker, task: worker,
failure: None, failure: None,
reconnect_required: false,
}); });
assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted); assert_eq!(lifecycle.request_disconnect(), ServiceResult::Accepted);
let stop = task.events.recv().await.unwrap(); let stop = task.events.recv().await.unwrap();
@@ -1076,6 +1163,7 @@ mod tests {
cancellation: cancellation.clone(), cancellation: cancellation.clone(),
task: tokio::spawn(async {}), task: tokio::spawn(async {}),
failure: None, failure: None,
reconnect_required: false,
}); });
task.send_state(VpnState::Connecting(Box::new( task.send_state(VpnState::Connecting(Box::new(
task.active.as_ref().unwrap().info.clone(), task.active.as_ref().unwrap().info.clone(),
@@ -151,7 +151,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
let (state, state_rx) = watch::channel(VpnState::Disconnected); let (state, state_rx) = watch::channel(VpnState::Disconnected);
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone()); let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
let reservation = registry let reservation = registry
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect()) .reserve_connection(session_id, 1, true, || lifecycle.reserve_connect(None))
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
registry.commit_connection(session_id, 1, true, || reservation.commit( registry.commit_connection(session_id, 1, true, || reservation.commit(
@@ -178,7 +178,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
.unwrap(); .unwrap();
assert!(lifecycle.has_attempt(0)); assert!(lifecycle.has_attempt(0));
assert!(!drain_waiter.is_finished()); assert!(!drain_waiter.is_finished());
assert!(lifecycle.reserve_connect().is_err()); assert!(lifecycle.reserve_connect(None).is_err());
assert!(!task.active.as_ref().unwrap().task.is_finished()); assert!(!task.active.as_ref().unwrap().task.is_finished());
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected)); assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
release.send(()).unwrap(); release.send(()).unwrap();
@@ -191,7 +191,7 @@ async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response(
} }
assert!(!lifecycle.has_attempt(0)); assert!(!lifecycle.has_attempt(0));
drain_waiter.await.unwrap(); drain_waiter.await.unwrap();
assert!(lifecycle.reserve_connect().is_ok()); assert!(lifecycle.reserve_connect(None).is_ok());
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected)); assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
let request = server.await.unwrap(); let request = server.await.unwrap();
assert!(request.starts_with("POST /ssl-vpn/logout.esp ")); assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
@@ -31,7 +31,17 @@ pub(crate) async fn prepare_connection(
brokered_macos: bool, brokered_macos: bool,
cancellation: CancellationToken, cancellation: CancellationToken,
) -> anyhow::Result<PreparedConnection> { ) -> anyhow::Result<PreparedConnection> {
let mode = request.args().packet_delivery().clone();
let request = request.with_packet_delivery(mode);
let args = request.args(); let args = request.args();
if let gpapi::script_tun::PacketDelivery::ScriptTun(consumer) = args.packet_delivery() {
consumer.validate()?;
anyhow::ensure!(
request.plan().members().len() == 1
&& request.plan().members()[0].authentication.mode() == gpapi::session::SessionMode::Tunnel,
"Script-tun requires a tunnel gateway"
);
}
let non_tunnel = request let non_tunnel = request
.plan() .plan()
.members() .members()
+80 -23
View File
@@ -31,10 +31,12 @@ struct TunnelInput {
source: Arc<openconnect::HipSource>, source: Arc<openconnect::HipSource>,
session_id: Option<Uuid>, session_id: Option<Uuid>,
registry: Arc<crate::session_registry::SessionRegistry>, registry: Arc<crate::session_registry::SessionRegistry>,
desktop_uid: Option<u32>,
} }
struct PreparedTunnel { struct PreparedTunnel {
vpn: Arc<Vpn>, vpn: Arc<Vpn>,
script_tun: Option<super::script_tun::PreparedScriptTun>,
} }
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers /// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
@@ -47,13 +49,6 @@ pub(super) fn spawn(
) -> JoinHandle<()> { ) -> JoinHandle<()> {
tokio::spawn(async move { tokio::spawn(async move {
let attempt = input.attempt; let attempt = input.attempt;
let non_tunnel = input
.connection
.request
.plan()
.members()
.iter()
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
let mut failure = None; let mut failure = None;
let mut approval = None; let mut approval = None;
if !cancellation.is_cancelled() { if !cancellation.is_cancelled() {
@@ -110,24 +105,65 @@ pub(super) fn spawn(
source, source,
session_id: input.session_id, session_id: input.session_id,
registry: input.registry.clone(), registry: input.registry.clone(),
desktop_uid: input.desktop_uid,
}; };
input.connection.request.release_script_tun_bootstrap();
let setup_cancel = cancellation.clone(); let setup_cancel = cancellation.clone();
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await; let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
match prepared { match prepared {
Ok(Ok(prepared)) => { Ok(Ok(mut prepared)) => {
run_tunnel( if let Some(script_tun) = prepared.script_tun.take() {
attempt, if let Some(session_id) = input.session_id {
&prepared, match super::script_tun::run(
guard, gpapi::script_tun::Identity {
&input.lifecycle, service_instance: input.registry.service_instance_id(),
&mut input.connection.sessions, attempt,
cancellation.clone(), launch_id: match input.connection.request.args().packet_delivery() {
events.clone(), gpapi::script_tun::PacketDelivery::ScriptTun(request) => request.launch_id,
) _ => unreachable!(),
.await },
},
prepared.vpn.clone(),
script_tun,
guard,
&input.lifecycle,
cancellation.clone(),
events.clone(),
session_id,
input.registry.clone(),
&mut input.connection.sessions,
)
.await
{
Ok(()) => {}
Err(error) if error.is::<super::script_tun::NetworkChanged>() && !cancellation.is_cancelled() => {
let _ = events.send(LifecycleEvent::ReconnectRequired { attempt }).await;
}
Err(error) if !cancellation.is_cancelled() => {
failure = Some(error.to_string());
}
Err(_) => {}
}
}
} else {
run_tunnel(
attempt,
&prepared,
guard,
&input.lifecycle,
&mut input.connection.sessions,
cancellation.clone(),
events.clone(),
)
.await;
}
}
Ok(Err(error)) => {
failure = Some(format!("Failed to prepare tunnel: {error:#}"));
}
Err(error) => {
failure = Some(format!("Tunnel setup worker failed: {error}"));
} }
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
Err(error) => warn!("Tunnel setup worker failed: {error}"),
} }
} }
} }
@@ -145,7 +181,7 @@ pub(super) fn spawn(
// Identity and approval remain alive through worker drain and logout. Ended // Identity and approval remain alive through worker drain and logout. Ended
// only releases admission after the actor also joins this task. // only releases admission after the actor also joins this task.
drop(approval); drop(approval);
if non_tunnel && !cancellation.is_cancelled() { if !cancellation.is_cancelled() {
if let Some(reason) = failure { if let Some(reason) = failure {
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await; let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
} }
@@ -210,8 +246,24 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
); );
let member = &input.request.plan().members()[0]; let member = &input.request.plan().members()[0];
let identity_files = &input.resources.identity_files; let identity_files = &input.resources.identity_files;
let (builder, script_tun) = match args.packet_delivery() {
gpapi::script_tun::PacketDelivery::System => (
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?,
None,
),
gpapi::script_tun::PacketDelivery::ScriptTun(request) => {
ensure!(input.session_id.is_some(), "Script-tun requires a desktop session");
let (builder, script_tun) = super::script_tun::builder(
member.gateway.server(),
member.authentication.cookie(),
request,
input.desktop_uid.context("Desktop identity is unavailable")?,
)?;
(builder, Some(script_tun))
}
};
let vpn = Arc::new( let vpn = Arc::new(
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)? builder
.user_agent(args.user_agent()) .user_agent(args.user_agent())
.os(args.openconnect_os()) .os(args.openconnect_os())
.os_version(args.os_version()) .os_version(args.os_version())
@@ -231,6 +283,11 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
.reconnect_timeout(args.reconnect_timeout()) .reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu()) .mtu(args.mtu())
.disable_ipv6(args.disable_ipv6()) .disable_ipv6(args.disable_ipv6())
.gateway_ip_preference(match args.gateway_ip_preference() {
gpapi::gateway::GatewayIpPreference::Auto => openconnect::GatewayIpPreference::Auto,
gpapi::gateway::GatewayIpPreference::Ipv4 => openconnect::GatewayIpPreference::Ipv4,
gpapi::gateway::GatewayIpPreference::Ipv6 => openconnect::GatewayIpPreference::Ipv6,
})
.no_dtls(args.no_dtls()) .no_dtls(args.no_dtls())
.local_hostname(args.local_hostname()) .local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd()) .dpd_interval(args.force_dpd())
@@ -247,7 +304,7 @@ fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyho
} }
}); });
} }
Ok(PreparedTunnel { vpn }) Ok(PreparedTunnel { vpn, script_tun })
} }
async fn run_tunnel( async fn run_tunnel(
+247
View File
@@ -0,0 +1,247 @@
//! Supervision of an unprivileged script-tun consumer; payload semantics belong to the caller.
use super::{LifecycleEvent, LifecycleHandle};
use anyhow::{Context, bail, ensure};
use gpapi::script_tun::{Bootstrap, Identity, Message, ScriptTunRequest, receive, send as send_message};
use openconnect::{Vpn, VpnBuilder, tunnel::Event};
use std::{sync::Arc, time::Duration};
use tokio::{net::UnixStream, sync::mpsc, time::Instant};
use tokio_util::sync::CancellationToken;
pub(super) struct PreparedScriptTun {
pub control: std::os::unix::net::UnixStream,
pub bootstrap: Bootstrap,
}
pub(super) fn builder(
server: &str,
cookie: &str,
request: &ScriptTunRequest,
uid: u32,
) -> anyhow::Result<(VpnBuilder, PreparedScriptTun)> {
request.validate()?;
ensure!(uid != 0, "Script-tun worker requires a desktop user");
let (control, child) = std::os::unix::net::UnixStream::pair()?;
let builder = Vpn::builder(server, cookie).script_tun_program(
request.program.to_str().context("Program is not UTF-8")?,
&request.args,
uid,
child.into(),
)?;
Ok((
builder,
PreparedScriptTun {
control,
bootstrap: request.bootstrap.clone(),
},
))
}
#[derive(Debug)]
pub(super) struct NetworkChanged;
impl std::fmt::Display for NetworkChanged {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("VPN network configuration changed")
}
}
impl std::error::Error for NetworkChanged {}
enum Native {
Event(Event),
Established(openconnect::VpnSessionInfo),
}
pub(super) async fn run(
identity: Identity,
vpn: Arc<Vpn>,
prepared: PreparedScriptTun,
approval: &crate::hip_source::HipApproval,
lifecycle: &LifecycleHandle,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
session_id: uuid::Uuid,
registry: Arc<crate::session_registry::SessionRegistry>,
sessions: &mut gpapi::session::GatewaySessions,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
let (native_tx, native) = mpsc::channel(64);
let observed = native_tx.clone();
let overflow = cancellation.clone();
let monitor = gptunnel::TunnelMonitor::attach_with_observer(vpn.clone(), move |event| {
if !matches!(event, Event::Statistics(_)) && observed.try_send(Native::Event(event.clone())).is_err() {
overflow.cancel();
}
});
let event_result = events
.send(LifecycleEvent::TunnelMonitor {
attempt,
monitor: monitor.clone(),
})
.await;
if event_result.is_err() {
monitor.stop().await;
return Ok(());
}
let worker_vpn = vpn.clone();
std::mem::take(sessions).relinquish();
let worker = tokio::task::spawn_blocking(move || {
worker_vpn.connect(move |session| {
let _ = native_tx.try_send(Native::Established(session));
})
});
tokio::pin!(worker);
let mut worker_done = false;
let stop = cancellation.child_token();
let supervisor = supervise(identity, prepared, native, stop.clone(), events);
tokio::pin!(supervisor);
let mut supervisor_done = false;
let mut approval_poll = tokio::time::interval(Duration::from_millis(250));
let result = loop {
tokio::select! {
biased;
result = &mut supervisor => { supervisor_done = true; break result; }
result = &mut worker => { worker_done = true; break Err(anyhow::anyhow!("VPN worker ended: {:?}", result)); }
_ = approval_poll.tick() => {
if !approval.approval_is_valid() || !registry.has_session(session_id) {
super::runtime::stop_for_revoked_approval(lifecycle, &cancellation);
}
}
}
};
stop.cancel();
if !supervisor_done {
let _ = supervisor.await;
}
vpn.disconnect();
if !worker_done {
let _ = worker.await;
}
monitor.stop().await;
result
}
#[derive(Debug, PartialEq, Eq)]
enum WorkerState {
Preparing,
Ready,
Activating,
Active,
Suspending,
}
// The same control loop runs against native observations in production and a
// generic socket consumer in tests; VPN ownership stays in run().
async fn supervise(
identity: Identity,
mut prepared: PreparedScriptTun,
mut native: mpsc::Receiver<Native>,
cancellation: CancellationToken,
events: mpsc::Sender<LifecycleEvent>,
) -> anyhow::Result<()> {
let attempt = identity.attempt;
prepared.control.set_nonblocking(true)?;
let control = UnixStream::from_std(prepared.control)?;
let (mut input, mut output) = control.into_split();
let (messages_tx, mut messages) = mpsc::channel(8);
let reader = tokio::spawn(async move {
loop {
let message = receive(&mut input).await;
let failed = message.is_err();
if messages_tx.send(message).await.is_err() || failed {
break;
}
}
});
let mut network = None;
let mut session = None;
let mut worker = WorkerState::Preparing;
let mut online = false;
let mut was_connected = false;
let mut deadline: Option<Instant> = None;
let result = async {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = async { if let Some(at) = deadline { tokio::time::sleep_until(at).await } else { std::future::pending().await } } => bail!("Script-tun worker activation timed out"),
message = messages.recv() => match message.context("Script-tun control reader stopped")?? {
Message::Ready if worker == WorkerState::Preparing && network.is_some() => {
worker = WorkerState::Ready;
}
Message::Activated if worker == WorkerState::Activating => {
ensure!(online, "Script-tun activation completed while VPN was offline");
ensure!(!cancellation.is_cancelled(), "Script-tun startup cancelled");
events.send(LifecycleEvent::Established { attempt, session: session.clone().context("Native session is missing")? }).await?;
worker = WorkerState::Active; was_connected = true; deadline = None;
}
Message::Suspended if worker == WorkerState::Suspending => { worker = WorkerState::Ready; deadline = None; }
Message::Error { message } => bail!("Script-tun worker: {message}"),
_ => bail!("Unexpected script-tun consumer message"),
},
event = native.recv() => match event.context("Native event stream ended")? {
Native::Established(value) => { session = Some(value); online = true; deadline.get_or_insert(Instant::now() + Duration::from_secs(10)); }
Native::Event(Event::Configuration(config)) => {
let observed = config.context("VPN configuration is absent").and_then(observed_network);
if was_connected && (observed.is_err() || network.as_ref().is_some_and(|old| observed.as_ref().is_ok_and(|new| old != new))) { return Err(NetworkChanged.into()); }
let observed = observed?;
if let Some(old) = &network { ensure!(old == &observed, "VPN configuration changed during startup"); }
else {
send(&mut output, &Message::Configure { identity, bootstrap: std::mem::take(&mut prepared.bootstrap), network: observed.clone() }).await?;
network = Some(observed);
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnecting) => {
ensure!(worker != WorkerState::Activating, "VPN connection interrupted during script-tun activation; reconnect the VPN");
online = false;
events.send(LifecycleEvent::ScriptTunSuspended { attempt }).await?;
if matches!(worker, WorkerState::Ready | WorkerState::Active) {
send(&mut output, &Message::Suspend).await?; worker = WorkerState::Suspending;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Native::Event(Event::Reconnected) => online = true,
Native::Event(_) => {},
}
}
if online && session.is_some() && worker == WorkerState::Ready && !cancellation.is_cancelled() {
send(&mut output, &Message::Activate).await?; worker = WorkerState::Activating;
deadline = Some(Instant::now() + Duration::from_secs(10));
}
}
Ok(())
}.await;
let _ = tokio::time::timeout(Duration::from_millis(250), send(&mut output, &Message::Stop)).await;
drop(output);
reader.abort();
let _ = reader.await;
result
}
fn observed_network(
config: openconnect::tunnel::Configuration,
) -> anyhow::Result<gpapi::session::tunnel::NegotiatedNetwork> {
ensure!(
!config.truncated && !config.dns.truncated && !config.search_domains.truncated,
"VPN configuration is truncated"
);
Ok(gpapi::session::tunnel::NegotiatedNetwork {
addresses: [config.ipv4, config.ipv6.or(config.netmask6)]
.into_iter()
.flatten()
.map(|a| a.split('/').next().unwrap().parse())
.collect::<Result<_, _>>()?,
dns: config.dns.items.iter().map(|a| a.parse()).collect::<Result<_, _>>()?,
search: config.search_domains.items,
mtu: config.mtu.context("VPN MTU is absent")? as usize,
})
}
async fn send(writer: &mut (impl tokio::io::AsyncWrite + Unpin), message: &Message) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_secs(10), send_message(writer, message))
.await
.context("Script-tun control write timed out")??;
Ok(())
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,293 @@
use super::*;
use openconnect::{VpnSessionInfo, tunnel::Configuration};
use tokio::io::AsyncWriteExt;
// A generic consumer, with no proxy settings or private worker protocol.
struct Consumer {
control: UnixStream,
native: mpsc::Sender<Native>,
events: mpsc::Receiver<LifecycleEvent>,
cancel: CancellationToken,
task: tokio::task::JoinHandle<anyhow::Result<()>>,
identity: Identity,
}
impl Consumer {
fn new() -> Self {
let (control, child) = std::os::unix::net::UnixStream::pair().unwrap();
child.set_nonblocking(true).unwrap();
let (native, observations) = mpsc::channel(64);
let (events, notifications) = mpsc::channel(8);
let identity = Identity {
service_instance: uuid::Uuid::new_v4(),
attempt: 7,
launch_id: uuid::Uuid::new_v4(),
};
let cancel = CancellationToken::new();
let task = tokio::spawn(supervise(
identity,
PreparedScriptTun {
control,
bootstrap: Bootstrap::new(b"consumer bootstrap").unwrap(),
},
observations,
cancel.clone(),
events,
));
Self {
control: UnixStream::from_std(child).unwrap(),
native,
events: notifications,
cancel,
task,
identity,
}
}
async fn message(&mut self) -> Message {
tokio::time::timeout(Duration::from_secs(2), receive(&mut self.control))
.await
.unwrap()
.unwrap()
}
async fn event(&mut self) -> LifecycleEvent {
tokio::time::timeout(Duration::from_secs(2), self.events.recv())
.await
.unwrap()
.unwrap()
}
async fn configure(&mut self) {
self
.native
.send(Native::Event(Event::Configuration(Some(configuration()))))
.await
.unwrap();
let Message::Configure {
identity,
network,
bootstrap,
} = self.message().await
else {
panic!("expected Configure")
};
assert_eq!(identity, self.identity);
assert_eq!(network.addresses, vec!["10.0.0.2".parse::<std::net::IpAddr>().unwrap()]);
assert_eq!(network.mtu, 1400);
assert_eq!(bootstrap.decode().unwrap(), b"consumer bootstrap");
}
async fn activate(&mut self) {
self.configure().await;
self
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut self.control, &Message::Ready).await.unwrap();
assert!(matches!(self.message().await, Message::Activate));
send_message(&mut self.control, &Message::Activated).await.unwrap();
assert!(matches!(
self.event().await,
LifecycleEvent::Established { attempt: 7, .. }
));
}
async fn finish(&mut self) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_secs(2), &mut self.task)
.await
.unwrap()
.unwrap()
}
}
impl Drop for Consumer {
fn drop(&mut self) {
self.cancel.cancel();
self.task.abort();
}
}
fn configuration() -> Configuration {
Configuration {
ipv4: Some("10.0.0.2".into()),
mtu: Some(1400),
..Default::default()
}
}
#[tokio::test]
async fn connected_requires_native_establishment_and_consumer_acknowledgment() {
let mut consumer = Consumer::new();
consumer.configure().await;
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut consumer.control))
.await
.is_err()
);
assert!(consumer.events.try_recv().is_err());
let session = VpnSessionInfo {
lifetime_secs: Some(3600),
..Default::default()
};
consumer
.native
.send(Native::Established(session.clone()))
.await
.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
assert!(consumer.events.try_recv().is_err());
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
let LifecycleEvent::Established {
attempt,
session: reported,
} = consumer.event().await
else {
panic!("expected Established")
};
assert_eq!(attempt, consumer.identity.attempt);
assert_eq!(reported, session);
consumer.cancel.cancel();
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
assert!(receive(&mut consumer.control).await.is_err());
}
#[tokio::test]
async fn unchanged_reconnect_waits_for_suspension_before_reactivation() {
let mut consumer = Consumer::new();
consumer.activate().await;
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::ScriptTunSuspended { attempt: 7 }
));
assert!(matches!(consumer.message().await, Message::Suspend));
consumer
.native
.send(Native::Event(Event::Configuration(Some(configuration()))))
.await
.unwrap();
consumer.native.send(Native::Event(Event::Reconnected)).await.unwrap();
assert!(
tokio::time::timeout(Duration::from_millis(30), receive(&mut consumer.control))
.await
.is_err()
);
send_message(&mut consumer.control, &Message::Suspended).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
assert!(consumer.events.try_recv().is_err());
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::Established { attempt: 7, .. }
));
consumer.cancel.cancel();
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
}
#[tokio::test]
async fn changed_reconnect_stops_consumer_and_returns_network_changed() {
let mut consumer = Consumer::new();
consumer.activate().await;
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(
consumer.event().await,
LifecycleEvent::ScriptTunSuspended { .. }
));
assert!(matches!(consumer.message().await, Message::Suspend));
send_message(&mut consumer.control, &Message::Suspended).await.unwrap();
let mut changed = configuration();
changed.ipv4 = Some("10.0.0.3".into());
consumer
.native
.send(Native::Event(Event::Configuration(Some(changed))))
.await
.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(consumer.finish().await.unwrap_err().is::<NetworkChanged>());
assert!(
!consumer.cancel.is_cancelled(),
"restart must not look like explicit cancellation"
);
assert!(consumer.events.try_recv().is_err());
assert!(receive(&mut consumer.control).await.is_err());
}
#[tokio::test]
async fn cancellation_during_activation_prevents_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
consumer
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
consumer.cancel.cancel();
// A late acknowledgment must not publish Connected after cancellation.
let _ = send_message(&mut consumer.control, &Message::Activated).await;
assert!(matches!(consumer.message().await, Message::Stop));
consumer.finish().await.unwrap();
assert!(consumer.events.try_recv().is_err());
}
#[tokio::test]
async fn consumer_eof_ends_startup_and_active_sessions() {
for active in [false, true] {
let mut consumer = Consumer::new();
if active {
consumer.activate().await;
} else {
consumer.configure().await;
}
consumer.control.shutdown().await.unwrap();
assert!(consumer.finish().await.is_err());
assert!(consumer.events.try_recv().is_err());
}
}
#[tokio::test]
async fn unexpected_acknowledgment_fails_before_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
send_message(&mut consumer.control, &Message::Activated).await.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(consumer.finish().await.unwrap_err().to_string().contains("Unexpected"));
assert!(consumer.events.try_recv().is_err());
}
#[test]
fn prepares_worker_for_current_desktop_user_without_enumerating_groups() {
let uid = unsafe { nix::libc::getuid() };
if uid == 0 {
return;
}
let request = ScriptTunRequest {
launch_id: uuid::Uuid::new_v4(),
program: "/usr/bin/true".into(),
args: vec![],
bootstrap: Bootstrap::default(),
};
builder("https://vpn.example", "test", &request, uid).unwrap();
}
#[tokio::test]
async fn reconnect_during_activation_returns_clear_error_without_connected() {
let mut consumer = Consumer::new();
consumer.configure().await;
consumer
.native
.send(Native::Established(VpnSessionInfo::default()))
.await
.unwrap();
send_message(&mut consumer.control, &Message::Ready).await.unwrap();
assert!(matches!(consumer.message().await, Message::Activate));
consumer.native.send(Native::Event(Event::Reconnecting)).await.unwrap();
assert!(matches!(consumer.message().await, Message::Stop));
assert!(
consumer
.finish()
.await
.unwrap_err()
.to_string()
.contains("during script-tun activation")
);
assert!(consumer.events.try_recv().is_err());
}
+19
View File
@@ -1,5 +1,24 @@
# Changelog # Changelog
## 3.2.0
### Added
- Added Local Proxy mode with configurable SOCKS5 and HTTP listeners, so selected apps can use the VPN without changing system routes or DNS.
- Added a gateway IP preference for trying IPv4 or IPv6 first, available in Settings and through `gpclient connect --ip-preference`.
### Improved
- Enabled switching between the macOS main window and menu bar popover without restarting the app.
- Refined gateway selection, connection status, and proxy listener details.
- Made numeric settings validation clearer before saving.
### Fixed
- Fixed VPN shutdown waiting too long when a gateway stops responding to logout.
- Fixed segmented controls sometimes losing the selected option when clicked.
- Fixed app shortcuts failing to open with some Linux and BSD desktop launchers.
## 3.1.0 ## 3.1.0
### Added ### Added
+10
View File
@@ -57,6 +57,16 @@ pub enum GatewaySelection {
Manual, Manual,
} }
#[derive(Debug, Default, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "camelCase")]
pub enum GatewayIpPreference {
#[default]
Auto,
Ipv4,
Ipv6,
}
impl GatewaySelection { impl GatewaySelection {
pub fn as_login_param(self) -> &'static str { pub fn as_login_param(self) -> &'static str {
match self { match self {
+2
View File
@@ -20,3 +20,5 @@ pub mod logger;
#[cfg(feature = "clap")] #[cfg(feature = "clap")]
pub mod clap; pub mod clap;
pub mod script_tun;
+139
View File
@@ -0,0 +1,139 @@
use crate::session::tunnel::NegotiatedNetwork;
use serde::{Deserialize, Serialize};
use std::{io, path::PathBuf};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use uuid::Uuid;
const MAX_MESSAGE: usize = 60 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
pub struct Identity {
pub service_instance: Uuid,
#[serde(with = "crate::session::tunnel::decimal")]
#[specta(type = String)]
pub attempt: u64,
pub launch_id: Uuid,
}
#[derive(Clone, Default, Serialize, Deserialize, specta::Type)]
#[serde(transparent)]
pub struct Bootstrap(String);
impl std::fmt::Debug for Bootstrap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[redacted bootstrap]")
}
}
impl Bootstrap {
pub fn new(bytes: &[u8]) -> anyhow::Result<Self> {
anyhow::ensure!(bytes.len() <= 16 * 1024, "Script-tun bootstrap too large");
use base64::Engine;
Ok(Self(base64::engine::general_purpose::STANDARD.encode(bytes)))
}
pub fn decode(&self) -> anyhow::Result<Vec<u8>> {
anyhow::ensure!(self.0.len() <= 21848, "Script-tun bootstrap too large");
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(&self.0)?;
anyhow::ensure!(bytes.len() <= 16 * 1024, "Script-tun bootstrap too large");
Ok(bytes)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, specta::Type)]
pub struct ScriptTunRequest {
pub launch_id: Uuid,
pub program: PathBuf,
pub args: Vec<String>,
pub bootstrap: Bootstrap,
}
impl ScriptTunRequest {
pub fn validate(&self) -> anyhow::Result<()> {
let program = self
.program
.to_str()
.ok_or_else(|| anyhow::anyhow!("Executable path must be UTF-8"))?;
anyhow::ensure!(
self.program.is_absolute() && !program.contains('\0'),
"Script-tun requires an absolute executable path"
);
anyhow::ensure!(
self.args.len() <= 64
&& self.args.iter().all(|a| !a.contains('\0'))
&& program.len() + self.args.iter().map(String::len).sum::<usize>() <= 16 * 1024,
"Invalid script-tun arguments"
);
self.bootstrap.decode()?;
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, specta::Type)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum PacketDelivery {
#[default]
System,
ScriptTun(ScriptTunRequest),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum PacketDeliveryKind {
#[default]
System,
ScriptTun,
}
impl PacketDelivery {
pub fn kind(&self) -> PacketDeliveryKind {
match self {
Self::System => PacketDeliveryKind::System,
Self::ScriptTun(_) => PacketDeliveryKind::ScriptTun,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum Message {
Configure {
identity: Identity,
network: NegotiatedNetwork,
bootstrap: Bootstrap,
},
Ready,
Activate,
Activated,
Suspend,
Suspended,
Stop,
Error {
message: String,
},
}
pub async fn send(stream: &mut (impl AsyncWrite + Unpin), message: &Message) -> io::Result<()> {
let bytes = serde_json::to_vec(message)?;
if bytes.len() > MAX_MESSAGE {
return Err(io::Error::other("Script-tun control message too large"));
}
stream.write_u32(bytes.len() as u32).await?;
stream.write_all(&bytes).await
}
pub async fn receive(stream: &mut (impl AsyncRead + Unpin)) -> io::Result<Message> {
let length = stream.read_u32().await? as usize;
if length > MAX_MESSAGE {
return Err(io::Error::other("Script-tun control message too large"));
}
let mut bytes = vec![0; length];
stream.read_exact(&mut bytes).await?;
serde_json::from_slice(&bytes).map_err(io::Error::from)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn rejects_oversized_unknown_and_truncated_frames() {
let oversized = (MAX_MESSAGE as u32 + 1).to_be_bytes();
assert!(receive(&mut oversized.as_slice()).await.is_err());
for payload in [br#"{"type":"UnknownCommand"}"#.as_slice(), b"not JSON"] {
let mut frame = (payload.len() as u32).to_be_bytes().to_vec();
frame.extend_from_slice(payload);
assert!(receive(&mut frame.as_slice()).await.is_err());
}
let truncated = [0, 0, 0, 10, b'{'];
assert!(receive(&mut truncated.as_slice()).await.is_err());
}
}
+67
View File
@@ -58,6 +58,8 @@ impl LaunchGuiRequest {
#[derive(Deserialize, Serialize, Type, Clone)] #[derive(Deserialize, Serialize, Type, Clone)]
pub struct ConnectArgs { pub struct ConnectArgs {
#[serde(default)]
packet_delivery: crate::script_tun::PacketDelivery,
vpnc_script: Option<String>, vpnc_script: Option<String>,
host_identity: Option<HostIdentity>, host_identity: Option<HostIdentity>,
ignore_tls_errors: bool, ignore_tls_errors: bool,
@@ -79,6 +81,8 @@ pub struct ConnectArgs {
reconnect_timeout: u32, reconnect_timeout: u32,
mtu: u32, mtu: u32,
disable_ipv6: bool, disable_ipv6: bool,
#[serde(default)]
gateway_ip_preference: crate::gateway::GatewayIpPreference,
no_dtls: bool, no_dtls: bool,
local_hostname: Option<String>, local_hostname: Option<String>,
force_dpd: u32, force_dpd: u32,
@@ -88,8 +92,13 @@ pub struct ConnectArgs {
} }
impl ConnectArgs { impl ConnectArgs {
pub fn packet_delivery(&self) -> &crate::script_tun::PacketDelivery {
&self.packet_delivery
}
fn new() -> Self { fn new() -> Self {
Self { Self {
packet_delivery: Default::default(),
vpnc_script: None, vpnc_script: None,
host_identity: None, host_identity: None,
ignore_tls_errors: false, ignore_tls_errors: false,
@@ -107,6 +116,7 @@ impl ConnectArgs {
reconnect_timeout: 300, reconnect_timeout: 300,
mtu: 0, mtu: 0,
disable_ipv6: false, disable_ipv6: false,
gateway_ip_preference: Default::default(),
no_dtls: false, no_dtls: false,
local_hostname: None, local_hostname: None,
force_dpd: 0, force_dpd: 0,
@@ -195,6 +205,10 @@ impl ConnectArgs {
self.disable_ipv6 self.disable_ipv6
} }
pub fn gateway_ip_preference(&self) -> crate::gateway::GatewayIpPreference {
self.gateway_ip_preference
}
pub fn no_dtls(&self) -> bool { pub fn no_dtls(&self) -> bool {
self.no_dtls self.no_dtls
} }
@@ -232,6 +246,7 @@ impl fmt::Debug for ConnectArgs {
.field("reconnect_timeout", &self.reconnect_timeout) .field("reconnect_timeout", &self.reconnect_timeout)
.field("mtu", &self.mtu) .field("mtu", &self.mtu)
.field("disable_ipv6", &self.disable_ipv6) .field("disable_ipv6", &self.disable_ipv6)
.field("gateway_ip_preference", &self.gateway_ip_preference)
.field("no_dtls", &self.no_dtls) .field("no_dtls", &self.no_dtls)
.field("allow_extend_session", &self.allow_extend_session) .field("allow_extend_session", &self.allow_extend_session)
.finish_non_exhaustive() .finish_non_exhaustive()
@@ -248,17 +263,40 @@ impl Drop for ConnectArgs {
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectRequest { pub struct ConnectRequest {
#[serde(default)]
restart_of: Option<u64>,
info: ConnectInfo, info: ConnectInfo,
plan: ConnectionPlan, plan: ConnectionPlan,
args: ConnectArgs, args: ConnectArgs,
} }
impl ConnectRequest { impl ConnectRequest {
pub fn with_restart_of(mut self, attempt: Option<u64>) -> Self {
self.restart_of = attempt;
self
}
pub fn restart_of(&self) -> Option<u64> {
self.restart_of
}
/// Release the one-shot payload once tunnel setup has taken ownership of it.
pub fn release_script_tun_bootstrap(&mut self) {
if let crate::script_tun::PacketDelivery::ScriptTun(request) = &mut self.args.packet_delivery {
request.bootstrap = Default::default();
}
}
pub fn with_packet_delivery(mut self, mode: crate::script_tun::PacketDelivery) -> Self {
self.info.set_packet_delivery(mode.kind());
self.args.packet_delivery = mode;
self
}
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self { pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
Self { Self {
info, info,
plan, plan,
args: ConnectArgs::new(), args: ConnectArgs::new(),
restart_of: None,
} }
} }
@@ -327,6 +365,11 @@ impl ConnectRequest {
self self
} }
pub fn with_gateway_ip_preference(mut self, preference: crate::gateway::GatewayIpPreference) -> Self {
self.args.gateway_ip_preference = preference;
self
}
pub fn with_no_dtls(mut self, no_dtls: bool) -> Self { pub fn with_no_dtls(mut self, no_dtls: bool) -> Self {
self.args.no_dtls = no_dtls; self.args.no_dtls = no_dtls;
self self
@@ -458,6 +501,30 @@ mod tests {
assert_eq!(value["args"]["allowExtendSession"], json!(true)); assert_eq!(value["args"]["allowExtendSession"], json!(true));
} }
#[test]
fn gateway_preference_round_trips_and_defaults_for_existing_requests() {
use crate::gateway::GatewayIpPreference;
for preference in [
GatewayIpPreference::Auto,
GatewayIpPreference::Ipv4,
GatewayIpPreference::Ipv6,
] {
let request = test_request(test_connect_info())
.with_disable_ipv6(true)
.with_gateway_ip_preference(preference);
let value = serde_json::to_value(&request).unwrap();
let decoded: ConnectRequest = serde_json::from_value(value).unwrap();
assert_eq!(decoded.args().gateway_ip_preference(), preference);
assert!(decoded.args().disable_ipv6());
}
let request = test_request(test_connect_info()).with_disable_ipv6(true);
let mut value = serde_json::to_value(request).unwrap();
value["args"].as_object_mut().unwrap().remove("gateway_ip_preference");
let decoded: ConnectRequest = serde_json::from_value(value).unwrap();
assert_eq!(decoded.args().gateway_ip_preference(), GatewayIpPreference::Auto);
assert!(decoded.args().disable_ipv6());
}
#[test] #[test]
fn with_os_profile_sets_user_agent_from_profile() { fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build(); let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
+32
View File
@@ -10,6 +10,10 @@ use crate::{
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo { pub struct ConnectInfo {
#[serde(default)]
packet_delivery: crate::script_tun::PacketDeliveryKind,
#[serde(default)]
script_tun_identity: Option<crate::script_tun::Identity>,
portal: String, portal: String,
gateway: Gateway, gateway: Gateway,
gateways: Vec<Gateway>, gateways: Vec<Gateway>,
@@ -71,14 +75,33 @@ fn unix_timestamp() -> u32 {
} }
impl ConnectInfo { impl ConnectInfo {
pub fn script_tun_identity(&self) -> Option<crate::script_tun::Identity> {
self.script_tun_identity
}
pub fn set_script_tun_identity(&mut self, identity: crate::script_tun::Identity) {
self.script_tun_identity = Some(identity);
}
pub fn packet_delivery(&self) -> &crate::script_tun::PacketDeliveryKind {
&self.packet_delivery
}
pub fn set_packet_delivery(&mut self, mode: crate::script_tun::PacketDeliveryKind) {
self.packet_delivery = mode;
self.script_tun_identity = None;
}
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self { pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self { Self {
packet_delivery: Default::default(),
script_tun_identity: None,
portal, portal,
gateway, gateway,
gateways, gateways,
} }
} }
pub fn portal(&self) -> &str {
&self.portal
}
pub fn gateway(&self) -> &Gateway { pub fn gateway(&self) -> &Gateway {
&self.gateway &self.gateway
} }
@@ -87,6 +110,7 @@ impl ConnectInfo {
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum VpnState { pub enum VpnState {
ReconnectRequired(Box<ReconnectRequest>),
Disconnected, Disconnected,
Failed(String), Failed(String),
Connecting(Box<ConnectInfo>), Connecting(Box<ConnectInfo>),
@@ -119,3 +143,11 @@ mod tests {
assert!(value["connected"]["connectedAt"].as_u64().is_some()); assert!(value["connected"]["connectedAt"].as_u64().is_some());
} }
} }
#[derive(Debug, Serialize, Deserialize, Clone, Type)]
#[serde(rename_all = "camelCase")]
pub struct ReconnectRequest {
pub attempt: u64,
pub owner: uuid::Uuid,
pub info: ConnectInfo,
}
+9 -1
View File
@@ -276,7 +276,7 @@ impl TunnelStatisticsSnapshot {
} }
} }
mod decimal { pub(crate) mod decimal {
use serde::{Deserialize, Deserializer, Serializer}; use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> { pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
@@ -351,3 +351,11 @@ mod tests {
); );
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NegotiatedNetwork {
pub addresses: Vec<std::net::IpAddr>,
pub dns: Vec<std::net::IpAddr>,
pub search: Vec<String>,
pub mtu: usize,
}
+7
View File
@@ -293,6 +293,12 @@ pub struct TunnelMonitor {
impl TunnelMonitor { impl TunnelMonitor {
pub fn attach(vpn: Arc<Vpn>) -> Arc<Self> { pub fn attach(vpn: Arc<Vpn>) -> Arc<Self> {
Self::attach_with_observer(vpn, |_| {})
}
/// Observe every native transition as well as the coalesced telemetry stream.
/// The callback runs on the native worker and must not block.
pub fn attach_with_observer(vpn: Arc<Vpn>, on_event: impl Fn(&Event) + Send + Sync + 'static) -> Arc<Self> {
let observation = Observation::new(); let observation = Observation::new();
let (updates, _) = watch::channel(observation.project(Instant::now())); let (updates, _) = watch::channel(observation.project(Instant::now()));
let monitor = Arc::new(Self { let monitor = Arc::new(Self {
@@ -304,6 +310,7 @@ impl TunnelMonitor {
}); });
let observer = Arc::downgrade(&monitor); let observer = Arc::downgrade(&monitor);
monitor.vpn.set_tunnel_observer(move |event| { monitor.vpn.set_tunnel_observer(move |event| {
on_event(&event);
if let Some(monitor) = observer.upgrade() { if let Some(monitor) = observer.upgrade() {
monitor.observe(event); monitor.observe(event);
} }
+127
View File
@@ -0,0 +1,127 @@
use std::{
ffi::{c_char, c_int},
ptr,
};
/// Resolve with the system's normal policy, then prefer one family without
/// discarding alternatives. The returned list remains owned by libc and is
/// released by OpenConnect with freeaddrinfo.
///
/// # Safety
/// Arguments must satisfy getaddrinfo's pointer and lifetime requirements.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn vpn_resolve_gateway(
node: *const c_char,
service: *const c_char,
hints: *const libc::addrinfo,
result: *mut *mut libc::addrinfo,
preference: u32,
) -> c_int {
// SAFETY: The OpenConnect callback forwards valid getaddrinfo arguments.
let status = unsafe { libc::getaddrinfo(node, service, hints, result) };
if status != 0 {
return status;
}
let family = match preference {
4 => libc::AF_INET,
6 => libc::AF_INET6,
_ => return 0,
};
// SAFETY: A successful getaddrinfo call returns an owned, writable list.
unsafe { *result = prefer_family(*result, family) };
0
}
/// # Safety
/// `head` must be an exclusively owned, writable addrinfo list with no cycles.
unsafe fn prefer_family(head: *mut libc::addrinfo, family: c_int) -> *mut libc::addrinfo {
let mut addresses = Vec::new();
let mut current = head;
// SAFETY: The caller owns every node; sorting only changes the list links.
unsafe {
while !current.is_null() {
addresses.push(current);
current = (*current).ai_next;
}
addresses.sort_by_key(|address| (**address).ai_family != family);
for (index, address) in addresses.iter().enumerate() {
(**address).ai_next = addresses.get(index + 1).copied().unwrap_or(ptr::null_mut());
}
}
addresses.first().copied().unwrap_or(ptr::null_mut())
}
#[cfg(test)]
mod tests {
use super::*;
fn ordered_indices(families: &[c_int], preferred: c_int) -> Vec<usize> {
let mut addresses: Vec<libc::addrinfo> = families
.iter()
.enumerate()
.map(|(index, family)| {
// SAFETY: All-zero addrinfo has null pointers; these fixtures own no OS data.
let mut address: libc::addrinfo = unsafe { std::mem::zeroed() };
address.ai_family = *family;
address.ai_flags = index as c_int;
address
})
.collect();
for index in 1..addresses.len() {
addresses[index - 1].ai_next = &mut addresses[index];
}
let head = if addresses.is_empty() {
ptr::null_mut()
} else {
addresses.as_mut_ptr()
};
// SAFETY: The fixture owns stable nodes throughout sorting and traversal.
unsafe {
let mut current = prefer_family(head, preferred);
let mut indices = Vec::new();
while !current.is_null() {
assert!(indices.len() < addresses.len(), "address list contains a cycle");
indices.push((*current).ai_flags as usize);
current = (*current).ai_next;
}
indices
}
}
#[test]
fn preferences_retain_all_addresses_and_order_within_each_family() {
let mixed = [libc::AF_INET6, libc::AF_INET, libc::AF_INET6, libc::AF_INET];
assert_eq!(ordered_indices(&mixed, libc::AF_INET), [1, 3, 0, 2]);
assert_eq!(ordered_indices(&mixed, libc::AF_INET6), [0, 2, 1, 3]);
assert_eq!(
ordered_indices(&[libc::AF_INET6, libc::AF_INET6], libc::AF_INET),
[0, 1]
);
assert_eq!(ordered_indices(&[libc::AF_INET, libc::AF_INET], libc::AF_INET6), [0, 1]);
assert!(ordered_indices(&[], libc::AF_INET).is_empty());
}
#[test]
fn native_lookup_preserves_errors_and_returns_freeable_results() {
let mut hints: libc::addrinfo = unsafe { std::mem::zeroed() };
hints.ai_socktype = libc::SOCK_STREAM;
hints.ai_flags = libc::AI_NUMERICHOST;
for preference in [0, 4, 6] {
let mut result = ptr::null_mut();
// SAFETY: Static NUL-terminated inputs, initialized hints and a writable output.
unsafe {
assert_ne!(
vpn_resolve_gateway(c"invalid".as_ptr(), c"443".as_ptr(), &hints, &mut result, preference),
0
);
assert_eq!(
vpn_resolve_gateway(c"::1".as_ptr(), c"443".as_ptr(), &hints, &mut result, preference),
0
);
assert!(!result.is_null());
assert_eq!((*result).ai_family, libc::AF_INET6);
libc::freeaddrinfo(result);
}
}
}
}
+13
View File
@@ -1,3 +1,4 @@
mod gateway;
mod hip; mod hip;
mod network_configuration; mod network_configuration;
mod tunnel; mod tunnel;
@@ -11,6 +12,16 @@ pub(crate) use network_configuration::{VpnOptionRaw, configure_network};
use std::ffi::{c_char, c_int, c_long, c_void}; use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind}; use std::panic::{AssertUnwindSafe, catch_unwind};
/// Borrowed launch data; layout must match openconnect_script_tun_launch in openconnect.h.
#[repr(C)]
#[derive(Debug)]
pub(crate) struct ScriptTunLaunchRaw {
pub program: *const c_char,
pub argv: *const *const c_char,
pub uid: u32,
pub control_fd: c_int,
}
/// ConnectOptions struct for FFI, the field names and order must match the C definition. /// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)] #[repr(C)]
#[derive(Debug)] #[derive(Debug)]
@@ -32,6 +43,7 @@ pub(crate) struct ConnectOptions {
pub configure_network: Option<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> c_int>, pub configure_network: Option<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> c_int>,
pub interface: *const c_char, pub interface: *const c_char,
pub script_tun: u32, pub script_tun: u32,
pub script_tun_launch: *const ScriptTunLaunchRaw,
pub certificate: *const c_char, pub certificate: *const c_char,
pub sslkey: *const c_char, pub sslkey: *const c_char,
@@ -44,6 +56,7 @@ pub(crate) struct ConnectOptions {
pub reconnect_timeout: u32, pub reconnect_timeout: u32,
pub mtu: u32, pub mtu: u32,
pub disable_ipv6: u32, pub disable_ipv6: u32,
pub gateway_ip_preference: u32,
pub no_dtls: u32, pub no_dtls: u32,
pub dpd_interval: u32, pub dpd_interval: u32,
+25 -3
View File
@@ -15,13 +15,21 @@ struct vpn_context {
vpn_connected_callback on_connected; vpn_connected_callback on_connected;
}; };
static int resolve_gateway(void *private_data, const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **result)
{
struct vpn_context *context = private_data;
return vpn_resolve_gateway(node, service, hints, result,
context->options->gateway_ip_preference);
}
static void observe_configuration(struct vpn_context *context) static void observe_configuration(struct vpn_context *context)
{ {
const struct oc_ip_info *info = NULL; const struct oc_ip_info *info = NULL;
if (openconnect_get_ip_info(context->vpninfo, &info, NULL, NULL)) if (openconnect_get_ip_info(context->vpninfo, &info, NULL, NULL))
info = NULL; info = NULL;
vpn_tunnel_configuration(context->options->user_data, vpn_tunnel_configuration(context->options->user_data,
openconnect_get_ifname(context->vpninfo), info); context->options->script_tun ? NULL : openconnect_get_ifname(context->vpninfo), info);
} }
static void observe_reconnected(void *private_data) static void observe_reconnected(void *private_data)
@@ -75,7 +83,13 @@ static void setup_tun_handler(void *private_data)
const vpn_options *options = context->options; const vpn_options *options = context->options;
int ret; int ret;
if (options->script_tun) { if (options->script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, options->script); const struct openconnect_script_tun_launch *launch = options->script_tun_launch;
if (launch) {
ret = openconnect_setup_tun_script_exec(_vpninfo, launch);
vpn_script_started(options->user_data);
} else {
ret = openconnect_setup_tun_script(_vpninfo, options->script);
}
} else { } else {
ret = openconnect_setup_tun_device(_vpninfo, options->script, ret = openconnect_setup_tun_device(_vpninfo, options->script,
options->interface); options->interface);
@@ -114,13 +128,19 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("OS: %s", options->os); INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version); INFO("CLIENT_VERSION: %s", options->client_version);
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)"); INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
INFO("Network configuration: %s", options->configure_network ? "callback" : options->script); const char *configuration = options->script;
if (options->configure_network)
configuration = "callback";
else if (options->script_tun_launch)
configuration = options->script_tun_launch->program;
INFO("Network configuration: %s", configuration);
INFO("SCRIPT_TUN: %d", options->script_tun); INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->hip_script.uid); INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path); INFO("CSD_WRAPPER: %s", options->hip_script.path);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout); INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
INFO("MTU: %d", options->mtu); INFO("MTU: %d", options->mtu);
INFO("DISABLE_IPV6: %d", options->disable_ipv6); INFO("DISABLE_IPV6: %d", options->disable_ipv6);
INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference);
INFO("NO_DTLS: %d", options->no_dtls); INFO("NO_DTLS: %d", options->no_dtls);
INFO("DPD_INTERVAL: %d", options->dpd_interval); INFO("DPD_INTERVAL: %d", options->dpd_interval);
INFO("NO_XMLPOST: %d", options->no_xmlpost); INFO("NO_XMLPOST: %d", options->no_xmlpost);
@@ -157,6 +177,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_init_ssl(); openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp"); openconnect_set_protocol(vpninfo, "gp");
openconnect_parse_url(vpninfo, options->server); openconnect_parse_url(vpninfo, options->server);
if (options->gateway_ip_preference)
openconnect_override_getaddrinfo(vpninfo, resolve_gateway);
openconnect_set_cookie(vpninfo, options->cookie); openconnect_set_cookie(vpninfo, options->cookie);
openconnect_set_useragent(vpninfo, options->user_agent); openconnect_set_useragent(vpninfo, options->user_agent);
+5
View File
@@ -47,6 +47,7 @@ typedef struct vpn_options {
openconnect_configure_tun_fn configure_network; openconnect_configure_tun_fn configure_network;
const char *interface; const char *interface;
const int script_tun; const int script_tun;
const struct openconnect_script_tun_launch *script_tun_launch;
const char *certificate; const char *certificate;
const char *sslkey; const char *sslkey;
@@ -59,6 +60,7 @@ typedef struct vpn_options {
const int reconnect_timeout; const int reconnect_timeout;
const int mtu; const int mtu;
const int disable_ipv6; const int disable_ipv6;
const int gateway_ip_preference;
const int no_dtls; const int no_dtls;
const int dpd_interval; const int dpd_interval;
@@ -66,11 +68,14 @@ typedef struct vpn_options {
} vpn_options; } vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback); int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
extern int vpn_resolve_gateway(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **result, unsigned int preference);
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *, int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *); const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
extern int vpn_attach_command_pipe(void *user_data, int fd); extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data); extern void vpn_detach_command_pipe(void *user_data);
extern void vpn_script_started(void *user_data);
enum vpn_tunnel_event { enum vpn_tunnel_event {
VPN_TUNNEL_ESTABLISHED = 5, VPN_TUNNEL_ESTABLISHED = 5,
VPN_TUNNEL_RECONNECTED, VPN_TUNNEL_RECONNECTED,
+3
View File
@@ -9,3 +9,6 @@ pub use hip::*;
pub use network_configuration::*; pub use network_configuration::*;
pub use vpn::*; pub use vpn::*;
pub use vpn_utils::*; pub use vpn_utils::*;
#[cfg(all(test, unix))]
mod script_child_tests;
@@ -0,0 +1,140 @@
use std::{
ffi::{CString, c_char, c_int, c_void},
process::Command,
time::{Duration, Instant},
};
unsafe extern "C" {
fn openconnect_vpninfo_new(
agent: *const c_char,
validate: Option<unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int>,
config: Option<unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int>,
auth: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
progress: Option<unsafe extern "C" fn(*mut c_void, c_int, *const c_char, ...)>,
data: *mut c_void,
) -> *mut c_void;
fn openconnect_setup_tun_script(info: *mut c_void, script: *const c_char) -> c_int;
fn openconnect_vpninfo_free(info: *mut c_void);
fn openconnect_set_loglevel(info: *mut c_void, level: c_int);
}
#[test]
fn script_children_are_reaped_including_term_resistant_children_without_reaping_others() {
for resistant in [false, true] {
let directory = tempfile::tempdir().unwrap();
let pid_file = directory.path().join("pid");
let behavior = if resistant {
"trap '' TERM; echo $$ >"
} else {
"echo $$ >"
};
let suffix = if resistant {
"; while :; do sleep 1; done"
} else {
"; exit 0"
};
let command = CString::new(format!("{behavior} '{}' {suffix}", pid_file.display())).unwrap();
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
// This raw fixture has no progress callback; suppress native logging.
unsafe { openconnect_set_loglevel(info, -1) };
assert_eq!(unsafe { openconnect_setup_tun_script(info, command.as_ptr()) }, 0);
let started = Instant::now();
let pid: i32 = loop {
if let Ok(text) = std::fs::read_to_string(&pid_file) {
if let Ok(pid) = text.trim().parse() {
break pid;
}
}
assert!(started.elapsed() < Duration::from_secs(3));
std::thread::sleep(Duration::from_millis(5));
};
let mut unrelated = Command::new("/bin/sh").args(["-c", "exit 17"]).spawn().unwrap();
let stop = Instant::now();
unsafe { openconnect_vpninfo_free(info) };
assert!(stop.elapsed() < Duration::from_secs(4));
assert_eq!(unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) }, -1);
assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ECHILD));
assert_eq!(unrelated.wait().unwrap().code(), Some(17));
}
}
unsafe extern "C" {
fn openconnect_setup_tun_script_exec(info: *mut c_void, launch: *const crate::ffi::ScriptTunLaunchRaw) -> c_int;
}
// Invoked by the native launcher in a fresh process, after credentials and FDs change.
#[test]
fn identity_probe() {
use std::{io::Write, os::fd::FromRawFd};
let Ok(fd) = std::env::var("IDENTITY_PROBE_FD") else {
return;
};
assert_eq!(std::env::var("OPENCONNECT_SCRIPT_TUN_CONTROL_FD").unwrap(), fd);
assert_ne!(unsafe { libc::getuid() }, 0);
assert_eq!(unsafe { libc::getuid() }, unsafe { libc::geteuid() });
assert_eq!(unsafe { libc::getgid() }, unsafe { libc::getegid() });
assert_eq!(unsafe { libc::setuid(0) }, -1);
assert_eq!(unsafe { libc::fcntl(500, libc::F_GETFD) }, -1);
let mut groups = vec![0; unsafe { libc::getgroups(0, std::ptr::null_mut()) } as usize];
assert_eq!(
unsafe { libc::getgroups(groups.len() as i32, groups.as_mut_ptr()) },
groups.len() as i32
);
groups.sort();
let expected = std::env::var("IDENTITY_PROBE_GROUPS").unwrap();
assert_eq!(
groups.iter().map(ToString::to_string).collect::<Vec<_>>().join(","),
expected
);
let mut control = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd.parse().unwrap()) };
control.write_all(b"identity verified").unwrap();
}
#[test]
fn identity_launcher_drops_credentials_and_excludes_unrelated_descriptors() {
use std::{io::Read, os::fd::AsRawFd};
let uid = std::env::var("GP_TEST_UID")
.ok()
.map(|s| s.parse().unwrap())
.unwrap_or_else(|| unsafe { libc::getuid() });
assert_ne!(uid, 0, "root runs must set GP_TEST_UID");
let user = unsafe { libc::getpwuid(uid) };
assert!(!user.is_null());
let gid = unsafe { (*user).pw_gid };
let mut groups = if unsafe { libc::geteuid() } == 0 {
vec![gid]
} else {
let n = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
assert!(n >= 0);
let mut groups = vec![0; n as usize];
assert_eq!(unsafe { libc::getgroups(n, groups.as_mut_ptr()) }, n);
groups
};
groups.sort();
let groups: Vec<u32> = groups.into_iter().map(|g| g as u32).collect();
let (mut parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
parent.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let unrelated = std::fs::File::open("/dev/null").unwrap();
assert_eq!(unsafe { libc::dup2(unrelated.as_raw_fd(), 500) }, 500);
let executable = std::env::current_exe().unwrap();
let command = CString::new(format!("DYLD_FALLBACK_LIBRARY_PATH='{}' IDENTITY_PROBE_FD={} IDENTITY_PROBE_GROUPS='{}' exec '{}' --exact script_child_tests::identity_probe --nocapture", std::env::var("DYLD_FALLBACK_LIBRARY_PATH").unwrap_or_default(), child.as_raw_fd(), groups.iter().map(ToString::to_string).collect::<Vec<_>>().join(","), executable.display())).unwrap();
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
unsafe { openconnect_set_loglevel(info, -1) };
let argv = [c"/bin/sh".as_ptr(), c"-c".as_ptr(), command.as_ptr(), std::ptr::null()];
let launch = crate::ffi::ScriptTunLaunchRaw {
program: c"/bin/sh".as_ptr(),
argv: argv.as_ptr(),
uid,
control_fd: child.as_raw_fd(),
};
let result = unsafe { openconnect_setup_tun_script_exec(info, &launch) };
unsafe { libc::close(500) };
assert_eq!(result, 0);
drop(child);
let mut response = [0; 17];
parent.read_exact(&mut response).unwrap();
assert_eq!(&response, b"identity verified");
unsafe { openconnect_vpninfo_free(info) };
}
+112
View File
@@ -1,6 +1,7 @@
use std::{ use std::{
ffi::{CStr, CString, c_char}, ffi::{CStr, CString, c_char},
fmt, io, fmt, io,
os::fd::{AsRawFd, OwnedFd},
sync::{Arc, Mutex, RwLock}, sync::{Arc, Mutex, RwLock},
}; };
@@ -124,6 +125,15 @@ impl Cancellation {
} }
} }
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum GatewayIpPreference {
#[default]
Auto = 0,
Ipv4 = 4,
Ipv6 = 6,
}
pub struct Vpn { pub struct Vpn {
cancellation: Cancellation, cancellation: Cancellation,
server: CString, server: CString,
@@ -140,6 +150,7 @@ pub struct Vpn {
pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>, pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
interface: Option<CString>, interface: Option<CString>,
script_tun: bool, script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
certificate: Option<CString>, certificate: Option<CString>,
sslkey: Option<CString>, sslkey: Option<CString>,
@@ -151,6 +162,7 @@ pub struct Vpn {
reconnect_timeout: u32, reconnect_timeout: u32,
mtu: u32, mtu: u32,
disable_ipv6: bool, disable_ipv6: bool,
gateway_ip_preference: GatewayIpPreference,
no_dtls: bool, no_dtls: bool,
dpd_interval: u32, dpd_interval: u32,
@@ -220,6 +232,20 @@ impl Vpn {
} }
self.callback.write().unwrap().replace(Box::new(on_connected)); self.callback.write().unwrap().replace(Box::new(on_connected));
let mut options = self.build_connect_options(); let mut options = self.build_connect_options();
let mut argv = Vec::new();
let launch = self.script_tun_launch.as_ref().map(|launch| {
argv.push(launch.program.as_ptr());
argv.extend(launch.arguments.iter().map(|s| s.as_ptr()));
argv.push(std::ptr::null());
ffi::ScriptTunLaunchRaw {
program: launch.program.as_ptr(),
argv: argv.as_ptr(),
uid: launch.uid,
control_fd: launch.control.lock().unwrap().as_ref().map_or(-1, AsRawFd::as_raw_fd),
}
});
// Both the borrowed launch record and argv remain alive through native connect.
options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch);
let environment = match self.hip_source.as_ref() { let environment = match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::script_environment(script), HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(), _ => Vec::new(),
@@ -287,6 +313,7 @@ impl Vpn {
.map(|_| ffi::configure_network as _), .map(|_| ffi::configure_network as _),
interface: Self::option_to_ptr(&self.interface), interface: Self::option_to_ptr(&self.interface),
script_tun: self.script_tun as u32, script_tun: self.script_tun as u32,
script_tun_launch: std::ptr::null(),
certificate: Self::option_to_ptr(&self.certificate), certificate: Self::option_to_ptr(&self.certificate),
sslkey: Self::option_to_ptr(&self.sslkey), sslkey: Self::option_to_ptr(&self.sslkey),
@@ -305,6 +332,7 @@ impl Vpn {
reconnect_timeout: self.reconnect_timeout, reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu, mtu: self.mtu,
disable_ipv6: self.disable_ipv6 as u32, disable_ipv6: self.disable_ipv6 as u32,
gateway_ip_preference: self.gateway_ip_preference as u32,
no_dtls: self.no_dtls as u32, no_dtls: self.no_dtls as u32,
dpd_interval: self.dpd_interval, dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost as u32, no_xmlpost: self.no_xmlpost as u32,
@@ -338,6 +366,13 @@ impl fmt::Display for VpnError {
impl std::error::Error for VpnError {} impl std::error::Error for VpnError {}
struct ScriptTunLaunch {
program: CString,
arguments: Vec<CString>,
uid: u32,
control: Mutex<Option<OwnedFd>>,
}
pub struct VpnBuilder { pub struct VpnBuilder {
server: String, server: String,
cookie: String, cookie: String,
@@ -346,6 +381,7 @@ pub struct VpnBuilder {
script_is_path: bool, script_is_path: bool,
interface: Option<String>, interface: Option<String>,
script_tun: bool, script_tun: bool,
script_tun_launch: Option<ScriptTunLaunch>,
user_agent: Option<String>, user_agent: Option<String>,
os: Option<String>, os: Option<String>,
@@ -363,6 +399,7 @@ pub struct VpnBuilder {
reconnect_timeout: u32, reconnect_timeout: u32,
mtu: u32, mtu: u32,
disable_ipv6: bool, disable_ipv6: bool,
gateway_ip_preference: GatewayIpPreference,
no_dtls: bool, no_dtls: bool,
dpd_interval: u32, dpd_interval: u32,
@@ -379,6 +416,7 @@ impl VpnBuilder {
script_is_path: false, script_is_path: false,
interface: None, interface: None,
script_tun: false, script_tun: false,
script_tun_launch: None,
user_agent: None, user_agent: None,
os: None, os: None,
@@ -396,6 +434,7 @@ impl VpnBuilder {
reconnect_timeout: 300, reconnect_timeout: 300,
mtu: 0, mtu: 0,
disable_ipv6: false, disable_ipv6: false,
gateway_ip_preference: GatewayIpPreference::Auto,
no_dtls: false, no_dtls: false,
dpd_interval: 0, dpd_interval: 0,
no_xmlpost: false, no_xmlpost: false,
@@ -430,6 +469,32 @@ impl VpnBuilder {
self self
} }
pub fn script_tun_program(
mut self,
program: &str,
arguments: &[String],
uid: u32,
inherited: OwnedFd,
) -> Result<Self, VpnError> {
if !std::path::Path::new(program).is_absolute() || program.contains('\0') {
return Err(VpnError::new("Script-tun requires an absolute executable path".into()));
}
let arguments = arguments
.iter()
.map(|arg| CString::new(arg.as_str()).map_err(|_| VpnError::new("Script-tun argument contains NUL".into())))
.collect::<Result<_, _>>()?;
self.script = None;
self.script_tun = true;
self.script_is_path = false;
self.script_tun_launch = Some(ScriptTunLaunch {
program: CString::new(program).expect("program was checked for NUL"),
arguments,
uid,
control: Mutex::new(Some(inherited)),
});
Ok(self)
}
pub fn script_tun(mut self, script_tun: bool) -> Self { pub fn script_tun(mut self, script_tun: bool) -> Self {
self.script_tun = script_tun; self.script_tun = script_tun;
self self
@@ -495,11 +560,18 @@ impl VpnBuilder {
self self
} }
/// Request IPv4-only connectivity inside the VPN tunnel.
pub fn disable_ipv6(mut self, disable_ipv6: bool) -> Self { pub fn disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6; self.disable_ipv6 = disable_ipv6;
self self
} }
/// Order gateway addresses without excluding either IP family.
pub fn gateway_ip_preference(mut self, preference: GatewayIpPreference) -> Self {
self.gateway_ip_preference = preference;
self
}
pub fn no_dtls(mut self, no_dtls: bool) -> Self { pub fn no_dtls(mut self, no_dtls: bool) -> Self {
self.no_dtls = no_dtls; self.no_dtls = no_dtls;
self self
@@ -524,6 +596,9 @@ impl VpnBuilder {
} }
return Ok(None); return Ok(None);
} }
if self.script_tun_launch.is_some() {
return Ok(None);
}
let script = match &self.script { let script = match &self.script {
Some(script) => { Some(script) => {
if self.script_is_path && !std::path::Path::new(script).exists() { if self.script_is_path && !std::path::Path::new(script).exists() {
@@ -543,6 +618,9 @@ impl VpnBuilder {
} }
pub fn build(self) -> Result<Vpn, VpnError> { pub fn build(self) -> Result<Vpn, VpnError> {
if self.script_tun_launch.is_some() && !self.script_tun {
return Err(VpnError::new("Child identity requires script-tun".into()));
}
let script = self.resolve_script()?; let script = self.resolve_script()?;
let user_agent = self.user_agent.unwrap_or_default(); let user_agent = self.user_agent.unwrap_or_default();
@@ -564,6 +642,7 @@ impl VpnBuilder {
network_configuration_handler: self.network_configuration_handler, network_configuration_handler: self.network_configuration_handler,
interface: self.interface.as_deref().map(Self::to_cstring), interface: self.interface.as_deref().map(Self::to_cstring),
script_tun: self.script_tun, script_tun: self.script_tun,
script_tun_launch: self.script_tun_launch,
certificate: self.certificate.as_deref().map(Self::to_cstring), certificate: self.certificate.as_deref().map(Self::to_cstring),
sslkey: self.sslkey.as_deref().map(Self::to_cstring), sslkey: self.sslkey.as_deref().map(Self::to_cstring),
@@ -575,6 +654,7 @@ impl VpnBuilder {
reconnect_timeout: self.reconnect_timeout, reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu, mtu: self.mtu,
disable_ipv6: self.disable_ipv6, disable_ipv6: self.disable_ipv6,
gateway_ip_preference: self.gateway_ip_preference,
no_dtls: self.no_dtls, no_dtls: self.no_dtls,
dpd_interval: self.dpd_interval, dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost, no_xmlpost: self.no_xmlpost,
@@ -694,6 +774,7 @@ mod tests {
network_configuration_handler: None, network_configuration_handler: None,
interface: None, interface: None,
script_tun: false, script_tun: false,
script_tun_launch: None,
certificate: None, certificate: None,
sslkey: None, sslkey: None,
key_password: None, key_password: None,
@@ -702,6 +783,7 @@ mod tests {
reconnect_timeout: 300, reconnect_timeout: 300,
mtu: 0, mtu: 0,
disable_ipv6: false, disable_ipv6: false,
gateway_ip_preference: GatewayIpPreference::Auto,
no_dtls: false, no_dtls: false,
dpd_interval: 0, dpd_interval: 0,
no_xmlpost: false, no_xmlpost: false,
@@ -717,6 +799,27 @@ mod tests {
assert_eq!(host_id, "profile-host-id"); assert_eq!(host_id, "profile-host-id");
} }
#[test]
fn gateway_preference_and_tunnel_ipv6_are_independent_in_native_options() {
for preference in [
GatewayIpPreference::Auto,
GatewayIpPreference::Ipv4,
GatewayIpPreference::Ipv6,
] {
for disable_ipv6 in [false, true] {
let vpn = Vpn::builder("https://gateway.example", "fixture")
.script_path("/bin/sh".to_string())
.disable_ipv6(disable_ipv6)
.gateway_ip_preference(preference)
.build()
.unwrap();
let options = vpn.build_connect_options();
assert_eq!(options.gateway_ip_preference, preference as u32);
assert_eq!(options.disable_ipv6, disable_ipv6 as u32);
}
}
}
#[test] #[test]
fn hip_report_callback_copies_only_bounded_utf8() { fn hip_report_callback_copies_only_bounded_utf8() {
let vpn = Vpn::builder("vpn.example.com", "cookie") let vpn = Vpn::builder("vpn.example.com", "cookie")
@@ -973,3 +1076,12 @@ mod tests {
cancellation.detach(); cancellation.detach();
} }
} }
#[unsafe(no_mangle)]
extern "C" fn vpn_script_started(data: *mut std::ffi::c_void) {
// Native setup has forked or failed; only the child may retain this endpoint.
let vpn = unsafe { &*(data as *const Vpn) };
if let Some(launch) = &vpn.script_tun_launch {
launch.control.lock().unwrap().take();
}
}
+81
View File
@@ -13,6 +13,38 @@ struct peer {
}; };
struct policy { int accept, calls, unsafe_renegotiation_denied; }; struct policy { int accept, calls, unsafe_renegotiation_denied; };
struct stalled_logout_peer {
int listener, stop, complete_tls;
gnutls_certificate_credentials_t credentials;
};
static void *stall_logout(void *data)
{
struct stalled_logout_peer *peer = data;
struct timeval timeout = { .tv_sec = 7 };
fd_set reads;
gnutls_session_t session = NULL;
int fd = accept(peer->listener, NULL, NULL);
assert(fd >= 0);
if (peer->complete_tls) {
assert(!gnutls_init(&session, GNUTLS_SERVER));
assert(!gnutls_set_default_priority(session));
assert(!gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, peer->credentials));
gnutls_transport_set_int(session, fd);
gnutls_handshake_set_timeout(session, 5000);
assert(!gnutls_handshake(session));
}
/* Stall either the TLS handshake or the HTTP logout response. The watchdog
* lets the regression fail without leaving either peer blocked forever. */
FD_ZERO(&reads);
FD_SET(peer->stop, &reads);
select(peer->stop + 1, &reads, NULL, NULL, &timeout);
if (session)
gnutls_deinit(session);
close(fd);
return NULL;
}
static void progress(void *data, int level, const char *format, ...) static void progress(void *data, int level, const char *format, ...)
{ {
va_list args; va_list args;
@@ -35,6 +67,53 @@ static int certificate_policy(void *data, const char *reason)
return policy->accept ? 0 : -EINVAL; return policy->accept ? 0 : -EINVAL;
} }
static void logout_finishes_when_gateway_stalls(const char *cert, const char *key, int complete_tls)
{
struct stalled_logout_peer peer;
struct policy policy = { .accept = 1 };
struct sockaddr_in address = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
socklen_t length = sizeof(address);
struct timespec start, end;
struct openconnect_info *client;
pthread_t thread;
char url[128];
int stop[2];
double elapsed;
assert(!pipe(stop));
peer.complete_tls = complete_tls;
assert(!gnutls_certificate_allocate_credentials(&peer.credentials));
assert(!gnutls_certificate_set_x509_key_file(peer.credentials, cert, key, GNUTLS_X509_FMT_PEM));
peer.stop = stop[0];
peer.listener = socket(AF_INET, SOCK_STREAM, 0);
assert(peer.listener >= 0);
assert(!bind(peer.listener, (struct sockaddr *)&address, sizeof(address)));
assert(!getsockname(peer.listener, (struct sockaddr *)&address, &length));
assert(!listen(peer.listener, 1));
assert(!pthread_create(&thread, NULL, stall_logout, &peer));
client = openconnect_vpninfo_new("Logout timeout regression", certificate_policy, NULL, NULL, progress, &policy);
assert(client);
snprintf(url, sizeof(url), "https://127.0.0.1:%u/", ntohs(address.sin_port));
assert(!openconnect_parse_url(client, url));
assert(!openconnect_set_protocol(client, "gp"));
assert(!openconnect_set_cookie(client, "user=fixture&authcookie=fixture"));
/* Enter the same cleanup branch as a consumed OC_CMD_CANCEL. */
client->quit_reason = "Aborted by caller";
assert(!clock_gettime(CLOCK_MONOTONIC, &start));
assert(openconnect_mainloop(client, 0, 0) < 0);
assert(!client->https_deadline.tv_sec && !client->https_deadline.tv_nsec);
assert(!clock_gettime(CLOCK_MONOTONIC, &end));
elapsed = end.tv_sec - start.tv_sec + (end.tv_nsec - start.tv_nsec) / 1e9;
(void)write(stop[1], "x", 1);
assert(!pthread_join(thread, NULL));
close(stop[0]);
close(stop[1]);
close(peer.listener);
gnutls_certificate_free_credentials(peer.credentials);
openconnect_vpninfo_free(client);
assert(elapsed < 6.0);
}
static void *serve(void *data) static void *serve(void *data)
{ {
struct peer *peer = data; struct peer *peer = data;
@@ -134,6 +213,8 @@ int main(int argc, char **argv)
assert(argc == 6); assert(argc == 6);
signal(SIGPIPE, SIG_IGN); signal(SIGPIPE, SIG_IGN);
assert(!openconnect_init_ssl()); assert(!openconnect_init_ssl());
logout_finishes_when_gateway_stalls(argv[1], argv[2], 0);
logout_finishes_when_gateway_stalls(argv[1], argv[2], 1);
#ifdef __APPLE__ #ifdef __APPLE__
/* Read-only check of the source-built library's native Keychain integration. /* Read-only check of the source-built library's native Keychain integration.
* Local fixture trust is tested separately, without changing OS trust settings. */ * Local fixture trust is tested separately, without changing OS trust settings. */
+5 -1
View File
@@ -9,7 +9,11 @@ escape_replacement() {
} }
# Each integration format has its own quoting rules. # Each integration format has its own quoting rules.
desktop_prefix=$(printf '%s' "$prefix" | sed -e 's/\\/\\\\\\\\/g' -e 's/["`$]/\\\\&/g' -e 's/%/%%/g') desktop_prefix=$(printf '%s' "$prefix" | sed -e 's/\\/\\\\\\\\/g' -e 's/["`$]/\\\\&/g' -e 's/%/%%/g')
desktop_command=$(escape_replacement "\"$desktop_prefix/bin/gpclient\"") # Avoid unnecessary quotes for older xdg-open parsers.
case "$prefix/bin/gpclient" in
*[!A-Za-z0-9_./-]*) desktop_command=$(escape_replacement "\"$desktop_prefix/bin/gpclient\"") ;;
*) desktop_command=$(escape_replacement "$desktop_prefix/bin/gpclient") ;;
esac
shell_prefix=$(printf '%s' "$prefix" | sed "s/'/'\\\\''/g") shell_prefix=$(printf '%s' "$prefix" | sed "s/'/'\\\\''/g")
shell_command=$(escape_replacement "'$shell_prefix/bin/gpclient'") shell_command=$(escape_replacement "'$shell_prefix/bin/gpclient'")
xml_prefix=$(printf '%s' "$prefix" | sed -e 's/\&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g') xml_prefix=$(printf '%s' "$prefix" | sed -e 's/\&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')
+1 -1
View File
@@ -24,7 +24,7 @@ for platform in linux bsd; do
installed="$stage/custom/gp" installed="$stage/custom/gp"
test -x "$installed/bin/gpclient" test -x "$installed/bin/gpclient"
test -x "$installed/libexec/gpclient/gp-vpnc-script-installer" test -x "$installed/libexec/gpclient/gp-vpnc-script-installer"
grep -q 'Exec="/custom/gp/bin/gpclient" ' "$installed/share/applications/gpgui.desktop" grep -Fxq 'Exec=/custom/gp/bin/gpclient launch-gui %u' "$installed/share/applications/gpgui.desktop"
grep -q '>/custom/gp/bin/gpservice<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy" grep -q '>/custom/gp/bin/gpservice<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy"
grep -q '>/custom/gp/libexec/gpclient/gp-hip-script-installer<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy" grep -q '>/custom/gp/libexec/gpclient/gp-hip-script-installer<' "$installed/share/polkit-1/actions/com.yuezk.gpgui.policy"
! grep -F "$stage" "$installed/share/applications/gpgui.desktop" ! grep -F "$stage" "$installed/share/applications/gpgui.desktop"