mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-17 13:46:27 -05:00
feat(gpclient): cache portal-cookie to skip SAML on reconnect (#608)
This commit is contained in:
1 parent
67de92044f
commit
7a571f9b27
3 files changed
+195
-1
No files matched your search
@@ -11,6 +11,7 @@ use common::constants::{GP_CLIENT_VERSION, GP_USER_AGENT};
|
||||
use gpapi::{
|
||||
auth::SamlAuthResult,
|
||||
clap::{ToVerboseArg, args::Os},
|
||||
cookie_store,
|
||||
credential::{Credential, PasswordCredential},
|
||||
error::PortalError,
|
||||
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
|
||||
@@ -55,6 +56,15 @@ pub(crate) struct ConnectArgs {
|
||||
#[arg(long, help = "Read the cookie from standard input")]
|
||||
cookie_on_stdin: bool,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
help = "Path to the portal-cookie cache file. Defaults to $HOME/.config/gpclient/cookie.json"
|
||||
)]
|
||||
cookie_file: Option<String>,
|
||||
|
||||
#[arg(long, help = "Do not read or write the portal-cookie cache")]
|
||||
no_cookie_cache: bool,
|
||||
|
||||
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
|
||||
script: Option<String>,
|
||||
|
||||
@@ -298,6 +308,12 @@ impl<'a> ConnectHandler<'a> {
|
||||
.await;
|
||||
}
|
||||
|
||||
if !self.args.no_cookie_cache && !self.args.cookie_on_stdin {
|
||||
if let Some(()) = self.try_cached_cookie(server).await {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -318,6 +334,50 @@ impl<'a> ConnectHandler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_cached_cookie(&self, server: &str) -> Option<()> {
|
||||
let path = cookie_store::cookie_path(self.args.cookie_file.as_deref());
|
||||
let stored = cookie_store::load(&path, server)?;
|
||||
info!(
|
||||
"Using cached portal cookie for {} (saved_at={}, gateway={})",
|
||||
stored.server, stored.saved_at, stored.last_gateway
|
||||
);
|
||||
|
||||
let cred: Credential = (&stored.auth_cookie).into();
|
||||
let mut gp_params = self.build_gp_params();
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Cached cookie rejected by gateway {}: {}. Clearing cache and falling back to SAML.",
|
||||
stored.last_gateway, err
|
||||
);
|
||||
cookie_store::clear(&path);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let result = self
|
||||
.connect_gateway(
|
||||
server,
|
||||
&stored.last_gateway,
|
||||
&login_session.cookie,
|
||||
self.args.client_version.as_deref(),
|
||||
false,
|
||||
login_session.extension_auth,
|
||||
)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(()) => Some(()),
|
||||
Err(err) => {
|
||||
warn!("Gateway connect failed after cached-cookie login: {}", err);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||
let gp_params = self.build_gp_params();
|
||||
|
||||
@@ -348,7 +408,21 @@ impl<'a> ConnectHandler<'a> {
|
||||
};
|
||||
|
||||
let gateway = selected_gateway.server();
|
||||
let cred = portal_config.auth_cookie().into();
|
||||
let cred: Credential = portal_config.auth_cookie().into();
|
||||
|
||||
if !self.args.no_cookie_cache {
|
||||
let path = cookie_store::cookie_path(self.args.cookie_file.as_deref());
|
||||
let stored = cookie_store::StoredCookie::new(
|
||||
portal.to_string(),
|
||||
cred.username().to_string(),
|
||||
gateway.to_string(),
|
||||
portal_config.auth_cookie().clone(),
|
||||
);
|
||||
match cookie_store::save(&path, &stored) {
|
||||
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
|
||||
Err(e) => warn!("Failed to save cookie cache to {}: {}", path.display(), e),
|
||||
}
|
||||
}
|
||||
|
||||
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await {
|
||||
Ok(login_session) => login_session,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::Write,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::credential::AuthCookieCredential;
|
||||
|
||||
const STORE_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct StoredCookie {
|
||||
pub version: u32,
|
||||
pub server: String,
|
||||
pub username: String,
|
||||
pub last_gateway: String,
|
||||
pub auth_cookie: AuthCookieCredential,
|
||||
pub saved_at: u64,
|
||||
}
|
||||
|
||||
impl StoredCookie {
|
||||
pub fn new(server: String, username: String, last_gateway: String, auth_cookie: AuthCookieCredential) -> Self {
|
||||
let saved_at = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
Self {
|
||||
version: STORE_VERSION,
|
||||
server,
|
||||
username,
|
||||
last_gateway,
|
||||
auth_cookie,
|
||||
saved_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie_path(custom: Option<&str>) -> PathBuf {
|
||||
if let Some(p) = custom {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
|
||||
PathBuf::from(home).join(".config/gpclient/cookie.json")
|
||||
}
|
||||
|
||||
pub fn load(path: &Path, server: &str) -> Option<StoredCookie> {
|
||||
let bytes = fs::read(path).ok()?;
|
||||
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
|
||||
if stored.version != STORE_VERSION || stored.server != server {
|
||||
return None;
|
||||
}
|
||||
Some(stored)
|
||||
}
|
||||
|
||||
pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?;
|
||||
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(&serde_json::to_vec(stored)?)?;
|
||||
tmp.flush()?;
|
||||
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o600))?;
|
||||
tmp.persist(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn clear(path: &Path) {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample() -> StoredCookie {
|
||||
StoredCookie::new(
|
||||
"vpn.example.com".to_string(),
|
||||
"alice".to_string(),
|
||||
"gw1.example.com".to_string(),
|
||||
AuthCookieCredential::new("alice", "user-auth", "prelogon-auth"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_and_mode_0600() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("cookie.json");
|
||||
let s = sample();
|
||||
save(&path, &s).unwrap();
|
||||
|
||||
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode);
|
||||
|
||||
let loaded = load(&path, "vpn.example.com").unwrap();
|
||||
assert_eq!(loaded.username, "alice");
|
||||
assert_eq!(loaded.last_gateway, "gw1.example.com");
|
||||
assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth");
|
||||
|
||||
assert!(load(&path, "other.example.com").is_none(), "must reject mismatched server");
|
||||
clear(&path);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_version_mismatch() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("cookie.json");
|
||||
let mut s = sample();
|
||||
s.version = STORE_VERSION + 1;
|
||||
save(&path, &s).unwrap();
|
||||
assert!(load(&path, "vpn.example.com").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod auth;
|
||||
pub mod cookie_store;
|
||||
pub mod credential;
|
||||
pub mod error;
|
||||
pub mod gateway;
|
||||
|
||||
Reference in new issue
Block a user