mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: prepare 3.2.0 with Local Proxy and gateway IP preference
This commit is contained in:
47 files changed
+3965
-233
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod gateway;
|
||||
mod hip;
|
||||
mod network_configuration;
|
||||
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::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.
|
||||
#[repr(C)]
|
||||
#[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 interface: *const c_char,
|
||||
pub script_tun: u32,
|
||||
pub script_tun_launch: *const ScriptTunLaunchRaw,
|
||||
|
||||
pub certificate: *const c_char,
|
||||
pub sslkey: *const c_char,
|
||||
@@ -44,6 +56,7 @@ pub(crate) struct ConnectOptions {
|
||||
pub reconnect_timeout: u32,
|
||||
pub mtu: u32,
|
||||
pub disable_ipv6: u32,
|
||||
pub gateway_ip_preference: u32,
|
||||
pub no_dtls: u32,
|
||||
|
||||
pub dpd_interval: u32,
|
||||
|
||||
@@ -15,13 +15,21 @@ struct vpn_context {
|
||||
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)
|
||||
{
|
||||
const struct oc_ip_info *info = NULL;
|
||||
if (openconnect_get_ip_info(context->vpninfo, &info, NULL, NULL))
|
||||
info = NULL;
|
||||
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)
|
||||
@@ -75,7 +83,13 @@ static void setup_tun_handler(void *private_data)
|
||||
const vpn_options *options = context->options;
|
||||
int ret;
|
||||
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 {
|
||||
ret = openconnect_setup_tun_device(_vpninfo, options->script,
|
||||
options->interface);
|
||||
@@ -114,13 +128,19 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
INFO("OS: %s", options->os);
|
||||
INFO("CLIENT_VERSION: %s", options->client_version);
|
||||
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("CSD_USER: %d", options->hip_script.uid);
|
||||
INFO("CSD_WRAPPER: %s", options->hip_script.path);
|
||||
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
||||
INFO("MTU: %d", options->mtu);
|
||||
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
|
||||
INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference);
|
||||
INFO("NO_DTLS: %d", options->no_dtls);
|
||||
INFO("DPD_INTERVAL: %d", options->dpd_interval);
|
||||
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_set_protocol(vpninfo, "gp");
|
||||
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_useragent(vpninfo, options->user_agent);
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ typedef struct vpn_options {
|
||||
openconnect_configure_tun_fn configure_network;
|
||||
const char *interface;
|
||||
const int script_tun;
|
||||
const struct openconnect_script_tun_launch *script_tun_launch;
|
||||
|
||||
const char *certificate;
|
||||
const char *sslkey;
|
||||
@@ -59,6 +60,7 @@ typedef struct vpn_options {
|
||||
const int reconnect_timeout;
|
||||
const int mtu;
|
||||
const int disable_ipv6;
|
||||
const int gateway_ip_preference;
|
||||
const int no_dtls;
|
||||
|
||||
const int dpd_interval;
|
||||
@@ -66,11 +68,14 @@ typedef struct vpn_options {
|
||||
} vpn_options;
|
||||
|
||||
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 *,
|
||||
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 void vpn_detach_command_pipe(void *user_data);
|
||||
extern void vpn_script_started(void *user_data);
|
||||
enum vpn_tunnel_event {
|
||||
VPN_TUNNEL_ESTABLISHED = 5,
|
||||
VPN_TUNNEL_RECONNECTED,
|
||||
|
||||
@@ -9,3 +9,6 @@ pub use hip::*;
|
||||
pub use network_configuration::*;
|
||||
pub use vpn::*;
|
||||
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) };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{
|
||||
ffi::{CStr, CString, c_char},
|
||||
fmt, io,
|
||||
os::fd::{AsRawFd, OwnedFd},
|
||||
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 {
|
||||
cancellation: Cancellation,
|
||||
server: CString,
|
||||
@@ -140,6 +150,7 @@ pub struct Vpn {
|
||||
pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
|
||||
interface: Option<CString>,
|
||||
script_tun: bool,
|
||||
script_tun_launch: Option<ScriptTunLaunch>,
|
||||
|
||||
certificate: Option<CString>,
|
||||
sslkey: Option<CString>,
|
||||
@@ -151,6 +162,7 @@ pub struct Vpn {
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
disable_ipv6: bool,
|
||||
gateway_ip_preference: GatewayIpPreference,
|
||||
no_dtls: bool,
|
||||
|
||||
dpd_interval: u32,
|
||||
@@ -220,6 +232,20 @@ impl Vpn {
|
||||
}
|
||||
self.callback.write().unwrap().replace(Box::new(on_connected));
|
||||
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() {
|
||||
HipSource::Script(script) => ffi::script_environment(script),
|
||||
_ => Vec::new(),
|
||||
@@ -287,6 +313,7 @@ impl Vpn {
|
||||
.map(|_| ffi::configure_network as _),
|
||||
interface: Self::option_to_ptr(&self.interface),
|
||||
script_tun: self.script_tun as u32,
|
||||
script_tun_launch: std::ptr::null(),
|
||||
|
||||
certificate: Self::option_to_ptr(&self.certificate),
|
||||
sslkey: Self::option_to_ptr(&self.sslkey),
|
||||
@@ -305,6 +332,7 @@ impl Vpn {
|
||||
reconnect_timeout: self.reconnect_timeout,
|
||||
mtu: self.mtu,
|
||||
disable_ipv6: self.disable_ipv6 as u32,
|
||||
gateway_ip_preference: self.gateway_ip_preference as u32,
|
||||
no_dtls: self.no_dtls as u32,
|
||||
dpd_interval: self.dpd_interval,
|
||||
no_xmlpost: self.no_xmlpost as u32,
|
||||
@@ -338,6 +366,13 @@ impl fmt::Display for VpnError {
|
||||
|
||||
impl std::error::Error for VpnError {}
|
||||
|
||||
struct ScriptTunLaunch {
|
||||
program: CString,
|
||||
arguments: Vec<CString>,
|
||||
uid: u32,
|
||||
control: Mutex<Option<OwnedFd>>,
|
||||
}
|
||||
|
||||
pub struct VpnBuilder {
|
||||
server: String,
|
||||
cookie: String,
|
||||
@@ -346,6 +381,7 @@ pub struct VpnBuilder {
|
||||
script_is_path: bool,
|
||||
interface: Option<String>,
|
||||
script_tun: bool,
|
||||
script_tun_launch: Option<ScriptTunLaunch>,
|
||||
|
||||
user_agent: Option<String>,
|
||||
os: Option<String>,
|
||||
@@ -363,6 +399,7 @@ pub struct VpnBuilder {
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
disable_ipv6: bool,
|
||||
gateway_ip_preference: GatewayIpPreference,
|
||||
no_dtls: bool,
|
||||
|
||||
dpd_interval: u32,
|
||||
@@ -379,6 +416,7 @@ impl VpnBuilder {
|
||||
script_is_path: false,
|
||||
interface: None,
|
||||
script_tun: false,
|
||||
script_tun_launch: None,
|
||||
|
||||
user_agent: None,
|
||||
os: None,
|
||||
@@ -396,6 +434,7 @@ impl VpnBuilder {
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
gateway_ip_preference: GatewayIpPreference::Auto,
|
||||
no_dtls: false,
|
||||
dpd_interval: 0,
|
||||
no_xmlpost: false,
|
||||
@@ -430,6 +469,32 @@ impl VpnBuilder {
|
||||
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 {
|
||||
self.script_tun = script_tun;
|
||||
self
|
||||
@@ -495,11 +560,18 @@ impl VpnBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Request IPv4-only connectivity inside the VPN tunnel.
|
||||
pub fn disable_ipv6(mut self, disable_ipv6: bool) -> Self {
|
||||
self.disable_ipv6 = disable_ipv6;
|
||||
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 {
|
||||
self.no_dtls = no_dtls;
|
||||
self
|
||||
@@ -524,6 +596,9 @@ impl VpnBuilder {
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
if self.script_tun_launch.is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let script = match &self.script {
|
||||
Some(script) => {
|
||||
if self.script_is_path && !std::path::Path::new(script).exists() {
|
||||
@@ -543,6 +618,9 @@ impl VpnBuilder {
|
||||
}
|
||||
|
||||
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 user_agent = self.user_agent.unwrap_or_default();
|
||||
@@ -564,6 +642,7 @@ impl VpnBuilder {
|
||||
network_configuration_handler: self.network_configuration_handler,
|
||||
interface: self.interface.as_deref().map(Self::to_cstring),
|
||||
script_tun: self.script_tun,
|
||||
script_tun_launch: self.script_tun_launch,
|
||||
|
||||
certificate: self.certificate.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,
|
||||
mtu: self.mtu,
|
||||
disable_ipv6: self.disable_ipv6,
|
||||
gateway_ip_preference: self.gateway_ip_preference,
|
||||
no_dtls: self.no_dtls,
|
||||
dpd_interval: self.dpd_interval,
|
||||
no_xmlpost: self.no_xmlpost,
|
||||
@@ -694,6 +774,7 @@ mod tests {
|
||||
network_configuration_handler: None,
|
||||
interface: None,
|
||||
script_tun: false,
|
||||
script_tun_launch: None,
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
@@ -702,6 +783,7 @@ mod tests {
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
gateway_ip_preference: GatewayIpPreference::Auto,
|
||||
no_dtls: false,
|
||||
dpd_interval: 0,
|
||||
no_xmlpost: false,
|
||||
@@ -717,6 +799,27 @@ mod tests {
|
||||
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]
|
||||
fn hip_report_callback_copies_only_bounded_utf8() {
|
||||
let vpn = Vpn::builder("vpn.example.com", "cookie")
|
||||
@@ -973,3 +1076,12 @@ mod tests {
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user