diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index c2b5788..d58e580 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -147,6 +147,7 @@ jobs: - name: Build ${{ matrix.package }} package in Docker run: | docker run --rm \ + -e LIBXML2_STATIC=1 \ -v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \ yuezk/gpdev:${{ matrix.package }}-builder - name: Install ${{ matrix.package }} package in Docker @@ -201,7 +202,7 @@ jobs: run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin - name: Build gpgui in Docker run: | - docker run --rm -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder + docker run --rm -e LIBXML2_STATIC=1 -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder - name: Install gpgui in Docker run: | cd gpgui-source diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index aab401f..a712c4b 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -111,6 +111,7 @@ jobs: - name: Build ${{ matrix.package }} package in Docker run: | docker run --rm \ + -e LIBXML2_STATIC=1 \ -v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \ -e INCLUDE_GUI=1 \ yuezk/gpdev:${{ matrix.package }}-builder @@ -151,4 +152,3 @@ jobs: tag_name: ${{ inputs.tag }} files: | gh-release/artifact-*/* - diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..9f23140 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "crates/openconnect/deps/openconnect"] + path = crates/openconnect/deps/openconnect + url = https://gitlab.com/openconnect/openconnect.git +[submodule "crates/openconnect/deps/libxml2"] + path = crates/openconnect/deps/libxml2 + url = https://gitlab.gnome.org/GNOME/libxml2.git diff --git a/Cargo.lock b/Cargo.lock index 9d5037b..2ca2fd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -128,6 +128,50 @@ version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" +[[package]] +name = "askama" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28" +dependencies = [ + "askama_derive", + "askama_escape", + "humansize", + "num-traits", + "percent-encoding", +] + +[[package]] +name = "askama_derive" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83" +dependencies = [ + "askama_parser", + "basic-toml", + "mime", + "mime_guess", + "proc-macro2", + "quote", + "serde", + "syn 2.0.96", +] + +[[package]] +name = "askama_escape" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341" + +[[package]] +name = "askama_parser" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0" +dependencies = [ + "nom", +] + [[package]] name = "async-trait" version = "0.1.85" @@ -169,6 +213,15 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" +[[package]] +name = "autotools" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef941527c41b0fc0dd48511a8154cd5fc7e29200a0ff8b7203c5d777dbc795cf" +dependencies = [ + "cc", +] + [[package]] name = "axum" version = "0.7.9" @@ -260,6 +313,15 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -471,8 +533,10 @@ checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" dependencies = [ "android-tzdata", "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-targets 0.52.6", ] @@ -1039,7 +1103,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -1128,6 +1192,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futf" version = "0.1.5" @@ -1489,9 +1559,11 @@ dependencies = [ "dns-lookup", "home", "log", + "machine-uid", "md5", "open", "openssl", + "os_info", "pem", "redact-engine", "regex", @@ -1509,6 +1581,7 @@ dependencies = [ "tokio", "url", "urlencoding", + "uuid", "uzers", "webbrowser", "which", @@ -1541,6 +1614,8 @@ name = "gpclient" version = "2.3.11" dependencies = [ "anyhow", + "askama", + "chrono", "clap", "common", "compile-time", @@ -1552,10 +1627,12 @@ dependencies = [ "openconnect", "reqwest", "serde_json", + "serde_urlencoded", "sysinfo", "tempfile", "tokio", "whoami", + "xmltree", ] [[package]] @@ -1816,6 +1893,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humansize" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" +dependencies = [ + "libm", +] + [[package]] name = "humantime" version = "2.1.0" @@ -2345,9 +2431,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.169" +version = "0.2.185" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" +checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" @@ -2426,6 +2518,17 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" +[[package]] +name = "machine-uid" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d7217d573cdb141d6da43113b098172e057d39915d79c4bdedbc3aacd46bd96" +dependencies = [ + "libc", + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "malloc_buf" version = "0.0.6" @@ -2497,6 +2600,22 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.3" @@ -2596,6 +2715,16 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "ntapi" version = "0.4.1" @@ -2749,9 +2878,12 @@ dependencies = [ name = "openconnect" version = "2.3.11" dependencies = [ + "autotools", "cc", "common", + "fs_extra", "log", + "pkg-config", ] [[package]] @@ -2814,6 +2946,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "os_info" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0e1ac5fde8d43c34139135df8ea9ee9465394b2d8d20f032d38998f64afffc3" +dependencies = [ + "log", + "plist", + "windows-sys 0.52.0", +] + [[package]] name = "overload" version = "0.1.1" @@ -3431,7 +3574,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -3695,6 +3838,12 @@ dependencies = [ "digest", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.8" @@ -4308,7 +4457,7 @@ dependencies = [ "getrandom 0.2.15", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -4679,6 +4828,12 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.14" @@ -4762,6 +4917,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b" dependencies = [ "getrandom 0.2.15", + "sha1_smol", ] [[package]] @@ -5103,7 +5259,7 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.48.0", ] [[package]] @@ -5174,12 +5330,47 @@ dependencies = [ "windows-tokens", ] +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-metadata" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ee5e275231f07c6e240d14f34e1b635bf1faa1c76c57cfd59a5cdb9848e4278" +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.45.0" @@ -5216,6 +5407,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.42.2" @@ -5561,9 +5761,9 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" [[package]] name = "wry" -version = "0.24.11" +version = "0.24.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c55c80b12287eb1ff7c365fc2f7a5037cb6181bd44c9fce81c8d1cf7605ffad6" +checksum = "4a2a144c3ab5e83e04724bc8e67cea552ffae413185fda459fafdae173fd985d" dependencies = [ "base64 0.13.1", "block", @@ -5629,6 +5829,21 @@ dependencies = [ "rustix", ] +[[package]] +name = "xml-rs" +version = "0.8.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" + +[[package]] +name = "xmltree" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b619f8c85654798007fb10afa5125590b43b088c225a25fc2fec100a9fad0fc6" +dependencies = [ + "xml-rs", +] + [[package]] name = "xz2" version = "0.1.7" diff --git a/Makefile b/Makefile index a2a6b69..44ea9ef 100644 --- a/Makefile +++ b/Makefile @@ -117,6 +117,9 @@ install: install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \ fi + install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script + install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + # Install the disconnect hooks install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook @@ -137,6 +140,9 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui + rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script + rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook @@ -156,7 +162,7 @@ init-debian: clean-debian tarball cp .build/tarball/${PKG}.tar.gz .build/deb tar -xzf .build/deb/${PKG}.tar.gz -C .build/deb - cd .build/deb/${PKG} && debmake + cd .build/deb/${PKG} && LC_ALL=C.UTF-8 LANG=C.UTF-8 PYTHONUTF8=1 debmake cp -f packaging/deb/control.in .build/deb/$(PKG)/debian/control cp -f packaging/deb/rules.in .build/deb/$(PKG)/debian/rules diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index bf94362..d9026a0 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -73,7 +73,9 @@ struct Cli { #[arg( long, - help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable" + help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers", + default_missing_value = "default", + num_args=0..=1 )] browser: Option, } @@ -104,7 +106,12 @@ impl Cli { }; if let Some(browser_auth) = browser_auth { - browser_auth.authenticate()?; + if let Some(auth_data) = browser_auth.authenticate()? { + info!("Authentication completed"); + println!("{}", json!(SamlAuthResult::Success(auth_data))); + + return Ok(()); + } info!("Please continue the authentication process in the default browser"); diff --git a/apps/gpclient/Cargo.toml b/apps/gpclient/Cargo.toml index ec44640..0d29894 100644 --- a/apps/gpclient/Cargo.toml +++ b/apps/gpclient/Cargo.toml @@ -10,6 +10,8 @@ common = { path = "../../crates/common" } gpapi = { path = "../../crates/gpapi", features = ["clap"] } openconnect = { path = "../../crates/openconnect" } anyhow.workspace = true +askama = "0.12" +chrono = "0.4" clap.workspace = true env_logger.workspace = true inquire = "0.6.2" @@ -17,8 +19,10 @@ log.workspace = true tokio = { workspace = true, features = ["rt-multi-thread"] } sysinfo.workspace = true serde_json.workspace = true +serde_urlencoded.workspace = true whoami.workspace = true tempfile.workspace = true reqwest.workspace = true directories = "5.0" compile-time.workspace = true +xmltree = "0.11" diff --git a/apps/gpclient/src/cli.rs b/apps/gpclient/src/cli.rs index 829f798..d879a0c 100644 --- a/apps/gpclient/src/cli.rs +++ b/apps/gpclient/src/cli.rs @@ -8,6 +8,7 @@ use tempfile::NamedTempFile; use crate::{ connect::{ConnectArgs, ConnectHandler}, disconnect::{DisconnectArgs, DisconnectHandler}, + hip::{HipArgs, HipHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, }; @@ -26,6 +27,8 @@ enum CliCommand { Disconnect(DisconnectArgs), #[command(about = "Launch the GUI")] LaunchGui(LaunchGuiArgs), + #[command(about = "Generate HIP report")] + Hip(HipArgs), } #[derive(Parser)] @@ -50,7 +53,10 @@ struct Cli { #[command(subcommand)] command: CliCommand, - #[arg(long, help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.")] + #[arg( + long, + help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats." + )] fix_openssl: bool, #[arg(long, help = "Ignore the TLS errors")] ignore_tls_errors: bool, @@ -83,6 +89,7 @@ impl Cli { CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await, CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await, CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await, + CliCommand::Hip(args) => HipHandler::new(args).handle().await, } } } diff --git a/apps/gpclient/src/connect.rs b/apps/gpclient/src/connect.rs index 3ae70ae..5b21282 100644 --- a/apps/gpclient/src/connect.rs +++ b/apps/gpclient/src/connect.rs @@ -104,7 +104,9 @@ pub(crate) struct ConnectArgs { #[arg( long, - help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable" + help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers", + default_missing_value = "default", + num_args=0..=1 )] browser: Option, } diff --git a/apps/gpclient/src/hip.rs b/apps/gpclient/src/hip.rs new file mode 100644 index 0000000..c5df9b7 --- /dev/null +++ b/apps/gpclient/src/hip.rs @@ -0,0 +1,258 @@ +use askama::Template; +use clap::Args; +use gpapi::{clap::args::Os, utils::host_utils}; +use log::debug; +use std::{collections::HashMap, env}; +use xmltree::Element; + +#[derive(Template)] +#[template(path = "hip_report.xml")] +struct HipReportTemplate<'a> { + client_version: &'a str, + generate_time: String, + day: String, + month: String, + year: String, + user_name: &'a str, + host_info: HostInfo<'a>, + md5: &'a str, +} + +struct HostInfo<'a> { + os_vendor: &'a str, + os_version: &'a str, + host_id: String, + host_name: String, + software_version: &'a str, + domain: String, + network_interfaces: Vec, +} + +impl<'a> HostInfo<'a> { + fn default_ipv4(&self) -> &str { + self + .network_interfaces + .first() + .and_then(|iface| iface.ipv4.as_deref()) + .unwrap_or_default() + } + + fn default_ipv6(&self) -> &str { + self + .network_interfaces + .first() + .and_then(|iface| iface.ipv6.as_deref()) + .unwrap_or_default() + } +} + +#[derive(Clone)] +struct NetworkInterface { + name: String, + description: String, + mac_address: Option, + ipv4: Option, + ipv6: Option, +} + +impl NetworkInterface { + fn new(name: impl Into, description: impl Into) -> Self { + Self { + name: name.into(), + description: description.into(), + mac_address: None, + ipv4: None, + ipv6: None, + } + } + + fn with_ipv4(mut self, ipv4: Option) -> Self { + self.ipv4 = ipv4; + self + } + + fn with_ipv6(mut self, ipv6: Option) -> Self { + self.ipv6 = ipv6; + self + } +} + +#[derive(Args)] +pub(crate) struct HipArgs { + #[arg( + long, + help = "The GP client version, defaults to APP_VERSION or the packaged version" + )] + client_version: Option, + + #[arg(long, value_enum, default_value_t = HipArgs::default_os(), help = "The client OS")] + client_os: Os, + + #[arg(long, help = "The OS version string, defaults to a computed value for the target OS")] + os_version: Option, + + #[arg(long, help = "The authentication cookie")] + cookie: String, + + #[arg(long, help = "The client IPv4 address")] + client_ip: Option, + + #[arg(long, help = "The client IPv6 address")] + client_ipv6: Option, + + #[arg(long, help = "The MD5 digest to encode into the HIP report")] + md5: String, +} + +impl HipArgs { + fn default_os() -> Os { + if cfg!(target_os = "macos") { + Os::Mac + } else if cfg!(target_os = "windows") { + Os::Windows + } else { + Os::Linux + } + } + + fn client_version(&self) -> String { + self + .client_version + .clone() + .or_else(|| env::var("APP_VERSION").ok()) + .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string()) + } + + fn os_version(&self) -> String { + self.os_version.clone().unwrap_or_else(|| match self.client_os { + Os::Linux => host_utils::get_linux_os_string().to_string(), + Os::Windows => host_utils::get_windows_os_string().to_string(), + Os::Mac => host_utils::get_macos_os_string().to_string(), + }) + } +} + +pub(crate) struct HipHandler<'a> { + args: &'a HipArgs, +} + +impl<'a> HipHandler<'a> { + pub(crate) fn new(args: &'a HipArgs) -> Self { + Self { args } + } + + pub(crate) async fn handle(&self) -> anyhow::Result<()> { + let cookie_params = self.parse_cookie(); + let report = self.generate_hip_report(&cookie_params)?; + + debug!("Generated HIP report:\n{}", report); + println!("{}", report); + + Ok(()) + } + + fn parse_cookie(&self) -> HashMap { + serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default() + } + + fn generate_hip_report(&self, cookie_params: &HashMap) -> anyhow::Result { + let (generate_time, day, month, year) = get_current_time_components(); + let client_version = self.args.client_version(); + let os_version = self.args.os_version(); + let user_name = cookie_params.get("user").map(|value| value.as_str()).unwrap_or(""); + let host_info = self.collect_host_info(cookie_params, &os_version); + + let template = HipReportTemplate { + client_version: &client_version, + generate_time, + day, + month, + year, + user_name, + host_info, + md5: &self.args.md5, + }; + + format_xml(&template.render()?) + } + + fn collect_host_info<'b>(&'b self, cookie_params: &'b HashMap, os_version: &'b str) -> HostInfo<'b> { + let domain = cookie_params.get("domain").cloned().unwrap_or_default(); + let ipv4 = self + .args + .client_ip + .clone() + .or_else(|| cookie_params.get("preferred-ip").cloned()); + let ipv6 = self + .args + .client_ipv6 + .clone() + .or_else(|| cookie_params.get("preferred-ipv6").cloned()); + + match self.args.client_os { + Os::Linux => HostInfo { + os_vendor: "Linux", + os_version, + host_id: host_utils::derive_uuid(&["linux"]), + host_name: whoami::devicename(), + software_version: "", + domain, + network_interfaces: vec![NetworkInterface::new("enp1s0f0", "enp1s0f0") + .with_ipv4(ipv4) + .with_ipv6(ipv6)], + }, + Os::Mac => HostInfo { + os_vendor: "Apple", + os_version, + host_id: host_utils::get_machine_id().to_string(), + host_name: whoami::devicename(), + software_version: host_utils::get_macos_version(), + domain, + network_interfaces: vec![NetworkInterface::new("en0", "en0").with_ipv4(ipv4).with_ipv6(ipv6)], + }, + Os::Windows => { + let iface = NetworkInterface::new( + format!("{{{}}}", host_utils::derive_uuid(&["pangp"]).to_uppercase()), + "PANGP Virtual Ethernet Adapter Secure", + ) + .with_ipv4(ipv4) + .with_ipv6(ipv6); + + let loopback = NetworkInterface { + name: iface.name.clone(), + description: "Software Loopback Interface 1".to_string(), + mac_address: Some(String::new()), + ipv4: Some("127.0.0.1".to_string()), + ipv6: Some("::1".to_string()), + }; + + HostInfo { + os_vendor: "Microsoft", + os_version, + host_id: host_utils::get_machine_id().to_string(), + host_name: whoami::devicename(), + software_version: host_utils::get_windows_version(), + domain, + network_interfaces: vec![iface, loopback], + } + } + } + } +} + +fn get_current_time_components() -> (String, String, String, String) { + let now = chrono::Local::now(); + ( + now.format("%m/%d/%Y %H:%M:%S").to_string(), + now.format("%d").to_string(), + now.format("%m").to_string(), + now.format("%Y").to_string(), + ) +} + +fn format_xml(xml_str: &str) -> anyhow::Result { + let xml = Element::parse(xml_str.as_bytes())?; + let mut xml_buf = Vec::new(); + xml.write_with_config(&mut xml_buf, xmltree::EmitterConfig::new().perform_indent(true))?; + Ok(String::from_utf8(xml_buf)?) +} diff --git a/apps/gpclient/src/main.rs b/apps/gpclient/src/main.rs index 41343ed..eacc565 100644 --- a/apps/gpclient/src/main.rs +++ b/apps/gpclient/src/main.rs @@ -1,6 +1,7 @@ mod cli; mod connect; mod disconnect; +mod hip; mod launch_gui; pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock"; diff --git a/apps/gpclient/templates/hip_report.xml b/apps/gpclient/templates/hip_report.xml new file mode 100644 index 0000000..4c1c699 --- /dev/null +++ b/apps/gpclient/templates/hip_report.xml @@ -0,0 +1,275 @@ + + + {{ md5 }} + {{ user_name }} + {{ host_info.domain }}.internal + {{ host_info.host_name }} + {{ host_info.host_id }} + {{ host_info.default_ipv4() }} + {{ host_info.default_ipv6() }} + {{ generate_time }} + 4 + + + {{ client_version }} + {{ host_info.os_version }} + {{ host_info.os_vendor }} + {{ host_info.domain }}.internal + {{ host_info.host_name }} + {{ host_info.host_id }} + + {% for iface in host_info.network_interfaces.iter() -%} + + {{ iface.description }} + {% if let Some(mac) = iface.mac_address -%} + {{ mac }} + {% endif -%} + {% if let Some(ipv4) = iface.ipv4 -%} + + + + {% endif -%} + {% if let Some(ipv6) = iface.ipv6 -%} + + + + {% endif -%} + + {% endfor -%} + + + {% if host_info.os_vendor == "Microsoft" -%} + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + n/a + + + + + + + + + + + + + C:\\ + full + + + + + + + + + + + + + yes + + + + + + + + + + + yes + + + + + + + yes + + + + + + {% else if host_info.os_vendor == "Apple" -%} + + + + + + yes + n/a + + + + + + yes + n/a + + + + + + + + + + n/a + + + + + + + + + + + + Macintosh HD + encrypted + + + Data + encrypted + + + All + encrypted + + + + + + + + + + + + yes + + + + + + no + + + + + + + + + + yes + + + + + + + {% else if host_info.os_vendor == "Linux" -%} + + + + + + + + + + + + + + + / + encrypted + + + + + + + + + + + + + no + + + + + + + n/a + + + + + + + + + + + yes + + + + + + + {% endif -%} + + diff --git a/crates/common/src/vpn_utils.rs b/crates/common/src/vpn_utils.rs index 5366154..ff1bfa0 100644 --- a/crates/common/src/vpn_utils.rs +++ b/crates/common/src/vpn_utils.rs @@ -2,22 +2,30 @@ use std::{io, path::Path}; use is_executable::IsExecutable; -const VPNC_SCRIPT_LOCATIONS: [&str; 6] = [ +const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ + "/usr/libexec/gpclient/vpnc-script", + "/usr/lib/gpclient/vpnc-script", "/usr/local/share/vpnc-scripts/vpnc-script", "/usr/local/sbin/vpnc-script", "/usr/share/vpnc-scripts/vpnc-script", "/usr/sbin/vpnc-script", "/etc/vpnc/vpnc-script", "/etc/openconnect/vpnc-script", + #[cfg(target_os = "macos")] + "/opt/homebrew/etc/vpnc/vpnc-script", ]; -const CSD_WRAPPER_LOCATIONS: [&str; 3] = [ +const CSD_WRAPPER_LOCATIONS: &[&str] = &[ + "/usr/libexec/gpclient/hipreport.sh", + "/usr/lib/gpclient/hipreport.sh", #[cfg(target_arch = "x86_64")] "/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh", #[cfg(target_arch = "aarch64")] "/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/openconnect/hipreport.sh", "/usr/libexec/openconnect/hipreport.sh", + #[cfg(target_os = "macos")] + "/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh", ]; fn find_executable(locations: &[&str]) -> Option { diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index e87456a..3e3754f 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -31,6 +31,8 @@ serde_urlencoded.workspace = true md5.workspace = true sha256.workspace = true which.workspace = true +machine-uid = "0.5" +uuid = { version = "1", features = ["v5"] } # Pin the version of home because the latest version requires Rust 1.81 home = "=0.5.9" @@ -40,6 +42,9 @@ clap = { workspace = true, optional = true } open = { version = "5", optional = true } webbrowser = { version = "1", optional = true } +[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies] +os_info = { version = "3", default-features = false } + [features] tauri = ["dep:tauri"] clap = ["dep:clap"] diff --git a/crates/gpapi/src/process/browser_authenticator.rs b/crates/gpapi/src/process/browser_authenticator.rs index 7657ca3..c1ade6f 100644 --- a/crates/gpapi/src/process/browser_authenticator.rs +++ b/crates/gpapi/src/process/browser_authenticator.rs @@ -1,8 +1,20 @@ -use std::{borrow::Cow, env::temp_dir, fs, io::Write, os::unix::fs::PermissionsExt}; +use std::{ + borrow::Cow, + env::temp_dir, + fs, + io::{Read, Write}, + net::{TcpListener, UdpSocket}, + os::unix::fs::PermissionsExt, + thread, +}; use anyhow::bail; use log::{info, warn}; +use crate::auth::SamlAuthData; + +const REMOTE_AUTH_PATH: &str = "/auth"; + pub struct BrowserAuthenticator<'a> { auth_request: &'a str, browser: Option<&'a str>, @@ -28,7 +40,14 @@ impl BrowserAuthenticator<'_> { } } - pub fn authenticate(&self) -> anyhow::Result<()> { + pub fn authenticate(&self) -> anyhow::Result> { + if self + .browser + .is_some_and(|browser| browser.eq_ignore_ascii_case("remote")) + { + return self.authenticate_remote(); + } + let path = if self.auth_request.starts_with("http") { Cow::Borrowed(self.auth_request) } else { @@ -60,7 +79,36 @@ impl BrowserAuthenticator<'_> { webbrowser::open(path.as_ref())?; } - Ok(()) + Ok(None) + } + + fn authenticate_remote(&self) -> anyhow::Result> { + let local_ip = detect_local_ip()?; + let listener = TcpListener::bind((local_ip.as_str(), 0))?; + let auth_url = format!("http://{}{}", listener.local_addr()?, REMOTE_AUTH_PATH); + let auth_request = self.auth_request.to_string(); + + thread::spawn(move || serve_auth_request(listener, auth_request)); + + info!( + r#" + +==== Manual Authentication Required ==== + +Please open the following URL in your browser: + +{} + +After completing the authentication, please paste the authentication data back to this terminal. +(The data should start with "globalprotectcallback:...") +"#, + auth_url + ); + + let mut data = String::new(); + std::io::stdin().read_line(&mut data)?; + + Ok(Some(SamlAuthData::from_gpcallback(data.trim())?)) } } @@ -75,3 +123,90 @@ fn find_browser_path(browser: &str) -> String { browser.into() } } + +fn detect_local_ip() -> anyhow::Result { + let socket = UdpSocket::bind("0.0.0.0:0")?; + socket.connect("1.1.1.1:80")?; + + let ip = socket.local_addr()?.ip().to_string(); + info!("Determined local IP address: {}", ip); + + Ok(ip) +} + +fn serve_auth_request(listener: TcpListener, auth_request: String) { + let Ok(addr) = listener.local_addr() else { + warn!("Failed to determine auth server address"); + return; + }; + + let auth_url = format!("http://{}{}", addr, REMOTE_AUTH_PATH); + info!("Auth server started at: {}", auth_url); + + for incoming in listener.incoming() { + let mut stream = match incoming { + Ok(stream) => stream, + Err(err) => { + warn!("Failed to accept auth request: {}", err); + continue; + } + }; + + let mut request = [0_u8; 4096]; + let size = match stream.read(&mut request) { + Ok(size) => size, + Err(err) => { + warn!("Failed to read auth request: {}", err); + continue; + } + }; + + let request = String::from_utf8_lossy(&request[..size]); + let path = request + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or("/"); + + if path != REMOTE_AUTH_PATH { + let _ = write_response(&mut stream, "404 Not Found", "text/plain", "not found", None); + continue; + } + + let response = if auth_request.starts_with("http") { + write_response( + &mut stream, + "302 Found", + "text/plain", + "redirect", + Some(("Location", auth_request.as_str())), + ) + } else { + write_response(&mut stream, "200 OK", "text/html; charset=utf-8", &auth_request, None) + }; + + if let Err(err) = response { + warn!("Failed to write auth response: {}", err); + } + + break; + } +} + +fn write_response( + stream: &mut std::net::TcpStream, + status: &str, + content_type: &str, + body: &str, + extra_header: Option<(&str, &str)>, +) -> std::io::Result<()> { + write!(stream, "HTTP/1.1 {}\r\n", status)?; + write!(stream, "Content-Type: {}\r\n", content_type)?; + if let Some((name, value)) = extra_header { + write!(stream, "{}: {}\r\n", name, value)?; + } + write!(stream, "Content-Length: {}\r\n", body.len())?; + write!(stream, "Connection: close\r\n\r\n")?; + stream.write_all(body.as_bytes())?; + stream.flush() +} diff --git a/crates/gpapi/src/utils/host_utils.rs b/crates/gpapi/src/utils/host_utils.rs new file mode 100644 index 0000000..caa078a --- /dev/null +++ b/crates/gpapi/src/utils/host_utils.rs @@ -0,0 +1,99 @@ +use std::sync::OnceLock; + +const DEFAULT_MACOS_VERSION: &str = "13.4.0"; +#[cfg(not(target_os = "linux"))] +const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS"; +#[cfg(not(target_os = "windows"))] +const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro"; +const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0"; +const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF"; + +static MACHINE_ID: OnceLock<&'static str> = OnceLock::new(); +static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new(); +static MACOS_OS_STRING: OnceLock = OnceLock::new(); +static LINUX_OS_STRING: OnceLock = OnceLock::new(); +static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new(); +static WINDOWS_OS_STRING: OnceLock = OnceLock::new(); + +pub fn get_macos_version() -> &'static str { + MACOS_VERSION.get_or_init(|| { + #[cfg(target_os = "macos")] + { + match os_info::get().version() { + os_info::Version::Unknown => DEFAULT_MACOS_VERSION, + version => Box::leak(version.to_string().into_boxed_str()), + } + } + + #[cfg(not(target_os = "macos"))] + DEFAULT_MACOS_VERSION + }) +} + +pub fn get_macos_os_string() -> &'static str { + MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version())) +} + +pub fn get_linux_os_string() -> &'static str { + LINUX_OS_STRING.get_or_init(|| { + #[cfg(target_os = "linux")] + { + format!("Linux {}", whoami::distro()) + } + + #[cfg(not(target_os = "linux"))] + { + format!("Linux {}", DEFAULT_LINUX_DISTRO) + } + }) +} + +pub fn get_windows_version() -> &'static str { + WINDOWS_VERSION.get_or_init(|| { + #[cfg(target_os = "windows")] + { + match os_info::get().version() { + os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION, + version => Box::leak(format!("{}.0", version).into_boxed_str()), + } + } + + #[cfg(not(target_os = "windows"))] + DEFAULT_WINDOWS_VERSION + }) +} + +pub fn get_windows_os_string() -> &'static str { + WINDOWS_OS_STRING.get_or_init(|| { + #[cfg(target_os = "windows")] + { + let edition = os_info::get() + .edition() + .map(|edition| edition.to_string()) + .unwrap_or_else(|| whoami::distro()); + format!("Microsoft {} , 64-bit", edition) + } + + #[cfg(not(target_os = "windows"))] + { + format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO) + } + }) +} + +pub fn get_machine_id() -> &'static str { + MACHINE_ID.get_or_init(|| { + machine_uid::get() + .map(|id| Box::leak(id.to_string().into_boxed_str()) as &'static str) + .unwrap_or(DEFAULT_MACHINE_ID) + }) +} + +pub fn derive_uuid(seeds: &[&str]) -> String { + use uuid::Uuid; + + let namespace = Uuid::NAMESPACE_DNS; + let name = format!("{}-{}", get_machine_id(), seeds.join("-")); + + Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string() +} diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index e2b43af..bb863b2 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -5,6 +5,7 @@ pub mod checksum; pub mod crypto; pub mod endpoint; pub mod env_file; +pub mod host_utils; pub mod lock_file; pub mod openssl; pub mod redact; @@ -93,3 +94,22 @@ async fn parse_gp_error(res: Response) -> (String, String) { (reason, res) } + +#[cfg(test)] +mod tests { + use super::normalize_server; + + #[test] + fn normalize_server_preserves_custom_port() { + let normalized = normalize_server("vpn.example.com:4443").unwrap(); + + assert_eq!(normalized, "https://vpn.example.com:4443"); + } + + #[test] + fn normalize_server_removes_path_but_keeps_custom_port() { + let normalized = normalize_server("https://vpn.example.com:4443/global-protect").unwrap(); + + assert_eq!(normalized, "https://vpn.example.com:4443"); + } +} diff --git a/crates/openconnect/Cargo.toml b/crates/openconnect/Cargo.toml index dc5e504..3c1c794 100644 --- a/crates/openconnect/Cargo.toml +++ b/crates/openconnect/Cargo.toml @@ -11,3 +11,6 @@ log.workspace = true [build-dependencies] cc = "1" +autotools = "0.2" +pkg-config = "0.3" +fs_extra = "1" diff --git a/crates/openconnect/build.rs b/crates/openconnect/build.rs index 0220ce0..f7e9e75 100644 --- a/crates/openconnect/build.rs +++ b/crates/openconnect/build.rs @@ -1,9 +1,156 @@ +use std::{env, path::PathBuf, process::Command}; + +fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) { + let mut patches = std::fs::read_dir(patches_dir) + .expect("Failed to read patches directory") + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.path().extension().and_then(|s| s.to_str()) == Some("patch")) + .map(|entry| entry.path()) + .collect::>(); + + patches.sort(); + + for patch in patches { + println!("cargo:rerun-if-changed={}", patch.display()); + + let status = Command::new("patch") + .arg("-p1") + .arg("-i") + .arg(&patch) + .current_dir(build_src) + .status() + .expect("Failed to execute patch command"); + + if !status.success() { + panic!("Failed to apply patch file: {}", patch.display()); + } + } +} + +fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { + let libxml2_dir = deps_dir.join("libxml2"); + let build_src = out_dir.join("libxml2_build"); + + println!("cargo:rerun-if-changed={}", libxml2_dir.display()); + + if build_src.exists() { + std::fs::remove_dir_all(&build_src).unwrap(); + } + std::fs::create_dir_all(&build_src).unwrap(); + + let mut options = fs_extra::dir::CopyOptions::new(); + options.overwrite = true; + options.content_only = true; + fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy libxml2 sources to OUT_DIR"); + + let dst = autotools::Config::new(&build_src) + .reconf("-ivf") + .enable_static() + .disable_shared() + .with("python", Some("no")) + .with("icu", Some("no")) + .with("http", Some("no")) + .with("ftp", Some("no")) + .with("catalog", Some("no")) + .with("docbook", Some("no")) + .with("legacy", Some("no")) + .with("threads", Some("no")) + .with("zlib", Some("no")) + .with("lzma", Some("no")) + .cflag("-fPIC") + .build(); + + let lib_dir = dst.join("lib"); + let include_dir = dst.join("include/libxml2"); + + println!("cargo:rustc-link-search=native={}", lib_dir.display()); + println!("cargo:rustc-link-lib=static=xml2"); + println!("cargo:include={}", include_dir.display()); + + dst +} + +fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf { + let openconnect_dir = deps_dir.join("openconnect"); + let patches_dir = deps_dir.join("patches"); + let build_src = out_dir.join("openconnect_build"); + + println!("cargo:rerun-if-changed={}", openconnect_dir.display()); + + if build_src.exists() { + std::fs::remove_dir_all(&build_src).unwrap(); + } + std::fs::create_dir_all(&build_src).unwrap(); + + let mut options = fs_extra::dir::CopyOptions::new(); + options.overwrite = true; + options.content_only = true; + fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy openconnect sources to OUT_DIR"); + + apply_patches(&patches_dir, &build_src); + + let dst = autotools::Config::new(&build_src) + .reconf("-ivf") + .enable_static() + .disable_shared() + .disable("nls", None) + .disable("docs", None) + .disable("dsa-tests", None) + .without("libproxy", None) + .without("stoken", None) + .without("libpcsclite", None) + .without("libpskc", None) + .without("gssapi", None) + .with("gnutls-tss2", Some("no")) + .with("vpnc-script", Some("/usr/libexec/gpclient/vpnc-script")) + .build(); + + let lib_dir = dst.join("lib"); + let include_dir = dst.join("include"); + + println!("cargo:rustc-link-search=native={}", lib_dir.display()); + println!("cargo:rustc-link-lib=static=openconnect"); + println!("cargo:include={}", include_dir.display()); + + dst +} + fn main() { - // Link to the native openconnect library - println!("cargo:rustc-link-lib=openconnect"); + let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let deps_dir = PathBuf::from(manifest_dir).join("deps"); + + let oc_dst = build_openconnect(&deps_dir, &out_dir); + + if env::var("LIBXML2_STATIC").is_ok() { + let _libxml2_dst = build_libxml2(&deps_dir, &out_dir); + } else { + pkg_config::probe_library("libxml-2.0").unwrap(); + } + + pkg_config::probe_library("zlib").unwrap(); + pkg_config::probe_library("liblz4").unwrap(); + pkg_config::probe_library("gnutls").unwrap(); + pkg_config::probe_library("p11-kit-1").unwrap(); + pkg_config::probe_library("hogweed").unwrap(); + pkg_config::probe_library("nettle").unwrap(); + if pkg_config::probe_library("gmp").is_err() { + println!("cargo:warning=Falling back to direct gmp linking because pkg-config metadata is unavailable"); + println!("cargo:rustc-link-lib=gmp"); + } + println!("cargo:rerun-if-changed=src/ffi/vpn.c"); println!("cargo:rerun-if-changed=src/ffi/vpn.h"); - // Compile the vpn.c file - cc::Build::new().file("src/ffi/vpn.c").include("src/ffi").compile("vpn"); + #[cfg(target_os = "linux")] + { + println!("cargo:rustc-link-arg=-Wl,-Bstatic"); + println!("cargo:rustc-link-arg=-Wl,-Bdynamic"); + } + + cc::Build::new() + .file("src/ffi/vpn.c") + .include("src/ffi") + .include(&oc_dst.join("include")) + .compile("vpn"); } diff --git a/crates/openconnect/deps/libxml2 b/crates/openconnect/deps/libxml2 new file mode 160000 index 0000000..f8a8c1f --- /dev/null +++ b/crates/openconnect/deps/libxml2 @@ -0,0 +1 @@ +Subproject commit f8a8c1f59db355b46962577e7b74f1a1e8149dc6 diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect new file mode 160000 index 0000000..0dcdff8 --- /dev/null +++ b/crates/openconnect/deps/openconnect @@ -0,0 +1 @@ +Subproject commit 0dcdff87db65daf692dc323732831391d595d98d diff --git a/crates/openconnect/deps/patches/0001-Add-support-for-GlobalProtect-app-version-handling.patch b/crates/openconnect/deps/patches/0001-Add-support-for-GlobalProtect-app-version-handling.patch new file mode 100644 index 0000000..8cd84a5 --- /dev/null +++ b/crates/openconnect/deps/patches/0001-Add-support-for-GlobalProtect-app-version-handling.patch @@ -0,0 +1,113 @@ +From a8d5ec198ca9ae47a0e6b4f1ea244d2738acf055 Mon Sep 17 00:00:00 2001 +From: Kevin Yue +Date: Sun, 14 Dec 2025 17:10:02 +0800 +Subject: [PATCH 1/4] Add support for GlobalProtect app version handling + +- Introduced `gp_app_version` field in `openconnect_info` structure. +- Implemented `openconnect_set_gp_app_version` and `openconnect_get_gp_app_version` functions. +- Updated `gpst_get_config` to use the app version in requests. +- Free `gp_app_version` in `openconnect_vpninfo_free` to prevent memory leaks. +--- + gpst.c | 8 +++++--- + library.c | 15 +++++++++++++++ + openconnect-internal.h | 4 ++++ + openconnect.h | 2 ++ + 4 files changed, 26 insertions(+), 3 deletions(-) + +diff --git a/gpst.c b/gpst.c +index 244aaf04..5c24bbd2 100644 +--- a/gpst.c ++++ b/gpst.c +@@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo) + + + /* submit getconfig request */ ++ const char *app_version = openconnect_get_gp_app_version(vpninfo); ++ vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version); ++ + buf_append(request_body, "client-type=1&protocol-version=p1&internal=no"); +- append_opt(request_body, "app-version", vpninfo->csd_ticket ? : "6.3.0-33"); ++ append_opt(request_body, "app-version", app_version); + append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes"); + append_opt(request_body, "clientos", gpst_os_name(vpninfo)); + append_opt(request_body, "os-version", vpninfo->platname); +@@ -1040,8 +1043,7 @@ static int run_hip_script(struct openconnect_info *vpninfo) + * accept new ones. + */ + unsetenv("APP_VERSION"); +- if (vpninfo->csd_ticket) +- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1)) ++ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1)) + goto out; + + execv(hip_argv[0], (char **)hip_argv); +diff --git a/library.c b/library.c +index b5e74e9b..18334c76 100644 +--- a/library.c ++++ b/library.c +@@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo) + + free(vpninfo->localname); + free(vpninfo->useragent); ++ free(vpninfo->gp_app_version); + free(vpninfo->authgroup); + #ifdef HAVE_LIBSTOKEN + if (vpninfo->stoken_pin) +@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo, + return 0; + } + ++int openconnect_set_gp_app_version(struct openconnect_info *vpninfo, ++ const char *gp_app_version) ++{ ++ UTF8CHECK(gp_app_version); ++ ++ STRDUP(vpninfo->gp_app_version, gp_app_version); ++ return 0; ++} ++ ++const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo) ++{ ++ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33"); ++} ++ + int openconnect_set_urlpath(struct openconnect_info *vpninfo, + const char *urlpath) + { +diff --git a/openconnect-internal.h b/openconnect-internal.h +index abf45bbd..988f85f0 100644 +--- a/openconnect-internal.h ++++ b/openconnect-internal.h +@@ -786,6 +786,7 @@ struct openconnect_info { + int is_dyndns; /* Attempt to redo DNS lookup on each CSTP reconnect */ + char *useragent; + char *version_string; ++ char *gp_app_version; + + const char *quit_reason; + const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */ +@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo); + /* hpke.c */ + int handle_external_browser(struct openconnect_info *vpninfo); + ++/* Get the app version */ ++const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo); ++ + /* version.c */ + extern const char openconnect_version_str[]; + +diff --git a/openconnect.h b/openconnect.h +index 136f181a..7d4f3399 100644 +--- a/openconnect.h ++++ b/openconnect.h +@@ -470,6 +470,8 @@ int openconnect_set_http_proxy(struct openconnect_info *vpninfo, + int openconnect_set_useragent(struct openconnect_info *vpninfo, + const char *useragent); + ++int openconnect_set_gp_app_version(struct openconnect_info *vpninfo, ++ const char *gp_app_version); + int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo); + int openconnect_obtain_cookie(struct openconnect_info *vpninfo); + int openconnect_init_ssl(void); +-- +2.50.1 (Apple Git-155) diff --git a/crates/openconnect/deps/patches/0002-Update-user-agent-for-common-headers-in-GlobalProtec.patch b/crates/openconnect/deps/patches/0002-Update-user-agent-for-common-headers-in-GlobalProtec.patch new file mode 100644 index 0000000..cd1f235 --- /dev/null +++ b/crates/openconnect/deps/patches/0002-Update-user-agent-for-common-headers-in-GlobalProtec.patch @@ -0,0 +1,31 @@ +From 8591eba702f52dae335601c997271786be50dff7 Mon Sep 17 00:00:00 2001 +From: Kevin Yue +Date: Sun, 14 Dec 2025 17:10:52 +0800 +Subject: [PATCH 2/4] Update user agent for common headers in GlobalProtect + authentication + +--- + auth-globalprotect.c | 7 ------- + 1 file changed, 7 deletions(-) + +diff --git a/auth-globalprotect.c b/auth-globalprotect.c +index 8d094273..27e41c2b 100644 +--- a/auth-globalprotect.c ++++ b/auth-globalprotect.c +@@ -34,14 +34,7 @@ struct login_context { + void gpst_common_headers(struct openconnect_info *vpninfo, + struct oc_text_buf *buf) + { +- char *orig_ua = vpninfo->useragent; +- +- /* XX: more recent servers don't appear to require this specific UA value, +- * but we don't have any good way to detect them. +- */ +- vpninfo->useragent = (char *)"PAN GlobalProtect"; + http_common_headers(vpninfo, buf); +- vpninfo->useragent = orig_ua; + } + + /* Translate platform names (derived from AnyConnect) into the values +-- +2.50.1 (Apple Git-155) diff --git a/crates/openconnect/deps/patches/0003-Add-support-for-OS-version-handling-in-GlobalProtect.patch b/crates/openconnect/deps/patches/0003-Add-support-for-OS-version-handling-in-GlobalProtect.patch new file mode 100644 index 0000000..754f2fd --- /dev/null +++ b/crates/openconnect/deps/patches/0003-Add-support-for-OS-version-handling-in-GlobalProtect.patch @@ -0,0 +1,120 @@ +From dda2aceca7e614af65b968e632065ef223cb6612 Mon Sep 17 00:00:00 2001 +From: Kevin Yue +Date: Sun, 14 Dec 2025 17:14:08 +0800 +Subject: [PATCH 3/4] Add support for OS version handling in GlobalProtect + authentication + +--- + auth-globalprotect.c | 2 +- + gpst.c | 4 ++-- + library.c | 15 +++++++++++++++ + openconnect-internal.h | 4 ++++ + openconnect.h | 3 +++ + 5 files changed, 25 insertions(+), 3 deletions(-) + +diff --git a/auth-globalprotect.c b/auth-globalprotect.c +index 27e41c2b..59d6de3b 100644 +--- a/auth-globalprotect.c ++++ b/auth-globalprotect.c +@@ -731,7 +731,7 @@ static int gpst_login(struct openconnect_info *vpninfo, int portal, struct login + buf_append(request_body, "jnlpReady=jnlpReady&ok=Login&direct=yes&clientVer=4100&prot=https:&internal=no"); + append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes"); + append_opt(request_body, "clientos", gpst_os_name(vpninfo)); +- append_opt(request_body, "os-version", vpninfo->platname); ++ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo)); + append_opt(request_body, "server", vpninfo->hostname); + append_opt(request_body, "computer", vpninfo->localname); + if (ctx->portal_userauthcookie) +diff --git a/gpst.c b/gpst.c +index 5c24bbd2..0373fce0 100644 +--- a/gpst.c ++++ b/gpst.c +@@ -657,7 +657,7 @@ static int gpst_get_config(struct openconnect_info *vpninfo) + append_opt(request_body, "app-version", app_version); + append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes"); + append_opt(request_body, "clientos", gpst_os_name(vpninfo)); +- append_opt(request_body, "os-version", vpninfo->platname); ++ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo)); + append_opt(request_body, "hmac-algo", "sha1,md5,sha256"); + append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc"); + if (old_addr || old_addr6) { +@@ -1044,7 +1044,7 @@ static int run_hip_script(struct openconnect_info *vpninfo) + */ + unsetenv("APP_VERSION"); + if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1)) +- goto out; ++ goto out; + + execv(hip_argv[0], (char **)hip_argv); + +diff --git a/library.c b/library.c +index 18334c76..e2169054 100644 +--- a/library.c ++++ b/library.c +@@ -897,6 +897,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo) + free(vpninfo->localname); + free(vpninfo->useragent); + free(vpninfo->gp_app_version); ++ free(vpninfo->gp_os_version); + free(vpninfo->authgroup); + #ifdef HAVE_LIBSTOKEN + if (vpninfo->stoken_pin) +@@ -1034,6 +1035,20 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo) + return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33"); + } + ++int openconnect_set_gp_os_version(struct openconnect_info *vpninfo, ++ const char *gp_os_version) ++{ ++ UTF8CHECK(gp_os_version); ++ ++ STRDUP(vpninfo->gp_os_version, gp_os_version); ++ return 0; ++} ++ ++const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo) ++{ ++ return vpninfo->gp_os_version ?: vpninfo->platname; ++} ++ + int openconnect_set_urlpath(struct openconnect_info *vpninfo, + const char *urlpath) + { +diff --git a/openconnect-internal.h b/openconnect-internal.h +index 988f85f0..5c8d2909 100644 +--- a/openconnect-internal.h ++++ b/openconnect-internal.h +@@ -787,6 +787,7 @@ struct openconnect_info { + char *useragent; + char *version_string; + char *gp_app_version; ++ char *gp_os_version; + + const char *quit_reason; + const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */ +@@ -1681,6 +1682,9 @@ int handle_external_browser(struct openconnect_info *vpninfo); + /* Get the app version */ + const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo); + ++/* Get the OS version string for GP */ ++const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo); ++ + /* version.c */ + extern const char openconnect_version_str[]; + +diff --git a/openconnect.h b/openconnect.h +index 7d4f3399..aa96a53b 100644 +--- a/openconnect.h ++++ b/openconnect.h +@@ -472,6 +472,9 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo, + + int openconnect_set_gp_app_version(struct openconnect_info *vpninfo, + const char *gp_app_version); ++int openconnect_set_gp_os_version(struct openconnect_info *vpninfo, ++ const char *gp_os_version); ++ + int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo); + int openconnect_obtain_cookie(struct openconnect_info *vpninfo); + int openconnect_init_ssl(void); +-- +2.50.1 (Apple Git-155) diff --git a/crates/openconnect/deps/patches/0004-Add-client-version-and-OS-information-to-HIP-script-.patch b/crates/openconnect/deps/patches/0004-Add-client-version-and-OS-information-to-HIP-script-.patch new file mode 100644 index 0000000..c24530d --- /dev/null +++ b/crates/openconnect/deps/patches/0004-Add-client-version-and-OS-information-to-HIP-script-.patch @@ -0,0 +1,38 @@ +From 3915a51c81831a1a9b087d82f0c760365682f23b Mon Sep 17 00:00:00 2001 +From: Kevin Yue +Date: Mon, 15 Dec 2025 19:20:44 +0800 +Subject: [PATCH 4/4] Add client version and OS information to HIP script + arguments + +--- + gpst.c | 8 ++++++-- + 1 file changed, 6 insertions(+), 2 deletions(-) + +diff --git a/gpst.c b/gpst.c +index 0373fce0..d04c42c2 100644 +--- a/gpst.c ++++ b/gpst.c +@@ -1013,6 +1013,12 @@ static int run_hip_script(struct openconnect_info *vpninfo) + exit(1); + + hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper); ++ hip_argv[i++] = "--client-version"; ++ hip_argv[i++] = openconnect_get_gp_app_version(vpninfo); ++ hip_argv[i++] = "--client-os"; ++ hip_argv[i++] = gpst_os_name(vpninfo); ++ hip_argv[i++] = "--os-version"; ++ hip_argv[i++] = openconnect_get_gp_os_version(vpninfo); + hip_argv[i++] = "--cookie"; + hip_argv[i++] = vpninfo->cookie; + if (vpninfo->ip_info.addr) { +@@ -1025,8 +1031,6 @@ static int run_hip_script(struct openconnect_info *vpninfo) + } + hip_argv[i++] = "--md5"; + hip_argv[i++] = vpninfo->csd_token; +- hip_argv[i++] = "--client-os"; +- hip_argv[i++] = gpst_os_name(vpninfo); + hip_argv[i++] = NULL; + + /* XX: Sending the above parameters as --long-options was a mistake that was +-- +2.50.1 (Apple Git-155) diff --git a/flake.nix b/flake.nix index a16b237..ef9e13b 100644 --- a/flake.nix +++ b/flake.nix @@ -34,7 +34,9 @@ nativeBuildInputs = with pkgs; [ perl jq - openconnect + autoconf + automake + libtool libsoup webkitgtk pkg-config @@ -43,7 +45,7 @@ overrideMain = {...}: { postPatch = '' substituteInPlace crates/common/src/vpn_utils.rs \ - --replace-fail /etc/vpnc/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script + --replace-fail /usr/libexec/gpclient/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script substituteInPlace crates/gpapi/src/lib.rs \ --replace-fail /usr/bin/gpclient $out/bin/gpclient \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \ diff --git a/packaging/binary/Makefile.in b/packaging/binary/Makefile.in index a9f9bdd..07d9547 100644 --- a/packaging/binary/Makefile.in +++ b/packaging/binary/Makefile.in @@ -10,6 +10,9 @@ install: install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \ fi + install -Dm755 artifacts/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script + install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + # Install the disconnect hooks install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook @@ -30,6 +33,9 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui + rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script + rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook diff --git a/packaging/deb/control.in b/packaging/deb/control.in index 27d046d..9b2aec8 100644 --- a/packaging/deb/control.in +++ b/packaging/deb/control.in @@ -4,20 +4,29 @@ Priority: optional Maintainer: Kevin Yue Standards-Version: 4.1.4 Build-Depends: debhelper (>= 9), + autoconf, + automake, + libtool, + patch, pkg-config, jq (>= 1), make (>= 4), - libxml2, + zlib1g-dev, + liblz4-dev, + libp11-kit-dev, + nettle-dev, + libgnutls28-dev, + libgmp-dev, libsecret-1-0, libayatana-appindicator3-1, gnome-keyring, libwebkit2gtk-4.0-dev, - libopenconnect-dev (>= 8.20),@RUST@ + libssl-dev,@RUST@ Homepage: https://github.com/yuezk/GlobalProtect-openconnect Package: globalprotect-openconnect Architecture: any Multi-Arch: foreign -Depends: ${misc:Depends}, ${shlibs:Depends}, openconnect (>=8.20), libxml2, libsecret-1-0, libayatana-appindicator3-1, gnome-keyring +Depends: ${misc:Depends}, ${shlibs:Depends}, libsecret-1-0, libayatana-appindicator3-1, gnome-keyring Description: A GUI for GlobalProtect VPN A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. diff --git a/packaging/deb/rules.in b/packaging/deb/rules.in index af86075..3d3dc3f 100755 --- a/packaging/deb/rules.in +++ b/packaging/deb/rules.in @@ -2,6 +2,7 @@ export OFFLINE = @OFFLINE@ export BUILD_FE = 0 +export LIBXML2_STATIC = 1 %: dh $@ --no-parallel diff --git a/packaging/files/usr/libexec/gpclient/hipreport.sh b/packaging/files/usr/libexec/gpclient/hipreport.sh new file mode 100755 index 0000000..d2add04 --- /dev/null +++ b/packaging/files/usr/libexec/gpclient/hipreport.sh @@ -0,0 +1,28 @@ +#!/bin/sh + +# Wrapper for gpclient hip +LOGFILE="/tmp/gpclient-hipreport.log" + +LINUX_GPCLIENT_BIN="/usr/bin/gpclient" +HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient" +GPCLIENT_BIN="${GPCLIENT_BIN:-}" + +if [ -n "$GPCLIENT_BIN" ] && [ -x "$GPCLIENT_BIN" ]; then + : +elif [ -x "$LINUX_GPCLIENT_BIN" ]; then + GPCLIENT_BIN="$LINUX_GPCLIENT_BIN" +elif [ -x "$HOMEBREW_GPCLIENT_BIN" ]; then + GPCLIENT_BIN="$HOMEBREW_GPCLIENT_BIN" +else + echo "Error: gpclient binary not found." > "$LOGFILE" + exit 1 +fi + +HIP_REPORT_OUTPUT=$("$GPCLIENT_BIN" hip "$@" 2> "$LOGFILE") +STATUS=$? + +if [ $STATUS -ne 0 ]; then + exit $STATUS +fi + +printf '%s\n' "$HIP_REPORT_OUTPUT" diff --git a/packaging/files/usr/libexec/gpclient/vpnc-script b/packaging/files/usr/libexec/gpclient/vpnc-script new file mode 100755 index 0000000..a935549 --- /dev/null +++ b/packaging/files/usr/libexec/gpclient/vpnc-script @@ -0,0 +1,1213 @@ +#!/bin/sh +# +# Originally part of vpnc source code: +# © 2005-2012 Maurice Massar, Jörg Mayer, Antonio Borneo et al. +# © 2009-2022 David Woodhouse , Daniel Lenski et al. +# Vendored from https://gitlab.com/openconnect/vpnc-scripts at commit +# ce9e961bd0f6b867e1c7c35f78f6fb973f6ff101. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# +################ +# +# List of parameters passed through environment +#* reason -- why this script was called, one of: pre-init connect disconnect reconnect attempt-reconnect +#* VPNGATEWAY -- VPN gateway address (always present) +#* VPNPID -- PID of the process controlling the VPN (OpenConnect v9.0+) +#* TUNDEV -- tunnel device (always present) +#* IDLE_TIMEOUT -- gateway's idle timeout in seconds (OpenConnect v8.06+); unused +#* LOG_LEVEL -- log level; ERROR=0, INFO=1, DEBUG=2, TRACE=3 (OpenConnect v9.0+) +#* INTERNAL_IP4_ADDRESS -- address (always present) +#* INTERNAL_IP4_MTU -- MTU (often unset) +#* INTERNAL_IP4_NETMASK -- netmask (often unset) +#* INTERNAL_IP4_NETMASKLEN -- netmask length (often unset) +#* INTERNAL_IP4_NETADDR -- address of network (only present if netmask is set) +#* INTERNAL_IP4_DNS -- list of DNS servers +#* INTERNAL_IP4_NBNS -- list of WINS servers +#* INTERNAL_IP6_ADDRESS -- IPv6 address +#* INTERNAL_IP6_NETMASK -- IPv6 netmask +#* INTERNAL_IP6_DNS -- IPv6 list of dns servers +#* CISCO_DEF_DOMAIN -- default domain name +#* CISCO_BANNER -- banner from server +#* CISCO_SPLIT_DNS -- DNS search domain list +#* CISCO_SPLIT_INC -- number of networks in split-network-list +#* CISCO_SPLIT_INC_%d_ADDR -- network address +#* CISCO_SPLIT_INC_%d_MASK -- subnet mask (for example: 255.255.255.0) +#* CISCO_SPLIT_INC_%d_MASKLEN -- subnet masklen (for example: 24) +#* CISCO_SPLIT_INC_%d_PROTOCOL -- protocol (often just 0); unused +#* CISCO_SPLIT_INC_%d_SPORT -- source port (often just 0); unused +#* CISCO_SPLIT_INC_%d_DPORT -- destination port (often just 0); unused +#* CISCO_IPV6_SPLIT_INC -- number of networks in IPv6 split-network-list +#* CISCO_IPV6_SPLIT_INC_%d_ADDR -- IPv6 network address +#* CISCO_IPV6_SPLIT_INC_$%d_MASKLEN -- IPv6 subnet masklen +# +# The split tunnel variables above have *_EXC* counterparts for network +# addresses to be excluded from the VPN tunnel. + +# FIXMEs: + +# Section A: route handling + +# 1) The 3 values CISCO_SPLIT_INC_%d_PROTOCOL/SPORT/DPORT are currently being ignored +# In order to use them, we'll probably need os specific solutions +# * Linux: iptables -t mangle -I PREROUTING -j ROUTE --oif $TUNDEV +# This would be an *alternative* to changing the routes (and thus 2) and 3) +# shouldn't be relevant at all) +# 2) There are two different functions to set routes: generic routes and the +# default route. Why isn't the defaultroute handled via the generic route case? +# 3) In the split tunnel case, all routes but the default route might get replaced +# without getting restored later. We should explicitly check and save them just +# like the defaultroute +# 4) Replies to a dhcp-server should never be sent into the tunnel + +# Section B: Split DNS handling + +# 1) Maybe dnsmasq can do something like that +# 2) Parse DNS packets going out via tunnel and redirect them to original DNS-server + +# ======== For test logging (CI/CD will uncomment automatically) ========= + +#TRACE# echo "------------------" +#TRACE# echo "vpnc-script environment:" +#TRACE# env | grep -E '^(CISCO_|INTERNAL_IP|VPNGATEWAY|TUNDEV|IDLE_TIMEOUT|reason)' | sort +#TRACE# echo "------------------" +#TRACE# set -x + +# =========== script (variable) setup ==================================== + +PATH=/sbin:/usr/sbin:$PATH + +OS="`uname -s`" + +HOOKS_DIR=/etc/vpnc + +# Use the PID of the controlling process (vpnc or OpenConnect) to +# uniquely identify this VPN connection. Normally, the parent process +# is a shell, and the grandparent's PID is the relevant one. +# OpenConnect v9.0+ provides VPNPID, so we don't need to determine it. +if [ -z "$VPNPID" ]; then + VPNPID=$PPID + PCMD=`ps -c -o args= -p $PPID` + case "$PCMD" in + *sh) VPNPID=`ps -o ppid= -p $PPID` ;; + esac +fi + +DEFAULT_ROUTE_FILE=/var/run/vpnc/defaultroute.${VPNPID} +DEFAULT_ROUTE_FILE_IPV6=/var/run/vpnc/defaultroute_ipv6.${VPNPID} +RESOLV_CONF_BACKUP=/var/run/vpnc/resolv.conf-backup.${VPNPID} +SCRIPTNAME=`basename $0` + +# some systems, eg. Darwin & FreeBSD, prune /var/run on boot +if [ ! -d "/var/run/vpnc" ]; then + mkdir -p /var/run/vpnc + [ -x /sbin/restorecon ] && /sbin/restorecon /var/run/vpnc +fi + +if ifconfig --help 2>&1 | grep BusyBox > /dev/null; then + ifconfig_syntax_inet="" +else + ifconfig_syntax_inet="inet" +fi + +if [ "$OS" = "Linux" ]; then + IPROUTE="`command -v ip | grep '^/'`" + ifconfig_syntax_ptp="pointopoint" + route_syntax_gw="gw" + route_syntax_del="del" + route_syntax_netmask="netmask" + route_syntax_inet6="-6" + route_syntax_inet6_host="-6" + route_syntax_inet6_net="-6" + ifconfig_syntax_add_inet6="add" + ifconfig_syntax_del() { case "$1" in *:*) echo del "$1" ;; *) echo 0.0.0.0 ;; esac; } + netstat_syntax_ipv6="-6" +else + # iproute2 is Linux only; if `command -v ip` returns something on another OS, it's likely an unrelated tool + # (see https://github.com/dlenski/openconnect/issues/132#issuecomment-470475009) + IPROUTE="" + ifconfig_syntax_ptp="" + route_syntax_gw="" + route_syntax_del="delete" + route_syntax_netmask="-netmask" + route_syntax_inet6="-inet6" + route_syntax_inet6_host="-inet6 -host" + route_syntax_inet6_net="-inet6 -net" + ifconfig_syntax_del() { case "$1" in *:*) echo inet6 "$1" delete ;; *) echo "$1" delete ;; esac; } + ifconfig_syntax_add_inet6="inet6" + netstat_syntax_ipv6="-f inet6" +fi +if [ "$OS" = "SunOS" ]; then + route_syntax_interface="-interface" + ifconfig_syntax_ptpv6="$INTERNAL_IP6_ADDRESS" +else + route_syntax_interface="" + ifconfig_syntax_ptpv6="" +fi + +detect_resolved_nss_resolve() { + # Detect usage of systemd-resolved via nss-resolve + # https://www.freedesktop.org/software/systemd/man/nss-resolve.html + grep '^hosts' /etc/nsswitch.conf 2>/dev/null | grep resolve >/dev/null 2>&1 +} + +detect_resolved_nss_dns() { + # Detect usage of systemd-resolved via nss-dns + # https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html + grep '^hosts' /etc/nsswitch.conf 2>/dev/null | grep dns >/dev/null 2>&1 && readlink /etc/resolv.conf | grep -e '/run/systemd/resolve/stub-resolv.conf$' -e '/usr/lib/systemd/resolv.conf$' -e '/run/systemd/resolve/resolv.conf$' >/dev/null 2>&1 +} + +detect_resolved_etc_files() { + detect_resolved_nss_resolve || detect_resolved_nss_dns +} + +detect_resolved_manager() { + # For systemd-resolved (version 239 and above) + detect_resolved_etc_files && /usr/bin/resolvectl status >/dev/null 2>&1 +} + +detect_resolved_manager_old() { + # For systemd-resolved (version 229 and above) + local dest + dest='org.freedesktop.resolve1' + detect_resolved_etc_files && /usr/bin/busctl status "$dest" >/dev/null 2>&1 +} + +if [ -r /etc/openwrt_release ] && [ -n "$OPENWRT_INTERFACE" ]; then + . /etc/functions.sh + include /lib/network + MODIFYRESOLVCONF=modify_resolvconf_openwrt + RESTORERESOLVCONF=restore_resolvconf_openwrt +elif [ -x /usr/bin/resolvectl ] && detect_resolved_manager; then + # For systemd-resolved (version 239 and above) + MODIFYRESOLVCONF=modify_resolved_manager + RESTORERESOLVCONF=restore_resolved_manager +elif [ -x /usr/bin/busctl ] && detect_resolved_manager_old; then + # For systemd-resolved (version 229 and above) + MODIFYRESOLVCONF=modify_resolved_manager_old + RESTORERESOLVCONF=restore_resolved_manager_old +elif [ -x /sbin/resolvconf ] && [ "`basename $(readlink /sbin/resolvconf) 2> /dev/null`" != resolvectl ]; then + # Optional tool on Debian, Ubuntu, Gentoo, FreeBSD and DragonFly BSD + # (ignored if symlink to resolvctl, created by some versions of systemd-resolved) + MODIFYRESOLVCONF=modify_resolvconf_manager + RESTORERESOLVCONF=restore_resolvconf_manager +elif [ -x /sbin/netconfig ] && [ ! -f /etc/slackware-version ]; then + # tool on Suse after 11.1 + # Slackware's netconfig is an unrelated tool that should not be invoked here + # (see https://www.linuxquestions.org/questions/slackware-14/vpnc-on-slackware-14-2-is-bringing-up-network-configuration-dialog-each-time-4175595447/#post5646866) + MODIFYRESOLVCONF=modify_resolvconf_suse_netconfig + RESTORERESOLVCONF=restore_resolvconf_suse_netconfig +elif [ -x /sbin/modify_resolvconf ]; then + # Mandatory tool on Suse earlier than 11.1 + MODIFYRESOLVCONF=modify_resolvconf_suse + RESTORERESOLVCONF=restore_resolvconf_suse +elif [ -x /usr/sbin/unbound-control ] && /usr/sbin/unbound-control status > /dev/null 2>&1; then + MODIFYRESOLVCONF=modify_resolvconf_unbound + RESTORERESOLVCONF=restore_resolvconf_unbound +elif [ -x /usr/sbin/rcctl ] && /usr/sbin/rcctl check resolvd >/dev/null; then + # OpenBSD's resolvd by sending route messages + MODIFYRESOLVCONF=modify_resolvconf_resolvd + RESTORERESOLVCONF=restore_resolvconf_resolvd +else # Generic for any OS + MODIFYRESOLVCONF=modify_resolvconf_generic + RESTORERESOLVCONF=restore_resolvconf_generic +fi + + +# =========== script hooks ================================================= + +run_hooks() { + HOOK="$1" + + if [ -d ${HOOKS_DIR}/${HOOK}.d ]; then + for script in ${HOOKS_DIR}/${HOOK}.d/* ; do + [ -f $script ] && . $script + done + fi +} + +# =========== tunnel interface handling ==================================== + +do_ifconfig() { + if [ -n "$INTERNAL_IP4_MTU" ]; then + MTU=$INTERNAL_IP4_MTU + elif [ -n "$IPROUTE" ]; then + MTUDEV=`$IPROUTE route get "$VPNGATEWAY" | sed -ne 's/^.*dev \([a-z0-9]*\).*$/\1/p'` + MTU=`$IPROUTE link show "$MTUDEV" | sed -ne 's/^.*mtu \([[:digit:]]\+\).*$/\1/p'` + if [ -n "$MTU" ]; then + MTU=`expr $MTU - 88` + fi + fi + + if [ -z "$MTU" ]; then + MTU=1412 + fi + + # Point to point interface require a netmask of 255.255.255.255 on some systems + if [ -n "$IPROUTE" ]; then + $IPROUTE link set dev "$TUNDEV" up mtu "$MTU" + $IPROUTE addr add "$INTERNAL_IP4_ADDRESS/32" peer "$INTERNAL_IP4_ADDRESS" dev "$TUNDEV" + else + ifconfig "$TUNDEV" ${ifconfig_syntax_inet} "$INTERNAL_IP4_ADDRESS" $ifconfig_syntax_ptp "$INTERNAL_IP4_ADDRESS" netmask 255.255.255.255 mtu ${MTU} up + fi + + if [ -n "$INTERNAL_IP4_NETMASK" ]; then + set_ipv4_network_route "$INTERNAL_IP4_NETADDR" "$INTERNAL_IP4_NETMASK" "$INTERNAL_IP4_NETMASKLEN" "$TUNDEV" + fi + + # If the netmask is provided, it contains the address _and_ netmask + if [ -n "$INTERNAL_IP6_ADDRESS" ] && [ -z "$INTERNAL_IP6_NETMASK" ]; then + INTERNAL_IP6_NETMASK="$INTERNAL_IP6_ADDRESS/128" + fi + if [ -n "$INTERNAL_IP6_NETMASK" ]; then + if [ -n "$IPROUTE" ]; then + $IPROUTE -6 addr add $INTERNAL_IP6_NETMASK dev $TUNDEV + else + # Unlike for Legacy IP, we don't specify the dest_address + # here on *BSD. OpenBSD for one will refuse to accept + # incoming packets to that address if we do. + # OpenVPN does the same (gives dest_address for Legacy IP + # but not for IPv6). + # Only Solaris needs it; hence $ifconfig_syntax_ptpv6 + ifconfig "$TUNDEV" $ifconfig_syntax_add_inet6 $INTERNAL_IP6_NETMASK $ifconfig_syntax_ptpv6 mtu $MTU up + fi + fi +} + +# =========== route handling ==================================== + +if [ -n "$IPROUTE" ]; then + fix_ip_get_output () { + sed -e 's/ /\n/g' | \ + sed -ne "1 s|\$|${1}|p;/via/{N;p};/dev/{N;p};/src/{N;p};/mtu/{N;p};/metric/{N;p};/onlink/{p}" + } + + # returns all routes to a destination *except* those through $TUNDEV, + # sorted by increasing metric (with absent metric as last) + list_non_loopback_routes () { + echo "$1" | grep -q : && FAMILY=-6 ROOT=::/0 || FAMILY=-4 ROOT=0/0 + # put metric in front, sort by metric, then chop off first two fields (metric and destination) + $IPROUTE $FAMILY route show to "$1" root "$ROOT" | + awk '/dev '"$TUNDEV"'/ { next; } { printf "%s %s\n", (match($0, /metric ([^ ]+)/) ? substr($0, RSTART+7, RLENGTH-7) : 4294967295), $0; }' | + sort -n | cut -d' ' -f3- + } + + set_vpngateway_route() { + # We'll attempt to add a host route to the gateway through every route that matches + # its address (excluding those through TUNDEV because the goal is to avoid loopback). + echo "$VPNGATEWAY" | grep -q : && FAMILY=-6 || FAMILY=-4 + + list_non_loopback_routes "$VPNGATEWAY" | + while read LINE ; do + # We do not want to use 'replace', since a route to the gateway that already + # exists is mostly likely the correct one (e.g. the case of a reconnect attempt + # after dead-peer detection, but no change in the underlying network devices). + $IPROUTE $FAMILY route add `echo "$VPNGATEWAY $LINE" | fix_ip_get_output` 2>/dev/null + done + if [ $FAMILY != -4 ]; then + $IPROUTE $FAMILY route flush cache 2>/dev/null + fi + } + + del_vpngateway_route() { + echo "$VPNGATEWAY" | grep -q : && FAMILY=-6 || FAMILY=-4 + + $IPROUTE route $route_syntax_del "$VPNGATEWAY" + if [ $FAMILY != -4 ]; then + $IPROUTE $FAMILY route flush cache 2>/dev/null + fi + } + + set_ipv4_default_route() { + $IPROUTE route | grep '^default' | fix_ip_get_output > "$DEFAULT_ROUTE_FILE" + $IPROUTE route replace default dev "$TUNDEV" + } + + set_ipv4_network_route() { + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + NETDEV="$4" + NETGW="$5" + if [ -n "$NETGW" ]; then + $IPROUTE route replace "$NETWORK/$NETMASKLEN" dev "$NETDEV" via "$NETGW" + else + $IPROUTE route replace "$NETWORK/$NETMASKLEN" dev "$NETDEV" + fi + } + + set_ipv4_exclude_route() { + # add explicit route to keep current routing for this target + # (keep traffic separate from VPN tunnel) + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + list_non_loopback_routes "$NETWORK/$NETMASKLEN" | + while read LINE ; do + $IPROUTE route add `echo "$NETWORK/$NETMASKLEN $LINE" | fix_ip_get_output` 2>/dev/null + done + } + + del_ipv4_exclude_route() { + # FIXME: In theory, this could delete existing routes which are + # identical to split-exclude routes specified by VPNGATEWAY + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + $IPROUTE route $route_syntax_del "$NETWORK/$NETMASKLEN" + } + + reset_ipv4_default_route() { + if [ -s "$DEFAULT_ROUTE_FILE" ]; then + $IPROUTE route replace `cat "$DEFAULT_ROUTE_FILE"` + rm -f -- "$DEFAULT_ROUTE_FILE" + fi + } + + del_ipv4_network_route() { + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + NETDEV="$4" + $IPROUTE route $route_syntax_del "$NETWORK/$NETMASKLEN" dev "$NETDEV" + } + + set_ipv6_default_route() { + # We don't save/restore IPv6 default route; just add a higher-priority one. + $IPROUTE -6 route add default dev "$TUNDEV" metric 1 + $IPROUTE -6 route flush cache 2>/dev/null + } + + set_ipv6_network_route() { + NETWORK="$1" + NETMASKLEN="$2" + NETDEV="$3" + NETGW="$4" + if [ -n "$NETGW" ]; then + $IPROUTE -6 route replace "$NETWORK/$NETMASKLEN" dev "$NETDEV" via "$NETGW" + else + $IPROUTE -6 route replace "$NETWORK/$NETMASKLEN" dev "$NETDEV" + fi + $IPROUTE -6 route flush cache 2>/dev/null + } + + set_ipv6_exclude_route() { + NETWORK="$1" + NETMASKLEN="$2" + set_ipv4_exclude_route "$NETWORK" nomask "$NETMASKLEN" + } + + reset_ipv6_default_route() { + $IPROUTE -6 route del default dev "$TUNDEV" + $IPROUTE -6 route flush cache 2>/dev/null + } + + del_ipv6_network_route() { + NETWORK="$1" + NETMASKLEN="$2" + NETDEV="$3" + $IPROUTE -6 route del "$NETWORK/$NETMASKLEN" dev "$NETDEV" + $IPROUTE -6 route flush cache 2>/dev/null + } + + del_ipv6_exclude_route() { + # FIXME: In theory, this could delete existing routes which are + # identical to split-exclude routes specified by VPNGATEWAY + NETWORK="$1" + NETMASKLEN="$2" + $IPROUTE -6 route del "$NETWORK/$NETMASKLEN" + $IPROUTE -6 route flush cache 2>/dev/null + } +else # use route command + get_default_gw() { + # Intended behavior, starting with `netstat -r -n` output: + # - keep lines starting with 'default' or '0.0.0.0', but exclude bogus routes '0.0.0.0/nn' where nn != 0 + # - remove lines containing IPv6 addresses (':') + # - remove lines for link-local routes (https://superuser.com/a/1067742) + # - remove lines containing $TUNDEV (we don't want loopback) + netstat -r -n | awk '/:/ { next; } /link#/ { next; } /^(default|0\.0\.0\.0([[:space:]]|\/0))/ { print $2; exit; } /[[:space:]]'"$TUNDEV"'([[:space:]]|$)/ { next; }' + } + + set_vpngateway_route() { + # Unlike with iproute2, there is no way to determine which current + # route(s) match the VPN gateway, so we simply find a default + # route and use its gateway. + case "$VPNGATEWAY" in + *:*) route add $route_syntax_inet6_host "$VPNGATEWAY" $route_syntax_gw "`get_ipv6_default_gw`";; + *) route add -host "$VPNGATEWAY" $route_syntax_gw "`get_default_gw`";; + esac + } + + del_vpngateway_route() { + case "$VPNGATEWAY" in + *:*) route $route_syntax_del $route_syntax_inet6_host "$VPNGATEWAY" $route_syntax_gw "`get_ipv6_default_gw`";; + *) route $route_syntax_del -host "$VPNGATEWAY" $route_syntax_gw "`get_default_gw`";; + esac + } + + set_ipv4_default_route() { + DEFAULTGW="`get_default_gw`" + echo "$DEFAULTGW" > "$DEFAULT_ROUTE_FILE" + route $route_syntax_del default $route_syntax_gw "$DEFAULTGW" + route add default $route_syntax_gw "$INTERNAL_IP4_ADDRESS" $route_syntax_interface + } + + set_ipv4_network_route() { + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + if [ -n "$5" ]; then + NETGW="$5" + else + NETGW="$INTERNAL_IP4_ADDRESS" + fi + route add -net "$NETWORK" $route_syntax_netmask "$NETMASK" $route_syntax_gw "$NETGW" $route_syntax_interface + } + + set_ipv4_exclude_route() { + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + DEFAULTGW="${DEFAULTGW:-`get_default_gw`}" + if [ -z "$DEFAULTGW" ]; then + echo "cannot find route for exclude route $NETWORK/$NETMASKLEN, ignoring" >&2 + return + fi + # Add explicit route to keep traffic for this target separate + # from tunnel. FIXME: We use default gateway - this is our best + # guess in absence of "ip" command to query effective route. + route add -net "$NETWORK" $route_syntax_netmask "$NETMASK" $route_syntax_gw "$DEFAULTGW" $route_syntax_interface + } + + del_ipv4_exclude_route() { + # FIXME: This can delete existing routes in case they're + # identical to split-exclude routes specified by VPNGATEWAY + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + route $route_syntax_del -net "$NETWORK" $route_syntax_netmask "$NETMASK" + } + + reset_ipv4_default_route() { + if [ -s "$DEFAULT_ROUTE_FILE" ]; then + route $route_syntax_del default $route_syntax_gw `get_default_gw` $route_syntax_interface + route add default $route_syntax_gw `cat "$DEFAULT_ROUTE_FILE"` + rm -f -- "$DEFAULT_ROUTE_FILE" + fi + } + + del_ipv4_network_route() { + NETWORK="$1" + NETMASK="$2" + NETMASKLEN="$3" + if [ -n "$5" ]; then + NETGW="$5" + else + NETGW="$INTERNAL_IP4_ADDRESS" + fi + route $route_syntax_del -net "$NETWORK" $route_syntax_netmask "$NETMASK" $route_syntax_gw "$NETGW" + } + + get_ipv6_default_gw() { + # Intended behavior, starting with `netstat -r -n` IPv6 output: + # - keep lines starting with 'default' or '::' + # - append %$interface to link-local routes (fe80::/10) + # - remove lines for loopback interface (lo) + # - remove lines containing $TUNDEV (we don't want loopback) + # FIXME: is there a better way to exclude loopback routes than filtering interface /^lo/? + netstat -r -n $netstat_syntax_ipv6 | awk '/^(default|::\/0)/ { if ($NF!~/^lo/ && $NF!~/'"$TUNDEV"'([[:space:]]|$)/) { print ($2~/^fe[89ab]/ ? $2"%"$NF : $2); } }' + } + + set_ipv6_default_route() { + DEFAULTGW="`get_ipv6_default_gw`" + echo "$DEFAULTGW" > "$DEFAULT_ROUTE_FILE_IPV6" + route $route_syntax_del $route_syntax_inet6 default $route_syntax_gw "$DEFAULTGW" + route add $route_syntax_inet6 default $route_syntax_gw "$INTERNAL_IP6_ADDRESS" $route_syntax_interface + } + + set_ipv6_network_route() { + NETWORK="$1" + NETMASK="$2" + DEVICE="$3" + if [ -n "$4" ]; then + NETGW="$4" + elif [ "$OS" = "Linux" ]; then + route add $route_syntax_inet6_net "$NETWORK/$NETMASK" dev "$DEVICE" + return + else + NETGW="$INTERNAL_IP6_ADDRESS" + fi + + route add $route_syntax_inet6_net "$NETWORK/$NETMASK" $route_syntax_gw "$NETGW" $route_syntax_interface + : + } + + set_ipv6_exclude_route() { + NETWORK="$1" + NETMASK="$2" + IPV6DEFAULTGW="${IPV6DEFAULTGW:-`get_ipv6_default_gw`}" + if [ -z "$IPV6DEFAULTGW" ]; then + echo "cannot find route for exclude route $NETWORK/$NETMASKLEN, ignoring" >&2 + return + fi + # Add explicit route to keep traffic for this target separate + # from tunnel. FIXME: We use default gateway - this is our best + # guess in absence of "ip" command to query effective route. + route add $route_syntax_inet6_net "$NETWORK/$NETMASK" "$IPV6DEFAULTGW" $route_syntax_interface + : + } + + reset_ipv6_default_route() { + if [ -s "$DEFAULT_ROUTE_FILE_IPV6" ]; then + route $route_syntax_del $route_syntax_inet6 default $route_syntax_gw "`get_ipv6_default_gw`" $route_syntax_interface + route add $route_syntax_inet6 default $route_syntax_gw `cat "$DEFAULT_ROUTE_FILE_IPV6"` + rm -f -- "$DEFAULT_ROUTE_FILE_IPV6" + fi + : + } + + del_ipv6_network_route() { + NETWORK="$1" + NETMASK="$2" + DEVICE="$3" + if [ -n "$4" ]; then + NETGW="$4" + elif [ "$OS" = "Linux" ]; then + route $route_syntax_del $route_syntax_inet6 "$NETWORK/$NETMASK" dev "$DEVICE" + return + else + NETGW="$INTERNAL_IP6_ADDRESS" + fi + route $route_syntax_del $route_syntax_inet6 "$NETWORK/$NETMASK" $route_syntax_gw "$NETGW" + : + } + + del_ipv6_exclude_route() { + NETWORK="$1" + NETMASK="$2" + route $route_syntax_del $route_syntax_inet6 "$NETWORK/$NETMASK" + : + } + +fi + +# =========== resolv.conf handling ==================================== + +# =========== resolv.conf handling for any OS ========================= + +modify_resolvconf_generic() { + grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 || cp -- /etc/resolv.conf "$RESOLV_CONF_BACKUP" + NEW_RESOLVCONF="#@VPNC_GENERATED@ -- this file is generated by vpnc +# and will be overwritten by vpnc +# as long as the above mark is intact" + + DOMAINS="$CISCO_DEF_DOMAIN" + + exec 6< "$RESOLV_CONF_BACKUP" + while read LINE <&6 ; do + case "$LINE" in + # omit; we will overwrite these + nameserver*) ;; + # extract listed domains and prepend to list + domain* | search*) DOMAINS="${LINE#* } $DOMAINS" ;; + # retain other lines + *) NEW_RESOLVCONF="$NEW_RESOLVCONF +$LINE" ;; + esac + done + exec 6<&- + + for i in $INTERNAL_IP4_DNS ; do + NEW_RESOLVCONF="$NEW_RESOLVCONF +nameserver $i" + done + # note that "search" is mutually exclusive with "domain"; + # "search" allows multiple domains to be listed, so use that + if [ -n "$DOMAINS" ]; then + NEW_RESOLVCONF="$NEW_RESOLVCONF +search $DOMAINS" + fi + echo "$NEW_RESOLVCONF" > /etc/resolv.conf + + if [ "$OS" = "Darwin" ]; then + case "`uname -r`" in + # Skip for pre-10.4 systems + 4.*|5.*|6.*|7.*) + ;; + # 10.4 and later require use of scutil for DNS to work properly + *) + OVERRIDE_PRIMARY="" + if [ -n "$CISCO_SPLIT_INC" ]; then + if [ $CISCO_SPLIT_INC -lt 1 ]; then + # Must override for correct default route + # Cannot use multiple DNS matching in this case + OVERRIDE_PRIMARY='d.add OverridePrimary # 1' + fi + # Overriding the default gateway breaks split routing + OVERRIDE_GATEWAY="" + # Not overriding the default gateway breaks usage of + # INTERNAL_IP4_DNS. Prepend INTERNAL_IP4_DNS to list + # of used DNS servers + SERVICE=`echo "show State:/Network/Global/IPv4" | scutil | grep -oE '[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}'` + SERVICE_DNS=`echo "show State:/Network/Service/$SERVICE/DNS" | scutil | grep -oE '([0-9]{1,3}[\.]){3}[0-9]{1,3}' | xargs` + if [ X"$SERVICE_DNS" != X"$INTERNAL_IP4_DNS" ]; then + scutil >/dev/null 2>&1 <<-EOF + open + get State:/Network/Service/$SERVICE/DNS + d.add ServerAddresses * $INTERNAL_IP4_DNS $SERVICE_DNS + set State:/Network/Service/$SERVICE/DNS + close + EOF + fi + else + # No split routing. Override default gateway + OVERRIDE_GATEWAY="d.add Router $INTERNAL_IP4_ADDRESS" + fi + # Uncomment the following if/fi pair to use multiple + # DNS matching when available. When multiple DNS matching + # is present, anything reading the /etc/resolv.conf file + # directly will probably not work as intended. + #if [ -z "$CISCO_DEF_DOMAIN" ]; then + # Cannot use multiple DNS matching without a domain + OVERRIDE_PRIMARY='d.add OverridePrimary # 1' + #fi + scutil >/dev/null 2>&1 <<-EOF + open + d.init + d.add ServerAddresses * $INTERNAL_IP4_DNS + set State:/Network/Service/$TUNDEV/DNS + d.init + $OVERRIDE_GATEWAY + d.add Addresses * $INTERNAL_IP4_ADDRESS + d.add SubnetMasks * 255.255.255.255 + d.add InterfaceName $TUNDEV + $OVERRIDE_PRIMARY + set State:/Network/Service/$TUNDEV/IPv4 + close + EOF + if [ -n "$CISCO_DEF_DOMAIN" ]; then + scutil >/dev/null 2>&1 <<-EOF + open + get State:/Network/Service/$TUNDEV/DNS + d.add DomainName $CISCO_DEF_DOMAIN + d.add SearchDomains * $CISCO_DEF_DOMAIN + d.add SupplementalMatchDomains * $CISCO_DEF_DOMAIN + set State:/Network/Service/$TUNDEV/DNS + close + EOF + fi + # For newer MacOS versions it is needed to set DNS + ACTIVE_INTERFACE=`route -n get default | grep interface | awk '{print $2}'` + ACTIVE_NETWORK_SERVICE=`networksetup -listnetworkserviceorder | grep -B 1 "$ACTIVE_INTERFACE" | head -n 1 | awk '/\([0-9]+\)/{ print }'|cut -d " " -f2-` + networksetup -setdnsservers "$ACTIVE_NETWORK_SERVICE" $INTERNAL_IP4_DNS + ;; + esac + fi +} + +restore_resolvconf_generic() { + if [ ! -f "$RESOLV_CONF_BACKUP" ]; then + return + fi + grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 && cat "$RESOLV_CONF_BACKUP" > /etc/resolv.conf + rm -f -- "$RESOLV_CONF_BACKUP" + + if [ "$OS" = "Darwin" ]; then + case "`uname -r`" in + # Skip for pre-10.4 systems + 4.*|5.*|6.*|7.*) + ;; + # 10.4 and later require use of scutil for DNS to work properly + *) + scutil >/dev/null 2>&1 <<-EOF + open + remove State:/Network/Service/$TUNDEV/IPv4 + remove State:/Network/Service/$TUNDEV/DNS + close + EOF + # Split routing required prepending of INTERNAL_IP4_DNS + # to list of used DNS servers + if [ -n "$CISCO_SPLIT_INC" ]; then + SERVICE=`echo "show State:/Network/Global/IPv4" | scutil | grep -oE '[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}'` + SERVICE_DNS=`echo "show State:/Network/Service/$SERVICE/DNS" | scutil | grep -oE '([0-9]{1,3}[\.]){3}[0-9]{1,3}'` + FILTERED_SERVICE_DNS=`echo "$SERVICE_DNS" | grep -Fv "$(echo $INTERNAL_IP4_DNS | tr ' ' '\n')" | xargs` + if [ -n "$FILTERED_SERVICE_DNS" ]; then + scutil >/dev/null 2>&1 <<-EOF + open + get State:/Network/Service/$SERVICE/DNS + d.add ServerAddresses * ${FILTERED_SERVICE_DNS} + set State:/Network/Service/$SERVICE/DNS + close + EOF + fi + fi + # For newer MacOS versions it is needed to unset DNS + ACTIVE_INTERFACE=`route -n get default | grep interface | awk '{print $2}'` + ACTIVE_NETWORK_SERVICE=`networksetup -listnetworkserviceorder | grep -B 1 "$ACTIVE_INTERFACE" | head -n 1 | awk '/\([0-9]+\)/{ print }'|cut -d " " -f2-` + networksetup -setdnsservers "$ACTIVE_NETWORK_SERVICE" Empty + ;; + esac + fi +} +# === resolv.conf handling via /sbin/netconfig (Suse 11.1) ===================== + +# Suse provides a script that modifies resolv.conf. Use it because it will +# restart/reload all other services that care about it (e.g. lwresd). [unclear if this is still true, but probably --mlk] + +modify_resolvconf_suse_netconfig() +{ + /sbin/netconfig modify -s vpnc -i "$TUNDEV" <<-EOF + INTERFACE='$TUNDEV' + DNSSERVERS='$INTERNAL_IP4_DNS' + DNSDOMAIN='$CISCO_DEF_DOMAIN' + EOF +} +# Restore resolv.conf to old contents on Suse +restore_resolvconf_suse_netconfig() +{ + /sbin/netconfig remove -s vpnc -i "$TUNDEV" +} + +# === resolv.conf handling via /sbin/modify_resolvconf (Suse) ===================== + +# Suse provides a script that modifies resolv.conf. Use it because it will +# restart/reload all other services that care about it (e.g. lwresd). + +modify_resolvconf_suse() +{ + FULL_SCRIPTNAME=`readlink -f $0` + RESOLV_OPTS='' + test -n "$INTERNAL_IP4_DNS" && RESOLV_OPTS="-n \"$INTERNAL_IP4_DNS\"" + test -n "$CISCO_DEF_DOMAIN" && RESOLV_OPTS="$RESOLV_OPTS -d $CISCO_DEF_DOMAIN" + test -n "$RESOLV_OPTS" && eval /sbin/modify_resolvconf modify -s vpnc -p $SCRIPTNAME -f $FULL_SCRIPTNAME -e $TUNDEV $RESOLV_OPTS -t \"This file was created by $SCRIPTNAME\" +} + +# Restore resolv.conf to old contents on Suse +restore_resolvconf_suse() +{ + FULL_SCRIPTNAME=`readlink -f $0` + /sbin/modify_resolvconf restore -s vpnc -p $SCRIPTNAME -f $FULL_SCRIPTNAME -e $TUNDEV +} + +# === resolv.conf handling via UCI (OpenWRT) ========= + +modify_resolvconf_openwrt() { + add_dns $OPENWRT_INTERFACE $INTERNAL_IP4_DNS +} + +restore_resolvconf_openwrt() { + remove_dns $OPENWRT_INTERFACE +} + +# === resolv.conf handling via /sbin/resolvconf (Debian, Ubuntu, Gentoo)) ========= + +modify_resolvconf_manager() { + NEW_RESOLVCONF="" + for i in $INTERNAL_IP4_DNS; do + NEW_RESOLVCONF="$NEW_RESOLVCONF +nameserver $i" + done + if [ -n "$CISCO_DEF_DOMAIN" ]; then + NEW_RESOLVCONF="$NEW_RESOLVCONF +search $CISCO_DEF_DOMAIN" + fi + echo "$NEW_RESOLVCONF" | /sbin/resolvconf -a $TUNDEV +} + +restore_resolvconf_manager() { + /sbin/resolvconf -d $TUNDEV +} + +# === resolv.conf handling via systemd-resolved ========= + +AF_INET=2 + +get_if_index() { + local link + link="$(ip link show dev "$1")" || return $? + echo ${link} | awk -F: '{print $1}' +} + +busctl_call() { + local dest node + dest=org.freedesktop.resolve1 + node=/org/freedesktop/resolve1 + /usr/bin/busctl call "$dest" "$node" "${dest}.Manager" "$@" +} + +busctl_set_nameservers() { + local if_index addresses args addr + if_index=$1 + shift + addresses="$@" + args="$if_index $#" + for addr in ${addresses}; do + args="$args ${AF_INET} 4 $(echo $addr | sed 's/[.]/ /g')" + done + busctl_call SetLinkDNS 'ia(iay)' ${args} +} + +resolvectl_set_nameservers() { + local if_index addresses + if_index=$1 + shift + addresses="$@" + /usr/bin/resolvectl dns $if_index $addresses +} + +busctl_set_search() { + local if_index domains args domain + if_index=$1 + shift + domains="$@" + args="$if_index $#" + for domain in ${domains}; do + args="$args ${domain} false" + done + busctl_call SetLinkDomains 'ia(sb)' ${args} +} + +resolvectl_set_search() { + local if_index domains + if_index=$1 + shift + domains="$@" + /usr/bin/resolvectl domain $if_index $domains +} + +modify_resolved_manager() { + local if_index split_dns_list + if_index=$(get_if_index $TUNDEV) + split_dns_list=$(echo $CISCO_SPLIT_DNS | tr ',' ' ') + resolvectl_set_nameservers $if_index $INTERNAL_IP4_DNS + if [ -n "$CISCO_DEF_DOMAIN" ] || [ -n "$split_dns_list" ]; then + resolvectl_set_search $if_index $CISCO_DEF_DOMAIN $split_dns_list + fi +} + +modify_resolved_manager_old() { + local if_index + if_index=$(get_if_index $TUNDEV) + busctl_set_nameservers $if_index $INTERNAL_IP4_DNS + if [ -n "$CISCO_DEF_DOMAIN" ]; then + busctl_set_search $if_index $CISCO_DEF_DOMAIN + fi +} + +restore_resolved_manager() { + local if_index + if_index=$(get_if_index $TUNDEV) + /usr/bin/resolvectl revert $if_index +} + +restore_resolved_manager_old() { + local if_index + if_index=$(get_if_index $TUNDEV) + busctl_call RevertLink 'i' $if_index +} + +# === resolv.conf handling via unbound ========= + +modify_resolvconf_unbound() { + if [ -n "$CISCO_DEF_DOMAIN" ]; then + /usr/sbin/unbound-control forward_add +i ${CISCO_DEF_DOMAIN} ${INTERNAL_IP4_DNS} + /usr/sbin/unbound-control flush_requestlist + /usr/sbin/unbound-control flush_zone ${CISCO_DEF_DOMAIN} + # flush infra cache + for i in $INTERNAL_IP4_DNS ; do + /usr/sbin/unbound-control flush_infra "$i" + done + + fi +} + +restore_resolvconf_unbound() { + if [ -n "$CISCO_DEF_DOMAIN" ]; then + /usr/sbin/unbound-control forward_remove +i ${CISCO_DEF_DOMAIN} + /usr/sbin/unbound-control flush_zone ${CISCO_DEF_DOMAIN} + /usr/sbin/unbound-control flush_requestlist + fi +} + +# === resolv.conf handling via resolvd (OpenBSD) ========= + +modify_resolvconf_resolvd() { + /sbin/route nameserver $TUNDEV $INTERNAL_IP4_DNS $INTERNAL_IP6_DNS +} + +restore_resolvconf_resolvd() { + /sbin/route nameserver $TUNDEV +} + +# ========= Toplevel state handling ======================================= + +do_pre_init() { + if [ "$OS" = "Linux" ]; then + if (exec 6< /dev/net/tun) > /dev/null 2>&1 ; then + : + else # can't open /dev/net/tun + test -e /proc/sys/kernel/modprobe && `cat /proc/sys/kernel/modprobe` tun 2>/dev/null + # make sure tun device exists + if [ ! -e /dev/net/tun ]; then + mkdir -p /dev/net + mknod -m 0640 /dev/net/tun c 10 200 + [ -x /sbin/restorecon ] && /sbin/restorecon /dev/net/tun + fi + # workaround for a possible latency caused by udev, sleep max. 10s + for x in $(seq 100) ; do + (exec 6<> /dev/net/tun) > /dev/null 2>&1 && break; + sleep 0.1 + done + fi + elif [ "$OS" = "FreeBSD" -o "$OS" = "DragonFly" ]; then + if ! ifconfig $TUNDEV > /dev/null; then + ifconfig $TUNDEV create + fi + elif [ "$OS" = "GNU/kFreeBSD" ]; then + if [ ! -e /dev/tun ]; then + kldload if_tun + fi + elif [ "$OS" = "NetBSD" ]; then + : + elif [ "$OS" = "OpenBSD" ]; then + if ! ifconfig $TUNDEV > /dev/null; then + ifconfig $TUNDEV create + fi + : + elif [ "$OS" = "SunOS" ]; then + : + elif [ "$OS" = "Darwin" ]; then + : + fi +} + +do_connect() { + if [ -n "$CISCO_BANNER" ]; then + echo "Connect Banner:" + echo "$CISCO_BANNER" | while read LINE ; do echo "|" "$LINE" ; done + echo + fi + + case "$VPNGATEWAY" in + 127.*|::1) ;; # localhost (probably proxy) + *) set_vpngateway_route ;; + esac + do_ifconfig + if [ -n "$CISCO_SPLIT_EXC" ]; then + i=0 + while [ $i -lt $CISCO_SPLIT_EXC ] ; do + eval NETWORK="\${CISCO_SPLIT_EXC_${i}_ADDR}" + eval NETMASK="\${CISCO_SPLIT_EXC_${i}_MASK}" + eval NETMASKLEN="\${CISCO_SPLIT_EXC_${i}_MASKLEN}" + case "$NETWORK" in + 0.*|127.*|169.254.*) echo "ignoring non-forwardable exclude route $NETWORK/$NETMASKLEN" >&2 ;; + *) set_ipv4_exclude_route "$NETWORK" "$NETMASK" "$NETMASKLEN" ;; + esac + i=`expr $i + 1` + done + fi + if [ -n "$CISCO_IPV6_SPLIT_EXC" ]; then + # untested + i=0 + while [ $i -lt $CISCO_IPV6_SPLIT_EXC ] ; do + eval NETWORK="\${CISCO_IPV6_SPLIT_EXC_${i}_ADDR}" + eval NETMASKLEN="\${CISCO_IPV6_SPLIT_EXC_${i}_MASKLEN}" + set_ipv6_exclude_route "$NETWORK" "$NETMASKLEN" + i=`expr $i + 1` + done + fi + if [ -n "$CISCO_SPLIT_INC" ]; then + i=0 + while [ $i -lt $CISCO_SPLIT_INC ] ; do + eval NETWORK="\${CISCO_SPLIT_INC_${i}_ADDR}" + eval NETMASK="\${CISCO_SPLIT_INC_${i}_MASK}" + eval NETMASKLEN="\${CISCO_SPLIT_INC_${i}_MASKLEN}" + if [ "$NETWORK" != "0.0.0.0" ]; then + set_ipv4_network_route "$NETWORK" "$NETMASK" "$NETMASKLEN" "$TUNDEV" + else + set_ipv4_default_route + fi + i=`expr $i + 1` + done + elif [ -n "$INTERNAL_IP4_ADDRESS" ]; then + set_ipv4_default_route + fi + if [ -n "$CISCO_IPV6_SPLIT_INC" ]; then + i=0 + while [ $i -lt $CISCO_IPV6_SPLIT_INC ] ; do + eval NETWORK="\${CISCO_IPV6_SPLIT_INC_${i}_ADDR}" + eval NETMASKLEN="\${CISCO_IPV6_SPLIT_INC_${i}_MASKLEN}" + if [ $NETMASKLEN -eq 0 ]; then + set_ipv6_default_route + else + set_ipv6_network_route "$NETWORK" "$NETMASKLEN" "$TUNDEV" + fi + i=`expr $i + 1` + done + elif [ -n "$INTERNAL_IP6_NETMASK" -o -n "$INTERNAL_IP6_ADDRESS" ]; then + set_ipv6_default_route + fi + + if [ -n "$INTERNAL_IP4_DNS" ]; then + $MODIFYRESOLVCONF + fi +} + +do_disconnect() { + if [ -n "$CISCO_SPLIT_INC" ]; then + i=0 + while [ $i -lt $CISCO_SPLIT_INC ] ; do + eval NETWORK="\${CISCO_SPLIT_INC_${i}_ADDR}" + eval NETMASK="\${CISCO_SPLIT_INC_${i}_MASK}" + eval NETMASKLEN="\${CISCO_SPLIT_INC_${i}_MASKLEN}" + if [ "$NETWORK" != "0.0.0.0" ]; then + # FIXME: This doesn't restore previously overwritten + # routes. + del_ipv4_network_route "$NETWORK" "$NETMASK" "$NETMASKLEN" "$TUNDEV" + else + reset_ipv4_default_route + fi + i=`expr $i + 1` + done + else + reset_ipv4_default_route + fi + if [ -n "$CISCO_SPLIT_EXC" ]; then + i=0 + while [ $i -lt $CISCO_SPLIT_EXC ] ; do + eval NETWORK="\${CISCO_SPLIT_EXC_${i}_ADDR}" + eval NETMASK="\${CISCO_SPLIT_EXC_${i}_MASK}" + eval NETMASKLEN="\${CISCO_SPLIT_EXC_${i}_MASKLEN}" + case "$NETWORK" in + 0.*|127.*|169.254.*) ;; # ignoring non-forwardable exclude route + *) del_ipv4_exclude_route "$NETWORK" "$NETMASK" "$NETMASKLEN" ;; + esac + i=`expr $i + 1` + done + fi + if [ -n "$CISCO_IPV6_SPLIT_EXC" ]; then + # untested + i=0 + while [ $i -lt $CISCO_IPV6_SPLIT_EXC ] ; do + eval NETWORK="\${CISCO_IPV6_SPLIT_EXC_${i}_ADDR}" + eval NETMASKLEN="\${CISCO_IPV6_SPLIT_EXC_${i}_MASKLEN}" + del_ipv6_exclude_route "$NETWORK" "$NETMASKLEN" + i=`expr $i + 1` + done + fi + if [ -n "$CISCO_IPV6_SPLIT_INC" ]; then + i=0 + while [ $i -lt $CISCO_IPV6_SPLIT_INC ] ; do + eval NETWORK="\${CISCO_IPV6_SPLIT_INC_${i}_ADDR}" + eval NETMASKLEN="\${CISCO_IPV6_SPLIT_INC_${i}_MASKLEN}" + if [ $NETMASKLEN -eq 0 ]; then + reset_ipv6_default_route + else + del_ipv6_network_route "$NETWORK" "$NETMASKLEN" "$TUNDEV" + fi + i=`expr $i + 1` + done + elif [ -n "$INTERNAL_IP6_NETMASK" -o -n "$INTERNAL_IP6_ADDRESS" ]; then + reset_ipv6_default_route + fi + + del_vpngateway_route + + if [ -n "$INTERNAL_IP4_DNS" ]; then + $RESTORERESOLVCONF + fi + + + if [ -n "$IPROUTE" ]; then + if [ -n "$INTERNAL_IP4_ADDRESS" ]; then + $IPROUTE addr del "$INTERNAL_IP4_ADDRESS/255.255.255.255" peer "$INTERNAL_IP4_ADDRESS" dev "$TUNDEV" + fi + # If the netmask is provided, it contains the address _and_ netmask + if [ -n "$INTERNAL_IP6_ADDRESS" ] && [ -z "$INTERNAL_IP6_NETMASK" ]; then + INTERNAL_IP6_NETMASK="$INTERNAL_IP6_ADDRESS/128" + fi + if [ -n "$INTERNAL_IP6_NETMASK" ]; then + $IPROUTE -6 addr del $INTERNAL_IP6_NETMASK dev $TUNDEV + fi + $IPROUTE link set dev "$TUNDEV" down + else + if [ -n "$INTERNAL_IP4_ADDRESS" ]; then + ifconfig "$TUNDEV" `ifconfig_syntax_del "$INTERNAL_IP4_ADDRESS"` + fi + if [ -n "$INTERNAL_IP6_ADDRESS" ] && [ -z "$INTERNAL_IP6_NETMASK" ]; then + INTERNAL_IP6_NETMASK="$INTERNAL_IP6_ADDRESS/128" + fi + if [ -n "$INTERNAL_IP6_NETMASK" ]; then + ifconfig "$TUNDEV" `ifconfig_syntax_del "$INTERNAL_IP6_NETMASK"` + fi + ifconfig "$TUNDEV" down + fi + + case "$OS" in + NetBSD|OpenBSD) # and probably others... + ifconfig "$TUNDEV" destroy + ;; + FreeBSD|DragonFly) + ifconfig "$TUNDEV" destroy > /dev/null 2>&1 & + ;; + esac +} + +do_attempt_reconnect() { + set_vpngateway_route +} + +#### Main + +if [ -z "$reason" ]; then + echo "this script must be called from vpnc" 1>&2 + exit 1 +fi + +case "$reason" in + pre-init) + run_hooks pre-init + do_pre_init + ;; + connect) + run_hooks connect + do_connect + run_hooks post-connect + ;; + disconnect) + run_hooks disconnect + do_disconnect + run_hooks post-disconnect + ;; + attempt-reconnect) + # Invoked before each attempt to re-establish the session. + # If the underlying physical connection changed, we might + # be left with a route to the VPN server through the VPN + # itself, which would need to be fixed. + run_hooks attempt-reconnect + do_attempt_reconnect + run_hooks post-attempt-reconnect + ;; + reconnect) + # After successfully re-establishing the session. + run_hooks reconnect + ;; + *) + echo "unknown reason '$reason'. Maybe vpnc-script is out of date" 1>&2 + exit 1 + ;; +esac + +exit 0 diff --git a/packaging/pkgbuild/PKGBUILD.in b/packaging/pkgbuild/PKGBUILD.in index a238afb..b32d9d8 100644 --- a/packaging/pkgbuild/PKGBUILD.in +++ b/packaging/pkgbuild/PKGBUILD.in @@ -8,8 +8,8 @@ pkgdesc="A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO aut arch=('x86_64' 'aarch64') url="https://github.com/yuezk/GlobalProtect-openconnect" license=('GPL3') -makedepends=('make' 'pkg-config' 'rust' 'cargo' 'jq' 'webkit2gtk' 'curl' 'wget' 'file' 'openssl' 'appmenu-gtk-module' 'gtk3' 'libappindicator-gtk3' 'librsvg' 'libvips' 'libayatana-appindicator' 'openconnect' 'libsecret') -depends=('openconnect>=8.20' webkit2gtk libappindicator-gtk3 libayatana-appindicator libsecret libxml2) +makedepends=('make' 'pkg-config' 'rust' 'cargo' 'jq' 'webkit2gtk' 'curl' 'wget' 'file' 'openssl' 'appmenu-gtk-module' 'gtk3' 'libappindicator-gtk3' 'librsvg' 'libvips' 'libayatana-appindicator' 'libsecret' 'autoconf' 'automake' 'libtool') +depends=('webkit2gtk' 'libappindicator-gtk3' 'libayatana-appindicator' 'libsecret' 'gnutls' 'lz4' 'nettle' 'libp11-kit' 'gmp') optdepends=('wmctrl: for window management') provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui') @@ -25,7 +25,7 @@ build() { # Must unset the CFLAGS, otherwise the build fails unset CFLAGS - make build OFFLINE=@OFFLINE@ BUILD_FE=0 + make build OFFLINE=@OFFLINE@ BUILD_FE=0 LIBXML2_STATIC=1 } package() { diff --git a/packaging/rpm/globalprotect-openconnect.spec.in b/packaging/rpm/globalprotect-openconnect.spec.in index 71199cd..0451171 100644 --- a/packaging/rpm/globalprotect-openconnect.spec.in +++ b/packaging/rpm/globalprotect-openconnect.spec.in @@ -13,17 +13,26 @@ BuildRequires: rust BuildRequires: cargo BuildRequires: jq BuildRequires: pkg-config -BuildRequires: openconnect-devel +BuildRequires: libtool +BuildRequires: autoconf +BuildRequires: automake +BuildRequires: gcc-c++ BuildRequires: openssl-devel +BuildRequires: zlib-devel +BuildRequires: lz4-devel +BuildRequires: p11-kit-devel +BuildRequires: nettle-devel +BuildRequires: gnutls-devel +BuildRequires: gmp-devel BuildRequires: wget BuildRequires: file BuildRequires: perl -BuildRequires: (webkit2gtk4.0-devel or webkit2gtk3-soup2-devel) +BuildRequires: (webkit2gtk4.0-devel or webkit2gtk3-devel or webkit2gtk3-soup2-devel) BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1) BuildRequires: (librsvg2-devel or librsvg-devel) -Requires: openconnect >= 8.20, (libayatana-appindicator or libappindicator-gtk3) +Requires: (libayatana-appindicator or libappindicator-gtk3) Conflicts: globalprotect-openconnect-snapshot %global debug_package %{nil} @@ -40,7 +49,7 @@ rm -f %{_bindir}/gpgui %build # The injected RUSTFLAGS could fail the build unset RUSTFLAGS -make build OFFLINE=@OFFLINE@ BUILD_FE=0 +make build OFFLINE=@OFFLINE@ BUILD_FE=0 LIBXML2_STATIC=1 %install %make_install @@ -48,6 +57,8 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0 %files %defattr(-,root,root) %{_bindir}/* +%{_libexecdir}/gpclient/vpnc-script +%{_libexecdir}/gpclient/hipreport.sh %{_datadir}/applications/gpgui.desktop %{_datadir}/icons/hicolor/32x32/apps/gpgui.png %{_datadir}/icons/hicolor/128x128/apps/gpgui.png @@ -62,6 +73,8 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0 /usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down /usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook +%dir %{_libexecdir} +%dir %{_libexecdir}/gpclient %dir %{_datadir}/icons/hicolor %dir %{_datadir}/icons/hicolor/32x32 %dir %{_datadir}/icons/hicolor/32x32/apps