mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: build and publish Windows NSH packages with verified updates
This commit is contained in:
113 files changed
+7264
-801
No files matched your search
@@ -5,5 +5,21 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
|
||||
log.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
ipnet = { version = "2", features = ["serde"] }
|
||||
base64.workspace = true
|
||||
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"] }
|
||||
|
||||
[dev-dependencies]
|
||||
ipnet = "2"
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Win32_System_LibraryLoader"] }
|
||||
@@ -1,2 +1,7 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod macos;
|
||||
#[cfg(windows)]
|
||||
pub mod windows;
|
||||
#[cfg(all(test, not(windows)))]
|
||||
#[path = "windows/configuration.rs"]
|
||||
mod windows_configuration;
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Convert OpenConnect's normal configuration callback into a Windows network plan.
|
||||
use ipnet::IpNet;
|
||||
use std::{collections::HashMap, io, net::IpAddr};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Configuration {
|
||||
pub interface: u32,
|
||||
pub gateway: IpAddr,
|
||||
pub addresses: Vec<IpNet>,
|
||||
pub mtu: Option<u32>,
|
||||
pub includes: Vec<IpNet>,
|
||||
pub excludes: Vec<IpNet>,
|
||||
pub servers: Vec<IpAddr>,
|
||||
pub domains: Vec<String>,
|
||||
pub split_dns: Vec<String>,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message.into())
|
||||
}
|
||||
impl Configuration {
|
||||
pub fn parse(environment: &[(String, Option<String>)]) -> io::Result<Self> {
|
||||
let values: HashMap<_, _> = environment
|
||||
.iter()
|
||||
.filter_map(|(key, value)| value.as_deref().map(|value| (key.as_str(), value)))
|
||||
.collect();
|
||||
let required = |key: &str| {
|
||||
values
|
||||
.get(key)
|
||||
.copied()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| invalid(format!("Missing VPN configuration: {key}")))
|
||||
};
|
||||
let interface: u32 = required("TUNIDX")?
|
||||
.parse()
|
||||
.map_err(|_| invalid("Invalid VPN interface index"))?;
|
||||
if interface == 0 {
|
||||
return Err(invalid("VPN interface index is zero"));
|
||||
}
|
||||
let gateway = required("VPNGATEWAY")?
|
||||
.parse()
|
||||
.map_err(|_| invalid("Invalid VPN gateway address"))?;
|
||||
let mut addresses = Vec::new();
|
||||
if let Some(address) = values.get("INTERNAL_IP4_ADDRESS") {
|
||||
let prefix = values.get("INTERNAL_IP4_NETMASKLEN").copied().unwrap_or("32");
|
||||
let network: IpNet = format!("{address}/{prefix}")
|
||||
.parse()
|
||||
.map_err(|_| invalid("Invalid VPN IPv4 address or prefix"))?;
|
||||
if !matches!(network, IpNet::V4(_)) {
|
||||
return Err(invalid("VPN IPv4 address has the wrong family"));
|
||||
}
|
||||
addresses.push(network);
|
||||
}
|
||||
if let Some(address) = values.get("INTERNAL_IP6_ADDRESS") {
|
||||
let prefix = values
|
||||
.get("INTERNAL_IP6_NETMASK")
|
||||
.and_then(|value| value.rsplit_once('/'))
|
||||
.map(|(_, prefix)| prefix)
|
||||
.unwrap_or("128");
|
||||
let network: IpNet = format!("{address}/{prefix}")
|
||||
.parse()
|
||||
.map_err(|_| invalid("Invalid VPN IPv6 address or prefix"))?;
|
||||
if !matches!(network, IpNet::V6(_)) {
|
||||
return Err(invalid("VPN IPv6 address has the wrong family"));
|
||||
}
|
||||
addresses.push(network);
|
||||
}
|
||||
if addresses.is_empty() {
|
||||
return Err(invalid("The VPN did not assign an IP address"));
|
||||
}
|
||||
let mtu = values
|
||||
.get("INTERNAL_IP4_MTU")
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| value.parse::<u32>().map_err(|_| invalid("Invalid VPN MTU")))
|
||||
.transpose()?
|
||||
.filter(|mtu| *mtu != 0);
|
||||
let mut includes = Vec::new();
|
||||
let mut excludes = Vec::new();
|
||||
for (family, prefix) in [(4, "CISCO_SPLIT"), (6, "CISCO_IPV6_SPLIT")] {
|
||||
if !addresses
|
||||
.iter()
|
||||
.any(|address| address.addr().is_ipv4() == (family == 4))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let included = routes(&values, &format!("{prefix}_INC"), family)?;
|
||||
if included.is_empty() {
|
||||
// Preserve the physical default route, using the two more-specific halves.
|
||||
let defaults: &[&str] = if family == 4 {
|
||||
&["0.0.0.0/1", "128.0.0.0/1"]
|
||||
} else {
|
||||
&["::/1", "8000::/1"]
|
||||
};
|
||||
includes.extend(defaults.iter().map(|route| route.parse::<IpNet>().unwrap()));
|
||||
} else {
|
||||
includes.extend(included);
|
||||
}
|
||||
excludes.extend(routes(&values, &format!("{prefix}_EXC"), family)?);
|
||||
}
|
||||
let mut servers = values
|
||||
.get("INTERNAL_IP4_DNS")
|
||||
.into_iter()
|
||||
.flat_map(|text| text.split_whitespace())
|
||||
.map(|address| address.parse().map_err(|_| invalid("Invalid VPN DNS server")))
|
||||
.collect::<io::Result<Vec<IpAddr>>>()?;
|
||||
let advertised_dns = !servers.is_empty();
|
||||
servers.retain(|server| {
|
||||
addresses
|
||||
.iter()
|
||||
.any(|address| address.addr().is_ipv4() == server.is_ipv4())
|
||||
});
|
||||
if advertised_dns && servers.is_empty() {
|
||||
return Err(invalid("No VPN DNS server matches an assigned address family"));
|
||||
}
|
||||
let domains = names(values.get("CISCO_DEF_DOMAIN").copied().unwrap_or(""));
|
||||
let split_dns = names(values.get("CISCO_SPLIT_DNS").copied().unwrap_or(""));
|
||||
Ok(Self {
|
||||
interface,
|
||||
gateway,
|
||||
addresses,
|
||||
mtu,
|
||||
includes,
|
||||
excludes,
|
||||
servers,
|
||||
domains,
|
||||
split_dns,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn names(text: &str) -> Vec<String> {
|
||||
text
|
||||
.split(|ch: char| ch == ',' || ch.is_whitespace())
|
||||
.filter(|part| !part.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
fn routes(values: &HashMap<&str, &str>, key: &str, family: u8) -> io::Result<Vec<IpNet>> {
|
||||
let count = values
|
||||
.get(key)
|
||||
.map(|value| {
|
||||
value
|
||||
.parse::<u32>()
|
||||
.map_err(|_| invalid(format!("Invalid {key} count")))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
(0..count)
|
||||
.map(|index| {
|
||||
let address = values
|
||||
.get(format!("{key}_{index}_ADDR").as_str())
|
||||
.ok_or_else(|| invalid(format!("Missing {key} address")))?;
|
||||
let prefix = values
|
||||
.get(format!("{key}_{index}_MASKLEN").as_str())
|
||||
.ok_or_else(|| invalid(format!("Missing {key} prefix")))?;
|
||||
let route: IpNet = format!("{address}/{prefix}")
|
||||
.parse()
|
||||
.map_err(|_| invalid(format!("Invalid {key} route")))?;
|
||||
if route.addr().is_ipv4() != (family == 4) {
|
||||
return Err(invalid(format!("Wrong {key} route family")));
|
||||
}
|
||||
Ok(route.trunc())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn environment(extra: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
|
||||
[
|
||||
("TUNIDX", "16"),
|
||||
("VPNGATEWAY", "198.51.100.1"),
|
||||
("INTERNAL_IP4_ADDRESS", "10.20.30.4"),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(extra.iter().copied())
|
||||
.map(|(key, value)| (key.into(), Some(value.into())))
|
||||
.collect()
|
||||
}
|
||||
#[test]
|
||||
fn full_tunnel_keeps_assigned_addresses_and_routes_both_families() {
|
||||
let plan = Configuration::parse(&environment(&[
|
||||
("INTERNAL_IP4_NETMASKLEN", "24"),
|
||||
("INTERNAL_IP6_ADDRESS", "fd00::4"),
|
||||
("INTERNAL_IP6_NETMASK", "fd00::4/64"),
|
||||
("INTERNAL_IP4_MTU", "1406"),
|
||||
("INTERNAL_IP4_DNS", "10.20.30.1 fd00::1"),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.addresses.iter().map(ToString::to_string).collect::<Vec<_>>(),
|
||||
["10.20.30.4/24", "fd00::4/64"]
|
||||
);
|
||||
assert_eq!(plan.includes.len(), 4);
|
||||
assert_eq!(plan.servers.len(), 2);
|
||||
assert_eq!(plan.mtu, Some(1406));
|
||||
assert_eq!(plan.interface, 16);
|
||||
assert_eq!(plan.gateway.to_string(), "198.51.100.1");
|
||||
}
|
||||
#[test]
|
||||
fn split_routes_and_dns_preserve_gateway_configuration() {
|
||||
let plan = Configuration::parse(&environment(&[
|
||||
("CISCO_SPLIT_INC", "1"),
|
||||
("CISCO_SPLIT_INC_0_ADDR", "172.16.5.9"),
|
||||
("CISCO_SPLIT_INC_0_MASKLEN", "16"),
|
||||
("CISCO_SPLIT_EXC", "1"),
|
||||
("CISCO_SPLIT_EXC_0_ADDR", "172.16.10.0"),
|
||||
("CISCO_SPLIT_EXC_0_MASKLEN", "24"),
|
||||
("CISCO_DEF_DOMAIN", "corp.example"),
|
||||
("CISCO_SPLIT_DNS", "corp.example, internal.example"),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.includes.iter().map(ToString::to_string).collect::<Vec<_>>(),
|
||||
["172.16.0.0/16"]
|
||||
);
|
||||
assert_eq!(plan.excludes[0].to_string(), "172.16.10.0/24");
|
||||
assert_eq!(plan.domains, ["corp.example"]);
|
||||
assert_eq!(plan.split_dns, ["corp.example", "internal.example"]);
|
||||
}
|
||||
#[test]
|
||||
fn unassigned_address_family_does_not_install_routes_or_resolvers() {
|
||||
let plan = Configuration::parse(&environment(&[
|
||||
("CISCO_IPV6_SPLIT_INC", "1"),
|
||||
("CISCO_IPV6_SPLIT_INC_0_ADDR", "fd00::"),
|
||||
("CISCO_IPV6_SPLIT_INC_0_MASKLEN", "64"),
|
||||
("INTERNAL_IP4_DNS", "10.20.30.1 fd00::1"),
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(plan.includes.iter().all(|route| route.addr().is_ipv4()));
|
||||
assert_eq!(
|
||||
plan.servers.iter().map(ToString::to_string).collect::<Vec<_>>(),
|
||||
["10.20.30.1"]
|
||||
);
|
||||
assert!(Configuration::parse(&environment(&[("INTERNAL_IP4_DNS", "fd00::1")])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_network_data_is_rejected_before_changes() {
|
||||
for extra in [
|
||||
vec![("TUNIDX", "0")],
|
||||
vec![("INTERNAL_IP4_NETMASKLEN", "99")],
|
||||
vec![("INTERNAL_IP4_DNS", "not-an-address")],
|
||||
vec![("CISCO_SPLIT_INC", "1")],
|
||||
] {
|
||||
assert!(Configuration::parse(&environment(&extra)).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
||||
switch ($request.operation) {
|
||||
'add' {
|
||||
Add-DnsClientNrptRule -Namespace ([string[]]$request.namespaces) -NameServers ([string[]]$request.servers) -Comment $request.tag | Out-Null
|
||||
}
|
||||
'remove' {
|
||||
Get-DnsClientNrptRule | Where-Object { $_.Comment -eq $request.tag } | ForEach-Object {
|
||||
Remove-DnsClientNrptRule -Name $_.Name -Force
|
||||
}
|
||||
}
|
||||
'clear-stale' {
|
||||
Get-DnsClientNrptRule | Where-Object { $_.Comment -like 'GPConnect:*' } | ForEach-Object {
|
||||
Remove-DnsClientNrptRule -Name $_.Name -Force
|
||||
}
|
||||
}
|
||||
default { throw 'Invalid DNS policy operation' }
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Adapter DNS settings and Windows name-resolution policy scoped to this connection.
|
||||
use super::configuration::Configuration;
|
||||
use base64::Engine;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
io::{self, Write},
|
||||
os::windows::process::CommandExt,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
use windows_sys::{
|
||||
Win32::{
|
||||
NetworkManagement::{IpHelper::*, Ndis::NET_LUID_LH},
|
||||
System::Threading::CREATE_NO_WINDOW,
|
||||
},
|
||||
core::GUID,
|
||||
};
|
||||
|
||||
struct Snapshot {
|
||||
domain: String,
|
||||
search: String,
|
||||
}
|
||||
pub(super) struct Installed {
|
||||
guid: GUID,
|
||||
snapshot: Option<Snapshot>,
|
||||
tag: Option<String>,
|
||||
}
|
||||
fn check(status: u32) -> io::Result<()> {
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::from_raw_os_error(status as i32))
|
||||
}
|
||||
}
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
unsafe fn string(pointer: *const u16) -> String {
|
||||
if pointer.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
unsafe {
|
||||
let mut length = 0;
|
||||
while *pointer.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
|
||||
}
|
||||
}
|
||||
impl Snapshot {
|
||||
fn capture(guid: GUID) -> io::Result<Self> {
|
||||
let mut settings = DNS_INTERFACE_SETTINGS {
|
||||
Version: DNS_INTERFACE_SETTINGS_VERSION1,
|
||||
..Default::default()
|
||||
};
|
||||
check(unsafe { GetInterfaceDnsSettings(guid, &mut settings) })?;
|
||||
let snapshot = unsafe {
|
||||
Self {
|
||||
domain: string(settings.Domain),
|
||||
search: string(settings.SearchList),
|
||||
}
|
||||
};
|
||||
unsafe {
|
||||
FreeInterfaceDnsSettings(&mut settings);
|
||||
}
|
||||
Ok(snapshot)
|
||||
}
|
||||
fn write(&self, guid: GUID) -> io::Result<()> {
|
||||
let (mut domain, mut search) = (wide(&self.domain), wide(&self.search));
|
||||
let settings = DNS_INTERFACE_SETTINGS {
|
||||
Version: DNS_INTERFACE_SETTINGS_VERSION1,
|
||||
Flags: (DNS_SETTING_DOMAIN | DNS_SETTING_SEARCHLIST) as u64,
|
||||
Domain: domain.as_mut_ptr(),
|
||||
SearchList: search.as_mut_ptr(),
|
||||
..Default::default()
|
||||
};
|
||||
check(unsafe { SetInterfaceDnsSettings(guid, &settings) })
|
||||
}
|
||||
}
|
||||
impl Installed {
|
||||
pub fn apply(configuration: &Configuration) -> io::Result<Self> {
|
||||
let mut luid = NET_LUID_LH::default();
|
||||
let mut guid = GUID::default();
|
||||
check(unsafe { ConvertInterfaceIndexToLuid(configuration.interface, &mut luid) })?;
|
||||
check(unsafe { ConvertInterfaceLuidToGuid(&luid, &mut guid) })?;
|
||||
let mut installed = Self {
|
||||
guid,
|
||||
snapshot: Some(Snapshot::capture(guid)?),
|
||||
tag: None,
|
||||
};
|
||||
Snapshot {
|
||||
domain: configuration.domains.first().cloned().unwrap_or_default(),
|
||||
search: configuration.domains.join(","),
|
||||
}
|
||||
.write(guid)?;
|
||||
// NRPT selects both IPv4 and IPv6 VPN resolvers. Split namespaces leave
|
||||
// unrelated DNS on the physical network; "." covers full-tunnel DNS.
|
||||
// Existing static/DHCP adapter nameserver configuration stays untouched.
|
||||
if !configuration.servers.is_empty() {
|
||||
let namespaces: Vec<String> = if configuration.split_dns.is_empty() {
|
||||
vec![".".into()]
|
||||
} else {
|
||||
configuration
|
||||
.split_dns
|
||||
.iter()
|
||||
.map(|domain| format!(".{}", domain.trim_matches('.')))
|
||||
.collect()
|
||||
};
|
||||
let tag = format!("GPConnect:{}", uuid::Uuid::new_v4());
|
||||
installed.tag = Some(tag.clone());
|
||||
policy(
|
||||
json!({"operation":"add", "tag":tag, "namespaces":namespaces, "servers":configuration.servers.iter().map(ToString::to_string).collect::<Vec<_>>()}),
|
||||
)?;
|
||||
}
|
||||
Ok(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})) {
|
||||
log::warn!("Could not remove VPN DNS policy: {error}");
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
if let Some(snapshot) = self.snapshot.take() {
|
||||
if let Err(error) = snapshot.write(self.guid) {
|
||||
log::warn!("Could not restore VPN adapter DNS: {error}");
|
||||
if failure.is_none() {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
}
|
||||
impl Drop for Installed {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.restore();
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"}))
|
||||
}
|
||||
fn policy(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");
|
||||
let mut child = Command::new(executable)
|
||||
.args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let input = child
|
||||
.stdin
|
||||
.take()
|
||||
.expect("stdin is piped")
|
||||
.write_all(request.to_string().as_bytes());
|
||||
if let Err(error) = input {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(error);
|
||||
}
|
||||
let output = child.wait_with_output()?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Windows DNS policy failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
//! Native IP Helper changes with ownership of only the rows this connection creates.
|
||||
use super::{
|
||||
configuration::Configuration,
|
||||
recovery::{Journal, Route},
|
||||
};
|
||||
use ipnet::IpNet;
|
||||
use std::{
|
||||
io,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr},
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_NOT_FOUND, ERROR_OBJECT_ALREADY_EXISTS},
|
||||
NetworkManagement::IpHelper::*,
|
||||
Networking::WinSock::*,
|
||||
};
|
||||
|
||||
struct InstalledRoute {
|
||||
row: MIB_IPFORWARD_ROW2,
|
||||
record: Option<String>,
|
||||
}
|
||||
pub(super) struct Installed {
|
||||
routes: Vec<InstalledRoute>,
|
||||
journal: Journal,
|
||||
addresses: Vec<MIB_UNICASTIPADDRESS_ROW>,
|
||||
interfaces: Vec<MIB_IPINTERFACE_ROW>,
|
||||
}
|
||||
fn check(status: u32) -> io::Result<()> {
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::from_raw_os_error(status as i32))
|
||||
}
|
||||
}
|
||||
fn socket_address(address: IpAddr) -> SOCKADDR_INET {
|
||||
let mut result = SOCKADDR_INET::default();
|
||||
match address {
|
||||
IpAddr::V4(address) => {
|
||||
result.Ipv4.sin_family = AF_INET;
|
||||
result.Ipv4.sin_addr.S_un.S_addr = u32::from_ne_bytes(address.octets());
|
||||
}
|
||||
IpAddr::V6(address) => {
|
||||
result.Ipv6.sin6_family = AF_INET6;
|
||||
result.Ipv6.sin6_addr.u.Byte = address.octets();
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
fn empty_address(ipv4: bool) -> SOCKADDR_INET {
|
||||
socket_address(if ipv4 {
|
||||
Ipv4Addr::UNSPECIFIED.into()
|
||||
} else {
|
||||
Ipv6Addr::UNSPECIFIED.into()
|
||||
})
|
||||
}
|
||||
fn route(prefix: IpNet, interface: u32) -> MIB_IPFORWARD_ROW2 {
|
||||
let mut storage = std::mem::MaybeUninit::<MIB_IPFORWARD_ROW2>::zeroed();
|
||||
// IP Helper initializes BOOLEAN fields to 0xff. They must contain canonical
|
||||
// Rust bool values before this storage can become an initialized Rust row.
|
||||
let mut row = unsafe {
|
||||
let pointer = storage.as_mut_ptr();
|
||||
InitializeIpForwardEntry(pointer);
|
||||
std::ptr::addr_of_mut!((*pointer).Loopback).write(false);
|
||||
std::ptr::addr_of_mut!((*pointer).AutoconfigureAddress).write(false);
|
||||
std::ptr::addr_of_mut!((*pointer).Publish).write(false);
|
||||
std::ptr::addr_of_mut!((*pointer).Immortal).write(true);
|
||||
storage.assume_init()
|
||||
};
|
||||
row.InterfaceIndex = interface;
|
||||
row.DestinationPrefix.Prefix = socket_address(prefix.network());
|
||||
row.DestinationPrefix.PrefixLength = prefix.prefix_len();
|
||||
row.NextHop = empty_address(prefix.addr().is_ipv4());
|
||||
row.SitePrefixLength = 0;
|
||||
row.Metric = 0;
|
||||
row.Protocol = MIB_IPPROTO_NETMGMT;
|
||||
row
|
||||
}
|
||||
fn physical_route(prefix: IpNet, tunnel: u32) -> io::Result<MIB_IPFORWARD_ROW2> {
|
||||
let destination = socket_address(prefix.addr());
|
||||
let mut existing = MIB_IPFORWARD_ROW2::default();
|
||||
let mut source = SOCKADDR_INET::default();
|
||||
check(unsafe { GetBestRoute2(ptr::null(), 0, ptr::null(), &destination, 0, &mut existing, &mut source) })?;
|
||||
if existing.InterfaceIndex == tunnel {
|
||||
return Err(io::Error::other(
|
||||
"The VPN gateway or exclusion resolves through the VPN adapter",
|
||||
));
|
||||
}
|
||||
let mut row = route(prefix, existing.InterfaceIndex);
|
||||
row.InterfaceLuid = existing.InterfaceLuid;
|
||||
row.NextHop = existing.NextHop;
|
||||
row.Metric = existing.Metric;
|
||||
Ok(row)
|
||||
}
|
||||
impl Installed {
|
||||
pub fn apply(configuration: &Configuration, recovery_key: &str) -> io::Result<Self> {
|
||||
// Resolve all physical paths before introducing any tunnel routes.
|
||||
let gateway = IpNet::new(
|
||||
configuration.gateway,
|
||||
if configuration.gateway.is_ipv4() { 32 } else { 128 },
|
||||
)
|
||||
.map_err(io::Error::other)?;
|
||||
let physical = std::iter::once(gateway)
|
||||
.chain(configuration.excludes.iter().copied())
|
||||
.map(|prefix| physical_route(prefix, configuration.interface))
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let mut installed = Self {
|
||||
routes: Vec::new(),
|
||||
addresses: Vec::new(),
|
||||
interfaces: Vec::new(),
|
||||
journal: Journal::begin(recovery_key)?,
|
||||
};
|
||||
for row in physical {
|
||||
installed.add_route(row, true)?;
|
||||
}
|
||||
for family in [AF_INET, AF_INET6] {
|
||||
if !configuration
|
||||
.addresses
|
||||
.iter()
|
||||
.any(|address| address.addr().is_ipv4() == (family == AF_INET))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut row = MIB_IPINTERFACE_ROW {
|
||||
Family: family,
|
||||
InterfaceIndex: configuration.interface,
|
||||
..Default::default()
|
||||
};
|
||||
check(unsafe { GetIpInterfaceEntry(&mut row) })?;
|
||||
installed.interfaces.push(row);
|
||||
row.UseAutomaticMetric = false;
|
||||
row.Metric = 1;
|
||||
row.DadTransmits = 0;
|
||||
row.RouterDiscoveryBehavior = RouterDiscoveryDisabled;
|
||||
if let Some(mtu) = configuration.mtu {
|
||||
row.NlMtu = mtu;
|
||||
}
|
||||
if family == AF_INET {
|
||||
row.SitePrefixLength = 0;
|
||||
}
|
||||
check(unsafe { SetIpInterfaceEntry(&mut row) })?;
|
||||
}
|
||||
for address in &configuration.addresses {
|
||||
let mut row = MIB_UNICASTIPADDRESS_ROW::default();
|
||||
unsafe {
|
||||
InitializeUnicastIpAddressEntry(&mut row);
|
||||
}
|
||||
row.InterfaceIndex = configuration.interface;
|
||||
row.Address = socket_address(address.addr());
|
||||
row.OnLinkPrefixLength = address.prefix_len();
|
||||
row.PrefixOrigin = IpPrefixOriginManual;
|
||||
row.SuffixOrigin = IpSuffixOriginManual;
|
||||
row.DadState = IpDadStatePreferred;
|
||||
let status = unsafe { CreateUnicastIpAddressEntry(&row) };
|
||||
if status != ERROR_OBJECT_ALREADY_EXISTS {
|
||||
check(status)?;
|
||||
installed.addresses.push(row);
|
||||
}
|
||||
}
|
||||
for prefix in &configuration.includes {
|
||||
installed.add_route(route(*prefix, configuration.interface), false)?;
|
||||
}
|
||||
for server in &configuration.servers {
|
||||
if *server == configuration.gateway {
|
||||
continue;
|
||||
}
|
||||
let prefix = IpNet::new(*server, if server.is_ipv4() { 32 } else { 128 }).map_err(io::Error::other)?;
|
||||
installed.add_route(route(prefix, configuration.interface), false)?;
|
||||
}
|
||||
Ok(installed)
|
||||
}
|
||||
fn add_route(&mut self, row: MIB_IPFORWARD_ROW2, physical: bool) -> io::Result<()> {
|
||||
let status = unsafe { CreateIpForwardEntry2(&row) };
|
||||
if status != ERROR_OBJECT_ALREADY_EXISTS {
|
||||
check(status)?;
|
||||
// Retain rollback ownership even if writing the registry record fails.
|
||||
self.routes.push(InstalledRoute { row, record: None });
|
||||
if physical {
|
||||
let name = self.journal.record(&Route::from_row(&row)?)?;
|
||||
self.routes.last_mut().expect("route was just installed").record = Some(name);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn restore(&mut self) -> io::Result<()> {
|
||||
let mut failure = None;
|
||||
for route in self.routes.drain(..).rev() {
|
||||
match remove_owned_route(&route.row) {
|
||||
Ok(()) => {
|
||||
if let Some(name) = route.record {
|
||||
if let Err(error) = self.journal.forget(&name) {
|
||||
log::warn!("Could not clear Windows route ownership: {error}");
|
||||
if failure.is_none() {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("Could not remove owned Windows route: {error}");
|
||||
if failure.is_none() {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut record = |status| {
|
||||
if status != ERROR_NOT_FOUND && status != 0 {
|
||||
let error = io::Error::from_raw_os_error(status as i32);
|
||||
log::warn!("Could not restore VPN network configuration: {error}");
|
||||
if failure.is_none() {
|
||||
failure = Some(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
for row in self.addresses.drain(..).rev() {
|
||||
record(unsafe { DeleteUnicastIpAddressEntry(&row) });
|
||||
}
|
||||
for original in self.interfaces.drain(..).rev() {
|
||||
let mut current = MIB_IPINTERFACE_ROW {
|
||||
Family: original.Family,
|
||||
InterfaceIndex: original.InterfaceIndex,
|
||||
..Default::default()
|
||||
};
|
||||
let status = unsafe { GetIpInterfaceEntry(&mut current) };
|
||||
if status != 0 {
|
||||
record(status);
|
||||
continue;
|
||||
}
|
||||
current.UseAutomaticMetric = original.UseAutomaticMetric;
|
||||
current.Metric = original.Metric;
|
||||
current.NlMtu = original.NlMtu;
|
||||
current.DadTransmits = original.DadTransmits;
|
||||
current.RouterDiscoveryBehavior = original.RouterDiscoveryBehavior;
|
||||
if current.Family == AF_INET {
|
||||
current.SitePrefixLength = 0;
|
||||
}
|
||||
record(unsafe { SetIpInterfaceEntry(&mut current) });
|
||||
}
|
||||
failure.map_or(Ok(()), Err)
|
||||
}
|
||||
}
|
||||
impl Drop for Installed {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.restore();
|
||||
}
|
||||
}
|
||||
|
||||
fn address(value: &SOCKADDR_INET) -> io::Result<IpAddr> {
|
||||
unsafe {
|
||||
match value.si_family {
|
||||
AF_INET => Ok(Ipv4Addr::from(value.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
|
||||
AF_INET6 => Ok(Ipv6Addr::from(value.Ipv6.sin6_addr.u.Byte).into()),
|
||||
_ => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Invalid route address family",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn scope(value: &SOCKADDR_INET) -> u32 {
|
||||
unsafe {
|
||||
if value.si_family == AF_INET6 {
|
||||
value.Ipv6.Anonymous.sin6_scope_id
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Route {
|
||||
fn from_row(row: &MIB_IPFORWARD_ROW2) -> io::Result<Self> {
|
||||
Ok(Self {
|
||||
prefix: IpNet::new(
|
||||
address(&row.DestinationPrefix.Prefix)?,
|
||||
row.DestinationPrefix.PrefixLength,
|
||||
)
|
||||
.map_err(io::Error::other)?,
|
||||
next_hop: address(&row.NextHop)?,
|
||||
interface_luid: unsafe { row.InterfaceLuid.Value },
|
||||
metric: row.Metric,
|
||||
prefix_scope: scope(&row.DestinationPrefix.Prefix),
|
||||
next_hop_scope: scope(&row.NextHop),
|
||||
})
|
||||
}
|
||||
fn row(&self) -> io::Result<MIB_IPFORWARD_ROW2> {
|
||||
if self.interface_luid == 0 || self.prefix.addr().is_ipv4() != self.next_hop.is_ipv4() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Invalid saved Windows route",
|
||||
));
|
||||
}
|
||||
let mut row = route(self.prefix, 0);
|
||||
row.InterfaceLuid.Value = self.interface_luid;
|
||||
row.Metric = self.metric;
|
||||
row.NextHop = socket_address(self.next_hop);
|
||||
if self.prefix.addr().is_ipv6() {
|
||||
row.DestinationPrefix.Prefix.Ipv6.Anonymous.sin6_scope_id = self.prefix_scope;
|
||||
row.NextHop.Ipv6.Anonymous.sin6_scope_id = self.next_hop_scope;
|
||||
}
|
||||
Ok(row)
|
||||
}
|
||||
}
|
||||
fn remove_owned_route(row: &MIB_IPFORWARD_ROW2) -> io::Result<()> {
|
||||
let mut current = *row;
|
||||
let status = unsafe { GetIpForwardEntry2(&mut current) };
|
||||
if status == ERROR_NOT_FOUND {
|
||||
return Ok(());
|
||||
}
|
||||
check(status)?;
|
||||
if current.Protocol != row.Protocol || current.Metric != row.Metric {
|
||||
log::warn!("Preserving a Windows route changed after VPN installation");
|
||||
return Ok(());
|
||||
}
|
||||
check(unsafe { DeleteIpForwardEntry2(¤t) })
|
||||
}
|
||||
pub(super) fn recover_route(saved: &Route) -> io::Result<()> {
|
||||
remove_owned_route(&saved.row()?)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Windows network installation driven by OpenConnect's normal configuration callback.
|
||||
mod configuration;
|
||||
mod dns;
|
||||
mod ip_helper;
|
||||
mod recovery;
|
||||
use configuration::Configuration;
|
||||
use std::io;
|
||||
|
||||
pub struct NetworkConfigurator {
|
||||
connection: Option<Connection>,
|
||||
recovery_key: String,
|
||||
}
|
||||
struct Connection {
|
||||
dns: dns::Installed,
|
||||
network: ip_helper::Installed,
|
||||
}
|
||||
impl NetworkConfigurator {
|
||||
/// The owner supplies an HKLM key under its administrator-controlled namespace.
|
||||
pub fn new(recovery_key: &str) -> io::Result<Self> {
|
||||
recovery::Journal::begin(recovery_key)?;
|
||||
Ok(Self {
|
||||
connection: None,
|
||||
recovery_key: recovery_key.into(),
|
||||
})
|
||||
}
|
||||
pub fn configure(&mut self, reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
|
||||
match reason {
|
||||
"pre-init" | "attempt-reconnect" => Ok(()),
|
||||
"connect" | "reconnect" => {
|
||||
let configuration = Configuration::parse(environment)?;
|
||||
self.disconnect()?;
|
||||
let network = ip_helper::Installed::apply(&configuration, &self.recovery_key)?;
|
||||
let dns = dns::Installed::apply(&configuration)?;
|
||||
self.connection = Some(Connection { dns, network });
|
||||
Ok(())
|
||||
}
|
||||
"disconnect" => self.disconnect(),
|
||||
_ => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Unknown VPN configuration reason: {reason}"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
fn disconnect(&mut self) -> io::Result<()> {
|
||||
if let Some(mut connection) = self.connection.take() {
|
||||
let dns = connection.dns.restore();
|
||||
let network = connection.network.restore();
|
||||
dns.and(network)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore process-owned physical routes and DNS policy before service admission.
|
||||
pub fn recover(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()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Ownership records for physical routes, retained across process termination.
|
||||
use ipnet::IpNet;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{io, net::IpAddr};
|
||||
use winreg::{RegKey, enums::*};
|
||||
|
||||
const PREFIX: &str = "Route-";
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct Route {
|
||||
pub prefix: IpNet,
|
||||
pub next_hop: IpAddr,
|
||||
pub interface_luid: u64,
|
||||
pub metric: u32,
|
||||
pub prefix_scope: u32,
|
||||
pub next_hop_scope: u32,
|
||||
}
|
||||
pub(super) struct Journal(RegKey);
|
||||
impl Journal {
|
||||
pub fn begin(path: &str) -> io::Result<Self> {
|
||||
let (parent, name) = path
|
||||
.rsplit_once('\\')
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Recovery key must have a registry parent"))?;
|
||||
let (parent, _) = RegKey::predef(HKEY_LOCAL_MACHINE).create_subkey(parent)?;
|
||||
// ActiveStore routes and this volatile key share the kernel's lifetime.
|
||||
// HKLM parent permissions restrict writes to SYSTEM and administrators.
|
||||
let (key, _) = parent.create_subkey_with_options_flags(name, REG_OPTION_VOLATILE, KEY_READ | KEY_WRITE)?;
|
||||
let journal = Self(key);
|
||||
if !journal.routes()?.is_empty() {
|
||||
return Err(io::Error::other(
|
||||
"Recover the previous Windows network state before connecting",
|
||||
));
|
||||
}
|
||||
Ok(journal)
|
||||
}
|
||||
pub fn open(path: &str) -> io::Result<Option<Self>> {
|
||||
match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(path, KEY_READ | KEY_WRITE) {
|
||||
Ok(key) => Ok(Some(Self(key))),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
pub fn routes(&self) -> io::Result<Vec<(String, Route)>> {
|
||||
self
|
||||
.0
|
||||
.enum_values()
|
||||
.filter_map(|value| match value {
|
||||
Ok((name, _)) if name.starts_with(PREFIX) => Some((|| {
|
||||
let text: String = self.0.get_value(&name)?;
|
||||
let route = serde_json::from_str(&text).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
|
||||
Ok((name, route))
|
||||
})()),
|
||||
Ok(_) => None,
|
||||
Err(error) => Some(Err(error)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn record(&self, route: &Route) -> io::Result<String> {
|
||||
let name = format!("{PREFIX}{}", uuid::Uuid::new_v4());
|
||||
self
|
||||
.0
|
||||
.set_value(&name, &serde_json::to_string(route).map_err(io::Error::other)?)?;
|
||||
Ok(name)
|
||||
}
|
||||
pub fn forget(&self, name: &str) -> io::Result<()> {
|
||||
match self.0.delete_value(name) {
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
#![cfg(windows)]
|
||||
//! Run as administrator with GP_TEST_WINTUN_DLL pointing to the signed Wintun DLL.
|
||||
use std::{ffi::c_void, io, net::IpAddr, os::windows::ffi::OsStrExt, path::PathBuf, ptr};
|
||||
use windows_sys::{
|
||||
Win32::{
|
||||
Foundation::{FreeLibrary, HMODULE},
|
||||
NetworkManagement::Ndis::NET_LUID_LH,
|
||||
System::LibraryLoader::*,
|
||||
},
|
||||
core::GUID,
|
||||
};
|
||||
type CloseAdapter = unsafe extern "system" fn(*mut c_void);
|
||||
type EndSession = unsafe extern "system" fn(*mut c_void);
|
||||
struct Library(HMODULE);
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
FreeLibrary(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Adapter {
|
||||
handle: *mut c_void,
|
||||
session: *mut c_void,
|
||||
close: CloseAdapter,
|
||||
end: EndSession,
|
||||
index: u32,
|
||||
_library: Library,
|
||||
}
|
||||
impl Adapter {
|
||||
fn create() -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let path =
|
||||
PathBuf::from(std::env::var_os("GP_TEST_WINTUN_DLL").ok_or("GP_TEST_WINTUN_DLL is required")?).canonicalize()?;
|
||||
let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
path.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
let library = Library(module);
|
||||
// Wintun's public C ABI uses WINAPI and pointer-sized opaque handles.
|
||||
let create: unsafe extern "system" fn(*const u16, *const u16, *const GUID) -> *mut c_void = unsafe {
|
||||
std::mem::transmute(
|
||||
GetProcAddress(module, c"WintunCreateAdapter".as_ptr().cast()).ok_or("Missing WintunCreateAdapter")?,
|
||||
)
|
||||
};
|
||||
let close: CloseAdapter = unsafe {
|
||||
std::mem::transmute(
|
||||
GetProcAddress(module, c"WintunCloseAdapter".as_ptr().cast()).ok_or("Missing WintunCloseAdapter")?,
|
||||
)
|
||||
};
|
||||
let luid: unsafe extern "system" fn(*mut c_void, *mut NET_LUID_LH) = unsafe {
|
||||
std::mem::transmute(
|
||||
GetProcAddress(module, c"WintunGetAdapterLUID".as_ptr().cast()).ok_or("Missing WintunGetAdapterLUID")?,
|
||||
)
|
||||
};
|
||||
let start: unsafe extern "system" fn(*mut c_void, u32) -> *mut c_void = unsafe {
|
||||
std::mem::transmute(
|
||||
GetProcAddress(module, c"WintunStartSession".as_ptr().cast()).ok_or("Missing WintunStartSession")?,
|
||||
)
|
||||
};
|
||||
let end: EndSession = unsafe {
|
||||
std::mem::transmute(
|
||||
GetProcAddress(module, c"WintunEndSession".as_ptr().cast()).ok_or("Missing WintunEndSession")?,
|
||||
)
|
||||
};
|
||||
let name: Vec<u16> = format!("GP Connect Test {}", uuid::Uuid::new_v4().simple())
|
||||
.encode_utf16()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
let kind: Vec<u16> = "GP Connect".encode_utf16().chain(Some(0)).collect();
|
||||
let handle = unsafe { create(name.as_ptr(), kind.as_ptr(), ptr::null()) };
|
||||
if handle.is_null() {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
let mut adapter = Self {
|
||||
handle,
|
||||
session: ptr::null_mut(),
|
||||
close,
|
||||
end,
|
||||
index: 0,
|
||||
_library: library,
|
||||
};
|
||||
let mut id = NET_LUID_LH::default();
|
||||
unsafe {
|
||||
luid(handle, &mut id);
|
||||
}
|
||||
check(unsafe { ConvertInterfaceLuidToIndex(&id, &mut adapter.index) });
|
||||
adapter.session = unsafe { start(handle, 0x400000) };
|
||||
if adapter.session.is_null() {
|
||||
return Err(io::Error::last_os_error().into());
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
Ok(adapter)
|
||||
}
|
||||
}
|
||||
impl Drop for Adapter {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if !self.session.is_null() {
|
||||
(self.end)(self.session);
|
||||
}
|
||||
(self.close)(self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use gpvpnc::windows::NetworkConfigurator;
|
||||
use windows_sys::Win32::{NetworkManagement::IpHelper::*, Networking::WinSock::*};
|
||||
fn check(status: u32) {
|
||||
assert_eq!(
|
||||
status,
|
||||
0,
|
||||
"Native IP Helper failed: {}",
|
||||
io::Error::from_raw_os_error(status as i32)
|
||||
);
|
||||
}
|
||||
fn address(value: &SOCKADDR_INET) -> IpAddr {
|
||||
unsafe {
|
||||
match value.si_family {
|
||||
AF_INET => std::net::Ipv4Addr::from(value.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into(),
|
||||
AF_INET6 => std::net::Ipv6Addr::from(value.Ipv6.sin6_addr.u.Byte).into(),
|
||||
_ => panic!("unexpected family"),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn routes(index: Option<u32>) -> Vec<String> {
|
||||
let mut result = Vec::new();
|
||||
unsafe {
|
||||
let mut table = std::ptr::null_mut();
|
||||
check(GetIpForwardTable2(AF_UNSPEC, &mut table));
|
||||
for row in std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize) {
|
||||
if Some(row.InterfaceIndex) != index
|
||||
&& !["198.51.100.1", "203.0.113.128"].contains(&address(&row.DestinationPrefix.Prefix).to_string().as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
result.push(format!(
|
||||
"route {} {}/{} {} {}",
|
||||
row.InterfaceIndex,
|
||||
address(&row.DestinationPrefix.Prefix),
|
||||
row.DestinationPrefix.PrefixLength,
|
||||
address(&row.NextHop),
|
||||
row.Metric
|
||||
));
|
||||
}
|
||||
FreeMibTable(table.cast());
|
||||
}
|
||||
result.sort();
|
||||
result
|
||||
}
|
||||
fn state(index: u32) -> Vec<String> {
|
||||
let mut result = routes(Some(index));
|
||||
unsafe {
|
||||
let mut table = std::ptr::null_mut();
|
||||
check(GetUnicastIpAddressTable(AF_UNSPEC, &mut table));
|
||||
for row in std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize) {
|
||||
if row.InterfaceIndex == index {
|
||||
result.push(format!("address {}/{}", address(&row.Address), row.OnLinkPrefixLength));
|
||||
}
|
||||
}
|
||||
FreeMibTable(table.cast());
|
||||
for family in [AF_INET, AF_INET6] {
|
||||
let mut row = MIB_IPINTERFACE_ROW {
|
||||
Family: family,
|
||||
InterfaceIndex: index,
|
||||
..Default::default()
|
||||
};
|
||||
check(GetIpInterfaceEntry(&mut row));
|
||||
result.push(format!(
|
||||
"interface {} {} {} {} {}",
|
||||
family, row.Metric, row.UseAutomaticMetric, row.NlMtu, row.DadTransmits
|
||||
));
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
let mut luid = NET_LUID_LH::default();
|
||||
let mut guid = GUID::default();
|
||||
check(ConvertInterfaceIndexToLuid(index, &mut luid));
|
||||
check(ConvertInterfaceLuidToGuid(&luid, &mut guid));
|
||||
let mut dns = DNS_INTERFACE_SETTINGS {
|
||||
Version: DNS_INTERFACE_SETTINGS_VERSION1,
|
||||
..Default::default()
|
||||
};
|
||||
check(GetInterfaceDnsSettings(guid, &mut dns));
|
||||
for (name, pointer) in [
|
||||
("dns-domain", dns.Domain),
|
||||
("dns-search", dns.SearchList),
|
||||
("dns-servers", dns.NameServer),
|
||||
] {
|
||||
let mut length = 0;
|
||||
if !pointer.is_null() {
|
||||
while *pointer.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
}
|
||||
let text = if pointer.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
|
||||
};
|
||||
result.push(format!("{name} {text}"));
|
||||
}
|
||||
FreeInterfaceDnsSettings(&mut dns);
|
||||
}
|
||||
result.sort();
|
||||
result
|
||||
}
|
||||
fn best_route(destination: &str) -> MIB_IPFORWARD_ROW2 {
|
||||
let ip: IpAddr = destination.parse().unwrap();
|
||||
let mut destination = SOCKADDR_INET::default();
|
||||
match ip {
|
||||
IpAddr::V4(ip) => {
|
||||
destination.Ipv4.sin_family = AF_INET;
|
||||
destination.Ipv4.sin_addr.S_un.S_addr = u32::from_ne_bytes(ip.octets());
|
||||
}
|
||||
IpAddr::V6(ip) => {
|
||||
destination.Ipv6.sin6_family = AF_INET6;
|
||||
destination.Ipv6.sin6_addr.u.Byte = ip.octets();
|
||||
}
|
||||
}
|
||||
let mut route = MIB_IPFORWARD_ROW2::default();
|
||||
let mut source = SOCKADDR_INET::default();
|
||||
check(unsafe { GetBestRoute2(ptr::null(), 0, ptr::null(), &destination, 0, &mut route, &mut source) });
|
||||
route
|
||||
}
|
||||
|
||||
fn assert_dns_policy(active: bool) {
|
||||
const CHECK: &str = r#"
|
||||
$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' }
|
||||
}
|
||||
"#;
|
||||
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", CHECK])
|
||||
.env("GP_TEST_EXPECTED_DNS_POLICIES", if active { "1" } else { "0" })
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires administrator privileges and GP_TEST_WINTUN_DLL"]
|
||||
fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let adapter = Adapter::create()?;
|
||||
let index = adapter.index;
|
||||
if let Some(recovery_key) = std::env::var_os("GP_TEST_CRASH_KEY") {
|
||||
let recovery_key = recovery_key.to_str().ok_or("Invalid registry key")?;
|
||||
let mut network = NetworkConfigurator::new(recovery_key)?;
|
||||
network.configure("connect", &environment(index))?;
|
||||
std::fs::write(
|
||||
std::env::var_os("GP_TEST_CRASH_READY").ok_or("Missing readiness path")?,
|
||||
index.to_string(),
|
||||
)?;
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}
|
||||
let environment = environment(index);
|
||||
let recovery_key = format!(r"SOFTWARE\GP Connect\Tests\Network{}", uuid::Uuid::new_v4().simple());
|
||||
assert_dns_policy(false);
|
||||
let before = state(index);
|
||||
{
|
||||
let mut network = NetworkConfigurator::new(&recovery_key)?;
|
||||
network.configure("connect", &environment)?;
|
||||
let during = state(index);
|
||||
assert!(during.iter().any(|row| row == "address 192.0.2.2/24"));
|
||||
assert!(during.iter().any(|row| row == "address fd42:1234::2/64"));
|
||||
assert!(
|
||||
during
|
||||
.iter()
|
||||
.any(|row| row.starts_with(&format!("route {index} 203.0.113.0/24 ")))
|
||||
);
|
||||
assert!(
|
||||
during
|
||||
.iter()
|
||||
.any(|row| row.starts_with(&format!("route {index} 2001:db8:1234::/64 ")))
|
||||
);
|
||||
assert_eq!(best_route("203.0.113.1").InterfaceIndex, index);
|
||||
assert_eq!(best_route("2001:db8:1234::1").InterfaceIndex, index);
|
||||
assert_eq!(best_route("198.18.0.53").InterfaceIndex, index);
|
||||
assert_eq!(best_route("fd42:1235::53").InterfaceIndex, index);
|
||||
assert_ne!(best_route("203.0.113.200").InterfaceIndex, index);
|
||||
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);
|
||||
network.configure("disconnect", &[])?;
|
||||
}
|
||||
assert_eq!(before, state(index), "Network state was not restored");
|
||||
assert_dns_policy(false);
|
||||
println!("PASS: disconnect restored addresses, routes and interface settings");
|
||||
{
|
||||
let mut network = NetworkConfigurator::new(&recovery_key)?;
|
||||
network.configure("connect", &environment)?;
|
||||
}
|
||||
assert_eq!(
|
||||
before,
|
||||
state(index),
|
||||
"Dropping the connection did not restore network state"
|
||||
);
|
||||
assert_dns_policy(false);
|
||||
let mut invalid = environment.clone();
|
||||
invalid[0].1 = Some(u32::MAX.to_string());
|
||||
assert!(
|
||||
NetworkConfigurator::new(&recovery_key)?
|
||||
.configure("connect", &invalid)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(before, state(index), "Failed connection left a physical gateway route");
|
||||
println!("PASS: partial setup failure rolled back its physical gateway route");
|
||||
drop(adapter);
|
||||
assert_crash_recovery(&recovery_key)?;
|
||||
winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE).delete_subkey(&recovery_key)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn environment(index: u32) -> Vec<(String, Option<String>)> {
|
||||
let pairs = [
|
||||
("TUNIDX", index.to_string()),
|
||||
("VPNGATEWAY", "198.51.100.1".into()),
|
||||
("INTERNAL_IP4_ADDRESS", "192.0.2.2".into()),
|
||||
("INTERNAL_IP4_NETMASKLEN", "24".into()),
|
||||
("INTERNAL_IP6_ADDRESS", "fd42:1234::2".into()),
|
||||
("INTERNAL_IP6_NETMASK", "fd42:1234::2/64".into()),
|
||||
("INTERNAL_IP4_MTU", "1406".into()),
|
||||
("CISCO_SPLIT_INC", "1".into()),
|
||||
("CISCO_SPLIT_INC_0_ADDR", "203.0.113.0".into()),
|
||||
("CISCO_SPLIT_INC_0_MASKLEN", "24".into()),
|
||||
("CISCO_SPLIT_EXC", "1".into()),
|
||||
("CISCO_SPLIT_EXC_0_ADDR", "203.0.113.128".into()),
|
||||
("CISCO_SPLIT_EXC_0_MASKLEN", "25".into()),
|
||||
("CISCO_IPV6_SPLIT_INC", "1".into()),
|
||||
("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()),
|
||||
];
|
||||
pairs
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.to_string(), Some(value)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct CrashChild {
|
||||
child: std::process::Child,
|
||||
key: String,
|
||||
modified_route: Option<MIB_IPFORWARD_ROW2>,
|
||||
}
|
||||
impl Drop for CrashChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
if let Some(route) = self.modified_route.take() {
|
||||
unsafe {
|
||||
DeleteIpForwardEntry2(&route);
|
||||
}
|
||||
}
|
||||
let _ = gpvpnc::windows::recover(&self.key);
|
||||
}
|
||||
}
|
||||
fn assert_crash_recovery(key: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let before = routes(None);
|
||||
let directory = tempfile::tempdir()?;
|
||||
let ready = directory.path().join("ready");
|
||||
let child = std::process::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--ignored",
|
||||
"--exact",
|
||||
"installs_and_restores_native_network_configuration",
|
||||
])
|
||||
.env("GP_TEST_CRASH_KEY", key)
|
||||
.env("GP_TEST_CRASH_READY", &ready)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()?;
|
||||
let mut child = CrashChild {
|
||||
child,
|
||||
key: key.into(),
|
||||
modified_route: None,
|
||||
};
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
while !ready.exists() {
|
||||
if child.child.try_wait()?.is_some() || std::time::Instant::now() > deadline {
|
||||
return Err("Crash child did not install its network state".into());
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let child_index: u32 = std::fs::read_to_string(&ready)?.parse()?;
|
||||
assert_dns_policy(true);
|
||||
let dirty = routes(None);
|
||||
assert_ne!(before, dirty, "Child did not create physical routes");
|
||||
child.child.kill()?;
|
||||
child.child.wait()?;
|
||||
assert_dns_policy(true);
|
||||
let mut addresses = ptr::null_mut();
|
||||
check(unsafe { GetUnicastIpAddressTable(AF_UNSPEC, &mut addresses) });
|
||||
let child_addresses = unsafe {
|
||||
std::slice::from_raw_parts((*addresses).Table.as_ptr(), (*addresses).NumEntries as usize)
|
||||
.iter()
|
||||
.any(|row| row.InterfaceIndex == child_index)
|
||||
};
|
||||
unsafe {
|
||||
FreeMibTable(addresses.cast());
|
||||
}
|
||||
assert!(!child_addresses, "Terminated process left its Wintun addresses");
|
||||
assert_ne!(
|
||||
before,
|
||||
routes(None),
|
||||
"Physical routes unexpectedly disappeared with the process"
|
||||
);
|
||||
// Model an administrator taking ownership of an exclusion after the crash.
|
||||
let mut modified = best_route("203.0.113.200");
|
||||
assert_eq!(address(&modified.DestinationPrefix.Prefix).to_string(), "203.0.113.128");
|
||||
modified.Metric += 1;
|
||||
check(unsafe { SetIpForwardEntry2(&modified) });
|
||||
child.modified_route = Some(modified);
|
||||
let mut expected = before.clone();
|
||||
expected.push(format!(
|
||||
"route {} {}/{} {} {}",
|
||||
modified.InterfaceIndex,
|
||||
address(&modified.DestinationPrefix.Prefix),
|
||||
modified.DestinationPrefix.PrefixLength,
|
||||
address(&modified.NextHop),
|
||||
modified.Metric
|
||||
));
|
||||
expected.sort();
|
||||
gpvpnc::windows::recover(key)?;
|
||||
assert_eq!(
|
||||
expected,
|
||||
routes(None),
|
||||
"Recovery must remove owned routes and preserve the changed route"
|
||||
);
|
||||
assert_dns_policy(false);
|
||||
drop(NetworkConfigurator::new(key)?);
|
||||
check(unsafe { DeleteIpForwardEntry2(&modified) });
|
||||
child.modified_route = None;
|
||||
assert_eq!(before, routes(None), "Crash recovery did not restore the baseline");
|
||||
println!("PASS: crash recovery removed owned physical routes and DNS policy and preserved an administrator's change");
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user