From 2a046670bd3efa17cb0adc022c642dc502bee04d Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Sun, 10 May 2026 13:09:54 +0800 Subject: [PATCH] fix: align gateway login context with official client --- apps/gpclient/src/connect.rs | 46 +++++-- crates/gpapi/src/gateway/login.rs | 144 ++++++++++++++++++++- crates/gpapi/src/gateway/mod.rs | 112 ++++++++++++++++ crates/gpapi/src/gateway/parse_gateways.rs | 65 +++++++++- crates/gpapi/src/portal/config.rs | 21 +++ 5 files changed, 370 insertions(+), 18 deletions(-) diff --git a/apps/gpclient/src/connect.rs b/apps/gpclient/src/connect.rs index ead80cf..887f9e5 100644 --- a/apps/gpclient/src/connect.rs +++ b/apps/gpclient/src/connect.rs @@ -13,7 +13,10 @@ use gpapi::{ clap::{ToVerboseArg, args::Os}, credential::{Credential, PasswordCredential}, error::PortalError, - gateway::{GatewayLogin, SessionExtensionAuth, gateway_login}, + gateway::{ + GatewayLogin, GatewayLoginContext, GatewaySelection, SessionExtensionAuth, gateway_login, + gateway_login_with_context, + }, gp_params::{ClientOs, GpParams}, portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config}, process::{ @@ -294,7 +297,7 @@ impl<'a> ConnectHandler<'a> { if as_gateway { info!("Treating the server as a gateway"); return self - .connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false) + .connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false, None) .await; } @@ -306,7 +309,7 @@ impl<'a> ConnectHandler<'a> { if err.root_cause().downcast_ref::().is_some() { info!("Trying the gateway authentication workflow..."); self - .connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false) + .connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false, None) .await?; eprintln!("\nNOTE: the server may be a gateway, not a portal."); @@ -326,6 +329,11 @@ impl<'a> ConnectHandler<'a> { let cred = self.obtain_credential(&prelogin, portal).await?; let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?; + let gateway_selection = if self.args.gateway.is_some() { + GatewaySelection::Manual + } else { + GatewaySelection::Auto + }; let selected_gateway = match &self.args.gateway { Some(gateway) => portal_config .find_gateway(gateway) @@ -349,22 +357,33 @@ impl<'a> ConnectHandler<'a> { let gateway = selected_gateway.server(); let cred = portal_config.auth_cookie().into(); + let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version()); + let gateway_context = GatewayLoginContext::new(selected_gateway, gateway_selection) + .with_connect_method(portal_config.connect_method()) + .with_client_version(client_version); - let login_session = match self.login_gateway(gateway, &cred, &gp_params).await { + let login_session = match self + .login_gateway(gateway, &cred, &gp_params, Some(&gateway_context)) + .await + { Ok(login_session) => login_session, Err(err) => { info!("Gateway login failed: {}", err); - let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version()); let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false); return self - .connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session) + .connect_gateway_with_prelogin( + portal, + gateway, + client_version, + allow_extend_session, + Some(gateway_context), + ) .await; } }; // Use the client version from the command line argument if specified, otherwise // use the version from the portal config if available - let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version()); let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false); self @@ -385,6 +404,7 @@ impl<'a> ConnectHandler<'a> { gateway: &str, client_version: Option<&str>, allow_extend_session: bool, + gateway_context: Option, ) -> anyhow::Result<()> { info!("Performing the gateway authentication..."); @@ -394,7 +414,9 @@ impl<'a> ConnectHandler<'a> { let prelogin = prelogin(gateway, &gp_params).await?; let cred = self.obtain_credential(&prelogin, gateway).await?; - let login_session = self.login_gateway(gateway, &cred, &gp_params).await?; + let login_session = self + .login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref()) + .await?; self .connect_gateway( @@ -413,11 +435,17 @@ impl<'a> ConnectHandler<'a> { gateway: &str, cred: &Credential, gp_params: &GpParams, + gateway_context: Option<&GatewayLoginContext>, ) -> anyhow::Result { let mut gp_params = gp_params.clone(); loop { - match gateway_login(gateway, cred, &gp_params).await? { + let login = match gateway_context { + Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?, + None => gateway_login(gateway, cred, &gp_params).await?, + }; + + match login { GatewayLogin::Cookie(cookie) => { return Ok(GatewayLoginSession { cookie, diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index e9619a9..8ab5d4f 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, collections::HashMap}; +use std::{borrow::Cow, collections::HashMap, net::UdpSocket}; use anyhow::bail; use log::{debug, info, warn}; @@ -9,6 +9,7 @@ use xmltree::Element; use crate::{ credential::Credential, error::PortalError, + gateway::GatewayLoginContext, gp_params::GpParams, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; @@ -19,7 +20,16 @@ pub enum GatewayLogin { } pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result { - gateway_login_with_options(gateway, cred, gp_params, false).await + gateway_login_with_options(gateway, cred, gp_params, None, false).await +} + +pub async fn gateway_login_with_context( + gateway: &str, + cred: &Credential, + gp_params: &GpParams, + context: &GatewayLoginContext, +) -> anyhow::Result { + gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await } pub async fn gateway_login_with_extend_lifetime( @@ -27,13 +37,14 @@ pub async fn gateway_login_with_extend_lifetime( cred: &Credential, gp_params: &GpParams, ) -> anyhow::Result { - gateway_login_with_options(gateway, cred, gp_params, true).await + gateway_login_with_options(gateway, cred, gp_params, None, true).await } async fn gateway_login_with_options( gateway: &str, cred: &Credential, gp_params: &GpParams, + context: Option<&GatewayLoginContext>, extend_lifetime: bool, ) -> anyhow::Result { let url = normalize_server(gateway)?; @@ -42,9 +53,23 @@ async fn gateway_login_with_options( let login_url = format!("{}/ssl-vpn/login.esp", url); let client = Client::try_from(gp_params)?; - let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime); + let client_ip = context.and_then(|context| { + context + .client_ip() + .map(|ip| ip.to_string()) + .or_else(|| detect_local_ipv4(context.host())) + }); + let params = build_gateway_login_params( + &gateway, + cred, + gp_params, + context, + client_ip.as_deref(), + extend_lifetime, + ); info!("Perform gateway login, user_agent: {}", gp_params.user_agent()); + log_gateway_login_context(context, client_ip.as_deref()); let res = client.post(&login_url).form(¶ms).send().await.map_err(|e| { warn!("Network error: {:?}", e); @@ -84,6 +109,8 @@ fn build_gateway_login_params( gateway: &str, cred: &Credential, gp_params: &GpParams, + context: Option<&GatewayLoginContext>, + client_ip: Option<&str>, extend_lifetime: bool, ) -> HashMap { let mut params = cred @@ -100,6 +127,30 @@ fn build_gateway_login_params( ); params.insert("server".to_string(), gateway.to_string()); + if let Some(context) = context { + params.insert("host".to_string(), context.host().to_string()); + params.insert("gw".to_string(), context.name().to_string()); + params.insert("gateway-name".to_string(), context.name().to_string()); + params.insert("internal".to_string(), context.kind().as_login_param().to_string()); + params.insert( + "selection-type".to_string(), + context.selection().as_login_param().to_string(), + ); + params.insert("client-ipv6".to_string(), String::new()); + + if let Some(connect_method) = context.connect_method() { + params.insert("connect-method".to_string(), connect_method.to_string()); + } + + if let Some(client_version) = context.client_version().or_else(|| gp_params.client_version()) { + params.insert("clientgpversion".to_string(), client_version.to_string()); + } + + if let Some(client_ip) = client_ip { + params.insert("client-ip".to_string(), client_ip.to_string()); + } + } + if extend_lifetime { params.insert("extend-lifetime".to_string(), "true".to_string()); } @@ -107,6 +158,31 @@ fn build_gateway_login_params( params } +fn detect_local_ipv4(host: &str) -> Option { + let socket = UdpSocket::bind("0.0.0.0:0").ok()?; + socket.connect((host, 443)).ok()?; + let ip = socket.local_addr().ok()?.ip(); + + if ip.is_ipv4() { Some(ip.to_string()) } else { None } +} + +fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>) { + let Some(context) = context else { + return; + }; + + info!( + "Gateway login context: host_present={}, gateway_name_present={}, connect_method_present={}, selection_type={}, internal={}, clientgpversion_present={}, client_ip_present={}", + !context.host().is_empty(), + !context.name().is_empty(), + context.connect_method().is_some(), + context.selection().as_login_param(), + context.kind().as_login_param(), + context.client_version().is_some(), + client_ip.is_some() + ); +} + fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result { let args = element .descendants("argument") @@ -193,6 +269,7 @@ fn parse_mfa(res: &str) -> Option<(String, String)> { #[cfg(test)] mod tests { use super::*; + use crate::gateway::{Gateway, GatewayKind, GatewaySelection}; #[test] fn mfa() { @@ -210,9 +287,17 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#; 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); + let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, false); assert!(!params.contains_key("extend-lifetime")); + assert!(!params.contains_key("host")); + assert!(!params.contains_key("gw")); + assert!(!params.contains_key("gateway-name")); + assert!(!params.contains_key("connect-method")); + assert!(!params.contains_key("selection-type")); + assert!(!params.contains_key("internal")); + assert!(!params.contains_key("client-ip")); + assert!(!params.contains_key("client-ipv6")); } #[test] @@ -220,11 +305,58 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#; 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); + let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, true); assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true")); } + #[test] + fn gateway_login_params_include_official_context_fields() { + let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret")); + let gp_params = GpParams::builder().build(); + let gateway = Gateway { + name: "US_East".to_string(), + address: "us1.vpn.example.com".to_string(), + kind: GatewayKind::External, + priority: 1, + priority_rules: vec![], + }; + let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto) + .with_connect_method(Some("on-demand")) + .with_client_version(Some("6.3.3-915")); + + let params = build_gateway_login_params( + "us1.vpn.example.com", + &cred, + &gp_params, + Some(&context), + Some("192.168.0.102"), + false, + ); + + assert_eq!(params.get("host").map(String::as_str), Some("us1.vpn.example.com")); + assert_eq!(params.get("gw").map(String::as_str), Some("US_East")); + assert_eq!(params.get("gateway-name").map(String::as_str), Some("US_East")); + assert_eq!(params.get("connect-method").map(String::as_str), Some("on-demand")); + assert_eq!(params.get("selection-type").map(String::as_str), Some("auto")); + assert_eq!(params.get("internal").map(String::as_str), Some("no")); + assert_eq!(params.get("clientgpversion").map(String::as_str), Some("6.3.3-915")); + assert_eq!(params.get("client-ip").map(String::as_str), Some("192.168.0.102")); + assert_eq!(params.get("client-ipv6").map(String::as_str), Some("")); + } + + #[test] + fn manual_gateway_selection_maps_to_manual_param() { + let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret")); + let gp_params = GpParams::builder().build(); + let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string()); + let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual); + + let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, Some(&context), None, false); + + assert_eq!(params.get("selection-type").map(String::as_str), Some("manual")); + } + #[test] fn gateway_token_keeps_upstream_cookie_fields() { let res = r#" diff --git a/crates/gpapi/src/gateway/mod.rs b/crates/gpapi/src/gateway/mod.rs index 189ded2..5d0ef61 100644 --- a/crates/gpapi/src/gateway/mod.rs +++ b/crates/gpapi/src/gateway/mod.rs @@ -23,10 +23,117 @@ pub(crate) struct PriorityRule { pub struct Gateway { pub(crate) name: String, pub(crate) address: String, + pub(crate) kind: GatewayKind, pub(crate) priority: u32, pub(crate) priority_rules: Vec, } +#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum GatewayKind { + Internal, + External, +} + +impl GatewayKind { + pub fn as_login_param(self) -> &'static str { + match self { + GatewayKind::Internal => "yes", + GatewayKind::External => "no", + } + } +} + +#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum GatewaySelection { + Auto, + Manual, +} + +impl GatewaySelection { + pub fn as_login_param(self) -> &'static str { + match self { + GatewaySelection::Auto => "auto", + GatewaySelection::Manual => "manual", + } + } +} + +#[derive(Debug, Clone)] +pub struct GatewayLoginContext { + host: String, + name: String, + kind: GatewayKind, + selection: GatewaySelection, + connect_method: Option, + client_version: Option, + client_ip: Option, +} + +impl GatewayLoginContext { + pub fn new(gateway: &Gateway, selection: GatewaySelection) -> Self { + let name = if gateway.name().is_empty() { + gateway.server() + } else { + gateway.name() + }; + + Self { + host: gateway.server().to_string(), + name: name.to_string(), + kind: gateway.kind(), + selection, + connect_method: None, + client_version: None, + client_ip: None, + } + } + + pub fn with_connect_method(mut self, connect_method: Option<&str>) -> Self { + self.connect_method = connect_method.filter(|s| !s.is_empty()).map(|s| s.to_string()); + self + } + + pub fn with_client_version(mut self, client_version: Option<&str>) -> Self { + self.client_version = client_version.filter(|s| !s.is_empty()).map(|s| s.to_string()); + self + } + + pub fn with_client_ip(mut self, client_ip: Option) -> Self { + self.client_ip = client_ip.filter(|s| !s.is_empty()); + self + } + + pub(crate) fn host(&self) -> &str { + &self.host + } + + pub(crate) fn name(&self) -> &str { + &self.name + } + + pub(crate) fn kind(&self) -> GatewayKind { + self.kind + } + + pub(crate) fn selection(&self) -> GatewaySelection { + self.selection + } + + pub(crate) fn connect_method(&self) -> Option<&str> { + self.connect_method.as_deref() + } + + pub(crate) fn client_version(&self) -> Option<&str> { + self.client_version.as_deref() + } + + pub(crate) fn client_ip(&self) -> Option<&str> { + self.client_ip.as_deref() + } +} + impl Display for Gateway { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} ({})", self.name, self.address) @@ -38,6 +145,7 @@ impl Gateway { Self { name, address, + kind: GatewayKind::External, priority: 0, priority_rules: vec![], } @@ -50,4 +158,8 @@ impl Gateway { pub fn server(&self) -> &str { &self.address } + + pub fn kind(&self) -> GatewayKind { + self.kind + } } diff --git a/crates/gpapi/src/gateway/parse_gateways.rs b/crates/gpapi/src/gateway/parse_gateways.rs index 489b876..fc27078 100644 --- a/crates/gpapi/src/gateway/parse_gateways.rs +++ b/crates/gpapi/src/gateway/parse_gateways.rs @@ -3,21 +3,28 @@ use xmltree::Element; use crate::utils::xml::ElementExt; -use super::{Gateway, PriorityRule}; +use super::{Gateway, GatewayKind, PriorityRule}; pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option> { let node_gateways = element.descendant("gateways")?; let internal_gateway_list = if prefer_internal { info!("Try to parse the internal gateways..."); - node_gateways.descendant("internal").and_then(|n| n.child("list")) + node_gateways + .descendant("internal") + .and_then(|n| n.child("list")) + .map(|list| (list, GatewayKind::Internal)) } else { None }; let gateway_list = internal_gateway_list.or_else(|| { info!("Try to parse the external gateways..."); - node_gateways.descendant("external").and_then(|n| n.child("list")) + node_gateways + .descendant("external") + .and_then(|n| n.child("list")) + .map(|list| (list, GatewayKind::External)) })?; + let (gateway_list, kind) = gateway_list; let gateways = gateway_list .children("entry") @@ -34,6 +41,7 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option Gateway { name, address, + kind, priority, priority_rules, } @@ -62,3 +70,54 @@ fn parse_priority(element: &Element) -> u32 { .and_then(|s| s.parse().ok()) .unwrap_or(u32::MAX) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_external_gateways_marks_gateway_kind() { + let xml = r#" + + + + + + US_East + + + + + +"#; + let root = Element::parse(xml.as_bytes()).unwrap(); + + let gateways = parse_gateways(&root, false).unwrap(); + + assert_eq!(gateways[0].name(), "US_East"); + assert_eq!(gateways[0].server(), "us1.vpn.example.com"); + assert_eq!(gateways[0].kind(), GatewayKind::External); + } + + #[test] + fn parse_internal_gateways_marks_gateway_kind_when_preferred() { + let xml = r#" + + + + + + Internal + + + + + +"#; + let root = Element::parse(xml.as_bytes()).unwrap(); + + let gateways = parse_gateways(&root, true).unwrap(); + + assert_eq!(gateways[0].kind(), GatewayKind::Internal); + } +} diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 0f77d4d..5b84151 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -21,6 +21,7 @@ pub struct PortalConfig { auth_cookie: AuthCookieCredential, config_cred: Credential, gateways: Vec, + connect_method: Option, config_digest: Option, /** * Variants: @@ -60,6 +61,10 @@ impl PortalConfig { self.internal_host_detection } + pub fn connect_method(&self) -> Option<&str> { + self.connect_method.as_deref() + } + pub fn version(&self) -> Option<&str> { self.version.as_deref() } @@ -169,6 +174,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara .descendant_text("portal-prelogonuserauthcookie") .unwrap_or_default(); let config_digest = root.descendant_text("config-digest"); + let connect_method = parse_connect_method(&root); if gateways.is_empty() { gateways.push(Gateway::new(server.to_string(), server.to_string())); @@ -183,6 +189,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), config_cred: cred.clone(), gateways, + connect_method, config_digest: config_digest.map(|s| s.to_string()), internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, version, @@ -198,6 +205,13 @@ fn parse_allow_extend_session(root: &Element) -> Option { } } +fn parse_connect_method(root: &Element) -> Option { + root + .descendant_text("connect-method") + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) +} + // Perform DNS lookup and compare the result with the expected hostname fn internal_host_detect(element: &Element) -> bool { let ip_info = [ @@ -267,4 +281,11 @@ mod tests { assert_eq!(parse_allow_extend_session(&root), None); } + + #[test] + fn parses_connect_method() { + let root = parse_xml("on-demand"); + + assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand")); + } }