feat: build and publish Windows NSH packages with verified updates

This commit is contained in:
Kevin Yue committed 2026-11-18 13:55:52 +08:00
1 parent 754b220a9d
commit b4c1dc1647
105 files changed
+6606 -798

No files matched your search

+5
View File
@@ -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;
+249
View File
@@ -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());
}
}
}
+18
View File
@@ -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' }
}
+178
View File
@@ -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(())
}
+317
View File
@@ -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(&current) })
}
pub(super) fn recover_route(saved: &Route) -> io::Result<()> {
remove_owned_route(&saved.row()?)
}
+64
View File
@@ -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()
}
+70
View File
@@ -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,
}
}
}