refactor: update session extension flow

This commit is contained in:
Kevin Yue committed 2026-05-06 23:20:57 +08:00
1 parent cdcf03ff2f
commit ab58dd6cec
19 files changed
+927 -419

No files matched your search

Generated
+8
View File
@@ -1748,12 +1748,14 @@ dependencies = [
"anyhow",
"base64 0.22.1",
"chacha20poly1305",
"chrono",
"clap",
"clap-verbosity-flag",
"common",
"dns-lookup",
"env_logger",
"gtk",
"humantime",
"log",
"log-reload",
"machine-uid",
@@ -2064,6 +2066,12 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "humantime"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
[[package]]
name = "hyper"
version = "1.8.1"
+1
View File
@@ -59,6 +59,7 @@ which = "8"
uuid = "1"
netdev = "0.40"
machine-uid = "0.5"
humantime = "2"
# Tauri dependencies
tauri = { version = "2" }
+46 -11
View File
@@ -13,7 +13,7 @@ use gpapi::{
clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{GatewayLogin, gateway_login},
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{
@@ -30,9 +30,14 @@ use tokio::{runtime::Handle, task::JoinHandle};
use crate::{
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, spawn_session_runtime},
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
@@ -342,8 +347,8 @@ impl<'a> ConnectHandler<'a> {
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(cookie) => cookie,
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(login_session) => login_session,
Err(err) => {
info!("Gateway login failed: {}", err);
return self.connect_gateway_with_prelogin(gateway).await;
@@ -354,7 +359,15 @@ impl<'a> ConnectHandler<'a> {
// use the version from the portal config if available
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
self.connect_gateway(portal, gateway, &cookie, client_version).await
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
login_session.extension_auth,
)
.await
}
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
@@ -366,20 +379,38 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?;
// When logging in to a gateway directly, there is no portal config to get the client version from
let client_version = self.args.client_version.as_deref();
self.connect_gateway(gateway, gateway, &cookie, client_version).await
self
.connect_gateway(
gateway,
gateway,
&login_session.cookie,
client_version,
login_session.extension_auth,
)
.await
}
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => return Ok(cookie),
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
@@ -397,6 +428,7 @@ impl<'a> ConnectHandler<'a> {
gateway: &str,
cookie: &str,
client_version: Option<&str>,
extension_auth: SessionExtensionAuth,
) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
@@ -418,6 +450,7 @@ impl<'a> ConnectHandler<'a> {
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
@@ -457,14 +490,16 @@ impl<'a> ConnectHandler<'a> {
vpn_clone.disconnect();
});
vpn.connect(move || {
vpn.connect(move |vpn_session_info| {
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime(&runtime_handle, session_ctx);
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
+58 -29
View File
@@ -2,11 +2,12 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, extend_session, retrieve_session_info_for_gateway},
gateway::{SessionContext, SessionExtensionAuth, extend_session},
gp_params::ClientOs,
service::session::{SessionInfo, SessionRequestArgs},
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
@@ -28,6 +29,7 @@ pub(crate) struct SessionContextInput {
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
@@ -43,22 +45,34 @@ pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContex
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
SessionContext::new(input.gateway, input.portal, session_args)
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn spawn_session_runtime(handle: &Handle, session_ctx: SessionContext) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx))
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
vpn_session_info.allow_extend_session,
)
}
async fn run_session_runtime(session_ctx: SessionContext) {
let mut session_info = match retrieve_session_info_for_gateway(session_ctx.server(), session_ctx.session_args()).await {
Ok(session_info) => session_info,
Err(err) => {
warn!("Failed to retrieve session info: {}", err);
return;
}
};
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
@@ -76,14 +90,13 @@ async fn run_session_runtime(session_ctx: SessionContext) {
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(next_session_info) => {
eprintln!("Session extended.");
if warning_due_immediately(&next_session_info) {
warn!("Session warning remained due after extension, stopping automatic extension");
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
}
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
@@ -113,12 +126,6 @@ fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionW
})
}
fn warning_due_immediately(session_info: &SessionInfo) -> bool {
build_session_warning_schedule(session_info)
.map(|schedule| schedule.delay.is_zero())
.unwrap_or(false)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -129,7 +136,6 @@ fn unix_timestamp() -> u32 {
#[cfg(test)]
mod tests {
use super::*;
use gpapi::service::session::SessionWarning;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
@@ -164,10 +170,14 @@ mod tests {
}
#[test]
fn warning_due_immediately_when_deadline_has_passed() {
let session_info = sample_session_info(Some(unix_timestamp() + 1800), true);
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
assert!(warning_due_immediately(&session_info));
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
@@ -184,6 +194,7 @@ mod tests {
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
@@ -198,4 +209,22 @@ mod tests {
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
Some(1_776_828_409),
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
}
+39 -5
View File
@@ -4,12 +4,13 @@ use gpapi::{
logger,
service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::VpnState,
session::{SessionInfo, SessionWarning},
vpn_state::{ConnectedInfo, VpnState},
},
};
use log::{info, warn};
use openconnect::Vpn;
use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext {
@@ -81,9 +82,19 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move || {
let connect_info = Box::new(info.clone());
vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
vpn.connect(move |vpn_session_info| {
let session_info = SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
vpn_session_info.allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
})
});
@@ -183,3 +194,26 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_openconnect_session_metadata_to_service_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
}
+2
View File
@@ -34,6 +34,8 @@ md5.workspace = true
sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
# Optional dependencies for features
tauri = { workspace = true, optional = true }
+66 -6
View File
@@ -1,4 +1,4 @@
use std::borrow::Cow;
use std::{borrow::Cow, collections::HashMap};
use anyhow::bail;
use log::{debug, info, warn};
@@ -19,17 +19,30 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &gateway);
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
@@ -67,6 +80,33 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
@@ -165,6 +205,26 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(input_str, "5ef64e83000119ed");
}
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
+1 -1
View File
@@ -4,8 +4,8 @@ mod parse_gateways;
pub mod session;
pub use login::*;
pub use session::*;
pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize};
use specta::Type;
+70 -226
View File
@@ -9,22 +9,43 @@ use reqwest::Client;
use xmltree::Element;
use crate::{
error::PortalError,
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
service::{
session::{SessionInfo, SessionRequestArgs, SessionWarning},
},
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
@@ -33,9 +54,15 @@ impl SessionContext {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
@@ -47,35 +74,15 @@ impl SessionContext {
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
}
pub async fn retrieve_session_info_for_gateway(server: &str, args: &SessionRequestArgs) -> anyhow::Result<SessionInfo> {
let base_url = normalize_server(server)?;
let client = build_session_client(args)?;
let form = build_session_form(args)?;
let url = format!("{base_url}/ssl-vpn/getconfig.esp");
info!("Retrieving gateway session info");
let response = client.post(&url).form(&form).send().await.map_err(|err| {
warn!("Network error: {:?}", err);
anyhow::anyhow!(PortalError::NetworkError(err))
})?;
let response = parse_gp_response(response).await?;
let response = response.trim();
if !response.starts_with('<') {
return Err(anyhow::anyhow!("Gateway session info error: {response}"));
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
let root = Element::parse(response.as_bytes())?;
let session_info = parse_session_info(&root)?;
info!("Parsed session info: {:?}", session_info);
Ok(session_info)
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<SessionInfo> {
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
@@ -91,15 +98,27 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<SessionInfo>
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => {
let session_info = retrieve_session_info_for_gateway(ctx.server(), ctx.session_args()).await?;
info!("Extend-session refreshed session info: {:?}", session_info);
Ok(session_info)
}
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
@@ -113,109 +132,6 @@ fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
Client::try_from(&builder.build())
}
fn build_session_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
let mut form = HashMap::from([
("client-type".to_string(), "1".to_string()),
("protocol-version".to_string(), "p1".to_string()),
("internal".to_string(), "no".to_string()),
(
"app-version".to_string(),
args.client_version().unwrap_or_else(|| "6.3.0-33".to_string()),
),
(
"ipv6-support".to_string(),
if args.disable_ipv6() { "no" } else { "yes" }.to_string(),
),
(
"clientos".to_string(),
args.os().unwrap_or_default().as_str().to_string(),
),
("hmac-algo".to_string(), "sha1,md5,sha256".to_string()),
("enc-algo".to_string(), "aes-128-cbc,aes-256-cbc".to_string()),
]);
if let Some(os_version) = args.os_version() {
form.insert("os-version".to_string(), os_version);
}
form.extend(serde_urlencoded::from_str::<HashMap<String, String>>(args.cookie())?);
Ok(form)
}
fn parse_session_info(root: &Element) -> anyhow::Result<SessionInfo> {
let user_expires = parse_optional_u32(root, "user-expires")?.or(parse_optional_u32(root, "user_expires")?);
let lifetime_secs = parse_optional_u32(root, "lifetime")?;
Ok(SessionInfo {
lifetime_secs,
user_expires,
expires_in_human: build_human_readable_expiry(user_expires, lifetime_secs),
lifetime_warning: parse_warning(root, "lifetime-notify-prior", "lifetime-notify-message")?,
inactivity_warning: parse_warning(root, "inactivity-notify-prior", "inactivity-notify-message")?,
admin_logout_message: root.descendant_text("admin-logout-notify-message"),
allow_extend_session: parse_bool_flag(root.descendant_text("allow-extend-session").as_deref()),
})
}
fn parse_warning(root: &Element, prior_tag: &str, message_tag: &str) -> anyhow::Result<Option<SessionWarning>> {
let prior_secs = parse_optional_u32(root, prior_tag)?;
let message = root.descendant_text(message_tag).filter(|value| !value.is_empty());
Ok(match (prior_secs, message) {
(Some(prior_secs), Some(message)) => Some(SessionWarning { prior_secs, message }),
_ => None,
})
}
fn parse_optional_u32(root: &Element, tag: &str) -> anyhow::Result<Option<u32>> {
let Some(value) = root.descendant_text(tag) else {
return Ok(None);
};
let value = value.trim();
if value.is_empty() {
return Ok(None);
}
Ok(Some(value.parse()?))
}
fn parse_bool_flag(value: Option<&str>) -> bool {
matches!(value, Some("yes" | "true" | "1"))
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
return Some(format_human_duration((user_expires as u64).saturating_sub(now)));
}
lifetime_secs.map(|secs| format_human_duration(secs as u64))
}
fn format_human_duration(total_secs: u64) -> String {
let days = total_secs / 86_400;
let hours = (total_secs % 86_400) / 3_600;
let minutes = (total_secs % 3_600) / 60;
let seconds = total_secs % 60;
let mut parts = Vec::new();
if days > 0 {
parts.push(format!("{days}days"));
}
if hours > 0 {
parts.push(format!("{hours}h"));
}
if minutes > 0 {
parts.push(format!("{minutes}m"));
}
if seconds > 0 || parts.is_empty() {
parts.push(format!("{seconds}s"));
}
parts.join(" ")
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
@@ -249,10 +165,7 @@ fn unix_timestamp() -> u64 {
#[cfg(test)]
mod tests {
use crate::{
gp_params::ClientOs,
service::session::SessionRequestArgs,
};
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use super::*;
@@ -265,87 +178,7 @@ mod tests {
}
#[test]
fn builds_gateway_session_form() {
let form = build_session_form(&build_session_args()).unwrap();
assert_eq!(form.get("client-type").map(String::as_str), Some("1"));
assert_eq!(form.get("protocol-version").map(String::as_str), Some("p1"));
assert_eq!(form.get("internal").map(String::as_str), Some("no"));
assert_eq!(form.get("app-version").map(String::as_str), Some("6.3.1-12"));
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("no"));
assert_eq!(form.get("clientos").map(String::as_str), Some("Mac"));
assert_eq!(form.get("os-version").map(String::as_str), Some("macOS 15.0"));
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_gateway_session_form_with_ipv6_enabled() {
let args = SessionRequestArgs::new("authcookie=AUTH".to_string()).with_client_version(Some("6.3.1-12".to_string()));
let form = build_session_form(&args).unwrap();
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("yes"));
}
#[test]
fn parses_session_info() {
let xml = r#"
<response>
<lifetime>43200</lifetime>
<user-expires>1776828409</user-expires>
<lifetime-notify-prior>1800</lifetime-notify-prior>
<lifetime-notify-message>The VPN will disconnect after 12 hours.</lifetime-notify-message>
<inactivity-notify-prior>300</inactivity-notify-prior>
<inactivity-notify-message>The VPN will disconnect after 5 minutes of inactivity.</inactivity-notify-message>
<admin-logout-notify-message>Logged out by administrator.</admin-logout-notify-message>
<allow-extend-session>yes</allow-extend-session>
</response>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert_eq!(info.lifetime_secs, Some(43200));
assert_eq!(info.user_expires, Some(1776828409));
assert!(info.expires_in_human.as_ref().is_some_and(|value| !value.is_empty()));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1800);
assert_eq!(info.inactivity_warning.unwrap().prior_secs, 300);
assert_eq!(
info.admin_logout_message.as_deref(),
Some("Logged out by administrator.")
);
assert!(info.allow_extend_session);
}
#[test]
fn parses_allow_extend_session_false() {
let xml = r#"<response><allow-extend-session>no</allow-extend-session></response>"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert!(!info.allow_extend_session);
}
#[test]
fn parses_user_expires_underscore_variant() {
let xml = r#"
<response>
<user_expires>1779810767</user_expires>
</response>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert_eq!(info.user_expires, Some(1779810767));
}
#[test]
fn active_session_context_preserves_connect_args_for_refresh() {
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
@@ -353,11 +186,12 @@ mod tests {
session_args,
);
let form = build_session_form(ctx.session_args()).unwrap();
let form = parse_cookie_form(ctx.session_args()).unwrap();
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("no"));
assert_eq!(form.get("clientos").map(String::as_str), Some("Mac"));
assert_eq!(form.get("os-version").map(String::as_str), Some("macOS 15.0"));
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
@@ -399,4 +233,14 @@ mod tests {
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
+1
View File
@@ -6,6 +6,7 @@ pub mod gp_params;
pub mod portal;
pub mod process;
pub mod service;
pub mod session;
pub mod utils;
#[cfg(feature = "logger")]
-1
View File
@@ -1,5 +1,4 @@
pub mod event;
pub mod request;
pub mod session;
pub mod vpn_env;
pub mod vpn_state;
-127
View File
@@ -1,127 +0,0 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
+51 -2
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gateway::Gateway;
use crate::{gateway::Gateway, session::SessionInfo};
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
@@ -10,6 +10,30 @@ pub struct ConnectInfo {
gateways: Vec<Gateway>,
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
}
impl ConnectedInfo {
pub fn new(info: ConnectInfo, session_info: Option<SessionInfo>) -> Self {
Self {
info: Box::new(info),
session_info,
}
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
}
impl ConnectInfo {
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self {
@@ -29,6 +53,31 @@ impl ConnectInfo {
pub enum VpnState {
Disconnected,
Connecting(Box<ConnectInfo>),
Connected(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>),
Disconnecting,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connected_state_serializes_session_info() {
let gateway = Gateway::new("vpn".to_string(), "vpn.example.com".to_string());
let connect_info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let session_info = SessionInfo {
lifetime_secs: Some(43_200),
allow_extend_session: true,
..Default::default()
};
let value = serde_json::to_value(VpnState::Connected(Box::new(ConnectedInfo::new(
connect_info,
Some(session_info),
))))
.unwrap();
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
}
}
+302
View File
@@ -0,0 +1,302 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
impl SessionInfo {
pub fn with_computed_human_times(mut self) -> Self {
self.expires_in_human = build_human_readable_expiry(self.user_expires, self.lifetime_secs);
self
}
pub fn from_vpn_session_fields(
lifetime_secs: Option<u32>,
user_expires: Option<u32>,
lifetime_warning: Option<SessionWarning>,
allow_extend_session: bool,
) -> Self {
Self {
lifetime_secs,
user_expires,
expires_in_human: None,
lifetime_warning,
inactivity_warning: None,
admin_logout_message: None,
allow_extend_session,
}
.with_computed_human_times()
}
pub fn rescheduled_after_extension(&self) -> Option<Self> {
let lifetime_secs = self.lifetime_secs?;
let mut session_info = self.clone();
session_info.user_expires = Some(unix_timestamp().saturating_add(lifetime_secs));
Some(session_info.with_computed_human_times())
}
pub fn log_summary(&self) -> String {
let lifetime_secs = self
.lifetime_secs
.map(format_secs_with_duration)
.unwrap_or_else(|| "none".to_string());
let user_expires = self
.user_expires
.map(format_epoch_with_local_time)
.unwrap_or_else(|| "none".to_string());
let lifetime_warning_prior = self
.lifetime_warning
.as_ref()
.map(|warning| format_secs_with_duration(warning.prior_secs))
.unwrap_or_else(|| "none".to_string());
format!(
"lifetime_secs={lifetime_secs}, user_expires={user_expires}, lifetime_warning_prior={lifetime_warning_prior}, allow_extend_session={}",
self.allow_extend_session
)
}
}
pub fn format_duration_secs(total_secs: u32) -> String {
humantime::format_duration(Duration::from_secs(total_secs as u64)).to_string()
}
fn format_secs_with_duration(secs: u32) -> String {
format!("{secs} ({})", format_duration_secs(secs))
}
fn format_epoch_with_local_time(epoch: u32) -> String {
let local_time = Local
.timestamp_opt(epoch as i64, 0)
.single()
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_else(|| "invalid time".to_string());
let now = unix_timestamp();
let relative = if epoch >= now {
format!("in {}", format_duration_secs(epoch.saturating_sub(now)))
} else {
format!("{} ago", format_duration_secs(now.saturating_sub(epoch)))
};
format!("{epoch} ({local_time}, {relative})")
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = unix_timestamp();
return Some(format_duration_secs(user_expires.saturating_sub(now)));
}
lifetime_secs.map(format_duration_secs)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_duration_secs() {
assert_eq!(format_duration_secs(43_200), "12h");
assert_eq!(format_duration_secs(1_830), "30m 30s");
}
#[test]
fn logs_session_info_with_human_readable_times() {
let info = SessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(unix_timestamp().saturating_add(43_200)),
lifetime_warning: Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
allow_extend_session: true,
..Default::default()
};
let summary = info.log_summary();
assert!(summary.contains("lifetime_secs=43200 (12h)"));
assert!(summary.contains("user_expires="));
assert!(summary.contains(", in "));
assert!(summary.contains("lifetime_warning_prior=1800 (30m)"));
assert!(summary.contains("allow_extend_session=true"));
}
#[test]
fn computes_expires_in_human_from_lifetime_or_epoch() {
let from_lifetime = SessionInfo {
lifetime_secs: Some(43_200),
..Default::default()
}
.with_computed_human_times();
assert_eq!(from_lifetime.expires_in_human.as_deref(), Some("12h"));
let from_epoch = SessionInfo {
user_expires: Some(unix_timestamp().saturating_add(1_830)),
..Default::default()
}
.with_computed_human_times();
assert!(
from_epoch
.expires_in_human
.as_deref()
.is_some_and(|value| value.starts_with("30m"))
);
}
#[test]
fn reschedules_after_extension_from_lifetime() {
let now = unix_timestamp();
let info = SessionInfo {
lifetime_secs: Some(7_200),
user_expires: Some(now.saturating_add(1_830)),
..Default::default()
};
let next = info.rescheduled_after_extension().unwrap();
assert!(
next
.user_expires
.is_some_and(|expires| expires >= now.saturating_add(7_200))
);
assert!(next.expires_in_human.is_some());
}
#[test]
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
}
@@ -0,0 +1,137 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..78c16d1c 100644
--- a/gpst.c
+++ b/gpst.c
@@ -438,8 +438,23 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
new_ip_info.mtu = atoi(s);
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
+ vpninfo->gp_session_lifetime = atoi(s);
vpninfo->auth_expiration = time(NULL) + atol(s);
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
+ vpninfo->gp_user_expires = atol(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
+ free(vpninfo->gp_lifetime_notify_message);
+ vpninfo->gp_lifetime_notify_message = s;
+ s = NULL;
+ } else if (!xmlnode_get_val(xml_node, "allow-extend-session", &s)) {
+ vpninfo->gp_allow_extend_session = !strcasecmp(s, "yes") ||
+ !strcasecmp(s, "true") ||
+ !strcmp(s, "1");
+ }
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
if (strcmp(s, "no"))
vpn_progress(vpninfo, PRG_DEBUG,
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
index f036c071..44110486 100644
--- a/libopenconnect.map.in
+++ b/libopenconnect.map.in
@@ -113,6 +113,11 @@ OPENCONNECT_5_7 {
openconnect_set_cookie;
openconnect_set_allow_insecure_crypto;
openconnect_get_auth_expiration;
+ openconnect_get_gp_session_lifetime;
+ openconnect_get_gp_user_expires;
+ openconnect_get_gp_lifetime_notify_prior;
+ openconnect_get_gp_lifetime_notify_message;
+ openconnect_get_gp_allow_extend_session;
openconnect_disable_dtls;
openconnect_get_connect_url;
openconnect_set_webview_callback;
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
index 7cb04d05..2c7af781 100644
--- a/libopenconnect5.symbols
+++ b/libopenconnect5.symbols
@@ -94,6 +94,11 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
openconnect_set_cookie@OPENCONNECT_5_7 8.20
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_allow_extend_session@OPENCONNECT_5_7 8.20
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
diff --git a/library.c b/library.c
index b5e74e9b..03f47004 100644
--- a/library.c
+++ b/library.c
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->dtls_cipher);
free(vpninfo->peer_cert_hash);
free(vpninfo->ciphersuite_config);
+ free(vpninfo->gp_lifetime_notify_message);
#if defined(OPENCONNECT_OPENSSL)
free(vpninfo->cstp_cipher);
#if defined(HAVE_BIO_METH_FREE)
@@ -1137,6 +1138,31 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
return vpninfo->auth_expiration;
}
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_session_lifetime;
+}
+
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_user_expires;
+}
+
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_prior;
+}
+
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_message;
+}
+
+int openconnect_get_gp_allow_extend_session(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_allow_extend_session;
+}
+
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
const struct oc_ip_info **info,
const struct oc_vpn_option **cstp_options,
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..dd5507ca 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -647,6 +647,11 @@ struct openconnect_info {
int dtls_attempt_period;
int udp_probes_sent;
time_t auth_expiration;
+ int gp_session_lifetime;
+ time_t gp_user_expires;
+ int gp_lifetime_notify_prior;
+ char *gp_lifetime_notify_message;
+ int gp_allow_extend_session;
time_t new_dtls_started;
#if defined(OPENCONNECT_OPENSSL)
SSL_CTX *dtls_ctx;
diff --git a/openconnect.h b/openconnect.h
index 136f181a..febf15cc 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -655,6 +655,11 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
int openconnect_get_idle_timeout(struct openconnect_info *);
time_t openconnect_get_auth_expiration(struct openconnect_info *);
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
+int openconnect_get_gp_allow_extend_session(struct openconnect_info *);
/* The returned structures are owned by the library and may be freed/replaced
due to rekey or reconnect. Assume that once the mainloop starts, the
+18 -4
View File
@@ -1,6 +1,6 @@
use crate::Vpn;
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_void};
use std::ffi::{c_char, c_int, c_long, c_void};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
@@ -38,10 +38,24 @@ pub(crate) struct ConnectOptions {
pub no_xmlpost: u32,
}
#[repr(C)]
#[derive(Debug)]
pub(crate) struct VpnSessionInfoRaw {
pub auth_expiration: c_long,
pub lifetime_secs: c_int,
pub user_expires: c_long,
pub lifetime_warning_prior: c_int,
pub lifetime_warning_message: *const c_char,
pub allow_extend_session: c_int,
}
#[link(name = "vpn")]
unsafe extern "C" {
#[link_name = "vpn_connect"]
fn vpn_connect(options: *const ConnectOptions, callback: extern "C" fn(i32, *mut c_void)) -> c_int;
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();
@@ -56,9 +70,9 @@ pub(crate) fn disconnect() {
}
#[unsafe(no_mangle)]
extern "C" fn on_vpn_connected(pipe_fd: i32, vpn: *mut c_void) {
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
let vpn = unsafe { &*(vpn as *const Vpn) };
vpn.on_connected(pipe_fd);
vpn.on_connected(pipe_fd, crate::vpn::session_info_from_raw(session_info));
}
// Logger used in the C code.
+12 -1
View File
@@ -51,7 +51,18 @@ static void setup_tun_handler(void *_vpninfo)
}
if (!ret) {
on_vpn_connected(g_cmd_pipe_fd, g_user_data);
vpn_session_info session_info = {
.auth_expiration = (long)openconnect_get_auth_expiration(_vpninfo),
.lifetime_secs = openconnect_get_gp_session_lifetime(_vpninfo),
.user_expires = (long)openconnect_get_gp_user_expires(_vpninfo),
.lifetime_warning_prior =
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
.lifetime_warning_message =
openconnect_get_gp_lifetime_notify_message(_vpninfo),
.allow_extend_session =
openconnect_get_gp_allow_extend_session(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
}
}
+12 -1
View File
@@ -3,7 +3,18 @@
#include <stdio.h>
#include <stdlib.h>
typedef void (*vpn_connected_callback)(int cmd_pipe_fd, void *user_data);
typedef struct vpn_session_info {
long auth_expiration;
int lifetime_secs;
long user_expires;
int lifetime_warning_prior;
const char *lifetime_warning_message;
int allow_extend_session;
} vpn_session_info;
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef struct vpn_options {
void *user_data;
+103 -5
View File
@@ -1,5 +1,5 @@
use std::{
ffi::{CString, c_char},
ffi::{CStr, CString, c_char},
fmt,
sync::{Arc, RwLock},
};
@@ -9,7 +9,54 @@ use log::info;
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce() + 'static + Send + Sync>>>>;
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + 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 allow_extend_session: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VpnSessionWarning {
pub prior_secs: u32,
pub message: String,
}
pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSessionInfo {
if raw.is_null() {
return VpnSessionInfo::default();
}
let raw = unsafe { &*raw };
let warning_message =
unsafe { optional_c_string(raw.lifetime_warning_message) }.filter(|message| !message.is_empty());
let user_expires = positive_i64_to_u32(raw.user_expires).or_else(|| positive_i64_to_u32(raw.auth_expiration));
VpnSessionInfo {
lifetime_secs: positive_i64_to_u32(raw.lifetime_secs as i64),
user_expires,
lifetime_warning: match (positive_i64_to_u32(raw.lifetime_warning_prior as i64), warning_message) {
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
_ => None,
},
allow_extend_session: raw.allow_extend_session != 0,
}
}
unsafe fn optional_c_string(value: *const c_char) -> Option<String> {
if value.is_null() {
return None;
}
unsafe { CStr::from_ptr(value) }.to_str().ok().map(ToOwned::to_owned)
}
fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
pub struct Vpn {
server: CString,
@@ -49,18 +96,18 @@ impl Vpn {
VpnBuilder::new(server, cookie)
}
pub fn connect(&self, on_connected: impl FnOnce() + 'static + Send + Sync) -> i32 {
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();
ffi::connect(&options)
}
pub(crate) fn on_connected(&self, pipe_fd: i32) {
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
if let Some(callback) = self.callback.write().unwrap().take() {
callback();
callback(session_info);
}
}
@@ -362,3 +409,54 @@ impl VpnBuilder {
CString::new(value.to_string()).expect("Failed to convert to CString")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
#[test]
fn maps_session_info_from_callback_payload() {
let message = CString::new("Session expires soon").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(),
allow_extend_session: 1,
};
let info = session_info_from_raw(&raw);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(
info.lifetime_warning,
Some(VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
})
);
assert!(info.allow_extend_session);
}
#[test]
fn falls_back_to_auth_expiration_when_user_expires_is_absent() {
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 1_776_828_409,
lifetime_secs: 0,
user_expires: 0,
lifetime_warning_prior: 0,
lifetime_warning_message: std::ptr::null(),
allow_extend_session: 0,
};
let info = session_info_from_raw(&raw);
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_secs, None);
assert_eq!(info.lifetime_warning, None);
assert!(!info.allow_extend_session);
}
}