mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
Release 3.6.0
This commit is contained in:
58 files changed
+2191
-642
No files matched your search
@@ -15,7 +15,7 @@ serde_json.workspace = true
|
||||
serde.workspace = true
|
||||
winreg = "0.56"
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Threading", "Win32_UI_Shell"] }
|
||||
|
||||
[dev-dependencies]
|
||||
ipnet = "2"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Adapter DNS settings and Windows name-resolution policy scoped to this connection.
|
||||
use super::configuration::Configuration;
|
||||
use super::{SystemTunnel, configuration::Configuration};
|
||||
use base64::Engine;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
@@ -23,6 +23,7 @@ pub(super) struct Installed {
|
||||
guid: GUID,
|
||||
snapshot: Option<Snapshot>,
|
||||
tag: Option<String>,
|
||||
tunnel: Option<SystemTunnel>,
|
||||
}
|
||||
fn check(status: u32) -> io::Result<()> {
|
||||
if status == 0 {
|
||||
@@ -77,7 +78,7 @@ impl Snapshot {
|
||||
}
|
||||
}
|
||||
impl Installed {
|
||||
pub fn apply(configuration: &Configuration) -> io::Result<Self> {
|
||||
pub fn apply(configuration: &Configuration, recovery_key: &str, tunnel: Option<&SystemTunnel>) -> io::Result<Self> {
|
||||
let mut luid = NET_LUID_LH::default();
|
||||
let mut guid = GUID::default();
|
||||
check(unsafe { ConvertInterfaceIndexToLuid(configuration.interface, &mut luid) })?;
|
||||
@@ -86,6 +87,7 @@ impl Installed {
|
||||
guid,
|
||||
snapshot: Some(Snapshot::capture(guid)?),
|
||||
tag: None,
|
||||
tunnel: tunnel.cloned(),
|
||||
};
|
||||
Snapshot {
|
||||
domain: configuration.domains.first().cloned().unwrap_or_default(),
|
||||
@@ -105,9 +107,13 @@ impl Installed {
|
||||
.map(|domain| format!(".{}", domain.trim_matches('.')))
|
||||
.collect()
|
||||
};
|
||||
let tag = format!("GPConnect:{}", uuid::Uuid::new_v4());
|
||||
let tag = match tunnel {
|
||||
Some(_) => format!("GPConnect:{}", uuid::Uuid::new_v4()),
|
||||
None => journal_tag(recovery_key),
|
||||
};
|
||||
installed.tag = Some(tag.clone());
|
||||
policy(
|
||||
tunnel,
|
||||
json!({"operation":"add", "tag":tag, "namespaces":namespaces, "servers":configuration.servers.iter().map(ToString::to_string).collect::<Vec<_>>()}),
|
||||
)?;
|
||||
}
|
||||
@@ -116,7 +122,7 @@ impl Installed {
|
||||
pub fn restore(&mut self) -> io::Result<()> {
|
||||
let mut failure = None;
|
||||
if let Some(tag) = self.tag.take() {
|
||||
if let Err(error) = policy(json!({"operation":"remove", "tag":tag})) {
|
||||
if let Err(error) = policy(self.tunnel.as_ref(), json!({"operation":"remove", "tag":tag})) {
|
||||
log::warn!("Could not remove VPN DNS policy: {error}");
|
||||
failure = Some(error);
|
||||
}
|
||||
@@ -140,21 +146,36 @@ impl Drop for Installed {
|
||||
|
||||
/// A crashed service cannot run Drop. Remove only GP Connect's tagged policies
|
||||
/// before accepting a new connection; adapter rows disappear with Wintun itself.
|
||||
pub(super) fn clear_stale_policies() -> io::Result<()> {
|
||||
policy(json!({"operation":"clear-stale"}))
|
||||
pub(super) fn clear_stale_policies(tunnel: &SystemTunnel) -> io::Result<()> {
|
||||
policy(Some(tunnel), json!({"operation":"clear-stale"}))
|
||||
}
|
||||
fn policy(request: serde_json::Value) -> io::Result<()> {
|
||||
// Keep isolated journals outside the GPConnect:* namespace used by system recovery.
|
||||
fn journal_tag(recovery_key: &str) -> String {
|
||||
format!("GPConnectJournal:{recovery_key}")
|
||||
}
|
||||
|
||||
pub(super) fn remove_journal_policy(recovery_key: &str) -> io::Result<()> {
|
||||
policy(None, json!({"operation":"remove", "tag":journal_tag(recovery_key)}))
|
||||
}
|
||||
|
||||
fn policy(tunnel: Option<&SystemTunnel>, request: serde_json::Value) -> io::Result<()> {
|
||||
const SCRIPT: &str = include_str!("dns-policy.ps1");
|
||||
let encoded = base64::engine::general_purpose::STANDARD
|
||||
.encode(SCRIPT.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<_>>());
|
||||
let root =
|
||||
std::env::var_os("SystemRoot").ok_or_else(|| io::Error::other("Windows system directory is unavailable"))?;
|
||||
let executable = std::path::PathBuf::from(root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
// The script produces no standard output. Use that handle to give the worker
|
||||
// a copy of the lease so it keeps ownership if the tunnel process dies.
|
||||
let stdout = match tunnel {
|
||||
Some(tunnel) => Stdio::from(tunnel.duplicate_lock()?),
|
||||
None => Stdio::null(),
|
||||
};
|
||||
let mut child = Command::new(executable)
|
||||
.args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stdout(stdout)
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let input = child
|
||||
|
||||
@@ -3,24 +3,32 @@ mod configuration;
|
||||
mod dns;
|
||||
mod ip_helper;
|
||||
mod recovery;
|
||||
mod system_tunnel;
|
||||
use configuration::Configuration;
|
||||
use std::io;
|
||||
pub use system_tunnel::SystemTunnel;
|
||||
|
||||
pub struct NetworkConfigurator {
|
||||
connection: Option<Connection>,
|
||||
recovery_key: String,
|
||||
system_tunnel: Option<SystemTunnel>,
|
||||
}
|
||||
struct Connection {
|
||||
dns: dns::Installed,
|
||||
network: ip_helper::Installed,
|
||||
}
|
||||
impl NetworkConfigurator {
|
||||
/// The owner supplies an HKLM key under its administrator-controlled namespace.
|
||||
/// Use a separate HKLM journal and DNS tag for an isolated network configuration.
|
||||
pub fn new(recovery_key: &str) -> io::Result<Self> {
|
||||
Self::with_owner(recovery_key, None)
|
||||
}
|
||||
|
||||
fn with_owner(recovery_key: &str, system_tunnel: Option<SystemTunnel>) -> io::Result<Self> {
|
||||
recovery::Journal::begin(recovery_key)?;
|
||||
Ok(Self {
|
||||
connection: None,
|
||||
recovery_key: recovery_key.into(),
|
||||
system_tunnel,
|
||||
})
|
||||
}
|
||||
pub fn configure(&mut self, reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
|
||||
@@ -30,7 +38,7 @@ impl NetworkConfigurator {
|
||||
let configuration = Configuration::parse(environment)?;
|
||||
self.disconnect()?;
|
||||
let network = ip_helper::Installed::apply(&configuration, &self.recovery_key)?;
|
||||
let dns = dns::Installed::apply(&configuration)?;
|
||||
let dns = dns::Installed::apply(&configuration, &self.recovery_key, self.system_tunnel.as_ref())?;
|
||||
self.connection = Some(Connection { dns, network });
|
||||
Ok(())
|
||||
}
|
||||
@@ -52,13 +60,18 @@ impl NetworkConfigurator {
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore process-owned physical routes and DNS policy before service admission.
|
||||
/// Recover an isolated journal and only the DNS rules recorded under its name.
|
||||
pub fn recover(recovery_key: &str) -> io::Result<()> {
|
||||
recover_routes(recovery_key)?;
|
||||
dns::remove_journal_policy(recovery_key)
|
||||
}
|
||||
|
||||
fn recover_routes(recovery_key: &str) -> io::Result<()> {
|
||||
if let Some(journal) = recovery::Journal::open(recovery_key)? {
|
||||
for (name, route) in journal.routes()? {
|
||||
ip_helper::recover_route(&route)?;
|
||||
journal.forget(&name)?;
|
||||
}
|
||||
}
|
||||
dns::clear_stale_policies()
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use super::NetworkConfigurator;
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fs::{File, OpenOptions},
|
||||
io,
|
||||
os::windows::{ffi::OsStringExt, fs::OpenOptionsExt},
|
||||
path::PathBuf,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::ERROR_SHARING_VIOLATION,
|
||||
UI::Shell::{CSIDL_COMMON_APPDATA, SHGetFolderPathW},
|
||||
};
|
||||
|
||||
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
|
||||
|
||||
/// Exclusive ownership of the installed Windows system tunnel, including recovery.
|
||||
#[derive(Clone)]
|
||||
pub struct SystemTunnel {
|
||||
lock: Arc<File>,
|
||||
}
|
||||
|
||||
impl SystemTunnel {
|
||||
pub fn try_acquire() -> io::Result<Option<Self>> {
|
||||
let path = machine_data()?.join(r"GP Connect\Private\system-tunnel.lock");
|
||||
let file = match OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.share_mode(0)
|
||||
.open(path)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let tunnel = Self { lock: Arc::new(file) };
|
||||
super::recover_routes(RECOVERY_KEY)?;
|
||||
super::dns::clear_stale_policies(&tunnel)?;
|
||||
Ok(Some(tunnel))
|
||||
}
|
||||
|
||||
pub fn acquire() -> io::Result<Self> {
|
||||
Self::try_acquire()?.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
"Another GP Connect system tunnel or installer is active. Disconnect the tunnel or wait for setup to finish.",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn configurator(&self) -> io::Result<NetworkConfigurator> {
|
||||
NetworkConfigurator::with_owner(RECOVERY_KEY, Some(self.clone()))
|
||||
}
|
||||
|
||||
pub(super) fn duplicate_lock(&self) -> io::Result<File> {
|
||||
self.lock.try_clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn machine_data() -> io::Result<PathBuf> {
|
||||
let mut path = [0; 260];
|
||||
let result = unsafe {
|
||||
SHGetFolderPathW(
|
||||
ptr::null_mut(),
|
||||
CSIDL_COMMON_APPDATA as i32,
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
path.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
if result < 0 {
|
||||
return Err(io::Error::other(format!(
|
||||
"Windows ProgramData lookup failed ({result:#x})"
|
||||
)));
|
||||
}
|
||||
let length = path
|
||||
.iter()
|
||||
.position(|&c| c == 0)
|
||||
.filter(|&n| n > 0)
|
||||
.ok_or_else(|| io::Error::other("Windows ProgramData path is unavailable"))?;
|
||||
Ok(PathBuf::from(OsString::from_wide(&path[..length])))
|
||||
}
|
||||
@@ -235,12 +235,18 @@ fn assert_dns_policy(active: bool) {
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
$expected = [int]$env:GP_TEST_EXPECTED_DNS_POLICIES
|
||||
$configured = @(Get-DnsClientNrptRule | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' })
|
||||
$effective = @(Get-DnsClientNrptPolicy | Where-Object { $_.Namespace -contains '.gp-connect-test.invalid' })
|
||||
if ($configured.Count -ne $expected -or $effective.Count -ne $expected) { throw 'Unexpected configured or effective VPN DNS policy' }
|
||||
if ($expected) {
|
||||
$servers = @($configured[0].NameServers)
|
||||
if ($servers -notcontains '198.18.0.53' -or $servers -notcontains 'fd42:1235::53') { throw 'VPN DNS server families are missing' }
|
||||
$configured = @(Get-DnsClientNrptRule)
|
||||
$effective = @(Get-DnsClientNrptPolicy)
|
||||
foreach ($namespace in '.gp-connect-test.invalid', '.second-gp-connect-test.invalid') {
|
||||
$rules = @($configured | Where-Object { $_.Namespace -contains $namespace })
|
||||
$policies = @($effective | Where-Object { $_.Namespace -contains $namespace })
|
||||
if ($rules.Count -ne $expected -or $policies.Count -ne $expected) {
|
||||
throw "Unexpected configured or effective VPN DNS policy for $namespace"
|
||||
}
|
||||
if ($expected) {
|
||||
$servers = @($rules[0].NameServers)
|
||||
if ($servers -notcontains '198.18.0.53' -or $servers -notcontains 'fd42:1235::53') { throw "VPN DNS server families are missing for $namespace" }
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let powershell =
|
||||
@@ -253,6 +259,22 @@ if ($expected) {
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
fn global_search_list() -> Vec<u8> {
|
||||
let powershell =
|
||||
PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
let output = std::process::Command::new(powershell)
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"$ErrorActionPreference = 'Stop'; (Get-DnsClientGlobalSetting).SuffixSearchList | ConvertTo-Json -Compress",
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
output.stdout
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires administrator privileges and GP_TEST_WINTUN_DLL"]
|
||||
fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -274,10 +296,17 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
|
||||
let recovery_key = format!(r"SOFTWARE\GP Connect\Tests\Network{}", uuid::Uuid::new_v4().simple());
|
||||
assert_dns_policy(false);
|
||||
let before = state(index);
|
||||
let original_search_list = global_search_list();
|
||||
{
|
||||
let mut network = NetworkConfigurator::new(&recovery_key)?;
|
||||
network.configure("connect", &environment)?;
|
||||
let during = state(index);
|
||||
assert!(during.iter().any(|row| row == "dns-domain gp-connect-test.invalid"));
|
||||
assert!(
|
||||
during
|
||||
.iter()
|
||||
.any(|row| row == "dns-search gp-connect-test.invalid,second-gp-connect-test.invalid")
|
||||
);
|
||||
assert!(during.iter().any(|row| row == "address 192.0.2.2/24"));
|
||||
assert!(during.iter().any(|row| row == "address fd42:1234::2/64"));
|
||||
assert!(
|
||||
@@ -298,10 +327,14 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
|
||||
assert_ne!(best_route("198.51.100.1").InterfaceIndex, index);
|
||||
println!("PASS: IPv4/IPv6 addresses, split routes, resolver routes and MTU installed");
|
||||
assert_dns_policy(true);
|
||||
gpvpnc::windows::recover(&format!(r"{recovery_key}-other"))?;
|
||||
assert_dns_policy(true);
|
||||
assert_eq!(global_search_list(), original_search_list);
|
||||
network.configure("disconnect", &[])?;
|
||||
}
|
||||
assert_eq!(before, state(index), "Network state was not restored");
|
||||
assert_dns_policy(false);
|
||||
assert_eq!(global_search_list(), original_search_list);
|
||||
println!("PASS: disconnect restored addresses, routes and interface settings");
|
||||
{
|
||||
let mut network = NetworkConfigurator::new(&recovery_key)?;
|
||||
@@ -324,6 +357,7 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
|
||||
println!("PASS: partial setup failure rolled back its physical gateway route");
|
||||
drop(adapter);
|
||||
assert_crash_recovery(&recovery_key)?;
|
||||
assert_eq!(global_search_list(), original_search_list);
|
||||
winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE).delete_subkey(&recovery_key)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -347,8 +381,14 @@ fn environment(index: u32) -> Vec<(String, Option<String>)> {
|
||||
("CISCO_IPV6_SPLIT_INC_0_ADDR", "2001:db8:1234::".into()),
|
||||
("CISCO_IPV6_SPLIT_INC_0_MASKLEN", "64".into()),
|
||||
("INTERNAL_IP4_DNS", "198.18.0.53 fd42:1235::53".into()),
|
||||
("CISCO_DEF_DOMAIN", "gp-connect-test.invalid".into()),
|
||||
("CISCO_SPLIT_DNS", "gp-connect-test.invalid".into()),
|
||||
(
|
||||
"CISCO_DEF_DOMAIN",
|
||||
"gp-connect-test.invalid,second-gp-connect-test.invalid".into(),
|
||||
),
|
||||
(
|
||||
"CISCO_SPLIT_DNS",
|
||||
"gp-connect-test.invalid,second-gp-connect-test.invalid".into(),
|
||||
),
|
||||
];
|
||||
pairs
|
||||
.into_iter()
|
||||
|
||||
Reference in new issue
Block a user