Compare commits

..
6 changed files with 69 additions and 120 deletions

No files matched your search

+43
View File
@@ -129,6 +129,49 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
);
}
#[tokio::test]
async fn explicit_user_skips_another_users_cached_gateway_and_portal_credentials() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let directory = tempfile::tempdir().unwrap();
let cache = directory.path().join("cookie.json");
let args = TestArgs::parse_from([
"test",
&origin,
"--user",
"bob",
"--cookie-cache",
cache.to_str().unwrap(),
])
.connect;
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
cookie_store::save(
&cache,
&StoredCookie::new(
args.server.clone(),
"alice".into(),
handler.os_profile.borrow().host_identity().host_id().into(),
origin,
AuthCookieCredential::new("alice", "portal-cookie", ""),
),
)
.unwrap();
assert!(handler.cached_portal_credential(&args.server).is_none());
tokio::select! {
result = handler.try_cached_cookie(&args.server) => assert!(result.is_none()),
_ = listener.accept() => panic!("a mismatched cache entry must be skipped before contacting the gateway"),
}
}
#[tokio::test]
async fn unreachable_gateway_keeps_cached_cookie() {
// Nothing listens here: the cached gateway login gets no answer at all.
+2 -2
View File
@@ -83,7 +83,7 @@ impl ConnectHandler<'_> {
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
let stored = cookie_store::load(&path, server, &host_id, self.args.user.as_deref())?;
if !stored.auth_cookie.can_authenticate_gateway() {
cookie_store::clear(&path);
return None;
@@ -145,7 +145,7 @@ impl ConnectHandler<'_> {
}
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
let stored = cookie_store::load(&path, server, &host_id, self.args.user.as_deref())?;
if !stored.auth_cookie.can_authenticate_gateway() {
cookie_store::clear(&path);
return None;
+20 -6
View File
@@ -59,12 +59,15 @@ pub fn cookie_path(custom: Option<&str>) -> Option<PathBuf> {
}
}
pub fn load(path: &Path, server: &str, host_id: &str) -> Option<StoredCookie> {
pub fn load(path: &Path, server: &str, host_id: &str, requested_user: Option<&str>) -> Option<StoredCookie> {
let bytes = zeroize::Zeroizing::new(platform::decode(fs::read(path).ok()?).ok()?);
let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?;
if stored.version != STORE_VERSION || stored.server != server || stored.host_id != host_id {
return None;
}
if requested_user.is_some_and(|user| user != stored.auth_cookie.username()) {
return None;
}
Some(stored)
}
@@ -116,7 +119,7 @@ mod tests {
.windows(b"prelogon-auth".len())
.any(|part| part == b"prelogon-auth")
);
assert!(load(&path, "vpn.example.com", "host-1").is_some());
assert!(load(&path, "vpn.example.com", "host-1", None).is_some());
}
#[test]
@@ -132,24 +135,35 @@ mod tests {
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
let loaded = load(&path, "vpn.example.com", "host-1").unwrap();
let loaded = load(&path, "vpn.example.com", "host-1", None).unwrap();
assert_eq!(loaded.username, "alice");
assert_eq!(loaded.host_id, "host-1");
assert_eq!(loaded.last_gateway, "gw1.example.com");
assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth");
assert!(
load(&path, "other.example.com", "host-1").is_none(),
load(&path, "other.example.com", "host-1", None).is_none(),
"must reject mismatched server"
);
assert!(
load(&path, "vpn.example.com", "host-2").is_none(),
load(&path, "vpn.example.com", "host-2", None).is_none(),
"must reject mismatched host id"
);
clear(&path);
assert!(!path.exists());
}
#[test]
fn matches_explicit_user_against_cached_credential() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("cookie.json");
let stored = sample();
save(&path, &stored).unwrap();
assert!(load(&path, &stored.server, &stored.host_id, Some("bob")).is_none());
assert!(load(&path, &stored.server, &stored.host_id, Some("alice")).is_some());
}
#[test]
fn rejects_version_mismatch() {
let dir = tempfile::tempdir().unwrap();
@@ -157,6 +171,6 @@ mod tests {
let mut s = sample();
s.version = STORE_VERSION + 1;
save(&path, &s).unwrap();
assert!(load(&path, "vpn.example.com", "host-1").is_none());
assert!(load(&path, "vpn.example.com", "host-1", None).is_none());
}
}
+3 -69
View File
@@ -19,49 +19,9 @@ 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>,
}
@@ -126,7 +86,6 @@ impl Installed {
let mut installed = Self {
guid,
snapshot: Some(Snapshot::capture(guid)?),
previous_servers: Vec::new(),
tag: None,
tunnel: tunnel.cloned(),
};
@@ -135,28 +94,9 @@ impl Installed {
search: configuration.domains.join(","),
}
.write(guid)?;
// 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);
}
}
// 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()]
@@ -187,12 +127,6 @@ 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}");
-42
View File
@@ -275,47 +275,6 @@ 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()
}
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>> {
@@ -396,7 +355,6 @@ 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);