mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
feat: generate HIP reports through OpenConnect callbacks
This commit is contained in:
46 files changed
+2511
-1184
No files matched your search
@@ -0,0 +1,437 @@
|
||||
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 result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
|
||||
let vpn = unsafe { &*(data as *const Vpn) };
|
||||
let HipSource::Generator(generate) = &vpn.hip_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 preview_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: preview_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 preview_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 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.preview(&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
|
||||
.preview(&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
|
||||
.preview(&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.preview(&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)
|
||||
.preview(&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)
|
||||
.preview(&HipRequest::default(), &check)
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(errno)
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
mod hip;
|
||||
use crate::Vpn;
|
||||
use hip::HipGenerateFn;
|
||||
pub(crate) use hip::{HipControlRaw, HipScriptRaw, generate_hip_report, preview_hip_script, 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)]
|
||||
@@ -28,8 +32,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,
|
||||
@@ -94,7 +98,9 @@ pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *cons
|
||||
}
|
||||
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
|
||||
if let Ok(report) = std::str::from_utf8(bytes) {
|
||||
vpn.on_hip_report_submitted(report);
|
||||
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
|
||||
warn!("HIP submission observer failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,8 +86,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
||||
INFO("VPNC_SCRIPT: %s", options->script);
|
||||
INFO("SCRIPT_TUN: %d", options->script_tun);
|
||||
INFO("CSD_USER: %d", options->csd_uid);
|
||||
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
|
||||
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);
|
||||
@@ -168,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) {
|
||||
@@ -225,3 +230,20 @@ int vpn_write_cancel(int fd)
|
||||
} 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,
|
||||
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;
|
||||
}
|
||||
@@ -19,6 +19,16 @@ typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
|
||||
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;
|
||||
@@ -42,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;
|
||||
@@ -55,6 +65,8 @@ typedef struct vpn_options {
|
||||
} vpn_options;
|
||||
|
||||
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
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),
|
||||
}
|
||||
|
||||
/// 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 preview(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
||||
ffi::preview_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"))
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
mod ffi;
|
||||
mod hip;
|
||||
mod vpn;
|
||||
mod vpn_utils;
|
||||
|
||||
pub use hip::*;
|
||||
pub use vpn::*;
|
||||
pub use vpn_utils::*;
|
||||
@@ -6,8 +6,8 @@ use std::{
|
||||
|
||||
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>>>;
|
||||
@@ -119,8 +119,7 @@ pub struct Vpn {
|
||||
key_password: Option<CString>,
|
||||
servercert: Option<CString>,
|
||||
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<CString>,
|
||||
pub(crate) hip_source: HipSource,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -141,8 +140,14 @@ impl Vpn {
|
||||
|
||||
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
|
||||
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 {
|
||||
HipSource::Script(script) => ffi::script_environment(script),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !environment.is_empty() {
|
||||
options.hip_script.environment = environment.as_ptr();
|
||||
}
|
||||
ffi::connect(&options)
|
||||
}
|
||||
|
||||
@@ -205,8 +210,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 {
|
||||
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
|
||||
_ => Default::default(),
|
||||
},
|
||||
generate_hip: match &self.hip_source {
|
||||
HipSource::Generator(_) => Some(ffi::generate_hip_report),
|
||||
_ => None,
|
||||
},
|
||||
|
||||
reconnect_timeout: self.reconnect_timeout,
|
||||
mtu: self.mtu,
|
||||
@@ -263,9 +274,7 @@ pub struct VpnBuilder {
|
||||
sslkey: Option<String>,
|
||||
key_password: Option<String>,
|
||||
|
||||
hip: bool,
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<String>,
|
||||
hip_source: HipSource,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -297,9 +306,7 @@ impl VpnBuilder {
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
|
||||
hip: false,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: HipSource::Disabled,
|
||||
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
@@ -377,18 +384,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: HipSource) -> Self {
|
||||
self.hip_source = hip_source;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -435,23 +432,6 @@ impl VpnBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
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 script = if self.script_is_path {
|
||||
@@ -459,7 +439,6 @@ impl VpnBuilder {
|
||||
} else {
|
||||
script
|
||||
};
|
||||
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
|
||||
|
||||
let user_agent = self.user_agent.unwrap_or_default();
|
||||
let os = self.os.unwrap_or("linux".to_string());
|
||||
@@ -485,8 +464,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,
|
||||
@@ -611,8 +589,7 @@ mod tests {
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
servercert: None,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: HipSource::Disabled,
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
|
||||
@@ -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);
|
||||
@@ -49,10 +34,6 @@ pub fn find_vpnc_script() -> Option<&'static str> {
|
||||
find_executable(VPNC_SCRIPT_LOCATIONS)
|
||||
}
|
||||
|
||||
pub fn find_csd_wrapper() -> Option<&'static str> {
|
||||
find_executable(CSD_WRAPPER_LOCATIONS)
|
||||
}
|
||||
|
||||
/// If file exists, check if it is executable
|
||||
pub fn check_executable(file: &str) -> Result<(), io::Error> {
|
||||
let path = Path::new(file);
|
||||
|
||||
Reference in new issue
Block a user