feat: add support for client version emulation and integrate OpenConnect submodule

This commit is contained in:
Kevin Yue committed 2025-12-08 21:46:02 +08:00
1 parent a08ae655cf
commit e4701c1bd8
21 files changed
+273 -29

No files matched your search

+15 -2
View File
@@ -1,6 +1,6 @@
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{info, warn};
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use roxmltree::{Document, Node};
use serde::Serialize;
@@ -9,7 +9,7 @@ use specta::Type;
use crate::{
credential::{AuthCookieCredential, Credential},
error::PortalError,
gateway::{parse_gateways, Gateway},
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::NodeExt},
};
@@ -29,6 +29,10 @@ pub struct PortalConfig {
* - Some(true): Internal host detection is supported and the user is connected to the internal network
*/
internal_host_detection: Option<bool>,
/**
* The version returned by the portal config, if any
*/
version: Option<String>,
}
impl PortalConfig {
@@ -52,6 +56,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -133,6 +141,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response: {}", res_xml);
let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let root = doc.root();
@@ -158,6 +167,9 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
gateways.push(Gateway::new(server.to_string(), server.to_string()));
}
let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version);
Ok(PortalConfig {
portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), user_auth_cookie, prelogon_user_auth_cookie),
@@ -165,6 +177,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
gateways,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version,
})
}
+15
View File
@@ -31,14 +31,19 @@ impl LaunchGuiRequest {
pub struct ConnectArgs {
cookie: String,
vpnc_script: Option<String>,
user_agent: Option<String>,
os: Option<ClientOs>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
reconnect_timeout: u32,
mtu: u32,
disable_ipv6: bool,
@@ -52,6 +57,7 @@ impl ConnectArgs {
vpnc_script: None,
user_agent: None,
os: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
@@ -81,6 +87,10 @@ impl ConnectArgs {
self.os.as_ref().map(|os| os.to_openconnect_os().to_string())
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
@@ -166,6 +176,11 @@ impl ConnectRequest {
self
}
pub fn with_client_version(mut self, client_version: &str) -> Self {
self.args.client_version = Some(client_version.to_string());
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.args.certificate = certificate.into();
self
+3
View File
@@ -11,3 +11,6 @@ is_executable.workspace = true
[build-dependencies]
cc = "1"
autotools = "0.2"
pkg-config = "0.3"
fs_extra = "1"
+82 -5
View File
@@ -1,14 +1,91 @@
use std::{env, path::PathBuf, process::Command};
fn main() {
// Link to the native openconnect library
println!("cargo:rustc-link-lib=openconnect");
println!("cargo:rustc-link-search=/opt/homebrew/lib"); // Homebrew path
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let deps_dir = PathBuf::from(&manifest_dir).join("../../deps");
let openconnect_dir = deps_dir.join("openconnect");
let gp_version_patch = deps_dir.join("patches/openconnect-gp-version.patch");
// The temporary location where we will build
let build_src = out_dir.join("openconnect_build");
// Track changes so cargo rebuilds if patch or submodule changes
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
println!("cargo:rerun-if-changed={}", gp_version_patch.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Apply the Patch
// We use the system `patch` command.
let status = Command::new("patch")
.arg("-p1") // Strip one level of path (standard for git diffs)
.arg("-i") // Input file
.arg(&gp_version_patch)
.current_dir(&build_src) // Run INSIDE the copied dir
.status()
.expect("Failed to execute patch command");
if !status.success() {
panic!("Failed to apply patch file: {}", gp_version_patch.display());
}
// Build the OpenConnect library using autotools
// We explicitly enable static and disable shared to ensure we get a .a file.
// .reconf("-ivf") is CRITICAL for git submodules because 'configure'
// usually doesn't exist yet and needs to be generated.
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
.disable("nls", None) // disable translations to save space
.disable("docs", None)
.disable("dsa-tests", None)
.without("libproxy", None)
.without("stoken", None)
.without("libpcsclite", None)
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")) // Specify vpnc-script, otherwise it will fail on macOS
.build();
// Link the 'openconnect' static library
println!("cargo:rustc-link-search=native={}/lib", dst.display());
println!("cargo:rustc-link-lib=static=openconnect");
// Using pkg-config to find system deps
pkg_config::probe_library("libxml-2.0").unwrap();
pkg_config::probe_library("zlib").unwrap();
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
// Compile the vpn.c file
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
// Compile the vpn.c file
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include("/opt/homebrew/include") // Homebrew path
.include(&dst.join("include"))
.compile("vpn");
}
+5 -1
View File
@@ -2,6 +2,7 @@ use crate::Vpn;
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_void};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
#[derive(Debug)]
pub(crate) struct ConnectOptions {
@@ -9,12 +10,15 @@ pub(crate) struct ConnectOptions {
pub server: *const c_char,
pub cookie: *const c_char,
pub user_agent: *const c_char,
pub os: *const c_char,
pub client_version: *const c_char,
pub script: *const c_char,
pub interface: *const c_char,
pub script_tun: u32,
pub os: *const c_char,
pub certificate: *const c_char,
pub sslkey: *const c_char,
pub key_password: *const c_char,
+6 -1
View File
@@ -58,7 +58,6 @@ static void setup_tun_handler(void *_vpninfo)
/* Initialize VPN connection */
int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
{
INFO("openconnect version: %s", openconnect_get_version());
struct openconnect_info *vpninfo;
struct utsname utsbuf;
@@ -70,6 +69,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("USER_AGENT: %s", options->user_agent);
INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version);
INFO("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", g_script_tun);
INFO("CSD_USER: %d", options->csd_uid);
@@ -99,6 +99,11 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_reported_os(vpninfo, options->os);
}
if (options->client_version) {
openconnect_set_gp_app_version(vpninfo,
options->client_version);
}
if (options->certificate) {
INFO("Setting client certificate: %s", options->certificate);
openconnect_set_client_cert(vpninfo, options->certificate,
+5 -1
View File
@@ -7,14 +7,18 @@ typedef void (*vpn_connected_callback)(int cmd_pipe_fd, void *user_data);
typedef struct vpn_options {
void *user_data;
const char *server;
const char *cookie;
const char *user_agent;
const char *os;
const char *client_version;
const char *script;
const char *interface;
const int script_tun;
const char *os;
const char *certificate;
const char *sslkey;
const char *key_password;
+20 -3
View File
@@ -14,11 +14,15 @@ type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce() + 'static + Send +
pub struct Vpn {
server: CString,
cookie: CString,
user_agent: CString,
os: CString,
client_version: Option<CString>,
script: CString,
interface: Option<CString>,
script_tun: bool,
os: CString,
certificate: Option<CString>,
sslkey: Option<CString>,
key_password: Option<CString>,
@@ -67,11 +71,14 @@ impl Vpn {
server: self.server.as_ptr(),
cookie: self.cookie.as_ptr(),
user_agent: self.user_agent.as_ptr(),
os: self.os.as_ptr(),
client_version: Self::option_to_ptr(&self.client_version),
script: self.script.as_ptr(),
interface: Self::option_to_ptr(&self.interface),
script_tun: self.script_tun as u32,
os: self.os.as_ptr(),
certificate: Self::option_to_ptr(&self.certificate),
sslkey: Self::option_to_ptr(&self.sslkey),
@@ -125,6 +132,7 @@ pub struct VpnBuilder {
user_agent: Option<String>,
os: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
@@ -153,6 +161,7 @@ impl VpnBuilder {
user_agent: None,
os: None,
client_version: None,
certificate: None,
sslkey: None,
@@ -195,6 +204,11 @@ impl VpnBuilder {
self
}
pub fn client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
@@ -287,11 +301,14 @@ impl VpnBuilder {
Ok(Vpn {
server: Self::to_cstring(&self.server),
cookie: Self::to_cstring(&self.cookie),
user_agent: Self::to_cstring(&user_agent),
os: Self::to_cstring(&os),
client_version: self.client_version.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script),
interface: self.interface.as_deref().map(Self::to_cstring),
script_tun: self.script_tun,
os: Self::to_cstring(&os),
certificate: self.certificate.as_deref().map(Self::to_cstring),
sslkey: self.sslkey.as_deref().map(Self::to_cstring),