mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
refactor: update session extension flow
This commit is contained in:
19 files changed
+927
-419
No files matched your search
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user