Compare commits

...
4 changed files with 181 additions and 4 deletions

No files matched your search

@@ -0,0 +1,22 @@
name: Windows adapter DNS check
on:
push:
branches: [ci/windows-adapter-dns-native]
permissions:
contents: read
jobs:
network:
runs-on: windows-11-arm
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- uses: dtolnay/[email protected]
- name: Test native Wintun adapter configuration
shell: pwsh
run: |
$zip = Join-Path $env:RUNNER_TEMP 'wintun.zip'
Invoke-WebRequest 'https://www.wintun.net/builds/wintun-0.14.1.zip' -OutFile $zip
if ((Get-FileHash $zip).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') { throw 'Wintun checksum mismatch' }
Expand-Archive $zip $env:RUNNER_TEMP
$env:GP_TEST_WINTUN_DLL = Join-Path $env:RUNNER_TEMP 'wintun/bin/arm64/wintun.dll'
cargo +1.97.0 test --locked -p gpvpnc --test windows_network -- --ignored --nocapture --test-threads=1
+69 -3
View File
@@ -19,9 +19,49 @@ struct Snapshot {
domain: String,
search: String,
}
struct AdapterServers {
ipv6: bool,
addresses: String,
}
impl AdapterServers {
fn capture(guid: GUID, ipv6: bool) -> io::Result<Self> {
// Save the static override only. Restoring an effective DHCP resolver as a
// static address would leave the adapter in manual mode after disconnect.
let service = if ipv6 { "Tcpip6" } else { "Tcpip" };
let id = uuid::Uuid::from_fields(guid.data1, guid.data2, guid.data3, &guid.data4);
let path = format!(
r"SYSTEM\CurrentControlSet\Services\{service}\Parameters\Interfaces\{}",
id.braced()
);
let addresses = winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE)
.open_subkey(path)
.and_then(|key| key.get_value("NameServer"));
let addresses = match addresses {
Ok(value) => value,
Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
Err(error) => return Err(error),
};
Ok(Self { ipv6, addresses })
}
fn write(&self, guid: GUID) -> io::Result<()> {
let mut servers = wide(&self.addresses);
let family = if self.ipv6 { DNS_SETTING_IPV6 } else { 0 };
let settings = DNS_INTERFACE_SETTINGS {
Version: DNS_INTERFACE_SETTINGS_VERSION1,
Flags: (DNS_SETTING_NAMESERVER | family) as u64,
NameServer: servers.as_mut_ptr(),
..Default::default()
};
check(unsafe { SetInterfaceDnsSettings(guid, &settings) })
}
}
pub(super) struct Installed {
guid: GUID,
snapshot: Option<Snapshot>,
previous_servers: Vec<AdapterServers>,
tag: Option<String>,
tunnel: Option<SystemTunnel>,
}
@@ -86,6 +126,7 @@ impl Installed {
let mut installed = Self {
guid,
snapshot: Some(Snapshot::capture(guid)?),
previous_servers: Vec::new(),
tag: None,
tunnel: tunnel.cloned(),
};
@@ -94,9 +135,28 @@ impl Installed {
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.
// With no split namespaces the VPN resolvers also belong on the adapter.
// Windows may accept the local NRPT rule without making it effective.
if configuration.split_dns.is_empty() {
for ipv6 in [false, true] {
let servers: Vec<_> = configuration
.servers
.iter()
.filter(|ip| ip.is_ipv6() == ipv6)
.map(ToString::to_string)
.collect();
if servers.is_empty() {
continue;
}
let previous = AdapterServers::capture(guid, ipv6)?;
AdapterServers {
ipv6,
addresses: servers.join(","),
}
.write(guid)?;
installed.previous_servers.push(previous);
}
}
if !configuration.servers.is_empty() {
let namespaces: Vec<String> = if configuration.split_dns.is_empty() {
vec![".".into()]
@@ -127,6 +187,12 @@ impl Installed {
failure = Some(error);
}
}
for previous in self.previous_servers.drain(..) {
if let Err(error) = previous.write(self.guid) {
log::warn!("Could not restore VPN adapter DNS servers: {error}");
failure.get_or_insert(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}");
+89
View File
@@ -275,6 +275,94 @@ fn global_search_list() -> Vec<u8> {
output.stdout
}
/// Check what DNS clients see for this adapter independently of the NRPT rule.
fn adapter_servers(index: u32) -> Vec<String> {
let command = format!("(Get-DnsClientServerAddress -InterfaceIndex {index} -ErrorAction Stop).ServerAddresses");
let output = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", &command])
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout)
.unwrap()
.lines()
.map(str::to_owned)
.collect()
}
#[test]
#[ignore = "requires an isolated Windows test host and signed Wintun"]
fn lookup_without_an_nrpt_rule() -> Result<(), Box<dyn std::error::Error>> {
use std::net::UdpSocket;
let adapter = Adapter::create()?;
let index = adapter.index;
let run = |script: &str| {
let out = std::process::Command::new("powershell.exe")
.args(["-NoProfile","-NonInteractive","-Command",script]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
};
run(&format!("Set-DnsClientServerAddress -ErrorAction Stop -InterfaceIndex {index} -ServerAddresses ('198.18.0.99','fd42:1235::99')"));
let baseline = adapter_servers(index);
assert!(baseline.iter().any(|s| s == "fd42:1235::99"));
let mut config = environment(index);
config.retain(|(key,_)| key != "CISCO_SPLIT_DNS");
config.iter_mut().find(|(key,_)| key=="INTERNAL_IP4_DNS").unwrap().1 = Some("192.0.2.2 198.18.0.53 fd42:1235::53".into());
let key = format!(r"SOFTWARE\GP Connect\Tests\Network{}", uuid::Uuid::new_v4().simple());
let mut net = NetworkConfigurator::new(&key)?;
net.configure("connect",&config)?;
run(&format!("$ErrorActionPreference='Stop'; Get-DnsClientNrptRule | Where-Object Comment -eq 'GPConnectJournal:{key}' | ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }}; if (Get-DnsClientNrptPolicy -Effective | Where-Object {{ $_.Namespace -contains '.' }}) {{ throw 'Unexpected root rule' }}"));
let socket = UdpSocket::bind("192.0.2.2:53")?;
socket.set_read_timeout(Some(std::time::Duration::from_secs(20)))?;
let server = std::thread::spawn(move || -> io::Result<()> {
let mut buf = [0u8; 2048];
let qname = b"\x0bsupport-dns\x04test\x00\x00\x01\x00\x01";
loop {
let (n,from) = socket.recv_from(&mut buf)?;
if n < 12 + qname.len() || &buf[12..12+qname.len()] != qname { continue; }
let mut answer = buf[..2].to_vec();
answer.extend_from_slice(&[0x81,0x80,0,1,0,1,0,0,0,0]);
answer.extend_from_slice(qname);
answer.extend_from_slice(&[0xc0,0x0c,0,1,0,1,0,0,0,0,0,4,198,51,100,55]);
socket.send_to(&answer,from)?;
return Ok(());
}
});
let result = run("(Resolve-DnsName support-dns.test. -Type A -DnsOnly -NoHostsFile -ErrorAction Stop).IPAddress");
assert_eq!(result.trim(), "198.51.100.55");
server.join().unwrap()?;
net.configure("disconnect",&[])?;
assert_eq!(adapter_servers(index),baseline);
println!("PASS: Windows resolved the fixture hostname through adapter DNS with no effective catch-all rule and restored pre-existing static IPv4 and IPv6 settings");
Ok(())
}
fn check_adapter_resolvers(index: u32, key: &str) -> io::Result<()> {
let split = environment(index);
let mut full = split.clone();
full.retain(|(key, _)| key != "CISCO_SPLIT_DNS");
let initial = adapter_servers(index);
let mut network = NetworkConfigurator::new(key)?;
network.configure("connect", &full)?;
let servers = adapter_servers(index);
assert!(servers.iter().any(|address| address == "198.18.0.53"));
assert!(servers.iter().any(|address| address == "fd42:1235::53"));
network.configure("reconnect", &split)?;
assert_eq!(
adapter_servers(index),
initial,
"split DNS must be scoped to its namespaces"
);
network.configure("reconnect", &full)?;
network.configure("disconnect", &[])?;
assert_eq!(
adapter_servers(index),
initial,
"disconnect must restore the adapter DNS settings"
);
Ok(())
}
#[test]
#[ignore = "requires administrator privileges and GP_TEST_WINTUN_DLL"]
fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn std::error::Error>> {
@@ -355,6 +443,7 @@ fn installs_and_restores_native_network_configuration() -> Result<(), Box<dyn st
);
assert_eq!(before, state(index), "Failed connection left a physical gateway route");
println!("PASS: partial setup failure rolled back its physical gateway route");
check_adapter_resolvers(index, &recovery_key)?;
drop(adapter);
assert_crash_recovery(&recovery_key)?;
assert_eq!(global_search_list(), original_search_list);