feat: prepare 3.0.0 release

This commit is contained in:
Kevin Yue committed 2026-10-09 18:21:44 +08:00
1 parent e98fd7894a
commit b7b708e9cd
252 files changed
+26210 -7457

No files matched your search

+513
View File
@@ -0,0 +1,513 @@
use crate::{HipControl, HipRequest, HipScript, HipSource, Vpn};
use std::{
ffi::{CString, c_char, c_int, c_void},
io,
marker::PhantomData,
panic::{AssertUnwindSafe, catch_unwind},
};
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_collect_hip_report(
script: *const HipScriptRaw,
request: *const HipRequestRaw,
control: *const HipControlRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int;
}
#[repr(C)]
pub(crate) struct HipRequestRaw {
cookie: *const c_char,
client_ip: *const c_char,
client_ipv6: *const c_char,
md5: *const c_char,
client_version: *const c_char,
client_os: *const c_char,
os_version: *const c_char,
host_id: *const c_char,
local_hostname: *const c_char,
}
#[repr(C)]
pub(crate) struct HipControlRaw {
pub data: *mut c_void,
pub check: unsafe extern "C" fn(*mut c_void) -> c_int,
}
pub(crate) type HipGenerateFn =
extern "C" fn(*mut c_void, *const HipRequestRaw, *const HipControlRaw, *mut c_char, usize, *mut usize) -> c_int;
#[repr(C)]
#[derive(Debug)]
pub(crate) struct HipScriptRaw {
pub path: *const c_char,
pub uid: u32,
pub uid_present: c_int,
pub validation_data: *mut c_void,
pub validate: Option<extern "C" fn(*mut c_void, *const HipControlRaw) -> c_int>,
pub environment: *const *const c_char,
pub cwd: *const c_char,
}
impl Default for HipScriptRaw {
fn default() -> Self {
Self {
path: std::ptr::null(),
uid: 0,
uid_present: 0,
validation_data: std::ptr::null_mut(),
validate: None,
environment: std::ptr::null(),
cwd: std::ptr::null(),
}
}
}
impl HipScriptRaw {
pub fn from_script(script: &HipScript) -> Self {
Self {
path: script.path.as_ptr(),
uid: script.user.unwrap_or(0),
uid_present: script.user.is_some().into(),
validation_data: script as *const _ as *mut _,
validate: script.validator.as_ref().map(|_| validate_hip_script as _),
environment: std::ptr::null(),
cwd: script.cwd.as_ref().map_or(std::ptr::null(), |value| value.as_ptr()),
}
}
}
pub(crate) fn script_environment(script: &HipScript) -> Vec<*const c_char> {
match &script.environment {
Some(values) => values
.iter()
.map(|value| value.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect(),
None => Vec::new(),
}
}
fn error_code(error: io::Error) -> c_int {
let errno = error.raw_os_error().unwrap_or_else(|| match error.kind() {
io::ErrorKind::Interrupted => libc::EINTR,
io::ErrorKind::TimedOut => libc::ETIMEDOUT,
io::ErrorKind::InvalidInput | io::ErrorKind::InvalidData => libc::EINVAL,
io::ErrorKind::PermissionDenied => libc::EPERM,
io::ErrorKind::NotFound => libc::ENOENT,
_ => libc::EIO,
});
-errno
}
unsafe fn request_string(pointer: *const c_char) -> io::Result<Option<String>> {
if pointer.is_null() {
return Ok(None);
}
unsafe { std::ffi::CStr::from_ptr(pointer) }
.to_str()
.map(|s| Some(s.to_owned()))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid HIP request encoding"))
}
unsafe fn read_hip_request(raw: &HipRequestRaw) -> io::Result<HipRequest> {
unsafe {
Ok(HipRequest {
cookie: request_string(raw.cookie)?.unwrap_or_default(),
client_ip: request_string(raw.client_ip)?,
client_ipv6: request_string(raw.client_ipv6)?,
md5: request_string(raw.md5)?.unwrap_or_default(),
client_version: request_string(raw.client_version)?.unwrap_or_default(),
client_os: request_string(raw.client_os)?.unwrap_or_default(),
os_version: request_string(raw.os_version)?.unwrap_or_default(),
host_id: request_string(raw.host_id)?,
local_hostname: request_string(raw.local_hostname)?,
})
}
}
pub(crate) extern "C" fn generate_hip_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let vpn = unsafe { &*(data as *const Vpn) };
generate_source_report(
vpn.hip_source.as_ref() as *const HipSource as *mut _,
request,
control,
output,
capacity,
written,
)
}
extern "C" fn generate_source_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
let source = unsafe { &*(data as *const HipSource) };
let HipSource::Generator(generate) = source else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
};
let request = unsafe { read_hip_request(&*request)? };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
let report = generate(&request, &control)?;
control.check()?;
if report.len() > capacity {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
unsafe {
std::ptr::copy_nonoverlapping(report.as_ptr(), output.cast(), report.len());
*written = report.len();
}
Ok(())
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlRaw) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let script = unsafe { &*(data as *const HipScript) };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
if let Some(validate) = &script.validator {
validate(&control)?;
}
control.check()
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
pub(crate) fn collect_hip_source(
source: &HipSource,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
match source {
HipSource::Disabled => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP collection is disabled",
)),
HipSource::Script(script) => collect_hip_script(script, request, check),
HipSource::Generator(_) => collect_hip_report(
&HipScriptRaw::default(),
Some(generate_source_report),
source as *const _ as *mut _,
request,
check,
),
}
}
pub(crate) fn collect_hip_script(
script: &HipScript,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let mut raw = HipScriptRaw::from_script(script);
let environment = script_environment(script);
if !environment.is_empty() {
raw.environment = environment.as_ptr();
}
collect_hip_report(&raw, None, std::ptr::null_mut(), request, check)
}
fn collect_hip_report(
script_raw: &HipScriptRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let values = [
Some(request.cookie.as_str()),
request.client_ip.as_deref(),
request.client_ipv6.as_deref(),
Some(request.md5.as_str()),
Some(request.client_version.as_str()),
Some(request.client_os.as_str()),
Some(request.os_version.as_str()),
request.host_id.as_deref(),
request.local_hostname.as_deref(),
]
.into_iter()
.map(|value| value.map(CString::new).transpose())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP request contains NUL"))?;
let ptr = |i: usize| values[i].as_ref().map_or(std::ptr::null(), |value| value.as_ptr());
let raw = HipRequestRaw {
cookie: ptr(0),
client_ip: ptr(1),
client_ipv6: ptr(2),
md5: ptr(3),
client_version: ptr(4),
client_os: ptr(5),
os_version: ptr(6),
host_id: ptr(7),
local_hostname: ptr(8),
};
let control = HipControlRaw {
data: &check as *const _ as *mut _,
check: collection_check,
};
let mut output = vec![0u8; 1024 * 1024 + 1];
let mut written = 0;
let result = unsafe {
vpn_collect_hip_report(
script_raw,
&raw,
&control,
generate,
data,
output.as_mut_ptr().cast(),
1024 * 1024,
&mut written,
)
};
if result < 0 {
return Err(io::Error::from_raw_os_error(-result));
}
output.truncate(written);
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
}
unsafe extern "C" fn collection_check(data: *mut c_void) -> c_int {
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
match catch_unwind(AssertUnwindSafe(check)) {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
#[cfg(test)]
mod hip_tests {
use super::*;
use std::{
fs,
os::unix::fs::PermissionsExt,
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, Instant},
};
fn provider(generate: impl Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync + 'static) -> Vpn {
Vpn::builder("vpn.example", "cookie")
.script_path("/bin/sh".to_owned())
.hip_source(HipSource::Generator(std::sync::Arc::new(generate)))
.build()
.unwrap()
}
fn collect(vpn: &Vpn, script: &HipScriptRaw, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
collect_hip_report(
script,
Some(generate_hip_report),
vpn as *const _ as *mut _,
&HipRequest::default(),
check,
)
}
struct ScriptFixture(std::path::PathBuf);
impl ScriptFixture {
fn new(contents: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let directory = std::env::temp_dir().join(format!(
"gp-hip-script-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&directory).unwrap();
let path = directory.join("script");
fs::write(&path, format!("#!/bin/sh\n{contents}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(directory)
}
fn script(&self, user: Option<u32>) -> HipScript {
HipScript::new(self.0.join("script").to_str().unwrap().to_owned(), user).unwrap()
}
}
impl Drop for ScriptFixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn standalone_source_uses_bounded_executor_without_a_vpn() {
let source = HipSource::Generator(std::sync::Arc::new(|request, control| {
control.check()?;
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.42"));
assert_eq!(request.md5, "physical-session-token");
Ok("<hip-report/>".into())
}));
let request = HipRequest {
client_ip: Some("192.0.2.42".into()),
md5: "physical-session-token".into(),
..Default::default()
};
assert_eq!(source.collect(&request, &|| Ok(())).unwrap(), "<hip-report/>");
let too_large = HipSource::Generator(std::sync::Arc::new(|_, _| Ok("x".repeat(1024 * 1024 + 1))));
assert_eq!(
too_large.collect(&request, &|| Ok(())).unwrap_err().raw_os_error(),
Some(libc::E2BIG)
);
assert!(HipSource::Disabled.collect(&request, &|| Ok(())).is_err());
}
#[test]
fn standalone_source_checks_cancellation_before_generation() {
let source = HipSource::Generator(std::sync::Arc::new(|_, _| panic!("Cancelled source must not run")));
assert_eq!(
source
.collect(&HipRequest::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn callback_outputs_are_bounded_and_validated_by_c() {
let raw = HipScriptRaw::default();
for (report, errno) in [
(String::new(), libc::EINVAL),
("x\0x".to_owned(), libc::EINVAL),
("x".repeat(1024 * 1024 + 1), libc::E2BIG),
] {
let vpn = provider(move |_, _| Ok(report.clone()));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap_err().raw_os_error(), Some(errno));
}
let vpn = provider(|_, _| Ok("x".repeat(1024 * 1024)));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap().len(), 1024 * 1024);
}
#[test]
fn callback_panics_and_control_errors_do_not_cross_ffi() {
let vpn = provider(|_, _| panic!("test generator panic"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
let vpn = provider(|_, _| Err(io::Error::from(io::ErrorKind::TimedOut)));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::ETIMEDOUT)
);
let vpn = provider(|_, _| panic!("Canceled provider must not run"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn explicit_script_wins_and_uid_presence_is_preserved() {
let fixture = ScriptFixture::new("printf '<script/>'");
let script = fixture.script(None);
let raw = HipScriptRaw::from_script(&script);
assert_eq!(raw.uid_present, 0);
let vpn = provider(|_, _| panic!("Script must win"));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
let script = fixture.script(Some(unsafe { libc::getuid() }));
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
assert_eq!(script.collect(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
}
#[test]
fn validator_refusal_prevents_execution_and_errors_propagate() {
let fixture = ScriptFixture::new("touch executed; printf '<script/>'");
let script = fixture
.script(None)
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(
script
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EPERM)
);
assert!(!fixture.0.join("executed").exists());
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
assert_eq!(
script
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
}
#[test]
fn child_environment_and_cwd_are_explicit_without_parent_mutation() {
let fixture = ScriptFixture::new("printf '%s:%s' \"$HIP_TEST_VALUE\" \"$PWD\"");
let cwd = fs::canonicalize(&fixture.0).unwrap().to_str().unwrap().to_owned();
let script = fixture
.script(None)
.with_environment(crate::HipScriptEnvironment {
variables: vec![("HIP_TEST_VALUE".into(), "child".into())],
cwd: cwd.clone(),
})
.unwrap();
assert_eq!(
script.collect(&HipRequest::default(), &|| Ok(())).unwrap(),
format!("child:{cwd}")
);
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
}
#[test]
fn script_empty_nul_and_nonzero_outputs_fail() {
for contents in ["true", "printf '\\000'", "printf '<script/>'; exit 1"] {
let fixture = ScriptFixture::new(contents);
assert_eq!(
fixture
.script(None)
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EINVAL)
);
}
}
#[test]
fn cancellation_and_deadline_kill_descendants_and_reap_child() {
for errno in [libc::EINTR, libc::ETIMEDOUT] {
let fixture = ScriptFixture::new("sleep 20 &\nwait\nprintf '<script/>'");
let start = Instant::now();
let check = || {
if start.elapsed() > Duration::from_millis(80) {
Err(io::Error::from_raw_os_error(errno))
} else {
Ok(())
}
};
assert_eq!(
fixture
.script(None)
.collect(&HipRequest::default(), &check)
.unwrap_err()
.raw_os_error(),
Some(errno)
);
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
+43 -6
View File
@@ -1,12 +1,19 @@
mod hip;
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};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
#[derive(Debug)]
pub(crate) struct ConnectOptions {
pub user_data: *mut c_void,
pub on_hip_report_submitted: Option<extern "C" fn(*mut c_void, *const c_char, usize)>,
pub server: *const c_char,
pub cookie: *const c_char,
@@ -27,8 +34,8 @@ pub(crate) struct ConnectOptions {
pub key_password: *const c_char,
pub servercert: *const c_char,
pub csd_uid: u32,
pub csd_wrapper: *const c_char,
pub hip_script: HipScriptRaw,
pub generate_hip: Option<HipGenerateFn>,
pub reconnect_timeout: u32,
pub mtu: u32,
@@ -47,26 +54,56 @@ pub(crate) struct VpnSessionInfoRaw {
pub user_expires: c_long,
pub lifetime_warning_prior: c_int,
pub lifetime_warning_message: *const c_char,
pub nlb_enabled: c_int,
pub nlb_connected_gw_ip: *const c_char,
}
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_write_cancel(fd: c_int) -> c_int;
#[link_name = "vpn_connect"]
fn vpn_connect(
options: *const ConnectOptions,
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
) -> c_int;
#[link_name = "vpn_disconnect"]
fn vpn_disconnect();
}
pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
let error = unsafe { vpn_write_cancel(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()
}
#[unsafe(no_mangle)]
extern "C" fn vpn_detach_command_pipe(vpn: *mut c_void) {
unsafe { &*(vpn as *const Vpn) }.detach_command_pipe();
}
pub(crate) fn connect(options: &ConnectOptions) -> i32 {
unsafe { vpn_connect(options, on_vpn_connected) }
}
pub(crate) fn disconnect() {
unsafe { vpn_disconnect() }
#[unsafe(no_mangle)]
pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *const c_char, length: usize) {
let vpn = unsafe { &*(vpn as *const Vpn) };
if report.is_null() || length > 1024 * 1024 {
return;
}
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
if let Ok(report) = std::str::from_utf8(bytes) {
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
warn!("HIP submission observer failed");
}
}
}
#[unsafe(no_mangle)]
+79 -45
View File
@@ -1,4 +1,5 @@
#include <openconnect.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -7,13 +8,12 @@
#include "vpn.h"
void *g_user_data;
static int g_cmd_pipe_fd;
static const char *g_vpnc_script;
static const char *g_vpnc_interface;
static int g_script_tun;
static vpn_connected_callback on_vpn_connected;
struct vpn_context {
struct openconnect_info *vpninfo;
int command_fd;
const vpn_options *options;
vpn_connected_callback on_connected;
};
/* Validate the peer certificate */
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
@@ -40,14 +40,17 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
}
}
static void setup_tun_handler(void *_vpninfo)
static void setup_tun_handler(void *private_data)
{
struct vpn_context *context = private_data;
struct openconnect_info *_vpninfo = context->vpninfo;
const vpn_options *options = context->options;
int ret;
if (g_script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
if (options->script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, options->script);
} else {
ret = openconnect_setup_tun_device(_vpninfo, g_vpnc_script,
g_vpnc_interface);
ret = openconnect_setup_tun_device(_vpninfo, options->script,
options->interface);
}
if (!ret) {
@@ -59,8 +62,11 @@ static void setup_tun_handler(void *_vpninfo)
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
.lifetime_warning_message =
openconnect_get_gp_lifetime_notify_message(_vpninfo),
.nlb_enabled = openconnect_get_gp_nlb_enabled(_vpninfo),
.nlb_connected_gw_ip =
openconnect_get_gp_nlb_connected_gw_ip(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
context->on_connected(context->command_fd, &session_info, options->user_data);
}
}
@@ -71,20 +77,17 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
struct utsname utsbuf;
const char *effective_local_hostname = NULL;
g_user_data = options->user_data;
g_vpnc_script = options->script;
g_vpnc_interface = options->interface;
g_script_tun = options->script_tun;
on_vpn_connected = callback;
struct vpn_context context = { .options = options, .on_connected = callback };
int result = 1;
INFO("USER_AGENT: %s", options->user_agent);
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("SCRIPT_TUN: %d", g_script_tun);
INFO("CSD_USER: %d", options->csd_uid);
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
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);
@@ -94,13 +97,28 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
vpninfo =
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
NULL, NULL, print_progress, NULL);
NULL, NULL, print_progress, &context);
if (!vpninfo) {
ERROR("openconnect_vpninfo_new failed");
return 1;
}
context.vpninfo = vpninfo;
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
options->on_hip_report_submitted);
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
if (context.command_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
goto cleanup;
}
/* An earlier disconnect remains latched on this attempt. */
if (vpn_attach_command_pipe(options->user_data, context.command_fd)) {
INFO("VPN attempt canceled before startup");
result = -EINTR;
goto cleanup;
}
openconnect_set_loglevel(vpninfo, PRG_TRACE);
openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp");
@@ -150,9 +168,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper);
openconnect_set_gp_hip_generator(vpninfo, options->user_data, options->generate_hip);
if (options->hip_script.path) {
result = openconnect_set_gp_hip_script(vpninfo, options->hip_script.path,
options->hip_script.uid_present, options->hip_script.uid,
options->hip_script.validation_data, options->hip_script.validate,
options->hip_script.environment, options->hip_script.cwd);
if (result)
goto cleanup;
}
if (options->mtu > 0) {
@@ -167,23 +190,15 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (options->dpd_interval > 0) {
openconnect_set_dpd(vpninfo, options->dpd_interval);
}
g_cmd_pipe_fd = openconnect_setup_cmd_pipe(vpninfo);
if (g_cmd_pipe_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
return 1;
}
// Essential step
if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed");
return 1;
goto cleanup;
}
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
openconnect_disable_dtls(vpninfo);
}
// Essential step
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
@@ -193,23 +208,42 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (ret) {
INFO("openconnect_mainloop returned %d, exiting", ret);
openconnect_vpninfo_free(vpninfo);
return ret;
result = ret;
goto cleanup;
}
INFO("openconnect_mainloop returned 0, reconnecting");
}
cleanup:
vpn_detach_command_pipe(options->user_data);
openconnect_vpninfo_free(vpninfo);
return result;
}
/* Stop the VPN connection */
void vpn_disconnect()
/* Called with the attempt cancellation mutex held, never after detach/free. */
int vpn_write_cancel(int fd)
{
char cmd = OC_CMD_CANCEL;
char command = OC_CMD_CANCEL;
ssize_t written;
do {
written = write(fd, &command, 1);
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
INFO("Stopping VPN connection: %d", g_cmd_pipe_fd);
if (write(g_cmd_pipe_fd, &cmd, 1) < 0) {
ERROR("Failed to write to command pipe, VPN connection may not "
"be stopped");
}
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,
char *output, size_t capacity, size_t *written)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("HIP preview", NULL, NULL, NULL, print_progress, NULL);
int result;
if (!vpninfo)
return -ENOMEM;
openconnect_set_gp_hip_generator(vpninfo, data, generate);
result = openconnect_set_gp_hip_script(vpninfo, script->path, script->uid_present,
script->uid, script->validation_data, script->validate, script->environment, script->cwd);
if (!result) result = openconnect_collect_gp_hip_report(vpninfo, request, control, output, capacity, written);
openconnect_vpninfo_free(vpninfo);
return result;
}
+22 -3
View File
@@ -9,14 +9,29 @@ typedef struct vpn_session_info {
long user_expires;
int lifetime_warning_prior;
const char *lifetime_warning_message;
int nlb_enabled;
const char *nlb_connected_gw_ip;
} vpn_session_info;
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
size_t length);
typedef struct vpn_hip_script {
const char *path;
uid_t uid;
int uid_present;
void *validation_data;
openconnect_gp_hip_validate_fn validate;
const char *const *environment;
const char *cwd;
} vpn_hip_script;
typedef struct vpn_options {
void *user_data;
vpn_hip_report_callback on_hip_report_submitted;
const char *server;
const char *cookie;
@@ -37,8 +52,8 @@ typedef struct vpn_options {
const char *key_password;
const char *servercert;
const uid_t csd_uid;
const char *csd_wrapper;
vpn_hip_script hip_script;
openconnect_gp_hip_generate_fn generate_hip;
const int reconnect_timeout;
const int mtu;
@@ -50,7 +65,11 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
void vpn_disconnect();
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_log(int level, const char *msg);
+123
View File
@@ -0,0 +1,123 @@
use std::{ffi::CString, io, marker::PhantomData, rc::Rc, sync::Arc};
use crate::{ffi, vpn_utils::check_executable};
pub type HipGenerator = dyn Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync;
type HipValidator = dyn Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync;
#[derive(Default)]
pub enum HipSource {
#[default]
Disabled,
Generator(Arc<HipGenerator>),
Script(HipScript),
}
impl HipSource {
/// Collect through the same bounded executor used by tunnel submissions.
/// Disabled posture is a caller policy; this method never invents a report.
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_source(self, request, check)
}
}
/// Current gateway and negotiated identity inputs for one report invocation.
#[derive(Clone, Default)]
pub struct HipRequest {
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub client_version: String,
pub client_os: String,
pub os_version: String,
pub host_id: Option<String>,
pub local_hostname: Option<String>,
}
/// Borrowed cancellation and deadline control. It must stay on the invocation thread.
pub struct HipControl<'a> {
pub(crate) raw: &'a ffi::HipControlRaw,
pub(crate) _thread: PhantomData<Rc<()>>,
}
impl HipControl<'_> {
pub fn check(&self) -> io::Result<()> {
let result = unsafe { (self.raw.check)(self.raw.data) };
if result < 0 {
Err(io::Error::from_raw_os_error(-result))
} else {
Ok(())
}
}
}
pub struct HipScriptEnvironment {
pub variables: Vec<(String, String)>,
pub cwd: String,
}
pub struct HipScript {
pub(crate) path: CString,
pub(crate) user: Option<u32>,
pub(crate) validator: Option<Arc<HipValidator>>,
pub(crate) environment: Option<Vec<CString>>,
pub(crate) cwd: Option<CString>,
}
impl HipScript {
pub fn new(path: String, user: Option<u32>) -> io::Result<Self> {
if !std::fs::metadata(&path)?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP executable is not a regular file",
));
}
check_executable(&path)?;
let path = c_string(path)?;
Ok(Self {
path,
user,
validator: None,
environment: None,
cwd: None,
})
}
pub fn with_validator(
mut self,
validator: impl Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync + 'static,
) -> Self {
self.validator = Some(Arc::new(validator));
self
}
/// A child-local replacement environment and working directory, never process-global changes.
pub fn with_environment(mut self, environment: HipScriptEnvironment) -> io::Result<Self> {
let variables = environment
.variables
.into_iter()
.map(|(key, value)| {
if key.is_empty() || key.contains('=') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid HIP environment key",
));
}
c_string(format!("{key}={value}"))
})
.collect::<io::Result<Vec<_>>>()?;
self.environment = Some(variables);
self.cwd = Some(c_string(environment.cwd)?);
Ok(self)
}
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_script(self, request, check)
}
}
fn c_string(value: String) -> io::Result<CString> {
CString::new(value).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP value contains NUL"))
}
+2
View File
@@ -1,6 +1,8 @@
mod ffi;
mod hip;
mod vpn;
mod vpn_utils;
pub use hip::*;
pub use vpn::*;
pub use vpn_utils::*;
+369 -55
View File
@@ -1,21 +1,24 @@
use std::{
ffi::{CStr, CString, c_char},
fmt,
sync::{Arc, RwLock},
fmt, io,
sync::{Arc, Mutex, RwLock},
};
use log::info;
use log::{info, warn};
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
use crate::vpn_utils::{check_executable, find_vpnc_script};
use crate::{HipSource, ffi};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub lifetime_warning: Option<VpnSessionWarning>,
pub nlb_enabled: bool,
pub nlb_connected_gw_ip: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -41,6 +44,8 @@ pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSe
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
_ => None,
},
nlb_enabled: raw.nlb_enabled != 0,
nlb_connected_gw_ip: unsafe { optional_c_string(raw.nlb_connected_gw_ip) },
}
}
@@ -56,7 +61,45 @@ fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
// The descriptor is borrowed only between attach and detach. Serialize writes
// against teardown and retain cancellation before the pipe exists.
#[derive(Default)]
struct Cancellation {
state: Mutex<CancellationState>,
}
#[derive(Default)]
struct CancellationState {
requested: bool,
command_fd: Option<i32>,
}
impl Cancellation {
fn attach(&self, fd: i32) -> bool {
let mut state = self.state.lock().unwrap();
state.command_fd = Some(fd);
state.requested
}
fn detach(&self) {
self.state.lock().unwrap().command_fd = None;
}
fn cancel(&self) -> io::Result<()> {
let mut state = self.state.lock().unwrap();
if state.requested {
return Ok(());
}
state.requested = true;
if let Some(fd) = state.command_fd {
ffi::write_cancel(fd)?;
}
Ok(())
}
}
pub struct Vpn {
cancellation: Cancellation,
server: CString,
cookie: CString,
@@ -76,8 +119,7 @@ pub struct Vpn {
key_password: Option<CString>,
servercert: Option<CString>,
csd_uid: u32,
csd_wrapper: Option<CString>,
pub(crate) hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -88,6 +130,7 @@ pub struct Vpn {
no_xmlpost: bool,
callback: OnConnectedCallback,
hip_report_callback: OnHipReportCallback,
}
impl Vpn {
@@ -96,12 +139,47 @@ impl Vpn {
}
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
match self.hip_source.as_ref() {
HipSource::Disabled => info!("HIP reporting: disabled"),
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
HipSource::Script(script) => {
#[cfg(unix)]
{
let uid = script.user.unwrap_or_else(|| unsafe { libc::geteuid() });
info!("HIP reporting: enabled, source=script, uid={uid}");
}
#[cfg(not(unix))]
match script.user {
Some(uid) => info!("HIP reporting: enabled, source=script, uid={uid}"),
None => info!("HIP reporting: enabled, source=script, user=process-user"),
}
}
}
self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options();
let mut options = self.build_connect_options();
let environment = match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
};
if !environment.is_empty() {
options.hip_script.environment = environment.as_ptr();
}
ffi::connect(&options)
}
/// Receives a borrowed report after the gateway accepts its HIP submission.
/// The callback must copy the XML if it needs to retain it.
pub fn set_hip_report_callback(&self, callback: impl Fn(&str) + Send + Sync + 'static) {
*self.hip_report_callback.write().unwrap() = Some(Arc::new(callback));
}
pub(crate) fn on_hip_report_submitted(&self, report: &str) {
let callback = self.hip_report_callback.read().unwrap().clone();
if let Some(callback) = callback {
callback(report);
}
}
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
@@ -110,13 +188,24 @@ impl Vpn {
}
}
pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool {
self.cancellation.attach(fd)
}
pub(crate) fn detach_command_pipe(&self) {
self.cancellation.detach();
}
pub fn disconnect(&self) {
ffi::disconnect();
if let Err(error) = self.cancellation.cancel() {
warn!("Failed to signal VPN cancellation: {error}");
}
}
fn build_connect_options(&self) -> ffi::ConnectOptions {
ffi::ConnectOptions {
user_data: self as *const _ as *mut _,
on_hip_report_submitted: Some(ffi::on_hip_report_submitted),
server: self.server.as_ptr(),
cookie: self.cookie.as_ptr(),
@@ -137,8 +226,14 @@ impl Vpn {
key_password: Self::option_to_ptr(&self.key_password),
servercert: Self::option_to_ptr(&self.servercert),
csd_uid: self.csd_uid,
csd_wrapper: Self::option_to_ptr(&self.csd_wrapper),
hip_script: match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
_ => Default::default(),
},
generate_hip: match self.hip_source.as_ref() {
HipSource::Generator(_) => Some(ffi::generate_hip_report),
_ => None,
},
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -180,6 +275,7 @@ pub struct VpnBuilder {
server: String,
cookie: String,
script: Option<String>,
script_is_path: bool,
interface: Option<String>,
script_tun: bool,
@@ -194,9 +290,7 @@ pub struct VpnBuilder {
sslkey: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -213,6 +307,7 @@ impl VpnBuilder {
server: server.to_string(),
cookie: cookie.to_string(),
script: None,
script_is_path: false,
interface: None,
script_tun: false,
@@ -227,9 +322,7 @@ impl VpnBuilder {
sslkey: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
@@ -242,6 +335,13 @@ impl VpnBuilder {
pub fn script<T: Into<Option<String>>>(mut self, script: T) -> Self {
self.script = script.into();
self.script_is_path = false;
self
}
pub fn script_path<T: Into<Option<String>>>(mut self, script: T) -> Self {
self.script = script.into();
self.script_is_path = true;
self
}
@@ -300,18 +400,8 @@ impl VpnBuilder {
self
}
pub fn hip(mut self, hip: bool) -> Self {
self.hip = hip;
self
}
pub fn csd_uid(mut self, csd_uid: u32) -> Self {
self.csd_uid = csd_uid;
self
}
pub fn csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.csd_wrapper = csd_wrapper.into();
pub fn hip_source(mut self, hip_source: impl Into<Arc<HipSource>>) -> Self {
self.hip_source = hip_source.into();
self
}
@@ -345,41 +435,32 @@ impl VpnBuilder {
self
}
fn determine_script(&self) -> Result<&str, VpnError> {
fn determine_script(&self) -> Result<String, VpnError> {
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}")));
}
check_executable(script).map_err(|e| VpnError::new(e.to_string()))?;
Ok(script)
Ok(script.clone())
}
None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))),
}
}
fn determine_csd_wrapper(&self) -> Result<Option<&str>, VpnError> {
if !self.hip {
return Ok(None);
}
match &self.csd_wrapper {
Some(csd_wrapper) if !csd_wrapper.is_empty() => {
check_executable(csd_wrapper).map_err(|e| VpnError::new(e.to_string()))?;
Ok(Some(csd_wrapper))
}
_ => {
let s = find_csd_wrapper().ok_or_else(|| VpnError::new(String::from("Failed to find csd wrapper")))?;
Ok(Some(s))
}
}
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?.to_owned();
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
let script = self.determine_script()?;
let script = if self.script_is_path || self.script.is_none() {
shell_quote_path(&script)
} else {
script
};
let user_agent = self.user_agent.unwrap_or_default();
let os = self.os.unwrap_or("linux".to_string());
Ok(Vpn {
cancellation: Cancellation::default(),
server: Self::to_cstring(&self.server),
cookie: Self::to_cstring(&self.cookie),
@@ -399,8 +480,7 @@ impl VpnBuilder {
key_password: self.key_password.as_deref().map(Self::to_cstring),
servercert: None,
csd_uid: self.csd_uid,
csd_wrapper: csd_wrapper.as_deref().map(Self::to_cstring),
hip_source: self.hip_source,
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -410,6 +490,7 @@ impl VpnBuilder {
no_xmlpost: self.no_xmlpost,
callback: Default::default(),
hip_report_callback: Default::default(),
})
}
@@ -418,20 +499,57 @@ impl VpnBuilder {
}
}
fn shell_quote_path(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
#[test]
fn quotes_vpnc_script_path_for_the_shell() {
assert_eq!(
shell_quote_path("/Applications/GP Connect.app/Contents/Helpers/vpnc-script"),
"'/Applications/GP Connect.app/Contents/Helpers/vpnc-script'"
);
assert_eq!(shell_quote_path("/tmp/user's script"), "'/tmp/user'\\''s script'");
}
#[test]
fn preserves_vpnc_script_commands() {
let command = "\"/tmp/script with spaces\" --option";
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script(command.to_string())
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), command);
}
#[test]
fn quotes_explicit_vpnc_script_paths() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), "'/bin/sh'");
}
#[test]
fn maps_session_info_from_callback_payload() {
let message = CString::new("Session expires soon").unwrap();
let connected_gw = CString::new("10.1.2.3").unwrap();
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 0,
lifetime_secs: 43_200,
user_expires: 1_776_828_409,
lifetime_warning_prior: 1_800,
lifetime_warning_message: message.as_ptr(),
nlb_enabled: 1,
nlb_connected_gw_ip: connected_gw.as_ptr(),
};
let info = session_info_from_raw(&raw);
@@ -445,6 +563,8 @@ mod tests {
message: "Session expires soon".to_string(),
})
);
assert!(info.nlb_enabled);
assert_eq!(info.nlb_connected_gw_ip.as_deref(), Some("10.1.2.3"));
}
#[test]
@@ -455,6 +575,8 @@ mod tests {
user_expires: 0,
lifetime_warning_prior: 0,
lifetime_warning_message: std::ptr::null(),
nlb_enabled: 0,
nlb_connected_gw_ip: std::ptr::null(),
};
let info = session_info_from_raw(&raw);
@@ -467,6 +589,7 @@ mod tests {
#[test]
fn connect_options_include_host_id() {
let vpn = Vpn {
cancellation: Cancellation::default(),
server: CString::new("gateway.example.com").unwrap(),
cookie: CString::new("cookie").unwrap(),
user_agent: CString::new("agent").unwrap(),
@@ -482,8 +605,7 @@ mod tests {
sslkey: None,
key_password: None,
servercert: None,
csd_uid: 0,
csd_wrapper: None,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
@@ -491,6 +613,7 @@ mod tests {
dpd_interval: 0,
no_xmlpost: false,
callback: Default::default(),
hip_report_callback: Default::default(),
};
let options = vpn.build_connect_options();
@@ -498,4 +621,195 @@ mod tests {
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
assert_eq!(host_id, "profile-host-id");
}
#[test]
fn hip_report_callback_copies_only_bounded_utf8() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
let reports = Arc::new(Mutex::new(Vec::new()));
let received = Arc::clone(&reports);
vpn.set_hip_report_callback(move |report| received.lock().unwrap().push(report.to_owned()));
let options = vpn.build_connect_options();
let callback = options.on_hip_report_submitted.unwrap();
callback(options.user_data, b"<report/>".as_ptr().cast(), 9);
callback(options.user_data, b"\xff".as_ptr().cast(), 1);
callback(options.user_data, b"x".as_ptr().cast(), 1024 * 1024 + 1);
assert_eq!(*reports.lock().unwrap(), ["<report/>"]);
}
#[test]
fn disconnect_before_connect_is_retained_without_contacting_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
vpn.disconnect();
vpn.disconnect();
assert_ne!(vpn.connect(|_| panic!("Canceled attempt connected")), 0);
assert_eq!(listener.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[test]
fn command_pipe_failure_preserves_stdin() {
use std::{
ffi::{c_int, c_void},
fs::File,
os::fd::AsFd,
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")
.args([
"-c",
"ulimit -n 64 && exec \"$1\" --exact vpn::tests::command_pipe_failure_preserves_stdin --nocapture",
"sh",
])
.arg(std::env::current_exe().unwrap())
.env(CHILD, "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
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_cmd_pipe(info: *mut c_void) -> c_int;
fn openconnect_vpninfo_free(info: *mut c_void);
}
// Construct first so resource exhaustion targets pipe creation specifically.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
let mut descriptors = Vec::new();
loop {
match File::open("/dev/null") {
Ok(file) => descriptors.push(file),
Err(error) => {
assert_eq!(error.raw_os_error(), Some(24)); // EMFILE on supported Unix platforms.
break;
}
}
}
assert!(unsafe { openconnect_setup_cmd_pipe(info) } < 0);
unsafe { openconnect_vpninfo_free(info) };
// Constructor resource acquisition may also fail before selecting a protocol.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
if !info.is_null() {
unsafe { openconnect_vpninfo_free(info) };
}
drop(descriptors);
std::io::stdin()
.as_fd()
.try_clone_to_owned()
.expect("Cleanup closed stdin");
}
#[test]
fn disconnect_interrupts_in_progress_tls_and_cannot_cancel_another_attempt() {
use std::{io::Read, sync::mpsc, thread, time::Duration};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Arc::new(
Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap(),
);
let (tx, rx) = mpsc::channel();
let worker_vpn = vpn.clone();
let worker = thread::spawn(move || {
tx.send(worker_vpn.connect(|_| panic!("Test peer never completes TLS")))
.unwrap();
});
let deadline = std::time::Instant::now() + Duration::from_secs(3);
let peer = loop {
match listener.accept() {
Ok((peer, _)) => break peer,
Err(error) if error.kind() == io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => {
thread::sleep(Duration::from_millis(5));
}
other => {
vpn.disconnect();
worker.join().unwrap();
panic!("Connection did not reach test peer: {other:?}");
}
}
};
vpn.disconnect();
let result = rx.recv_timeout(Duration::from_secs(2));
drop(peer); // Release the peer even if cancellation regresses.
worker.join().unwrap();
assert_ne!(result.expect("Cancellation did not interrupt TLS"), 0);
use std::os::{fd::AsRawFd, unix::net::UnixStream};
let next = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!next.attach(writer.as_raw_fd()));
vpn.disconnect(); // A late stop of the old attempt cannot affect the new one.
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
next.detach();
}
#[test]
fn cancellation_racing_pipe_attachment_is_never_lost() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
thread,
};
for _ in 0..100 {
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
let pending = thread::scope(|scope| {
let cancel = scope.spawn(|| cancellation.cancel().unwrap());
let pending = cancellation.attach(writer.as_raw_fd());
cancel.join().unwrap();
pending
});
if !pending {
let mut command = [0];
assert_eq!(reader.read(&mut command).unwrap(), 1);
assert_eq!(command[0], b'x');
}
cancellation.detach();
}
}
#[test]
fn disconnect_after_detach_never_writes_to_the_old_descriptor() {
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.attach(writer.as_raw_fd()));
cancellation.detach();
cancellation.cancel().unwrap();
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
}
+24 -19
View File
@@ -19,21 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
for location in locations.iter() {
let path = Path::new(location);
@@ -45,12 +30,18 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
None
}
pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS)
pub fn find_vpnc_script() -> Option<String> {
if let Some(path) = std::env::var_os("GP_VPNC_SCRIPT").filter(|path| !path.is_empty()) {
return configured_script(Path::new(&path));
}
find_executable(VPNC_SCRIPT_LOCATIONS).map(str::to_owned)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS)
fn configured_script(path: &Path) -> Option<String> {
if path.is_absolute() && path.is_file() && path.is_executable() {
return path.to_str().map(str::to_owned);
}
None
}
/// If file exists, check if it is executable
@@ -66,3 +57,17 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn configured_script_requires_an_absolute_executable_path() {
assert_eq!(configured_script(Path::new("/bin/sh")), Some("/bin/sh".to_owned()));
assert!(configured_script(Path::new("bin/sh")).is_none());
assert!(configured_script(Path::new("/missing-openconnect-vpnc-script")).is_none());
assert!(configured_script(Path::new("/etc/passwd")).is_none());
assert!(configured_script(Path::new("/tmp")).is_none());
}
}