feat: prepare 3.1.0 with connection details and improved authentication

Add tunnel statistics and an optional CLI dashboard, native sign-in controls and recovery, and broader client certificate support. Include platform integration fixes and the approved release notes.
This commit is contained in:
Kevin Yue committed 2026-10-19 23:47:11 +08:00
1 parent 18ed6bac1a
commit 4faa2ecb0d
158 files changed
+13752 -1038

No files matched your search

+15 -2
View File
@@ -117,7 +117,11 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
#[cfg(target_os = "macos")]
{
config.disable_static().enable_shared().without("gnutls", None);
config
.disable_static()
.enable_shared()
.with("gnutls", None)
.without("openssl", None);
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
@@ -139,6 +143,15 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
#[cfg(target_os = "macos")]
{
let configuration = std::fs::read_to_string(dst.join("build/config.h"))
.expect("Failed to read the OpenConnect TLS backend configuration");
assert!(
configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1")
&& !configuration
.lines()
.any(|line| line == "#define OPENCONNECT_OPENSSL 1"),
"macOS OpenConnect must use GnuTLS"
);
// Do not embed Cargo's temporary build directory in consumers of this library.
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
let library_name = library.file_name().unwrap().to_str().unwrap();
@@ -198,7 +211,7 @@ fn main() {
// Using pkg-config to find system deps
pkg_config::probe_library("zlib").unwrap();
#[cfg(target_os = "macos")]
pkg_config::probe_library("openssl").unwrap();
pkg_config::probe_library("gnutls").unwrap();
#[cfg(not(target_os = "macos"))]
{
+14
View File
@@ -1,10 +1,13 @@
mod hip;
mod network_configuration;
mod tunnel;
use crate::Vpn;
use hip::HipGenerateFn;
pub(crate) use hip::{
HipControlRaw, HipScriptRaw, collect_hip_script, collect_hip_source, generate_hip_report, script_environment,
};
use log::{debug, info, trace, warn};
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};
@@ -26,6 +29,7 @@ pub(crate) struct ConnectOptions {
pub local_hostname: *const c_char,
pub script: *const c_char,
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,
@@ -61,6 +65,7 @@ pub(crate) struct VpnSessionInfoRaw {
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_write_cancel(fd: c_int) -> c_int;
fn vpn_write_statistics(fd: c_int) -> c_int;
#[link_name = "vpn_connect"]
fn vpn_connect(
options: *const ConnectOptions,
@@ -78,6 +83,15 @@ pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
}
}
pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> {
let error = unsafe { vpn_write_statistics(fd) };
if error == 0 {
Ok(())
} else {
Err(std::io::Error::from_raw_os_error(error))
}
}
#[unsafe(no_mangle)]
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int {
unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into()
@@ -0,0 +1,177 @@
use std::{
ffi::{CStr, c_char, c_int, c_void},
io,
panic::{AssertUnwindSafe, catch_unwind},
};
use crate::{NetworkConfiguration, Vpn};
/// Matches OpenConnect's oc_vpn_option list. Borrowed for this invocation only.
#[repr(C)]
pub(crate) struct VpnOptionRaw {
pub option: *const c_char,
pub value: *const c_char,
pub next: *const VpnOptionRaw,
}
/// # Safety
/// A non-null `value` must point to a readable, NUL-terminated string that
/// remains valid and unchanged until this function returns.
unsafe fn read_string(value: *const c_char) -> io::Result<String> {
if value.is_null() {
return Err(io::Error::from_raw_os_error(libc::EINVAL));
}
// SAFETY: The caller guarantees a valid C string; null was rejected above.
unsafe { CStr::from_ptr(value) }
.to_str()
.map(str::to_owned)
.map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))
}
/// # Safety
/// Non-null strings must satisfy `read_string`'s contract. `options` must be
/// null or a finite, acyclic list of aligned, readable nodes. The list and its
/// strings must remain valid and unchanged until this function returns.
unsafe fn snapshot(reason: *const c_char, mut options: *const VpnOptionRaw) -> io::Result<NetworkConfiguration> {
// SAFETY: The caller guarantees the string lifetime and validity.
let reason = unsafe { read_string(reason)? };
let mut environment = Vec::new();
while !options.is_null() {
// SAFETY: This is a non-null node in the valid list supplied by the caller.
let option = unsafe { &*options };
// SAFETY: Node strings satisfy read_string's contract, including null handling.
let name = unsafe { read_string(option.option)? };
let value = if option.value.is_null() {
None
} else {
// SAFETY: The caller guarantees this non-null string's validity and lifetime.
Some(unsafe { read_string(option.value)? })
};
environment.push((name, value));
options = option.next;
}
Ok(NetworkConfiguration { reason, environment })
}
/// # Safety
/// `data` must point to an aligned, live `Vpn` that may be shared immutably for
/// this entire invocation. `reason` and `options` must satisfy `snapshot`'s
/// contract. OpenConnect invokes this callback synchronously during `connect`,
/// including cleanup, before the borrowed `Vpn` or configuration data is freed.
pub(crate) unsafe extern "C" fn configure_network(
data: *mut c_void,
reason: *const c_char,
options: *const VpnOptionRaw,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
// SAFETY: The caller supplies the live Vpn pointer registered for this connection.
let vpn = unsafe { &*(data as *const Vpn) };
// SAFETY: The caller keeps OpenConnect's list and strings valid during this call.
let configuration = unsafe { snapshot(reason, options)? };
let handler = vpn
.network_configuration_handler
.as_ref()
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
handler(&configuration)
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => {
log::warn!("Network configuration failed: {error}");
-error.raw_os_error().filter(|code| *code > 0).unwrap_or(libc::EIO)
}
Err(_) => {
log::warn!("Network configuration handler panicked");
-libc::EIO
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
ffi::CString,
sync::{Arc, Mutex},
};
#[test]
fn callback_copies_configuration_and_preserves_unset_values() {
let observed = Arc::new(Mutex::new(None));
let output = observed.clone();
let vpn = Vpn::builder("server", "cookie")
.network_configuration_handler(move |configuration| {
*output.lock().unwrap() = Some(configuration.clone());
Ok(())
})
.build()
.unwrap();
let name = CString::new("TUNDEV").unwrap();
let value = CString::new("utun3").unwrap();
let unset_name = CString::new("INTERNAL_IP6_ADDRESS").unwrap();
let unset = VpnOptionRaw {
option: unset_name.as_ptr(),
value: std::ptr::null(),
next: std::ptr::null(),
};
let option = VpnOptionRaw {
option: name.as_ptr(),
value: value.as_ptr(),
next: &unset,
};
// SAFETY: vpn, both list nodes, and their C strings remain live for the call.
let result = unsafe { configure_network((&vpn as *const Vpn).cast_mut().cast(), c"connect".as_ptr(), &option) };
assert_eq!(result, 0);
let configuration = observed.lock().unwrap().take().unwrap();
assert_eq!(configuration.reason, "connect");
assert_eq!(
configuration.environment,
vec![
("TUNDEV".into(), Some("utun3".into())),
("INTERNAL_IP6_ADDRESS".into(), None)
]
);
}
#[test]
fn callback_errors_and_panics_do_not_cross_ffi() {
for panics in [false, true] {
let vpn = Vpn::builder("server", "cookie")
.network_configuration_handler(move |_| {
if panics {
panic!("test panic");
}
Err(io::Error::from_raw_os_error(libc::EPERM))
})
.build()
.unwrap();
// SAFETY: vpn and the static reason are live; a null list is permitted.
let result = unsafe {
configure_network(
(&vpn as *const Vpn).cast_mut().cast(),
c"connect".as_ptr(),
std::ptr::null(),
)
};
assert_eq!(result, if panics { -libc::EIO } else { -libc::EPERM });
}
}
#[test]
fn callback_rejects_script_options() {
assert!(
Vpn::builder("server", "cookie")
.network_configuration_handler(|_| Ok(()))
.script_tun(true)
.build()
.is_err()
);
assert!(
Vpn::builder("server", "cookie")
.network_configuration_handler(|_| Ok(()))
.script(Some("/bin/true".into()))
.build()
.is_err()
);
}
}
+355
View File
@@ -0,0 +1,355 @@
use std::{
ffi::{CStr, c_char, c_int, c_void},
panic::{AssertUnwindSafe, catch_unwind},
};
use crate::{
Vpn,
tunnel::{Configuration, Event, NativeList, Statistics, Transport},
};
const TEXT_LIMIT: usize = 1024;
const COPY_BUDGET: usize = 16 * 1024;
const LIST_LIMIT: usize = 256;
#[repr(C)]
struct SplitInclude {
route: *const c_char,
next: *const SplitInclude,
}
/// Matches oc_ip_info in the bundled public openconnect.h.
#[repr(C)]
struct IpInfo {
addr: *const c_char,
netmask: *const c_char,
addr6: *const c_char,
netmask6: *const c_char,
dns: [*const c_char; 3],
nbns: [*const c_char; 3],
domain: *const c_char,
proxy_pac: *const c_char,
mtu: c_int,
split_dns: *const SplitInclude,
split_includes: *const SplitInclude,
split_excludes: *const SplitInclude,
gateway_addr: *const c_char,
}
#[repr(C)]
struct Stats {
tx_pkts: u64,
tx_bytes: u64,
rx_pkts: u64,
rx_bytes: u64,
}
struct CopyBudget {
remaining: usize,
truncated: bool,
}
impl CopyBudget {
fn new() -> Self {
Self {
remaining: COPY_BUDGET,
truncated: false,
}
}
fn text(&mut self, bytes: &[u8]) -> String {
let limit = self.remaining.min(TEXT_LIMIT).min(bytes.len());
// Lossy UTF-8 is bounded before allocation, then truncated at a character
// boundary so replacement characters cannot exceed the retained budget.
let mut text = String::from_utf8_lossy(&bytes[..limit]).into_owned();
let mut end = text.len().min(limit);
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
self.truncated |= end < bytes.len();
self.remaining -= text.len();
text
}
unsafe fn optional(&mut self, value: *const c_char) -> Option<String> {
if value.is_null() {
return None;
}
// The native value is NUL terminated and borrowed only during the callback.
// Bound the scan as well as the retained allocation for scalar fields.
let length = unsafe { libc::strnlen(value, TEXT_LIMIT + 1) };
Some(self.text(unsafe { std::slice::from_raw_parts(value.cast(), length) }))
}
fn push(&mut self, list: &mut NativeList, bytes: &[u8]) {
list.total_count = list.total_count.saturating_add(1);
// Retain whole list entries; the native list is not a user-owned buffer.
if list.items.len() >= LIST_LIMIT || bytes.len() > TEXT_LIMIT || bytes.len() > self.remaining {
list.truncated = true;
self.truncated = true;
return;
}
let text = self.text(bytes);
list.truncated |= text.len() != bytes.len();
list.items.push(text);
}
unsafe fn routes(&mut self, mut node: *const SplitInclude) -> NativeList {
let mut list = NativeList::default();
while !node.is_null() {
let entry = unsafe { &*node };
if !entry.route.is_null() {
self.push(&mut list, unsafe { CStr::from_ptr(entry.route) }.to_bytes());
}
node = entry.next;
}
list
}
}
unsafe fn configuration(interface: *const c_char, raw: &IpInfo) -> Configuration {
let mut budget = CopyBudget::new();
let mut result = Configuration {
interface: unsafe { budget.optional(interface) },
ipv4: unsafe { budget.optional(raw.addr) },
netmask: unsafe { budget.optional(raw.netmask) },
ipv6: unsafe { budget.optional(raw.addr6) },
netmask6: unsafe { budget.optional(raw.netmask6) },
server_ip: unsafe { budget.optional(raw.gateway_addr) },
mtu: u32::try_from(raw.mtu).ok().filter(|mtu| *mtu > 0),
..Configuration::default()
};
for server in raw.dns {
if !server.is_null() {
budget.push(&mut result.dns, unsafe { CStr::from_ptr(server) }.to_bytes());
}
}
if !raw.domain.is_null() {
// GlobalProtect builds its search list with spaces in gpst.c.
for domain in unsafe { CStr::from_ptr(raw.domain) }
.to_bytes()
.split(u8::is_ascii_whitespace)
{
if !domain.is_empty() {
budget.push(&mut result.search_domains, domain);
}
}
}
result.split_dns = unsafe { budget.routes(raw.split_dns) };
result.included_routes = unsafe { budget.routes(raw.split_includes) };
result.excluded_routes = unsafe { budget.routes(raw.split_excludes) };
result.truncated = budget.truncated;
result
}
fn observe(vpn: *mut c_void, action: impl FnOnce(&Vpn)) {
if vpn.is_null() {
return;
}
// All exports are called synchronously with the live Vpn registered by connect.
if catch_unwind(AssertUnwindSafe(|| action(unsafe { &*vpn.cast::<Vpn>() }))).is_err() {
log::warn!("Tunnel observer panicked");
}
}
#[unsafe(no_mangle)]
extern "C" fn vpn_tunnel_configuration(vpn: *mut c_void, interface: *const c_char, info: *const IpInfo) {
observe(vpn, |vpn| {
let configuration = unsafe { info.as_ref().map(|info| configuration(interface, info)) };
vpn.on_tunnel_event(Event::Configuration(configuration));
});
}
#[unsafe(no_mangle)]
extern "C" fn vpn_tunnel_event(vpn: *mut c_void, event: c_int) {
observe(vpn, |vpn| match event {
0 => vpn.on_tunnel_event(Event::Transport(Transport::Negotiating)),
1 => vpn.on_tunnel_event(Event::Transport(Transport::IpsecEsp)),
2 => vpn.on_tunnel_event(Event::Transport(Transport::SslTls)),
3 => vpn.on_tunnel_event(Event::Transport(Transport::Unavailable)),
4 => {
vpn.on_tunnel_event(Event::Transport(Transport::Unavailable));
vpn.on_tunnel_event(Event::Reconnecting);
}
5 => vpn.on_tunnel_event(Event::Established),
6 => vpn.on_tunnel_event(Event::Reconnected),
7 => {
vpn.on_tunnel_event(Event::Transport(Transport::Unavailable));
vpn.on_tunnel_event(Event::Ended);
}
_ => log::warn!("Unknown native tunnel observation: {event}"),
});
}
#[unsafe(no_mangle)]
extern "C" fn vpn_tunnel_statistics(vpn: *mut c_void, stats: *const Stats) {
observe(vpn, |vpn| {
vpn.statistics_received();
if let Some(stats) = unsafe { stats.as_ref() } {
vpn.on_tunnel_event(Event::Statistics(Statistics {
received_bytes: stats.rx_bytes,
sent_bytes: stats.tx_bytes,
received_packets: stats.rx_pkts,
sent_packets: stats.tx_pkts,
}));
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use std::{
ffi::CString,
sync::{Arc, Mutex},
};
fn empty_info() -> IpInfo {
// Every pointer is nullable, and zero MTU denotes unavailable.
unsafe { std::mem::zeroed() }
}
#[test]
fn snapshot_owns_configuration_and_preserves_native_mask_semantics() {
let domain = CString::new("one.example two.example\tthree.example").unwrap();
let ipv6 = CString::new("2001:db8::1").unwrap();
let mask6 = CString::new("2001:db8::1/64").unwrap();
let server = CString::new("2001:db8::53").unwrap();
let route = CString::new("10.0.0.0/8").unwrap();
let node = SplitInclude {
route: route.as_ptr(),
next: std::ptr::null(),
};
let raw = IpInfo {
domain: domain.as_ptr(),
addr6: ipv6.as_ptr(),
netmask6: mask6.as_ptr(),
dns: [server.as_ptr(), std::ptr::null(), std::ptr::null()],
split_includes: &node,
mtu: 1400,
..empty_info()
};
let snapshot = unsafe { configuration(std::ptr::null(), &raw) };
drop((domain, ipv6, mask6, server, route));
assert_eq!(
snapshot.search_domains.items,
["one.example", "two.example", "three.example"]
);
assert_eq!(snapshot.dns.items, ["2001:db8::53"]);
assert_eq!(snapshot.netmask6.as_deref(), Some("2001:db8::1/64"));
assert_eq!(snapshot.included_routes.items, ["10.0.0.0/8"]);
assert_eq!(snapshot.mtu, Some(1400));
assert!(!snapshot.truncated);
}
#[test]
fn observation_budget_keeps_whole_entries_and_counts_omitted_values() {
let domain = CString::new(
std::iter::repeat_n("example.internal", 2000)
.collect::<Vec<_>>()
.join(" "),
)
.unwrap();
let long_ipv6 = CString::new("界".repeat(500)).unwrap();
let raw = IpInfo {
domain: domain.as_ptr(),
addr6: long_ipv6.as_ptr(),
..empty_info()
};
let snapshot = unsafe { configuration(std::ptr::null(), &raw) };
assert!(snapshot.truncated);
assert!(snapshot.ipv6.as_ref().unwrap().len() <= TEXT_LIMIT);
assert_eq!(snapshot.search_domains.total_count, 2000);
assert!(snapshot.search_domains.truncated);
assert!(snapshot.search_domains.items.len() <= LIST_LIMIT);
assert!(
snapshot
.search_domains
.items
.iter()
.all(|item| item == "example.internal")
);
let retained = snapshot.ipv6.unwrap().len() + snapshot.search_domains.items.iter().map(String::len).sum::<usize>();
assert!(retained <= COPY_BUDGET);
}
#[test]
fn observer_deduplicates_transport_and_survives_panics() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_owned())
.build()
.unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let collected = events.clone();
vpn.set_tunnel_observer(move |event| collected.lock().unwrap().push(event));
let pointer = (&vpn as *const Vpn).cast_mut().cast();
vpn_tunnel_event(pointer, 1);
vpn_tunnel_event(pointer, 1);
vpn_tunnel_event(pointer, 4);
vpn_tunnel_event(pointer, 6);
vpn_tunnel_event(pointer, 7);
assert_eq!(
*events.lock().unwrap(),
[
Event::Transport(Transport::IpsecEsp),
Event::Transport(Transport::Unavailable),
Event::Reconnecting,
Event::Reconnected,
Event::Ended,
]
);
vpn.set_tunnel_observer(|_| panic!("test observer panic"));
vpn_tunnel_event(pointer, 5);
vpn.clear_tunnel_observer();
vpn_tunnel_event(pointer, 5);
}
#[test]
fn statistics_callback_clears_pending_before_notifying_observer() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
};
let vpn = Arc::new(
Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_owned())
.build()
.unwrap(),
);
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!vpn.attach_command_pipe(writer.as_raw_fd()));
assert!(vpn.request_statistics().unwrap());
let received = Arc::new(Mutex::new(None));
let captured = received.clone();
let weak = Arc::downgrade(&vpn);
vpn.set_tunnel_observer(move |event| {
if let Event::Statistics(statistics) = event {
*captured.lock().unwrap() = Some(statistics);
assert!(weak.upgrade().unwrap().request_statistics().unwrap());
}
});
let raw = Stats {
tx_pkts: u64::MAX,
tx_bytes: 1 << 54,
rx_pkts: 12,
rx_bytes: 34,
};
vpn_tunnel_statistics(Arc::as_ptr(&vpn).cast_mut().cast(), &raw);
assert_eq!(
*received.lock().unwrap(),
Some(Statistics {
sent_packets: u64::MAX,
sent_bytes: 1 << 54,
received_packets: 12,
received_bytes: 34,
})
);
let mut commands = [0; 2];
reader.read_exact(&mut commands).unwrap();
assert_eq!(commands, [b's', b's']);
vpn.detach_command_pipe();
vpn.clear_tunnel_observer();
}
}
+50 -1
View File
@@ -15,6 +15,34 @@ struct vpn_context {
vpn_connected_callback on_connected;
};
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);
}
static void observe_reconnected(void *private_data)
{
struct vpn_context *context = private_data;
observe_configuration(context);
vpn_tunnel_event(context->options->user_data, VPN_TUNNEL_RECONNECTED);
}
static void observe_tunnel(void *private_data, enum openconnect_tunnel_event event)
{
struct vpn_context *context = private_data;
vpn_tunnel_event(context->options->user_data, event);
}
static void observe_statistics(void *private_data, const struct oc_stats *stats)
{
struct vpn_context *context = private_data;
vpn_tunnel_statistics(context->options->user_data, stats);
}
/* Validate the peer certificate */
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
const char *reason)
@@ -54,6 +82,8 @@ static void setup_tun_handler(void *private_data)
}
if (!ret) {
observe_configuration(context);
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ESTABLISHED);
vpn_session_info session_info = {
.auth_expiration = (long)openconnect_get_auth_expiration(_vpninfo),
.lifetime_secs = openconnect_get_gp_session_lifetime(_vpninfo),
@@ -84,7 +114,7 @@ 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("VPNC_SCRIPT: %s", options->script);
INFO("Network configuration: %s", options->configure_network ? "callback" : options->script);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path);
@@ -101,10 +131,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (!vpninfo) {
ERROR("openconnect_vpninfo_new failed");
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED);
return 1;
}
context.vpninfo = vpninfo;
openconnect_set_tunnel_handler(vpninfo, observe_tunnel);
openconnect_set_reconnected_handler(vpninfo, observe_reconnected);
openconnect_set_stats_handler(vpninfo, observe_statistics);
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
options->on_hip_report_submitted);
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
@@ -191,6 +225,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_dpd(vpninfo, options->dpd_interval);
}
// Essential step
vpn_tunnel_event(options->user_data, OC_TUNNEL_NEGOTIATING);
if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed");
goto cleanup;
@@ -200,6 +235,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_disable_dtls(vpninfo);
}
// Essential step
openconnect_set_configure_tun_handler(vpninfo, options->user_data,
options->configure_network);
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
while (1) {
@@ -216,7 +253,9 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
}
cleanup:
vpn_detach_command_pipe(options->user_data);
openconnect_set_tunnel_handler(vpninfo, NULL);
openconnect_vpninfo_free(vpninfo);
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED);
return result;
}
@@ -231,6 +270,16 @@ int vpn_write_cancel(int fd)
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
int vpn_write_statistics(int fd)
{
char command = OC_CMD_STATS;
ssize_t written;
do {
written = write(fd, &command, 1);
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
int vpn_collect_hip_report(const vpn_hip_script *script,
const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, openconnect_gp_hip_generate_fn generate, void *data,
+10
View File
@@ -44,6 +44,7 @@ typedef struct vpn_options {
const char *local_hostname;
const char *script;
openconnect_configure_tun_fn configure_network;
const char *interface;
const int script_tun;
@@ -70,6 +71,15 @@ int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_h
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
enum vpn_tunnel_event {
VPN_TUNNEL_ESTABLISHED = 5,
VPN_TUNNEL_RECONNECTED,
VPN_TUNNEL_ENDED,
};
extern void vpn_tunnel_event(void *user_data, int event);
extern void vpn_tunnel_configuration(void *user_data, const char *interface,
const struct oc_ip_info *info);
extern void vpn_tunnel_statistics(void *user_data, const struct oc_stats *stats);
extern void vpn_log(int level, const char *msg);
+3
View File
@@ -1,8 +1,11 @@
mod ffi;
mod hip;
mod network_configuration;
pub mod tunnel;
mod vpn;
mod vpn_utils;
pub use hip::*;
pub use network_configuration::*;
pub use vpn::*;
pub use vpn_utils::*;
@@ -0,0 +1,12 @@
use std::io;
pub type NetworkConfigurationHandler = dyn Fn(&NetworkConfiguration) -> io::Result<()> + Send + Sync;
/// OpenConnect's configuration inputs for one lifecycle event.
/// Values are copied from OpenConnect before calling the handler. A missing
/// value means the variable must be unset, rather than inherited by a child.
#[derive(Debug, Clone)]
pub struct NetworkConfiguration {
pub reason: String,
pub environment: Vec<(String, Option<String>)>,
}
+57
View File
@@ -0,0 +1,57 @@
//! Owned observations of one native tunnel. Callbacks run synchronously on the
//! connection thread; observers must return promptly and must not call connect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport {
Negotiating,
IpsecEsp,
SslTls,
Unavailable,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NativeList {
pub items: Vec<String>,
pub total_count: u32,
pub truncated: bool,
}
/// Negotiated settings, not proof that OS network configuration succeeded.
/// Copy limits apply only to observation and never alter native configuration.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Configuration {
pub interface: Option<String>,
pub ipv4: Option<String>,
pub netmask: Option<String>,
pub ipv6: Option<String>,
pub netmask6: Option<String>,
pub server_ip: Option<String>,
pub dns: NativeList,
pub search_domains: NativeList,
pub split_dns: NativeList,
pub included_routes: NativeList,
pub excluded_routes: NativeList,
pub mtu: Option<u32>,
pub truncated: bool,
}
/// Plaintext packets crossing TUN, excluding outer transport overhead. Sent
/// counters measure local TUN reads, not confirmed delivery to the VPN server.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Statistics {
pub received_bytes: u64,
pub sent_bytes: u64,
pub received_packets: u64,
pub sent_packets: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
Configuration(Option<Configuration>),
Established,
Reconnecting,
Reconnected,
Transport(Transport),
Statistics(Statistics),
Ended,
}
+183 -23
View File
@@ -7,10 +7,11 @@ use std::{
use log::{info, warn};
use crate::vpn_utils::{check_executable, find_vpnc_script};
use crate::{HipSource, ffi};
use crate::{HipSource, NetworkConfiguration, NetworkConfigurationHandler, ffi};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
type OnTunnelCallback = RwLock<Option<Arc<dyn Fn(crate::tunnel::Event) + Send + Sync>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
@@ -72,6 +73,7 @@ struct Cancellation {
struct CancellationState {
requested: bool,
command_fd: Option<i32>,
statistics_pending: bool,
}
impl Cancellation {
@@ -82,7 +84,31 @@ impl Cancellation {
}
fn detach(&self) {
self.state.lock().unwrap().command_fd = None;
let mut state = self.state.lock().unwrap();
state.command_fd = None;
state.statistics_pending = false;
}
fn request_statistics(&self) -> io::Result<bool> {
let mut state = self.state.lock().unwrap();
if state.requested || state.statistics_pending {
return Ok(false);
}
let Some(fd) = state.command_fd else {
return Ok(false);
};
match ffi::write_statistics(fd) {
Ok(()) => {
state.statistics_pending = true;
Ok(true)
}
Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(false),
Err(error) => Err(error),
}
}
fn statistics_received(&self) {
self.state.lock().unwrap().statistics_pending = false;
}
fn cancel(&self) -> io::Result<()> {
@@ -110,7 +136,8 @@ pub struct Vpn {
host_id: Option<CString>,
local_hostname: Option<CString>,
script: CString,
script: Option<CString>,
pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
interface: Option<CString>,
script_tun: bool,
@@ -131,9 +158,45 @@ pub struct Vpn {
callback: OnConnectedCallback,
hip_report_callback: OnHipReportCallback,
tunnel_callback: OnTunnelCallback,
observed_transport: Mutex<Option<crate::tunnel::Transport>>,
}
impl Vpn {
/// Install before `connect`. The observer runs synchronously on the native
/// connection thread and must return promptly. Clear it after joining connect.
pub fn set_tunnel_observer(&self, callback: impl Fn(crate::tunnel::Event) + Send + Sync + 'static) {
*self.tunnel_callback.write().unwrap() = Some(Arc::new(callback));
}
pub fn clear_tunnel_observer(&self) {
*self.tunnel_callback.write().unwrap() = None;
}
/// Signal a nonblocking statistics request. False means no command was issued
/// because collection was coalesced, unavailable, cancelled, or the pipe full.
pub fn request_statistics(&self) -> io::Result<bool> {
self.cancellation.request_statistics()
}
pub(crate) fn statistics_received(&self) {
self.cancellation.statistics_received();
}
pub(crate) fn on_tunnel_event(&self, event: crate::tunnel::Event) {
if let crate::tunnel::Event::Transport(transport) = &event {
let mut previous = self.observed_transport.lock().unwrap();
if previous.as_ref() == Some(transport) {
return;
}
*previous = Some(*transport);
}
let callback = self.tunnel_callback.read().unwrap().clone();
if let Some(callback) = callback {
callback(event);
}
}
pub fn builder(server: &str, cookie: &str) -> VpnBuilder {
VpnBuilder::new(server, cookie)
}
@@ -217,7 +280,11 @@ impl Vpn {
host_id: Self::option_to_ptr(&self.host_id),
local_hostname: Self::option_to_ptr(&self.local_hostname),
script: self.script.as_ptr(),
script: Self::option_to_ptr(&self.script),
configure_network: self
.network_configuration_handler
.as_ref()
.map(|_| ffi::configure_network as _),
interface: Self::option_to_ptr(&self.interface),
script_tun: self.script_tun as u32,
@@ -275,6 +342,7 @@ pub struct VpnBuilder {
server: String,
cookie: String,
script: Option<String>,
network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
script_is_path: bool,
interface: Option<String>,
script_tun: bool,
@@ -307,6 +375,7 @@ impl VpnBuilder {
server: server.to_string(),
cookie: cookie.to_string(),
script: None,
network_configuration_handler: None,
script_is_path: false,
interface: None,
script_tun: false,
@@ -345,6 +414,17 @@ impl VpnBuilder {
self
}
/// Handle network configuration synchronously on OpenConnect's connection thread.
/// Replaces the external configuration script, not the tunnel device or packet I/O.
/// The handler receives a snapshot; it must not mutate the process environment.
pub fn network_configuration_handler(
mut self,
handler: impl Fn(&NetworkConfiguration) -> io::Result<()> + Send + Sync + 'static,
) -> Self {
self.network_configuration_handler = Some(Arc::new(handler));
self
}
pub fn interface<T: Into<Option<String>>>(mut self, interface: T) -> Self {
self.interface = interface.into();
self
@@ -435,8 +515,16 @@ impl VpnBuilder {
self
}
fn determine_script(&self) -> Result<String, VpnError> {
match &self.script {
fn resolve_script(&self) -> Result<Option<CString>, VpnError> {
if self.network_configuration_handler.is_some() {
if self.script.is_some() || self.script_tun {
return Err(VpnError::new(
"Network configuration handler conflicts with script options".into(),
));
}
return Ok(None);
}
let script = match &self.script {
Some(script) => {
if self.script_is_path && !std::path::Path::new(script).exists() {
return Err(VpnError::new(format!("VPN script does not exist: {script}")));
@@ -445,16 +533,17 @@ impl VpnBuilder {
Ok(script.clone())
}
None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))),
}
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?;
}?;
let script = if self.script_is_path || self.script.is_none() {
shell_quote_path(&script)
} else {
script
};
Ok(Some(Self::to_cstring(&script)))
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.resolve_script()?;
let user_agent = self.user_agent.unwrap_or_default();
let os = self.os.unwrap_or("linux".to_string());
@@ -471,7 +560,8 @@ impl VpnBuilder {
host_id: self.host_id.as_deref().map(Self::to_cstring),
local_hostname: self.local_hostname.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script),
script,
network_configuration_handler: self.network_configuration_handler,
interface: self.interface.as_deref().map(Self::to_cstring),
script_tun: self.script_tun,
@@ -491,6 +581,8 @@ impl VpnBuilder {
callback: Default::default(),
hip_report_callback: Default::default(),
tunnel_callback: Default::default(),
observed_transport: Default::default(),
})
}
@@ -525,7 +617,7 @@ mod tests {
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), command);
assert_eq!(vpn.script.as_ref().unwrap().to_str().unwrap(), command);
}
#[test]
@@ -535,7 +627,7 @@ mod tests {
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), "'/bin/sh'");
assert_eq!(vpn.script.as_ref().unwrap().to_str().unwrap(), "'/bin/sh'");
}
#[test]
@@ -598,7 +690,8 @@ mod tests {
client_version: None,
host_id: Some(CString::new("profile-host-id").unwrap()),
local_hostname: None,
script: CString::new("/bin/true").unwrap(),
script: Some(CString::new("/bin/true").unwrap()),
network_configuration_handler: None,
interface: None,
script_tun: false,
certificate: None,
@@ -614,6 +707,8 @@ mod tests {
no_xmlpost: false,
callback: Default::default(),
hip_report_callback: Default::default(),
tunnel_callback: Default::default(),
observed_transport: Default::default(),
};
let options = vpn.build_connect_options();
@@ -661,23 +756,38 @@ mod tests {
ffi::{c_int, c_void},
fs::File,
os::fd::AsFd,
os::unix::process::CommandExt,
process::{Command, Stdio},
};
const CHILD: &str = "OPENCONNECT_TEST_PIPE_FAILURE";
if std::env::var_os(CHILD).is_none() {
// Limit descriptors only in a subprocess, leaving the test runner untouched.
let output = Command::new("sh")
let mut child = Command::new(std::env::current_exe().unwrap());
child
.args([
"-c",
"ulimit -n 64 && exec \"$1\" --exact vpn::tests::command_pipe_failure_preserves_stdin --nocapture",
"sh",
"--exact",
"vpn::tests::command_pipe_failure_preserves_stdin",
"--nocapture",
])
.arg(std::env::current_exe().unwrap())
.env(CHILD, "1")
.stdin(Stdio::null())
.output()
.unwrap();
.stdin(Stdio::null());
// Launch directly: system shells can strip the dynamic-library search
// environment required by the replaceable macOS OpenConnect library.
unsafe {
child.pre_exec(|| {
let limit = libc::rlimit {
rlim_cur: 64,
rlim_max: 64,
};
if libc::setrlimit(libc::RLIMIT_NOFILE, &limit) == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
});
}
let output = child.output().unwrap();
assert!(
output.status.success(),
"{}\n{}",
@@ -812,4 +922,54 @@ mod tests {
cancellation.cancel().unwrap();
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[test]
fn statistics_are_coalesced_and_fenced_by_cancellation_and_detach() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
};
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!cancellation.request_statistics().unwrap());
assert!(!cancellation.attach(writer.as_raw_fd()));
assert!(cancellation.request_statistics().unwrap());
assert!(!cancellation.request_statistics().unwrap());
let mut command = [0];
reader.read_exact(&mut command).unwrap();
assert_eq!(command, [b's']);
cancellation.statistics_received();
assert!(cancellation.request_statistics().unwrap());
reader.read_exact(&mut command).unwrap();
cancellation.cancel().unwrap();
assert!(!cancellation.request_statistics().unwrap());
reader.read_exact(&mut command).unwrap();
assert_eq!(command, [b'x']);
cancellation.detach();
assert!(!cancellation.state.lock().unwrap().statistics_pending);
assert!(!cancellation.request_statistics().unwrap());
assert_eq!(reader.read(&mut command).unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[test]
fn full_command_pipe_does_not_latch_a_statistics_request() {
use std::{
io::{Read, Write},
os::{fd::AsRawFd, unix::net::UnixStream},
};
let cancellation = Cancellation::default();
let (mut reader, mut writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
writer.set_nonblocking(true).unwrap();
while writer.write(&[0; 1024]).is_ok() {}
while writer.write(&[0]).is_ok() {}
assert!(!cancellation.attach(writer.as_raw_fd()));
assert!(!cancellation.request_statistics().unwrap());
assert!(!cancellation.state.lock().unwrap().statistics_pending);
let mut bytes = [0; 4096];
while reader.read(&mut bytes).is_ok() {}
assert!(cancellation.request_statistics().unwrap());
cancellation.detach();
}
}
+202
View File
@@ -0,0 +1,202 @@
/* Exercise the production parser and probe dispatch, inspecting packets at the
* encryption boundary. No VPN server, privileged networking, or real keys. */
#define construct_esp_packet inspect_esp_packet
#define openconnect_open_https fixture_open_https
#include "gpst.c"
#undef construct_esp_packet
#undef openconnect_open_https
#include "gpst_nlb.c"
#include <assert.h>
static const char *expected_destination;
static int packets_inspected;
static enum openconnect_tunnel_event observed_events[4];
static int observed_count;
static int ssl_response_valid;
int fixture_open_https(struct openconnect_info *vpninfo)
{
return 0;
}
static int fixture_ssl_write(struct openconnect_info *vpninfo, char *buf, size_t len)
{
return len;
}
static int fixture_ssl_read(struct openconnect_info *vpninfo, char *buf, size_t len)
{
const char *response = ssl_response_valid ? "START_TUNNEL" : "invalid";
assert(len >= strlen(response));
memcpy(buf, response, strlen(response));
return strlen(response);
}
static void observe_transport(void *data, enum openconnect_tunnel_event event)
{
assert(observed_count < 4);
observed_events[observed_count++] = event;
}
static void progress(void *data, int level, const char *format, ...)
{
if (level > PRG_INFO)
return;
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
}
int inspect_esp_packet(struct openconnect_info *vpninfo, struct pkt *pkt, uint8_t next_header)
{
struct in_addr destination;
struct ip *ip = (void *)pkt->data;
struct icmp *icmp = (void *)(pkt->data + sizeof(*ip));
const unsigned char *payload;
size_t payload_len;
assert(inet_pton(AF_INET, expected_destination, &destination) == 1);
assert(next_header == IPPROTO_IPIP);
assert(ip->ip_v == 4 && ip->ip_p == IPPROTO_ICMP);
assert(ip->ip_dst.s_addr == destination.s_addr);
assert(ip->ip_src.s_addr == inet_addr("10.253.0.120"));
assert(icmp->icmp_type == ICMP_ECHO);
if (vpninfo->gp_nlb.enabled)
payload = gpst_nlb_probe_payload(&payload_len);
else {
payload = (const unsigned char *)magic_ping_payload_gcm;
payload_len = sizeof(magic_ping_payload_gcm);
}
assert(pkt->len == sizeof(*ip) + ICMP_MINLEN + payload_len);
assert(!memcmp(pkt->data + sizeof(*ip) + ICMP_MINLEN, payload, payload_len));
packets_inspected++;
/* Send a placeholder datagram over a local socket pair. */
return 1;
}
int main(int argc, char **argv)
{
static const char key[] =
"000000000000000000000000000000000000000000000000000000000000000000000000";
static const char nlb_config[] =
"<hs-key><bits>256</bits><val>"
"0000000000000000000000000000000000000000000000000000000000000000"
"</val></hs-key><enc-hs-key>fixture</enc-hs-key>"
"<tunnel-opaque><val>fixture</val><valid-period>3600</valid-period></tunnel-opaque>";
const char *gateway = "0.0.0.0", *default_gateway = "192.0.2.10";
char xml[4096], gateway_xml[128];
struct sockaddr_in peer = { .sin_family = AF_INET };
struct openconnect_info *vpninfo;
xmlDoc *doc;
int sockets[2], nlb, invalid, length;
assert(argc == 2);
nlb = !strncmp(argv[1], "nlb-", 4);
invalid = !strcmp(argv[1], "regular-invalid") || !strcmp(argv[1], "regular-missing");
if (!strcmp(argv[1], "regular-address") || !strcmp(argv[1], "nlb-address"))
gateway = "192.0.2.1";
else if (!strcmp(argv[1], "regular-invalid"))
gateway = "invalid";
if (!strcmp(argv[1], "nlb-client-vip"))
default_gateway = "0.0.0.0";
if (!strcmp(argv[1], "regular-missing"))
gateway_xml[0] = 0;
else
snprintf(gateway_xml, sizeof(gateway_xml), "<gw-address>%s</gw-address>", gateway);
length = snprintf(xml, sizeof(xml),
"<response>%s<ip-address>10.253.0.120</ip-address>"
"<default-gateway>%s</default-gateway><ipsec>"
"<udp-port>4501</udp-port><enc-algo>aes-256-gcm</enc-algo><hmac-algo>sha1</hmac-algo>"
"<c2s-spi>0x12345678</c2s-spi><s2c-spi>0x87654321</s2c-spi>"
"<ekey-c2s><bits>288</bits><val>%s</val></ekey-c2s>"
"<ekey-s2c><bits>288</bits><val>%s</val></ekey-s2c>"
"</ipsec>%s</response>", gateway_xml, default_gateway, key, key, nlb ? nlb_config : "");
assert(length > 0 && length < sizeof(xml));
doc = xmlReadMemory(xml, length, "config.xml", NULL, XML_PARSE_NONET);
assert(doc);
vpninfo = openconnect_vpninfo_new("ESP gateway test", NULL, NULL, NULL, progress, NULL);
assert(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
vpninfo->peer_addr = malloc(sizeof(peer));
assert(vpninfo->peer_addr);
memcpy(vpninfo->peer_addr, &peer, sizeof(peer));
assert(!gpst_parse_config_xml(vpninfo, xmlDocGetRootElement(doc), NULL));
xmlFreeDoc(doc);
assert(!!vpninfo->gp_nlb.enabled == nlb);
if (invalid) {
assert(!vpninfo->esp_magic_af);
assert(!vpninfo->delay_tunnel_reason);
openconnect_vpninfo_free(vpninfo);
return 0;
}
assert(vpninfo->esp_magic_af == AF_INET);
assert(!memcmp(vpninfo->esp_magic, &(struct in_addr){ .s_addr = inet_addr(gateway) }, 4));
assert(vpninfo->delay_tunnel_reason);
assert(vpninfo->dtls_state == DTLS_SECRET);
assert(!socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets));
vpninfo->dtls_fd = sockets[0];
if (nlb) {
const char *vip = gateway;
if (!strcmp(gateway, "0.0.0.0")) {
vip = default_gateway;
if (!strcmp(default_gateway, "0.0.0.0"))
vip = "10.253.0.120";
}
assert(vpninfo->gp_nlb.tunnel_vip);
assert(!strcmp(vpninfo->gp_nlb.tunnel_vip, vip));
assert(!gpst_nlb_prepare(vpninfo));
assert(vpninfo->gp_nlb.control_state == GP_NLB_CONTROL_PENDING);
assert(!gpst_nlb_control_ready(vpninfo));
assert(!memcmp(vpninfo->esp_magic, &(struct in_addr){ .s_addr = inet_addr(vip) }, 4));
/* Model completed tunnel control: keepalives must use the real inner
* gateway, not the zero probe address or the initial virtual IP. */
vpninfo->gp_nlb.control_state = GP_NLB_CONTROL_READY;
vpninfo->gp_nlb.inner_gw_ip = strdup("192.0.2.20");
expected_destination = "192.0.2.20";
assert(!gpst_esp_send_probes(vpninfo));
assert(packets_inspected == 3);
assert(vpninfo->gp_nlb.keepalive_sent);
free(vpninfo->gp_nlb.inner_gw_ip);
vpninfo->gp_nlb.inner_gw_ip = NULL;
expected_destination = vip;
assert(!gpst_nlb_send_esp_keepalive(vpninfo));
assert(packets_inspected == 4);
} else {
assert(!vpninfo->gp_nlb.tunnel_vip || strcmp(vpninfo->gp_nlb.tunnel_vip, "0.0.0.0"));
expected_destination = gateway;
assert(!gpst_esp_send_probes(vpninfo));
assert(packets_inspected == 1);
/* Configuration/probes alone do not advertise ESP. Exercise the actual
* GP activation and ESP shutdown paths rather than synthesizing events. */
int timeout = 1000;
openconnect_set_tunnel_handler(vpninfo, observe_transport);
assert(observed_count == 0);
vpninfo->dtls_state = DTLS_CONNECTED;
memset(&vpninfo->ssl_times, 0, sizeof(vpninfo->ssl_times));
vpninfo->trojan_interval = 0;
assert(!gpst_mainloop(vpninfo, &timeout, 0));
assert(vpninfo->dtls_state == DTLS_ESTABLISHED);
assert(observed_count == 1 && observed_events[0] == OC_TUNNEL_IPSEC_ESP);
esp_close(vpninfo);
assert(observed_count == 2 && observed_events[1] == OC_TUNNEL_UNAVAILABLE);
/* Repeated shutdown of an inactive transport cannot claim another loss. */
esp_close(vpninfo);
assert(observed_count == 2);
/* Replace only HTTPS I/O: run the actual SSL response acceptance path. */
vpninfo->dtls_state = DTLS_DISABLED;
vpninfo->ssl_read = fixture_ssl_read;
vpninfo->ssl_write = fixture_ssl_write;
openconnect_set_cookie(vpninfo, "user=test&authcookie=fixture");
free(vpninfo->urlpath);
vpninfo->urlpath = strdup("ssl-tunnel-connect.sslvpn");
assert(gpst_connect(vpninfo) == -EINVAL);
assert(observed_count == 2);
ssl_response_valid = 1;
assert(!gpst_connect(vpninfo));
assert(observed_count == 3 && observed_events[2] == OC_TUNNEL_SSL_TLS);
}
close(sockets[1]);
openconnect_vpninfo_free(vpninfo);
return 0;
}
+60
View File
@@ -0,0 +1,60 @@
use std::{fs, path::PathBuf, process::Command};
#[test]
fn c_esp_gateway_configuration_and_probes() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
let directory = tempfile::tempdir().unwrap();
let executable = directory.path().join("esp-gateway");
let mut packages = vec!["libxml-2.0", "gnutls"];
if fs::read_to_string(build.join("config.h"))
.unwrap()
.contains("#define HAVE_LZ4 ")
{
packages.push("liblz4");
}
let flags = Command::new("pkg-config")
.arg("--cflags")
.args(packages)
.output()
.unwrap();
assert!(flags.status.success(), "{}", String::from_utf8_lossy(&flags.stderr));
let output = Command::new(build.join("libtool"))
.args(["--mode=link", "cc"])
.arg(manifest.join("tests/esp_gateway.c"))
.arg("-I")
.arg(&build)
.arg("-I")
.arg(&source)
.arg("-I")
.arg(source.join("json"))
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
.arg(build.join("libopenconnect.la"))
.arg("-o")
.arg(&executable)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
for case in [
"regular-zero",
"regular-address",
"regular-invalid",
"regular-missing",
"nlb-zero",
"nlb-address",
"nlb-client-vip",
] {
let output = Command::new(build.join("libtool"))
.arg("--mode=execute")
.arg(&executable)
.arg(case)
.output()
.unwrap();
assert!(
output.status.success(),
"{case}: {}",
String::from_utf8_lossy(&output.stderr)
);
}
}
+1 -5
View File
@@ -34,11 +34,7 @@ fn c_protocol_submits_initial_periodic_and_reconnect_reports() {
fs::create_dir(&directory.0).unwrap();
let executable = directory.0.join("hip-protocol");
let flags = Command::new("pkg-config")
.args([
"--cflags",
"libxml-2.0",
if cfg!(target_os = "macos") { "openssl" } else { "gnutls" },
])
.args(["--cflags", "libxml-2.0", "gnutls"])
.output()
.unwrap();
assert!(flags.status.success());
@@ -0,0 +1,203 @@
/* No privileged networking: exercise the actual configuration dispatcher. */
#include <config.h>
#include "openconnect-internal.h"
#include <assert.h>
struct state {
pid_t parent;
const char *reason;
int calls;
int result;
const char *failure_reason;
const char **expected_reasons;
int expected_count;
int tcp_connections;
int reconnection_notifications;
int reconnect_started;
};
static int configure(void *data, const char *reason, const struct oc_vpn_option *env)
{
struct state *state = data;
const struct oc_vpn_option *option;
int found = 0;
assert(getpid() == state->parent);
if (state->expected_reasons) {
assert(state->calls < state->expected_count);
assert(!strcmp(reason, state->expected_reasons[state->calls]));
} else {
assert(!strcmp(reason, state->reason));
}
for (option = env; option; option = option->next) {
if (!strcmp(option->option, "GP_TEST_CONFIG")) {
assert(!strcmp(option->value, "child value"));
found = 1;
}
}
assert(found);
assert(!strcmp(getenv("GP_TEST_CONFIG"), "parent value"));
state->calls++;
return !state->failure_reason || !strcmp(reason, state->failure_reason) ? state->result : 0;
}
static void progress(void *data, int level, const char *format, ...) {}
/* The production library.c is compiled with os_setup_tun redirected here.
* All setup, configuration dispatch, attachment, and cleanup code stays real. */
static int device_fd = -1;
static int device_creations;
intptr_t test_os_setup_tun(struct openconnect_info *vpninfo)
{
device_creations++;
assert(device_fd >= 0);
free(vpninfo->ifname);
vpninfo->ifname = strdup("gp-test-tun");
assert(vpninfo->ifname);
return device_fd;
}
static struct openconnect_info *new_vpn(struct state *state)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("network callback test", NULL, NULL, NULL, progress, state);
assert(vpninfo);
script_setenv(vpninfo, "GP_TEST_CONFIG", "child value", 0, 0);
openconnect_set_configure_tun_handler(vpninfo, state, configure);
return vpninfo;
}
static void connect_failure_rolls_back(void)
{
const char *expected[] = { "pre-init", "connect", "disconnect" };
struct state state = {
.parent = getpid(), .result = -EPERM, .failure_reason = "connect",
.expected_reasons = expected, .expected_count = 3,
};
struct openconnect_info *vpninfo = new_vpn(&state);
int fds[2];
assert(!pipe(fds));
device_fd = fds[0];
assert(openconnect_setup_tun_device(vpninfo, NULL, NULL) == -EPERM);
assert(device_creations == 1);
assert(state.calls == 3);
assert(vpninfo->tun_fd == -1);
assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
close(fds[1]);
openconnect_vpninfo_free(vpninfo);
/* Freeing an already rolled-back connection must not disconnect again. */
assert(state.calls == 3);
device_fd = -1;
}
static int tcp_connect(struct openconnect_info *vpninfo)
{
struct state *state = vpninfo->cbdata;
state->tcp_connections++;
return 0;
}
static void reconnected(void *data)
{
struct state *state = data;
state->reconnection_notifications++;
}
static void tunnel_event(void *data, enum openconnect_tunnel_event event)
{
struct state *state = data;
assert(event == OC_TUNNEL_RECONNECTING);
state->reconnect_started++;
/* Start observation precedes configuration callbacks and new TCP work. */
assert(state->calls == 0);
}
static void reconnect_refusal_propagates(void)
{
const char *expected[] = { "attempt-reconnect", "reconnect" };
struct state state = {
.parent = getpid(), .result = -EPERM, .failure_reason = "attempt-reconnect",
.expected_reasons = expected, .expected_count = 1,
};
struct openconnect_info *vpninfo = new_vpn(&state);
const struct vpn_proto *original = vpninfo->proto;
struct vpn_proto protocol = *original;
int fds[2];
assert(!pipe(fds));
vpninfo->tun_fd = fds[0];
protocol.tcp_connect = tcp_connect;
protocol.proto = PROTO_GPST;
vpninfo->proto = &protocol;
openconnect_set_reconnected_handler(vpninfo, reconnected);
openconnect_set_tunnel_handler(vpninfo, tunnel_event);
/* Attempt refusal prevents even the protocol's reconnect request. */
assert(ssl_reconnect(vpninfo) == -EPERM);
assert(state.calls == 1 && state.tcp_connections == 0);
assert(state.reconnection_notifications == 0);
/* Post-reconnect refusal prevents the successful reconnection observer. */
state.calls = 0;
state.expected_count = 2;
state.failure_reason = "reconnect";
state.result = -EACCES;
assert(ssl_reconnect(vpninfo) == -EACCES);
assert(state.calls == 2 && state.tcp_connections == 1);
assert(state.reconnection_notifications == 0);
state.calls = 0;
state.result = 0;
assert(!ssl_reconnect(vpninfo));
assert(state.calls == 2 && state.tcp_connections == 2);
assert(state.reconnection_notifications == 1);
assert(state.reconnect_started == 3);
state.expected_reasons = NULL;
state.reason = "disconnect";
os_shutdown_tun(vpninfo);
assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
close(fds[1]);
vpninfo->proto = original;
openconnect_vpninfo_free(vpninfo);
}
int main(void)
{
const char *reasons[] = { "pre-init", "connect", "attempt-reconnect", "reconnect", "disconnect" };
struct state state = { .parent = getpid() };
struct openconnect_info *vpninfo = new_vpn(&state);
int fds[2], i;
assert(vpninfo);
assert(!setenv("GP_TEST_CONFIG", "parent value", 1));
script_setenv(vpninfo, "GP_TEST_CONFIG", "child value", 0, 0);
openconnect_set_configure_tun_handler(vpninfo, &state, configure);
/* A callback works without an external script and executes before fork. */
assert(!vpninfo->vpnc_script);
for (i = 0; i < 5; i++) {
state.reason = reasons[i];
assert(!script_config_tun(vpninfo, reasons[i]));
}
assert(state.calls == 5);
state.result = -EPERM;
state.reason = "pre-init";
/* Refusal propagates before attempting to create an OS tunnel device. */
assert(openconnect_setup_tun_device(vpninfo, NULL, NULL) == -EPERM);
assert(vpninfo->tun_fd == -1);
assert(device_creations == 0);
state.result = 0;
state.reason = "disconnect";
/* The callback path owns the created descriptor even with no script path. */
assert(!pipe(fds));
vpninfo->tun_fd = fds[0];
os_shutdown_tun(vpninfo);
assert(vpninfo->tun_fd == -1);
assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
close(fds[1]);
assert(state.calls == 7);
openconnect_set_configure_tun_handler(vpninfo, NULL, NULL);
assert(!script_config_tun(vpninfo, "connect"));
assert(state.calls == 7);
openconnect_vpninfo_free(vpninfo);
connect_failure_rolls_back();
reconnect_refusal_propagates();
return 0;
}
@@ -0,0 +1,49 @@
use std::{fs, path::PathBuf, process::Command};
#[test]
fn c_network_configuration_lifecycle_and_failure_paths() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
let directory = std::env::temp_dir().join(format!("gp-network-configuration-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let executable = directory.join("network-configuration");
let flags = Command::new("pkg-config")
.args(["--cflags", "libxml-2.0", "gnutls"])
.output()
.unwrap();
assert!(flags.status.success());
let output = Command::new(build.join("libtool"))
.args(["--mode=link", "cc"])
.arg(manifest.join("tests/network_configuration.c"))
// Compile the production setup implementation with only OS device creation
// replaced, so rollback is exercised without privileges or a real TUN.
.arg(source.join("library.c"))
.arg("-Dos_setup_tun=test_os_setup_tun")
.arg("-I")
.arg(&build)
.arg("-I")
.arg(&source)
.arg("-I")
.arg(source.join("json"))
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
.arg(build.join("libopenconnect.la"))
.arg("-o")
.arg(&executable)
.output()
.unwrap();
assert!(
output.status.success(),
"{}: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
let output = Command::new(&executable).output().unwrap();
fs::remove_dir_all(&directory).unwrap();
assert!(
output.status.success(),
"{}: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
}
+154
View File
@@ -0,0 +1,154 @@
/* Exercise the production OpenConnect TLS client against a local GnuTLS peer. */
#include <config.h>
#include "openconnect-internal.h"
#include <gnutls/gnutls.h>
#include <assert.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
struct peer {
int listener, legacy, expect_rejection, handshake, renegotiation, require_identity;
gnutls_certificate_credentials_t credentials;
};
struct policy { int accept, calls, unsafe_renegotiation_denied; };
static void progress(void *data, int level, const char *format, ...)
{
va_list args;
char message[2048];
struct policy *policy = data;
if (level > PRG_DEBUG) return;
va_start(args, format);
vsnprintf(message, sizeof(message), format, args);
va_end(args);
fputs(message, stderr);
if (strstr(message, gnutls_strerror(GNUTLS_E_UNSAFE_RENEGOTIATION_DENIED)))
policy->unsafe_renegotiation_denied = 1;
}
static int certificate_policy(void *data, const char *reason)
{
struct policy *policy = data;
assert(reason && *reason);
policy->calls++;
return policy->accept ? 0 : -EINVAL;
}
static void *serve(void *data)
{
struct peer *peer = data;
gnutls_session_t session;
int fd = accept(peer->listener, NULL, NULL);
struct timeval timeout = { .tv_sec = 5 };
assert(fd >= 0);
assert(!setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)));
assert(!setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)));
assert(!gnutls_init(&session, GNUTLS_SERVER));
assert(!gnutls_priority_set_direct(session, peer->legacy
? "NORMAL:-VERS-ALL:+VERS-TLS1.2:%DISABLE_SAFE_RENEGOTIATION"
: "NORMAL:-VERS-ALL:+VERS-TLS1.2", NULL));
assert(!gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, peer->credentials));
if (peer->require_identity)
gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUIRE);
gnutls_transport_set_int(session, fd);
gnutls_handshake_set_timeout(session, 5000);
peer->handshake = gnutls_handshake(session);
if (!peer->expect_rejection) {
unsigned int status, count;
assert(!peer->handshake);
if (peer->require_identity) {
assert(gnutls_certificate_get_peers(session, &count) && count > 0);
assert(!gnutls_certificate_verify_peers2(session, &status));
assert(!status);
}
assert(gnutls_safe_renegotiation_status(session) == !peer->legacy);
assert(gnutls_record_send(session, "OK", 2) == 2);
if (peer->legacy) {
assert(!gnutls_rehandshake(session));
peer->renegotiation = gnutls_handshake(session);
}
}
gnutls_deinit(session);
close(fd);
return NULL;
}
static void check(const char *cert, const char *key, const char *ca,
int legacy, int trusted, int accept_certificate, const char *identity, const char *identity_key)
{
struct peer peer = { .legacy = legacy, .expect_rejection = !trusted && !accept_certificate,
.require_identity = identity != NULL };
struct policy policy = { .accept = accept_certificate };
struct sockaddr_in address = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
socklen_t address_length = sizeof(address);
pthread_t thread;
char url[128], record[16];
int result;
struct openconnect_info *client;
assert(!gnutls_certificate_allocate_credentials(&peer.credentials));
assert(!gnutls_certificate_set_x509_key_file(peer.credentials, cert, key, GNUTLS_X509_FMT_PEM));
if (peer.require_identity)
assert(gnutls_certificate_set_x509_trust_file(peer.credentials, ca, GNUTLS_X509_FMT_PEM) > 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, &address_length));
assert(!listen(peer.listener, 1));
assert(!pthread_create(&thread, NULL, serve, &peer));
client = openconnect_vpninfo_new("TLS backend regression", certificate_policy, NULL, NULL, progress, &policy);
assert(client);
/* localhost matches the fixture certificate; no external DNS or connection. */
snprintf(url, sizeof(url), "https://localhost:%u/", ntohs(address.sin_port));
assert(!openconnect_parse_url(client, url));
if (trusted) assert(!openconnect_set_cafile(client, ca));
if (identity) assert(!openconnect_set_client_cert(client, identity, identity_key));
result = openconnect_open_https(client);
if (peer.expect_rejection) {
assert(result < 0);
assert(policy.calls == 1);
} else {
assert(!result);
assert(policy.calls == !trusted);
assert(client->ssl_read(client, record, sizeof(record)) == 2);
assert(!memcmp(record, "OK", 2));
if (legacy) {
assert(client->ssl_read(client, record, sizeof(record)) < 0);
/* OpenConnect translates backend failures to -EIO. Its progress
* callback preserves the specific GnuTLS failure; require that
* reason so a timeout/disconnect cannot pass as policy refusal. */
assert(policy.unsafe_renegotiation_denied);
}
}
openconnect_vpninfo_free(client);
assert(!pthread_join(thread, NULL));
if (legacy) {
assert(peer.renegotiation < 0);
}
close(peer.listener);
gnutls_certificate_free_credentials(peer.credentials);
}
int main(int argc, char **argv)
{
assert(argc == 6);
signal(SIGPIPE, SIG_IGN);
assert(!openconnect_init_ssl());
#ifdef __APPLE__
/* Read-only check of the source-built library's native Keychain integration.
* Local fixture trust is tested separately, without changing OS trust settings. */
{
gnutls_certificate_credentials_t system;
assert(!gnutls_certificate_allocate_credentials(&system));
assert(gnutls_certificate_set_x509_system_trust(system) > 0);
gnutls_certificate_free_credentials(system);
}
#endif
check(argv[1], argv[2], argv[3], 0, 1, 0, NULL, NULL);
check(argv[1], argv[2], argv[3], 0, 0, 0, NULL, NULL);
check(argv[1], argv[2], argv[3], 0, 0, 1, NULL, NULL);
check(argv[1], argv[2], argv[3], 1, 1, 0, NULL, NULL);
check(argv[1], argv[2], argv[3], 0, 1, 0, argv[4], argv[5]);
puts("OpenConnect: trusted TLS, certificate rejection/acceptance, legacy initial handshake, unsafe renegotiation refusal, mutual TLS passed");
return 0;
}
+90
View File
@@ -0,0 +1,90 @@
use std::{
fs,
os::unix::process::CommandExt,
path::{Path, PathBuf},
process::{Child, Command},
time::{Duration, Instant},
};
struct TestDirectory(PathBuf);
impl Drop for TestDirectory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
unsafe { libc::kill(-(self.0.id() as i32), libc::SIGKILL) };
let _ = self.0.wait();
}
}
fn run_bounded(command: &mut Command, log: &Path) {
let output = fs::File::create(log).unwrap();
let mut child = ChildGuard(
command
.process_group(0)
.stdout(output.try_clone().unwrap())
.stderr(output)
.spawn()
.unwrap(),
);
let deadline = Instant::now() + Duration::from_secs(45);
loop {
if let Some(status) = child.0.try_wait().unwrap() {
assert!(status.success(), "{status}: {}", fs::read_to_string(log).unwrap());
return;
}
assert!(
Instant::now() < deadline,
"TLS test timed out: {}",
fs::read_to_string(log).unwrap()
);
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn openconnect_certificate_policy_and_legacy_renegotiation() {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
let directory = TestDirectory(std::env::temp_dir().join(format!("gp-tls-backend-{}", std::process::id())));
fs::create_dir(&directory.0).unwrap();
let executable = directory.0.join("tls-backend");
let flags = Command::new("pkg-config")
.args(["--cflags", "--libs", "libxml-2.0", "gnutls"])
.output()
.unwrap();
assert!(flags.status.success(), "{}", String::from_utf8_lossy(&flags.stderr));
run_bounded(
Command::new(build.join("libtool"))
.args(["--mode=link", "cc", "-pthread"])
.arg(manifest.join("tests/tls_backend.c"))
.arg("-I")
.arg(&build)
.arg("-I")
.arg(&source)
.arg("-I")
.arg(source.join("json"))
.arg(build.join("libopenconnect.la"))
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
.arg("-o")
.arg(&executable),
&directory.0.join("compile.log"),
);
let certificates = manifest.join("deps/openconnect/tests/certs");
run_bounded(
Command::new(build.join("libtool"))
.arg("--mode=execute")
.arg(executable)
.arg(certificates.join("server-cert.pem"))
.arg(certificates.join("server-key.pem"))
.arg(certificates.join("ca.pem"))
.arg(certificates.join("user-cert.pem"))
.arg(certificates.join("user-key-pkcs1.pem")),
&directory.0.join("runtime.log"),
);
}