Compare commits

...
28 changed files with 1901 additions and 88 deletions

No files matched your search

+10 -16
View File
@@ -29,19 +29,8 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
jobs: jobs:
setup-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set up matrix
id: set-matrix
run: |
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT
tarball: tarball:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [setup-matrix]
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v5
with: with:
@@ -132,12 +121,15 @@ jobs:
build-gp: build-gp:
needs: needs:
- setup-matrix
- tarball - tarball
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}} os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
package: [deb, rpm, pkg, apk, binary, ubuntu-rolling] package: [deb, rpm, pkg, apk, binary, ubuntu-rolling]
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }}) name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
@@ -238,12 +230,14 @@ jobs:
retention-days: 1 retention-days: 1
build-gpgui: build-gpgui:
needs:
- setup-matrix
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}} os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc: libc:
- name: glibc - name: glibc
builder: gpgui-builder-tauri2 builder: gpgui-builder-tauri2
+1
View File
@@ -8,6 +8,7 @@
.cargo .cargo
.build .build
SNAPSHOT SNAPSHOT
SOURCE_COMMIT
# Tauri generated files # Tauri generated files
gen gen
Generated
+1
View File
@@ -1702,6 +1702,7 @@ dependencies = [
"log-reload", "log-reload",
"machine-uid", "machine-uid",
"md5", "md5",
"netdev",
"openssl", "openssl",
"os_info", "os_info",
"pem", "pem",
+12
View File
@@ -7,6 +7,16 @@ RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0 IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/') VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true) GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
REVISION ?= 1 REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz RPM_SOURCE ?= %{name}.tar.gz
@@ -55,11 +65,13 @@ clean-tarball:
rm -rf .vendor rm -rf .vendor
rm -rf vendor.tar.xz rm -rf vendor.tar.xz
rm -rf .cargo rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1 # Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball tarball: clean-tarball
mkdir -p .cargo mkdir -p .cargo
mkdir -p .build/tarball mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies # If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build # Generate a OFFLINE_BUILD file to indicate offline build
+59
View File
@@ -1,4 +1,63 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() { fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
tauri_build::build() tauri_build::build()
} }
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -11,7 +11,14 @@ use log::info;
use serde_json::json; use serde_json::json;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)] #[derive(Parser)]
#[command( #[command(
+56
View File
@@ -0,0 +1,56 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+13 -6
View File
@@ -19,7 +19,14 @@ use crate::{
launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
}; };
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
pub(crate) struct SharedArgs<'a> { pub(crate) struct SharedArgs<'a> {
pub(crate) fix_openssl: bool, pub(crate) fix_openssl: bool,
@@ -147,11 +154,11 @@ fn init_logger(cli: &Cli) {
// Output the log messages to a file if the command is the auth callback // Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = &cli.command { if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default(); let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() { if !auth_data.is_empty()
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) { && let Ok(log_file) = File::create(temp_dir().join("gpcallback.log"))
let target = Box::new(log_file); {
builder.target(env_logger::Target::Pipe(target)); let target = Box::new(log_file);
} builder.target(env_logger::Target::Pipe(target));
} }
} }
+179 -11
View File
@@ -2,6 +2,7 @@ use std::{
borrow::Cow, borrow::Cow,
cell::RefCell, cell::RefCell,
fs, fs,
str::FromStr,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@@ -13,7 +14,10 @@ use gpapi::{
clap::{ToVerboseArg, args::Os}, clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential}, credential::{Credential, PasswordCredential},
error::PortalError, error::PortalError,
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login}, gateway::{
GatewayLogin, GatewayLoginContext, GatewaySelection, SessionExtensionAuth, gateway_login,
gateway_login_with_context,
},
gp_params::{ClientOs, GpParams}, gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config}, portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{ process::{
@@ -38,6 +42,56 @@ struct GatewayLoginSession {
extension_auth: SessionExtensionAuth, extension_auth: SessionExtensionAuth,
} }
#[derive(Default)]
struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CscPreferenceArg {
domain: String,
key: String,
value: String,
}
impl FromStr for CscPreferenceArg {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let (name, value) = input
.split_once('=')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
let (domain, key) = name
.split_once(':')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
if domain.is_empty() || key.is_empty() || value.is_empty() {
return Err("domain, key, and value must be non-empty".to_string());
}
Ok(Self {
domain: domain.to_string(),
key: key.to_string(),
value: value.to_string(),
})
}
}
#[derive(Args)] #[derive(Args)]
pub(crate) struct ConnectArgs { pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")] #[arg(help = "The portal server to connect to")]
@@ -130,6 +184,13 @@ pub(crate) struct ConnectArgs {
)] )]
local_hostname: Option<String>, local_hostname: Option<String>,
#[arg(
long = "csc-preference",
help = "Override a Mac CSC plist preference value, in the form <domain>:<key>=<value>",
value_name = "DOMAIN:KEY=VALUE"
)]
csc_preferences: Vec<CscPreferenceArg>,
#[arg( #[arg(
long = "force-dpd", long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command" help = "Same as the '--force-dpd' option in the openconnect command"
@@ -192,16 +253,23 @@ pub(crate) struct ConnectHandler<'a> {
latest_key_password: RefCell<Option<String>>, latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>, password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>, cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
} }
impl<'a> ConnectHandler<'a> { impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self { pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self { Self {
args, args,
shared_args, shared_args,
latest_key_password: Default::default(), latest_key_password: Default::default(),
password_from_stdin: Default::default(), password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(), cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
} }
} }
@@ -234,6 +302,10 @@ impl<'a> ConnectHandler<'a> {
builder.computer(local_hostname); builder.computer(local_hostname);
} }
for preference in &self.args.csc_preferences {
builder.csc_preference_override(&preference.domain, &preference.key, &preference.value);
}
builder.build() builder.build()
} }
@@ -294,7 +366,7 @@ impl<'a> ConnectHandler<'a> {
if as_gateway { if as_gateway {
info!("Treating the server as a gateway"); info!("Treating the server as a gateway");
return self 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; .await;
} }
@@ -306,7 +378,7 @@ impl<'a> ConnectHandler<'a> {
if err.root_cause().downcast_ref::<PortalError>().is_some() { if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow..."); info!("Trying the gateway authentication workflow...");
self 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?; .await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal."); eprintln!("\nNOTE: the server may be a gateway, not a portal.");
@@ -326,6 +398,11 @@ impl<'a> ConnectHandler<'a> {
let cred = self.obtain_credential(&prelogin, portal).await?; let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).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 { let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config Some(gateway) => portal_config
.find_gateway(gateway) .find_gateway(gateway)
@@ -349,22 +426,33 @@ impl<'a> ConnectHandler<'a> {
let gateway = selected_gateway.server(); let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into(); 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, Ok(login_session) => login_session,
Err(err) => { Err(err) => {
info!("Gateway login failed: {}", 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); let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
return self 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; .await;
} }
}; };
// Use the client version from the command line argument if specified, otherwise // Use the client version from the command line argument if specified, otherwise
// use the version from the portal config if available // 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); let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
self self
@@ -385,6 +473,7 @@ impl<'a> ConnectHandler<'a> {
gateway: &str, gateway: &str,
client_version: Option<&str>, client_version: Option<&str>,
allow_extend_session: bool, allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
info!("Performing the gateway authentication..."); info!("Performing the gateway authentication...");
@@ -394,7 +483,9 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?; let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).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 self
.connect_gateway( .connect_gateway(
@@ -413,11 +504,17 @@ impl<'a> ConnectHandler<'a> {
gateway: &str, gateway: &str,
cred: &Credential, cred: &Credential,
gp_params: &GpParams, gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> { ) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone(); let mut gp_params = gp_params.clone();
loop { 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) => { GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession { return Ok(GatewayLoginSession {
cookie, cookie,
@@ -555,7 +652,7 @@ impl<'a> ConnectHandler<'a> {
.saml_request(prelogin.saml_request()) .saml_request(prelogin.saml_request())
.user_agent(&user_agent) .user_agent(&user_agent)
.os(self.args.os.as_str()) .os(self.args.os.as_str())
.os_version(Some(&os_version)) .os_version(Some(os_version))
.fix_openssl(self.shared_args.fix_openssl) .fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors) .ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser) .browser(browser)
@@ -563,10 +660,29 @@ impl<'a> ConnectHandler<'a> {
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser; let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let browser_kind = if browser.is_some() || use_default_browser {
"external"
} else {
"embedded"
};
#[cfg(not(feature = "webview-auth"))]
let browser_kind = "external";
let clean_auth = self
.clean_auth_state
.borrow_mut()
.consume_for_webview(browser_kind == "embedded");
info!(
"SAML auth launch: gateway={}, clean={}, browser={}",
is_gateway, clean_auth, browser_kind
);
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher let auth_launcher = auth_launcher
.hidpi(self.args.hidpi) .hidpi(self.args.hidpi)
.clean(self.args.clean) .clean(clean_auth)
.default_browser(use_default_browser); .default_browser(use_default_browser);
let cred = auth_launcher.launch().await?; let cred = auth_launcher.launch().await?;
@@ -677,3 +793,55 @@ fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid())) get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_csc_preference_override() {
let preference = CscPreferenceArg::from_str("com.example.settings:ExampleKey=ExampleValue").unwrap();
assert_eq!(
preference,
CscPreferenceArg {
domain: "com.example.settings".to_string(),
key: "ExampleKey".to_string(),
value: "ExampleValue".to_string(),
}
);
}
#[test]
fn rejects_invalid_csc_preference_override() {
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str(":ExampleKey=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings:=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey=").is_err());
}
#[test]
fn clean_auth_state_is_consumed_once_for_webview() {
let mut state = CleanAuthState::new(true);
assert!(state.consume_for_webview(true));
assert!(!state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_is_not_consumed_by_external_browser() {
let mut state = CleanAuthState::new(true);
assert!(!state.consume_for_webview(false));
assert!(state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_remains_false_when_not_requested() {
let mut state = CleanAuthState::new(false);
assert!(!state.consume_for_webview(true));
assert!(!state.consume_for_webview(false));
}
}
+59
View File
@@ -1,3 +1,62 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() { fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build() tauri_build::build()
} }
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -7,7 +7,14 @@ use log::info;
use crate::app::App; use crate::app::App;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const GP_API_KEY: &[u8; 32] = &[0; 32]; const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)] #[derive(Parser)]
+60
View File
@@ -0,0 +1,60 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+8 -1
View File
@@ -16,7 +16,14 @@ use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer}; use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)] #[derive(Parser)]
#[command(version = VERSION)] #[command(version = VERSION)]
+1
View File
@@ -36,6 +36,7 @@ machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] } uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true chrono.workspace = true
humantime.workspace = true humantime.workspace = true
netdev.workspace = true
# Optional dependencies for features # Optional dependencies for features
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
+27 -2
View File
@@ -72,7 +72,11 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid) let auth_data =
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
} }
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!( Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
"SAML auth status: {}", "SAML auth status: {}",
@@ -102,6 +106,7 @@ impl SamlAuthData {
AuthDataParseError::Invalid(anyhow::anyhow!(e)) AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?; })?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data); return Ok(auth_data);
} }
@@ -122,9 +127,28 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref() self.prelogin_cookie.as_deref()
} }
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> { pub fn token(&self) -> Option<&str> {
self.token.as_deref() self.token.as_deref()
} }
fn log_summary(&self, source: &str) {
info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
source,
!self.username.is_empty(),
optional_len(self.prelogin_cookie.as_deref()),
optional_len(self.portal_userauthcookie.as_deref()),
optional_len(self.token.as_deref())
);
}
}
fn optional_len(value: Option<&str>) -> usize {
value.unwrap_or_default().len()
} }
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> { fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
@@ -160,11 +184,12 @@ mod tests {
#[test] #[test]
fn auth_data_from_gpcallback_non_cas() { fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4="; let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap(); let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]"); assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie")); assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
} }
} }
+60 -3
View File
@@ -41,14 +41,21 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential { pub struct PreloginCredential {
username: String, username: String,
prelogin_cookie: Option<String>, prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>, token: Option<String>,
} }
impl PreloginCredential { impl PreloginCredential {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self { pub fn new(
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
Self { Self {
username: username.to_string(), username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()), prelogin_cookie: prelogin_cookie.map(|s| s.to_string()),
portal_userauthcookie: portal_userauthcookie.map(|s| s.to_string()),
token: token.map(|s| s.to_string()), token: token.map(|s| s.to_string()),
} }
} }
@@ -61,6 +68,10 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref() self.prelogin_cookie.as_deref()
} }
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> { pub fn token(&self) -> Option<&str> {
self.token.as_deref() self.token.as_deref()
} }
@@ -70,9 +81,10 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self { fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string(); let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie(); let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token(); let token = value.token();
Self::new(&username, prelogin_cookie, token) Self::new(&username, prelogin_cookie, portal_userauthcookie, token)
} }
} }
@@ -186,7 +198,13 @@ impl Credential {
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self { let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None), Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()), Credential::Prelogin(cred) => (
None,
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => ( Credential::AuthCookie(cred) => (
None, None,
None, None,
@@ -255,3 +273,42 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone()) Self::Cached(value.clone())
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_params_include_saml_cookies() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
Some("portal-userauthcookie".to_string()),
)
.unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("passwd"), Some(&""));
assert_eq!(params.get("prelogin-cookie"), Some(&"prelogin-cookie"));
assert_eq!(params.get("portal-userauthcookie"), Some(&"portal-userauthcookie"));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
}
#[test]
fn prelogin_credential_params_keep_cas_token_without_cookies() {
let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("prelogin-cookie"), Some(&""));
assert_eq!(params.get("portal-userauthcookie"), Some(&""));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
assert_eq!(params.get("token"), Some(&"cas-token"));
}
}
+138 -6
View File
@@ -1,4 +1,4 @@
use std::{borrow::Cow, collections::HashMap}; use std::{borrow::Cow, collections::HashMap, net::UdpSocket};
use anyhow::bail; use anyhow::bail;
use log::{debug, info, warn}; use log::{debug, info, warn};
@@ -9,6 +9,7 @@ use xmltree::Element;
use crate::{ use crate::{
credential::Credential, credential::Credential,
error::PortalError, error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, 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<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 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<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
} }
pub async fn gateway_login_with_extend_lifetime( pub async fn gateway_login_with_extend_lifetime(
@@ -27,13 +37,14 @@ pub async fn gateway_login_with_extend_lifetime(
cred: &Credential, cred: &Credential,
gp_params: &GpParams, gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> { ) -> anyhow::Result<GatewayLogin> {
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( async fn gateway_login_with_options(
gateway: &str, gateway: &str,
cred: &Credential, cred: &Credential,
gp_params: &GpParams, gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
extend_lifetime: bool, extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> { ) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?; 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 login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?; 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()); 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(&params).send().await.map_err(|e| { let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
@@ -84,6 +109,8 @@ fn build_gateway_login_params(
gateway: &str, gateway: &str,
cred: &Credential, cred: &Credential,
gp_params: &GpParams, gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
client_ip: Option<&str>,
extend_lifetime: bool, extend_lifetime: bool,
) -> HashMap<String, String> { ) -> HashMap<String, String> {
let mut params = cred let mut params = cred
@@ -100,6 +127,30 @@ fn build_gateway_login_params(
); );
params.insert("server".to_string(), gateway.to_string()); 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 { if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string()); params.insert("extend-lifetime".to_string(), "true".to_string());
} }
@@ -107,6 +158,31 @@ fn build_gateway_login_params(
params params
} }
fn detect_local_ipv4(host: &str) -> Option<String> {
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<String> { fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element let args = element
.descendants("argument") .descendants("argument")
@@ -193,6 +269,7 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::gateway::{Gateway, GatewayKind, GatewaySelection};
#[test] #[test]
fn mfa() { fn mfa() {
@@ -210,9 +287,17 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret")); let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build(); 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("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] #[test]
@@ -220,11 +305,58 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret")); let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build(); 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")); 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] #[test]
fn gateway_token_keeps_upstream_cookie_fields() { fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#" let res = r#"
+145
View File
@@ -23,10 +23,130 @@ pub(crate) struct PriorityRule {
pub struct Gateway { pub struct Gateway {
pub(crate) name: String, pub(crate) name: String,
pub(crate) address: String, pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32, pub(crate) priority: u32,
pub(crate) priority_rules: Vec<PriorityRule>, pub(crate) priority_rules: Vec<PriorityRule>,
} }
#[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",
}
}
}
impl Default for GatewayKind {
fn default() -> Self {
Self::External
}
}
#[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",
}
}
}
impl Default for GatewaySelection {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Clone)]
pub struct GatewayLoginContext {
host: String,
name: String,
kind: GatewayKind,
selection: GatewaySelection,
connect_method: Option<String>,
client_version: Option<String>,
client_ip: Option<String>,
}
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<String>) -> 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 { impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address) write!(f, "{} ({})", self.name, self.address)
@@ -38,6 +158,7 @@ impl Gateway {
Self { Self {
name, name,
address, address,
kind: GatewayKind::External,
priority: 0, priority: 0,
priority_rules: vec![], priority_rules: vec![],
} }
@@ -50,4 +171,28 @@ impl Gateway {
pub fn server(&self) -> &str { pub fn server(&self) -> &str {
&self.address &self.address
} }
pub fn kind(&self) -> GatewayKind {
self.kind
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_gateway_without_kind_as_external() {
let gateway: Gateway = serde_json::from_str(
r#"{
"name": "US East",
"address": "us-east.example.com",
"priority": 1,
"priorityRules": []
}"#,
)
.unwrap();
assert_eq!(gateway.kind(), GatewayKind::External);
}
} }
+63 -4
View File
@@ -3,21 +3,28 @@ use xmltree::Element;
use crate::utils::xml::ElementExt; 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<Vec<Gateway>> { pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?; let node_gateways = element.descendant("gateways")?;
let internal_gateway_list = if prefer_internal { let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways..."); 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 { } else {
None None
}; };
let gateway_list = internal_gateway_list.or_else(|| { let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways..."); 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 let gateways = gateway_list
.children("entry") .children("entry")
@@ -28,12 +35,13 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
let priority = parse_priority(gateway_item); let priority = parse_priority(gateway_item);
let priority_rules = gateway_item let priority_rules = gateway_item
.child("priority-rule") .child("priority-rule")
.map(|n| parse_priority_rules(n)) .map(parse_priority_rules)
.unwrap_or_default(); .unwrap_or_default();
Gateway { Gateway {
name, name,
address, address,
kind,
priority, priority,
priority_rules, priority_rules,
} }
@@ -62,3 +70,54 @@ fn parse_priority(element: &Element) -> u32 {
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX) .unwrap_or(u32::MAX)
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_external_gateways_marks_gateway_kind() {
let xml = r#"
<policy>
<gateways>
<external>
<list>
<entry name="us1.vpn.example.com">
<description>US_East</description>
</entry>
</list>
</external>
</gateways>
</policy>
"#;
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#"
<policy>
<gateways>
<internal>
<list>
<entry name="internal.vpn.example.com">
<description>Internal</description>
</entry>
</list>
</internal>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, true).unwrap();
assert_eq!(gateways[0].kind(), GatewayKind::Internal);
}
}
+22
View File
@@ -58,6 +58,7 @@ pub struct GpParams {
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
// Used for MFA // Used for MFA
input_str: Option<String>, input_str: Option<String>,
otp: Option<String>, otp: Option<String>,
@@ -100,6 +101,13 @@ impl GpParams {
self.client_version.as_deref() self.client_version.as_deref()
} }
pub fn csc_preference_override(&self, domain: &str, key: &str) -> Option<&str> {
self
.csc_preference_overrides
.get(&csc_preference_key(domain, key))
.map(String::as_str)
}
pub fn set_input_str(&mut self, input_str: &str) { pub fn set_input_str(&mut self, input_str: &str) {
self.input_str = Some(input_str.to_string()); self.input_str = Some(input_str.to_string());
} }
@@ -152,6 +160,7 @@ pub struct GpParamsBuilder {
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
} }
impl GpParamsBuilder { impl GpParamsBuilder {
@@ -169,6 +178,7 @@ impl GpParamsBuilder {
certificate: Default::default(), certificate: Default::default(),
sslkey: Default::default(), sslkey: Default::default(),
key_password: Default::default(), key_password: Default::default(),
csc_preference_overrides: Default::default(),
} }
} }
@@ -222,6 +232,13 @@ impl GpParamsBuilder {
self self
} }
pub fn csc_preference_override(&mut self, domain: &str, key: &str, value: &str) -> &mut Self {
self
.csc_preference_overrides
.insert(csc_preference_key(domain, key), value.to_string());
self
}
pub fn build(&self) -> GpParams { pub fn build(&self) -> GpParams {
GpParams { GpParams {
is_gateway: self.is_gateway, is_gateway: self.is_gateway,
@@ -234,12 +251,17 @@ impl GpParamsBuilder {
certificate: self.certificate.clone(), certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(), sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(), key_password: self.key_password.clone(),
csc_preference_overrides: self.csc_preference_overrides.clone(),
input_str: Default::default(), input_str: Default::default(),
otp: Default::default(), otp: Default::default(),
} }
} }
} }
fn csc_preference_key(domain: &str, key: &str) -> String {
format!("{domain}:{key}")
}
impl Default for GpParamsBuilder { impl Default for GpParamsBuilder {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
+181 -25
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use anyhow::bail; use anyhow::bail;
use dns_lookup::lookup_addr; use dns_lookup::lookup_addr;
use log::{debug, info, warn}; use log::{debug, info, warn};
@@ -11,9 +13,11 @@ use crate::{
error::PortalError, error::PortalError,
gateway::{Gateway, parse_gateways}, gateway::{Gateway, parse_gateways},
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
}; };
use super::csc;
#[derive(Debug, Serialize, Type)] #[derive(Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PortalConfig { pub struct PortalConfig {
@@ -21,6 +25,7 @@ pub struct PortalConfig {
auth_cookie: AuthCookieCredential, auth_cookie: AuthCookieCredential,
config_cred: Credential, config_cred: Credential,
gateways: Vec<Gateway>, gateways: Vec<Gateway>,
connect_method: Option<String>,
config_digest: Option<String>, config_digest: Option<String>,
/** /**
* Variants: * Variants:
@@ -60,6 +65,10 @@ impl PortalConfig {
self.internal_host_detection self.internal_host_detection
} }
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub fn version(&self) -> Option<&str> { pub fn version(&self) -> Option<&str> {
self.version.as_deref() self.version.as_deref()
} }
@@ -118,14 +127,11 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal); let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let mut params = cred.to_params(); let swg_nonce = csc::swg_nonce();
let extra_params = gp_params.to_params(); let params = build_config_params(cred, gp_params, &server, &swg_nonce);
params.extend(extra_params);
params.insert("server", &server);
params.insert("host", &server);
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent()); info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| { let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
@@ -152,11 +158,102 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml); debug!("Portal config response: {}", res_xml);
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
info!("Portal returned CSC criteria: {}", csc_criteria_summary(&root));
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
}
fn build_config_params<'a>(
cred: &'a Credential,
gp_params: &'a GpParams,
server: &'a str,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", server);
params.insert("host", server);
params.insert("csc-digest", "");
params.insert("config-digest", "");
params.insert("csc-support", "yes");
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
async fn retrieve_csc_config(
client: &Client,
portal: &str,
root: &Element,
username: &str,
gp_params: &GpParams,
) -> anyhow::Result<String> {
let csc_req = csc::build_csc_request(root, username, gp_params)?;
let swg_nonce = csc::swg_nonce();
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
info!("Portal CSC config request summary: {}", csc_req.summary());
info!("Portal CSC config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal CSC config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
}
fn redact_params(params: &HashMap<&str, &str>) -> String {
let params = params.iter().map(|(key, value)| (*key, *value)).collect::<Vec<_>>();
redact_form_params(&params)
}
fn csc_criteria_summary(root: &Element) -> String {
let auth_cookie = present(root.descendant_text("portal-csc-auth-cookie").as_deref());
let config_digest = present(root.descendant_text("config-digest").as_deref());
let custom_check_entries = root
.descendant("custom-checks")
.map(|custom_checks| custom_checks.descendants("entry").len())
.unwrap_or_default();
format!("auth_cookie={auth_cookie}, config_digest={config_digest}, custom_check_entries={custom_check_entries}")
}
fn present(value: Option<&str>) -> &'static str {
match value {
Some(value) if !value.is_empty() => "present",
_ => "empty",
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false; let mut ihd_enabled = false;
let mut prefer_internal = false; let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") { if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true; ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node) prefer_internal = internal_host_detect(ihd_node)
} }
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| { let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -169,9 +266,12 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
.descendant_text("portal-prelogonuserauthcookie") .descendant_text("portal-prelogonuserauthcookie")
.unwrap_or_default(); .unwrap_or_default();
let config_digest = root.descendant_text("config-digest"); let config_digest = root.descendant_text("config-digest");
let connect_method = parse_connect_method(&root);
if gateways.is_empty() { if gateways.is_empty() {
gateways.push(Gateway::new(server.to_string(), server.to_string())); gateways.push(Gateway::new(server.to_string(), server.to_string()));
} else {
info!("Found {} gateways in portal config", gateways.len());
} }
let version = root.descendant_text("version").map(|s| s.to_string()); let version = root.descendant_text("version").map(|s| s.to_string());
@@ -183,6 +283,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), auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(), config_cred: cred.clone(),
gateways, gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()), config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version, version,
@@ -198,6 +299,13 @@ fn parse_allow_extend_session(root: &Element) -> Option<bool> {
} }
} }
fn parse_connect_method(root: &Element) -> Option<String> {
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 // Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool { fn internal_host_detect(element: &Element) -> bool {
let ip_info = [ let ip_info = [
@@ -208,23 +316,24 @@ fn internal_host_detect(element: &Element) -> bool {
info!("Found internal-host-detection, performing DNS lookup"); info!("Found internal-host-detection, performing DNS lookup");
for (ip_address, host) in ip_info.iter() { for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) { if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
if !ip_address.is_empty() && !host.is_empty() { && !ip_address.is_empty()
match ip_address.parse::<std::net::IpAddr>() { && !host.is_empty()
Ok(ip) => match lookup_addr(&ip) { {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => { match ip_address.parse::<std::net::IpAddr>() {
return true; Ok(ip) => match lookup_addr(&ip) {
} Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
Ok(host_lookup) => { return true;
info!( }
"rDNS lookup for {} returned {}, expected {}", Ok(host_lookup) => {
ip_address, host_lookup, host info!(
); "rDNS lookup for {} returned {}, expected {}",
} ip_address, host_lookup, host
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err), );
}, }
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err), Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
} },
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
} }
} }
} }
@@ -240,6 +349,20 @@ mod tests {
Element::parse(xml.as_bytes()).unwrap() Element::parse(xml.as_bytes()).unwrap()
} }
#[test]
fn getconfig_params_include_csc_support_fields() {
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_config_params(&cred, &gp_params, "vpn.example.com", "123");
assert_eq!(params.get("csc-support"), Some(&"yes"));
assert_eq!(params.get("csc-digest"), Some(&""));
assert_eq!(params.get("config-digest"), Some(&""));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
assert_eq!(params.get("host"), Some(&"vpn.example.com"));
}
#[test] #[test]
fn parses_allow_extend_session_yes() { fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>"); let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
@@ -267,4 +390,37 @@ mod tests {
assert_eq!(parse_allow_extend_session(&root), None); assert_eq!(parse_allow_extend_session(&root), None);
} }
#[test]
fn parses_connect_method() {
let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>");
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie>prelogon-cookie</portal-prelogonuserauthcookie>
<gateways>
<external>
<list>
<entry name="US_East">
<description>us1.vpn.example.com</description>
</entry>
</list>
</external>
</gateways>
</policy>"#,
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
assert_eq!(config.gateways().len(), 1);
}
} }
+715
View File
@@ -0,0 +1,715 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{
gp_params::GpParams,
utils::{host_utils, xml::ElementExt},
};
const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__";
pub(super) struct CscRequest {
pub(super) auth_cookie: String,
pub(super) config_digest: String,
pub(super) csc_digest: String,
pub(super) csc_data: String,
summary: CscBuildSummary,
host_id: String,
serial_number: String,
}
impl CscRequest {
pub(super) fn summary(&self) -> String {
format!(
"digest_len={}, xml_len={}, plist_entries={}, plist_present={}, plist_missing={}, process_entries={}, process_present={}, process_missing={}",
self.csc_digest.len(),
self.csc_data.len(),
self.summary.plist_entries,
self.summary.plist_present,
self.summary.plist_missing,
self.summary.process_entries,
self.summary.process_present,
self.summary.process_missing,
)
}
}
#[derive(Default)]
struct CscBuildSummary {
plist_entries: usize,
plist_present: usize,
plist_missing: usize,
process_entries: usize,
process_present: usize,
process_missing: usize,
}
struct CscDataInput<'a> {
criteria: &'a Element,
auth_cookie: &'a str,
username: &'a str,
gp_params: &'a GpParams,
host_id: &'a str,
serial_number: &'a str,
csc_digest: &'a str,
}
pub(super) trait CscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String>;
fn process_exists(&self, name: &str) -> bool;
}
struct SystemCscDataReader;
impl CscDataReader for SystemCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
read_macos_preference(domain, key)
}
fn process_exists(&self, name: &str) -> bool {
linux_process_names().iter().any(|process_name| process_name == name)
}
}
pub(super) fn swg_nonce() -> String {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis())
.unwrap_or_default();
(millis % 2_147_483_647).to_string()
}
pub(super) fn is_config_criteria(root: &Element) -> bool {
root.name == "config-criteria"
}
pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result<CscRequest> {
let reader = SystemCscDataReader;
build_csc_request_with_reader(root, username, gp_params, &reader)
}
pub(super) fn build_csc_request_with_reader(
root: &Element,
username: &str,
gp_params: &GpParams,
reader: &dyn CscDataReader,
) -> anyhow::Result<CscRequest> {
let auth_cookie = root
.descendant_text("portal-csc-auth-cookie")
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?;
let config_digest = root.descendant_text("config-digest").unwrap_or_default();
let host_id = collect_host_id(gp_params);
let serial_number = collect_serial_number();
let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data(
CscDataInput {
criteria: root,
auth_cookie: &auth_cookie,
username,
gp_params,
host_id: &host_id,
serial_number: &serial_number,
csc_digest: DIGEST_PLACEHOLDER,
},
reader,
&mut summary,
)?;
let csc_digest = pan_md5_hex(csc_data.as_bytes());
let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest);
Ok(CscRequest {
auth_cookie,
config_digest,
csc_digest,
csc_data,
summary,
host_id,
serial_number,
})
}
pub(super) fn csc_params<'a>(
req: &'a CscRequest,
username: &'a str,
gp_params: &'a GpParams,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = HashMap::new();
params.insert("user", username);
params.insert("clientVer", "4100");
params.insert("clientos", gp_params.client_os());
params.insert("os-version", gp_params.os_version().unwrap_or_default());
params.insert("hostid", req.host_id.as_str());
params.insert("serialno", req.serial_number.as_str());
params.insert("portal-cc-auth-cookie", req.auth_cookie.as_str());
params.insert("config-digest", req.config_digest.as_str());
params.insert("csc-digest", req.csc_digest.as_str());
params.insert("csc-data", req.csc_data.as_str());
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
fn build_csc_data(
input: CscDataInput<'_>,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> anyhow::Result<String> {
let mut root = Element::new("hip-report");
push_text(&mut root, "portal-csc-auth-cookie", input.auth_cookie);
push_text(&mut root, "user-name", &urlencoding::encode(input.username));
push_text(&mut root, "client-os", &client_os_report_value(input.gp_params));
push_text(&mut root, "host-id", input.host_id);
push_text(&mut root, "device-serial-number", input.serial_number);
push_text(&mut root, "csc-digest", input.csc_digest);
root.children.push(XMLNode::Element(Element::new("categories")));
root.children.push(XMLNode::Element(build_custom_checks(
input.criteria,
input.gp_params,
reader,
summary,
)));
let mut bytes = Vec::new();
root.write_with_config(
&mut bytes,
EmitterConfig::new()
.perform_indent(true)
.write_document_declaration(true),
)?;
String::from_utf8(bytes).map_err(Into::into)
}
fn build_custom_checks(
criteria: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut custom_checks = Element::new("custom-checks");
let Some(requested_checks) = criteria.descendant("custom-checks") else {
return custom_checks;
};
if gp_params.client_os() == "Mac"
&& let Some(plist) = requested_checks
.child("mac-os")
.and_then(|mac_os| mac_os.child("plist"))
{
custom_checks
.children
.push(XMLNode::Element(build_plist_checks(plist, gp_params, reader, summary)));
}
if gp_params.client_os() == "Linux"
&& let Some(process_list) = requested_checks
.child("linux")
.and_then(|linux| linux.child("process-list"))
.or_else(|| requested_checks.child("process-list"))
{
custom_checks.children.push(XMLNode::Element(build_process_list_checks(
process_list,
reader,
summary,
)));
}
custom_checks
}
fn build_plist_checks(
plist: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("plist");
for entry in plist.children("entry") {
let domain = entry.attr("name").unwrap_or_default();
let mut out_entry = Element::new("entry");
out_entry.attributes.insert("name".to_string(), domain.to_string());
let keys = plist_entry_keys(entry);
let values: Vec<_> = keys
.iter()
.map(|key| {
let value = gp_params
.csc_preference_override(domain, key)
.map(str::to_string)
.or_else(|| reader.read_preference(domain, key));
(key.as_str(), value)
})
.collect();
let plist_exists = values.iter().any(|(_, value)| value.is_some());
summary.plist_entries += keys.len();
summary.plist_present += values.iter().filter(|(_, value)| value.is_some()).count();
summary.plist_missing += values.iter().filter(|(_, value)| value.is_none()).count();
push_text(&mut out_entry, "exist", yes_no(plist_exists));
push_text(&mut out_entry, "value", "");
let mut preference_value = Element::new("preference-value");
for (key, value) in values {
let mut pref_entry = Element::new("entry");
pref_entry.attributes.insert("name".to_string(), key.to_string());
push_text(&mut pref_entry, "exist", yes_no(value.is_some()));
push_text(&mut pref_entry, "value", value.as_deref().unwrap_or_default());
preference_value.children.push(XMLNode::Element(pref_entry));
}
out_entry.children.push(XMLNode::Element(preference_value));
out.children.push(XMLNode::Element(out_entry));
}
out
}
fn build_process_list_checks(
process_list: &Element,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("process-list");
for process_name in process_list_names(process_list) {
let exists = reader.process_exists(&process_name);
summary.process_entries += 1;
if exists {
summary.process_present += 1;
} else {
summary.process_missing += 1;
}
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), process_name.clone());
push_text(&mut entry, "exist", yes_no(exists));
push_text(&mut entry, "value", if exists { &process_name } else { "" });
out.children.push(XMLNode::Element(entry));
}
out
}
fn plist_entry_keys(entry: &Element) -> Vec<String> {
let keys: Vec<String> = entry
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.to_string())
.collect();
if keys.is_empty() {
entry
.attr("name")
.map(|name| vec![name.to_string()])
.unwrap_or_default()
} else {
keys
}
}
fn process_list_names(process_list: &Element) -> Vec<String> {
let mut names: Vec<String> = process_list
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
process_list
.children("entry")
.into_iter()
.filter_map(|entry| entry.attr("name"))
.map(str::to_string),
);
names.sort();
names.dedup();
names
}
fn pan_md5_hex(value: &[u8]) -> String {
let digest = md5::compute(value);
let mut out = String::new();
for byte in digest.0 {
write!(&mut out, "{:x}", byte).expect("writing to String should not fail");
}
out
}
fn collect_host_id(gp_params: &GpParams) -> String {
match gp_params.client_os() {
"Mac" => netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.unwrap_or_default(),
"Windows" => host_utils::get_machine_id().to_string(),
_ => host_utils::derive_uuid(&[]),
}
}
fn collect_serial_number() -> String {
collect_macos_serial_number()
.or_else(collect_linux_serial_number)
.or_else(collect_windows_serial_number)
.unwrap_or_default()
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.into_iter()
.filter_map(|path| fs::read_to_string(path).ok())
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M.")
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn read_macos_preference(domain: &str, key: &str) -> Option<String> {
if cfg!(not(target_os = "macos")) {
return None;
}
let output = Command::new("defaults").args(["read", domain, key]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn linux_process_names() -> Vec<String> {
let Ok(entries) = fs::read_dir("/proc") else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
entry
.file_name()
.to_str()
.filter(|name| name.chars().all(|ch| ch.is_ascii_digit()))
.map(|_| entry.path().join("stat"))
})
.filter_map(|path| fs::read_to_string(path).ok())
.filter_map(|stat| {
let start = stat.find('(')?;
let end = stat.rfind(')')?;
stat.get(start + 1..end).map(str::to_string)
})
.filter(|name| !name.is_empty())
.collect()
}
fn client_os_report_value(gp_params: &GpParams) -> String {
gp_params
.os_version()
.unwrap_or_else(|| gp_params.client_os())
.replace(' ', "+")
}
fn push_text(parent: &mut Element, name: &str, value: &str) {
let mut element = Element::new(name);
element.children.push(XMLNode::Text(value.to_string()));
parent.children.push(XMLNode::Element(element));
}
fn yes_no(value: bool) -> &'static str {
if value { "yes" } else { "no" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gp_params::{ClientOs, GpParams};
struct TestCscDataReader {
values: HashMap<String, String>,
processes: Vec<String>,
}
impl CscDataReader for TestCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
self.values.get(&format!("{domain}:{key}")).cloned()
}
fn process_exists(&self, name: &str) -> bool {
self.processes.iter().any(|process| process == name)
}
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
fn gp_params(client_os: ClientOs) -> GpParams {
GpParams::builder()
.client_os(client_os)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.build()
}
#[test]
fn detects_config_criteria_response() {
assert!(is_config_criteria(&parse_xml("<config-criteria/>")));
assert!(!is_config_criteria(&parse_xml("<policy/>")));
}
#[test]
fn builds_macos_plist_csc_report_with_existing_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings">
<key><member>ExampleKey</member></key>
</entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([(
"com.example.settings:ExampleKey".to_string(),
"ExampleValue".to_string(),
)]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "[email protected]", &gp_params(ClientOs::Mac), &reader).unwrap();
assert_eq!(req.auth_cookie, "cookie");
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>"));
assert!(req.csc_data.contains("<client-os>Apple+Mac+OS+X+26.4.1</client-os>"));
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
#[test]
fn reports_missing_macos_plist_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>Missing</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[test]
fn macos_plist_override_works_without_native_preference() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings"><key><member>ExampleKey</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = GpParams::builder()
.client_os(ClientOs::Mac)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.csc_preference_override("com.example.settings", "ExampleKey", "ExampleValue")
.build();
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
}
#[test]
fn unsupported_client_os_ignores_macos_plist_branch() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>HipID</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([("com.example:HipID".to_string(), "present".to_string())]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(!req.csc_data.contains("<plist>"));
assert!(!req.csc_data.contains("<exist>no</exist>"));
assert!(!req.csc_data.contains("present"));
}
#[test]
fn builds_linux_process_list_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<linux>
<process-list>
<entry name="present-process" />
<entry name="missing-process" />
</process-list>
</linux>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: vec!["present-process".to_string()],
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(req.csc_data.contains(r#"<entry name="present-process">"#));
assert!(req.csc_data.contains("<value>present-process</value>"));
assert!(req.csc_data.contains(r#"<entry name="missing-process">"#));
assert!(req.summary().contains("process_entries=2"));
assert!(req.summary().contains("process_present=1"));
assert!(req.summary().contains("process_missing=1"));
}
#[test]
fn uses_pan_non_padded_md5_digest() {
assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e");
assert_ne!(pan_md5_hex(b""), format!("{:x}", md5::compute(b"")));
}
#[test]
fn builds_getconfig_csc_params() {
let req = CscRequest {
auth_cookie: "cookie".to_string(),
config_digest: "config-digest".to_string(),
csc_digest: "csc-digest".to_string(),
csc_data: "<hip-report><host-id>host</host-id><device-serial-number>serial</device-serial-number></hip-report>"
.to_string(),
summary: CscBuildSummary::default(),
host_id: "host".to_string(),
serial_number: "serial".to_string(),
};
let nonce = "123";
let gp_params = gp_params(ClientOs::Mac);
let params = csc_params(&req, "alice", &gp_params, nonce);
assert_eq!(params.get("user"), Some(&"alice"));
assert_eq!(params.get("hostid"), Some(&"host"));
assert_eq!(params.get("serialno"), Some(&"serial"));
assert_eq!(params.get("portal-cc-auth-cookie"), Some(&"cookie"));
assert_eq!(params.get("config-digest"), Some(&"config-digest"));
assert_eq!(params.get("csc-digest"), Some(&"csc-digest"));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
}
#[test]
fn generated_getconfig_csc_params_include_final_digest_and_data() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks />
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = gp_params(ClientOs::Linux);
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
let params = csc_params(&req, "alice", &gp_params, "123");
assert_eq!(params.get("csc-digest"), Some(&req.csc_digest.as_str()));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
}
+1
View File
@@ -1,4 +1,5 @@
mod config; mod config;
mod csc;
mod prelogin; mod prelogin;
pub use config::*; pub use config::*;
+54
View File
@@ -123,6 +123,46 @@ pub fn redact_uri(uri: &str) -> String {
url.to_string() url.to_string()
} }
pub fn redact_form_params(params: &[(&str, &str)]) -> String {
let mut pairs = params
.iter()
.map(|(key, value)| (*key, redact_form_value(key, value)))
.collect::<Vec<_>>();
pairs.sort_by(|(left, _), (right, _)| left.cmp(right));
form_urlencoded::Serializer::new(String::new())
.extend_pairs(pairs)
.finish()
}
fn redact_form_value(key: &str, value: &str) -> String {
if value.is_empty() || is_safe_form_param(key) {
return value.to_string();
}
format!("redacted-{}", value.len())
}
fn is_safe_form_param(key: &str) -> bool {
matches!(
key,
"clientVer"
| "clientos"
| "config-digest"
| "csc-digest"
| "csc-support"
| "direct"
| "ipv6-support"
| "jnlpReady"
| "ok"
| "os-version"
| "prot"
| "swg-auth-token"
| "swg-nonce"
)
}
fn redact_query(query: Option<&str>) -> Option<String> { fn redact_query(query: Option<&str>) -> Option<String> {
let query = query?; let query = query?;
@@ -190,6 +230,20 @@ mod tests {
assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x"); assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x");
} }
#[test]
fn it_should_redact_form_params() {
let params = [
("portal-userauthcookie", "secret-cookie"),
("csc-support", "yes"),
("prelogin-cookie", ""),
];
assert_eq!(
redact_form_params(&params),
"csc-support=yes&portal-userauthcookie=redacted-13&prelogin-cookie="
);
}
#[test] #[test]
fn it_should_redact_data_uri() { fn it_should_redact_data_uri() {
let uri = "data:text/plain;a"; let uri = "data:text/plain;a";
+4 -4
View File
@@ -46,10 +46,10 @@ impl ElementExt for Element {
} }
for child in &self.children { for child in &self.children {
if let Some(element) = child.as_element() { if let Some(element) = child.as_element()
if let Some(found) = element.descendant(name) { && let Some(found) = element.descendant(name)
return Some(found); {
} return Some(found);
} }
} }
+9 -5
View File
@@ -1,6 +1,10 @@
use std::{env, path::PathBuf, process::Command}; use std::{
env,
path::{Path, PathBuf},
process::Command,
};
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) { fn apply_patches(patches_dir: &Path, build_src: &Path) {
let patches = std::fs::read_dir(patches_dir) let patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory") .expect("Failed to read patches directory")
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())
@@ -30,7 +34,7 @@ fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
} }
} }
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { fn build_libxml2(deps_dir: &Path, out_dir: &Path) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2"); let libxml2_dir = deps_dir.join("libxml2");
// The temporary location where we will build // The temporary location where we will build
@@ -89,7 +93,7 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
dst dst
} }
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { fn build_openconnect(deps_dir: &Path, out_dir: &Path) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect"); let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches"); let patches_dir = deps_dir.join("patches");
@@ -200,6 +204,6 @@ fn main() {
cc::Build::new() cc::Build::new()
.file("src/ffi/vpn.c") .file("src/ffi/vpn.c")
.include("src/ffi") .include("src/ffi")
.include(&oc_dst.join("include")) .include(oc_dst.join("include"))
.compile("vpn"); .compile("vpn");
} }
+2 -2
View File
@@ -44,11 +44,11 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
} }
pub fn find_vpnc_script() -> Option<&'static str> { pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(&VPNC_SCRIPT_LOCATIONS) find_executable(VPNC_SCRIPT_LOCATIONS)
} }
pub fn find_csd_wrapper() -> Option<&'static str> { pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(&CSD_WRAPPER_LOCATIONS) find_executable(CSD_WRAPPER_LOCATIONS)
} }
/// If file exists, check if it is executable /// If file exists, check if it is executable
@@ -336,7 +336,11 @@ if [ -n "$IPROUTE" ]; then
del_vpngateway_route() { del_vpngateway_route() {
echo "$VPNGATEWAY" | grep -q : && FAMILY=-6 || FAMILY=-4 echo "$VPNGATEWAY" | grep -q : && FAMILY=-6 || FAMILY=-4
$IPROUTE route $route_syntax_del "$VPNGATEWAY" # iproute2 deletes only one matching route at a time. The connect path may
# add one host route per matching uplink, so remove them until none remain.
while $IPROUTE $FAMILY route $route_syntax_del "$VPNGATEWAY" 2>/dev/null ; do
:
done
if [ $FAMILY != -4 ]; then if [ $FAMILY != -4 ]; then
$IPROUTE $FAMILY route flush cache 2>/dev/null $IPROUTE $FAMILY route flush cache 2>/dev/null
fi fi