feat: support internal non-tunnel gateway sessions

This commit is contained in:
Kevin Yue committed 2026-10-04 00:32:10 +08:00
1 parent eec18375cd
commit d518177bd1
58 files changed
+7897 -949

No files matched your search

@@ -1,4 +1,7 @@
use std::process::{Command, Stdio};
use std::{
os::unix::process::CommandExt,
process::{Command, Stdio},
};
use anyhow::Context;
use log::{debug, info, warn};
@@ -139,6 +142,7 @@ fn open_with_launcher(url: &str, launcher: &BrowserLauncher) -> anyhow::Result<(
info!("Launching Flatpak browser: {app_id}");
Command::new(executable)
.args(["run", app_id, url])
.process_group(0)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
+34 -1
View File
@@ -81,8 +81,27 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
let current_exe = env::current_exe().ok()?;
let bin_dir = current_exe.parent()?;
let binary = bin_dir.join(binary_name);
if is_file(&binary) {
return Some(binary);
}
#[cfg(target_os = "macos")]
if let Some(binary) = bundled_helper_path(&current_exe, binary_name)
&& is_file(&binary)
{
return Some(binary);
}
None
}
is_file(&binary).then_some(binary)
#[cfg(target_os = "macos")]
fn bundled_helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
let bin_dir = executable.parent()?;
let contents = bin_dir.parent()?;
let bundle = contents.parent()?;
if bin_dir.file_name()? != "MacOS" || contents.file_name()? != "Contents" || bundle.extension()? != "app" {
return None;
}
Some(contents.join("Helpers").join(binary_name))
}
fn is_file(path: &Path) -> bool {
@@ -93,6 +112,20 @@ fn is_file(path: &Path) -> bool {
mod tests {
use super::*;
#[test]
#[cfg(target_os = "macos")]
fn desktop_resolves_helpers_in_the_actual_app_bundle_layout() {
assert_eq!(
bundled_helper_path(
Path::new("/Applications/GP Connect.app/Contents/MacOS/gpgui"),
"gpclient"
),
Some(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers/gpclient"))
);
assert!(bundled_helper_path(Path::new("/usr/local/bin/gpgui"), "gpclient").is_none());
assert!(bundled_helper_path(Path::new("/tmp/Contents/MacOS/gpgui"), "gpclient").is_none());
}
#[test]
fn default_path_is_used_when_no_sibling_exists() {
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
+3 -1
View File
@@ -18,9 +18,10 @@ version-compare = "0.2"
pem.workspace = true
xmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive", "uuid"] }
urlencoding.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
tokio-util.workspace = true
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
@@ -59,6 +60,7 @@ gtk = { version = "0.18", optional = true }
[dev-dependencies]
proptest.workspace = true
tokio = { workspace = true, features = ["test-util"] }
[features]
tauri = ["dep:tauri", "dep:gtk"]
+565 -60
View File
@@ -1,10 +1,15 @@
use std::{borrow::Cow, net::UdpSocket};
use std::{
borrow::Cow,
net::{SocketAddr, UdpSocket},
};
use anyhow::bail;
use log::{debug, info, warn};
use reqwest::Client;
use tokio_util::sync::CancellationToken;
use urlencoding::{decode, encode};
use xmltree::Element;
use zeroize::Zeroizing;
use crate::{
credential::Credential,
@@ -12,68 +17,238 @@ use crate::{
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
session::{
GatewayAuthentication,
network::GatewayBinding,
transport::{bound_client, gateway_origin},
},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
pub enum GatewayLogin {
Cookie(String),
Authenticated(GatewayAuthentication),
Mfa(String, String),
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, false).await
/// Protocol failures cannot be repaired by repeating login with different
/// credentials. Issued credentials, when identifiable, are cleaned up first.
#[derive(Debug, thiserror::Error)]
#[error("Gateway login returned invalid session configuration")]
pub struct GatewayLoginProtocolError;
#[derive(Clone)]
pub struct GatewayLoginClient {
origin: reqwest::Url,
client: Client,
params: GpParams,
binding: Option<GatewayBinding>,
login_endpoint: Option<SocketAddr>,
login_url: Option<reqwest::Url>,
maintenance_client: Option<Client>,
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
impl GatewayLoginClient {
pub fn register_session(
&self,
gateway: crate::gateway::Gateway,
authentication: GatewayAuthentication,
sessions: &mut crate::session::GatewaySessions,
) {
sessions.register(crate::session::GatewaySession {
gateway,
transport: self.authenticated_transport(authentication),
addresses: self
.binding
.as_ref()
.map(|binding| binding.addresses())
.unwrap_or_default(),
});
}
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
let client = Client::try_from(&params)?;
Ok(Self {
origin,
client,
params,
binding: None,
login_endpoint: None,
login_url: None,
maintenance_client: None,
})
}
/// Only called after an authenticated non-tunnel response and registration in
/// the caller's cleanup ledger. Tunnel login never inspects physical routing.
pub async fn bind_non_tunnel(
&mut self,
disable_ipv6: bool,
detection: Option<&crate::session::network::InternalHostDetection>,
cancellation: &tokio_util::sync::CancellationToken,
) -> anyhow::Result<()> {
let origin = gateway_origin(self.origin.as_str())?;
let response_url = self
.login_url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?;
anyhow::ensure!(
response_url.origin() == origin.origin(),
"Redirected non-tunnel authentication is unsupported"
);
let endpoint = self
.login_endpoint
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?;
let binding = network
.bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation)
.await?;
network
.validate_internal_binding(&binding, detection, cancellation)
.await?;
let client = bound_client(origin.as_str(), &self.params, &binding)?;
self.binding = Some(binding);
self.maintenance_client = Some(client);
Ok(())
}
pub fn update_registered_session(
&self,
gateway: &crate::gateway::Gateway,
authentication: &GatewayAuthentication,
sessions: &mut crate::session::GatewaySessions,
) {
sessions.update(crate::session::GatewaySession {
gateway: gateway.clone(),
transport: self.authenticated_transport(authentication.clone()),
addresses: self
.binding
.as_ref()
.map(|binding| binding.addresses())
.unwrap_or_default(),
});
}
pub fn authenticated_transport(
&self,
authentication: GatewayAuthentication,
) -> crate::session::transport::GatewayTransport {
crate::session::transport::GatewayTransport::from_authenticated_login(
self.maintenance_client.as_ref().unwrap_or(&self.client).clone(),
self.origin.clone(),
authentication,
self.params.os_profile().clone(),
)
}
pub fn binding(&self) -> Option<&GatewayBinding> {
self.binding.as_ref()
}
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
self.params.client_identity()
}
pub(crate) fn request_client(&self) -> &Client {
&self.client
}
pub(crate) fn origin(&self) -> &reqwest::Url {
&self.origin
}
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
self.params.set_input_str(input);
self.params.set_otp(otp);
}
pub async fn login(
&mut self,
cred: &Credential,
context: Option<&GatewayLoginContext>,
cancellation: &CancellationToken,
) -> anyhow::Result<GatewayLogin> {
if cancellation.is_cancelled() {
return Err(crate::auth::AuthenticationCancelled.into());
}
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(str::to_owned)
.or_else(|| detect_local_ipv4(context.host()))
});
let request = receive_gateway_login(
&self.origin,
&self.client,
cred,
&self.params,
context,
client_ip.as_deref(),
false,
);
let response = tokio::select! {
biased;
response = request => response?,
_ = cancellation.cancelled() => return Err(crate::auth::AuthenticationCancelled.into()),
};
// Once the full response is available, retain issued authentication or finish
// cleanup-only logout before the caller observes cancellation.
let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?;
self.login_endpoint = response.endpoint;
self.login_url = Some(response.url);
Ok(response.login)
}
pub(crate) async fn extend_lifetime(&self, cred: &Credential) -> anyhow::Result<GatewayLogin> {
let response = receive_gateway_login(&self.origin, &self.client, cred, &self.params, None, None, true).await?;
Ok(
parse_login_response(response, &self.client, &self.origin, &self.params)
.await?
.login,
)
}
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, true).await
struct LoginResponse {
login: GatewayLogin,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
}
async fn gateway_login_with_options(
gateway: &str,
struct ReceivedLogin {
body: String,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
async fn receive_gateway_login(
origin: &reqwest::Url,
client: &Client,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
client_ip: Option<&str>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
) -> anyhow::Result<ReceivedLogin> {
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
let request_params = gateway_login::build(&GatewayLoginInput {
gp_params,
cred,
gateway_host: &gateway,
context,
client_ip: client_ip.as_deref(),
client_ip,
extend_lifetime,
});
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
log_gateway_login_context(context, client_ip, gp_params);
let res = client
.post(&login_url)
.post(login_url)
.form(&request_params.body)
.send()
.await
@@ -82,11 +257,32 @@ async fn gateway_login_with_options(
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let endpoint = res.remote_addr();
let url = res.url().clone();
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason)
})?;
Ok(ReceivedLogin {
body: res,
endpoint,
url,
})
}
async fn parse_login_response(
response: ReceivedLogin,
client: &Client,
origin: &reqwest::Url,
gp_params: &GpParams,
) -> anyhow::Result<LoginResponse> {
let ReceivedLogin {
body: res,
endpoint,
url,
} = response;
// It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res);
@@ -96,27 +292,47 @@ async fn gateway_login_with_options(
// MFA detected
if res.contains("Challenge") {
let Some((message, input_str)) = parse_mfa(&res) else {
bail!("Failed to parse MFA challenge: {res}");
bail!("Failed to parse MFA challenge");
};
return Ok(GatewayLogin::Mfa(message, input_str));
return Ok(LoginResponse {
login: GatewayLogin::Mfa(message, input_str),
endpoint,
url,
});
}
debug!("Gateway login response: {}", res);
let root = Element::parse(res.as_bytes())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie))
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
let lower = res.to_ascii_lowercase();
if lower.contains("<!doctype") || lower.contains("<!entity") {
return Err(GatewayLoginProtocolError.into());
}
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
let (cookie, connection_type) =
parse_issued_authentication(&root, gp_params.computer()).map_err(|_| GatewayLoginProtocolError)?;
let cookie = Zeroizing::new(cookie);
let authentication = connection_type.and_then(|mode| GatewayAuthentication::new(cookie.to_string(), mode));
let authentication = match authentication {
Ok(authentication) => authentication,
Err(_) => {
match tokio::time::timeout(
std::time::Duration::from_secs(5),
crate::session::transport::logout_cookie(client, origin, &cookie, gp_params.os_profile()),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(error)) => warn!("Cleanup-only gateway logout failed: {error}"),
Err(_) => warn!("Cleanup-only gateway logout timed out"),
}
return Err(GatewayLoginProtocolError.into());
}
};
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
Ok(LoginResponse {
login: GatewayLogin::Authenticated(authentication),
endpoint,
url,
})
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
@@ -136,13 +352,33 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
);
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
anyhow::ensure!(
element.attr("status").is_none_or(|status| status == "success"),
"Gateway login response rejected authentication"
);
let application = element
.child("application-desc")
.ok_or_else(|| anyhow::anyhow!("Gateway login response has no application description"))?;
let args = application
.children("argument")
.iter()
.map(|e| e.get_text().unwrap_or_default())
.collect::<Vec<_>>();
let cookie = build_gateway_token(&args, computer)?;
let connection_type = read_arg_value(&args, 12)
.and_then(|mode| mode.ok_or_else(|| anyhow::anyhow!("Gateway login response has no connection type")));
Ok((cookie, connection_type))
}
#[cfg(test)]
fn parse_gateway_authentication(element: &Element, computer: &str) -> anyhow::Result<GatewayAuthentication> {
let (cookie, mode) = parse_issued_authentication(element, computer)?;
GatewayAuthentication::new(cookie, mode?)
}
fn build_gateway_token(args: &[Cow<'_, str>], computer: &str) -> anyhow::Result<String> {
let mut params = vec![
read_required_arg(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?,
@@ -198,11 +434,15 @@ fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
let value = decode(value)?;
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
anyhow::ensure!(
!value.chars().any(char::is_control),
"Gateway argument contains control characters"
);
Ok(Some(value.into_owned()))
}
fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -223,6 +463,268 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
mod tests {
use super::*;
fn tunnel_response() -> String {
let root = login_response(Some("tunnel"), "issued-cookie");
let mut xml = Vec::new();
root.write(&mut xml).unwrap();
crate::session::transport::tests::response(std::str::from_utf8(&xml).unwrap())
}
fn test_params() -> GpParams {
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
}
#[tokio::test]
async fn gateway_login_cancels_stalled_headers_and_body() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
for partial_response in ["", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<jnlp>"] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (ready, received) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = [0; 4096];
assert!(socket.read(&mut buffer).await.unwrap() > 0);
socket.write_all(partial_response.as_bytes()).await.unwrap();
ready.send(()).unwrap();
released.await.unwrap();
});
let cancellation = CancellationToken::new();
let token = cancellation.clone();
let login = tokio::spawn(async move {
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
client.login(&credential, None, &token).await
});
received.await.unwrap();
cancellation.cancel();
let result = tokio::time::timeout(std::time::Duration::from_secs(1), login)
.await
.unwrap()
.unwrap();
assert!(result.err().unwrap().is::<crate::auth::AuthenticationCancelled>());
release.send(()).unwrap();
server.await.unwrap();
}
}
#[tokio::test]
async fn cancellation_during_cleanup_only_logout_awaits_cleanup() {
use crate::session::transport::tests::response;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let mut xml = Vec::new();
login_response(None, "issued-cookie").write(&mut xml).unwrap();
let login_response = response(std::str::from_utf8(&xml).unwrap());
let (ready, received) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = [0; 4096];
assert!(socket.read(&mut buffer).await.unwrap() > 0);
socket.write_all(login_response.as_bytes()).await.unwrap();
drop(socket);
let (mut socket, _) = listener.accept().await.unwrap();
let read = socket.read(&mut buffer).await.unwrap();
assert!(
std::str::from_utf8(&buffer[..read])
.unwrap()
.contains("/ssl-vpn/logout.esp")
);
ready.send(()).unwrap();
released.await.unwrap();
socket
.write_all(response("<response status='success'/>").as_bytes())
.await
.unwrap();
});
let cancellation = CancellationToken::new();
let token = cancellation.clone();
let mut login = tokio::spawn(async move {
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
client.login(&credential, None, &token).await
});
received.await.unwrap();
cancellation.cancel();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), &mut login)
.await
.is_err()
);
release.send(()).unwrap();
assert!(login.await.unwrap().err().unwrap().is::<GatewayLoginProtocolError>());
server.await.unwrap();
}
#[tokio::test]
async fn ordinary_tunnel_login_follows_redirects_without_physical_binding() {
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
tunnel_response(),
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
tunnel_response(),
]).await;
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(
matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel)
);
assert!(client.binding().is_none());
assert!(matches!(
client.extend_lifetime(&credential).await.unwrap(),
GatewayLogin::Authenticated(_)
));
let requests = server.await.unwrap();
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
assert_eq!(requests[1].0, "/redirected-login");
assert_eq!(requests[3].0, "/redirected-login");
assert!(requests[3].1.contains("extend-lifetime=true"));
}
#[tokio::test]
async fn ordinary_login_keeps_reqwest_address_fallback() {
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
let port = origin.port().unwrap();
let params = test_params();
let mut client = GatewayLoginClient::new(&format!("http://gateway.invalid:{port}"), params.clone()).unwrap();
// Supply deterministic DNS candidates; all other client behavior is the
// ordinary request path. The first address refuses, the second is reachable.
client.client = params
.client_builder()
.unwrap()
.no_proxy()
.resolve_to_addrs(
"gateway.invalid",
&[
SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
SocketAddr::from(([127, 0, 0, 1], port)),
],
)
.build()
.unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(matches!(
client
.login(&credential, None, &CancellationToken::new())
.await
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(server.await.unwrap().len(), 1);
}
#[tokio::test]
async fn ordinary_tunnel_login_can_use_a_proxy_without_local_gateway_resolution() {
let (_, proxy, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
let params = test_params();
let mut client = GatewayLoginClient::new("http://unresolvable.invalid", params.clone()).unwrap();
client.client = params
.client_builder()
.unwrap()
.proxy(reqwest::Proxy::all(proxy.as_str()).unwrap())
.build()
.unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(matches!(
client
.login(&credential, None, &CancellationToken::new())
.await
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(
server.await.unwrap()[0].0,
"http://unresolvable.invalid/ssl-vpn/login.esp"
);
}
#[tokio::test]
async fn invalid_mode_logs_out_issued_cookie_before_returning_protocol_error() {
use crate::session::transport::tests::{login_gateway, response};
let root = login_response(None, "issued-cookie");
let mut xml = Vec::new();
root.write(&mut xml).unwrap();
let (client, origin, server) = login_gateway(vec![
response(std::str::from_utf8(&xml).unwrap()),
response("<response status='success'/>"),
])
.await;
let params =
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let mut client = GatewayLoginClient {
client,
..GatewayLoginClient::new(origin.as_str(), params).unwrap()
};
let error = client
.login(&credential, None, &CancellationToken::new())
.await
.err()
.unwrap();
assert!(error.is::<GatewayLoginProtocolError>());
let requests = server.await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[1].1).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("issued-cookie"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
}
#[test]
fn cleanup_only_parsing_does_not_salvage_server_error_authentication() {
let mut root = login_response(None, "issued-cookie");
root.attributes.insert("status".into(), "error".into());
assert!(parse_issued_authentication(&root, "computer").is_err());
for encoded in ["%28null%29", "%2D1", "%00"] {
assert!(parse_issued_authentication(&login_response(Some("tunnel"), encoded), "computer").is_err());
}
}
fn login_response(mode: Option<&str>, cookie: &str) -> Element {
let mut args = vec![""; 19];
args[1] = cookie;
args[4] = "alice";
if let Some(mode) = mode {
args[12] = mode;
}
let arguments = args
.iter()
.map(|value| format!("<argument>{value}</argument>"))
.collect::<String>();
Element::parse(format!("<jnlp><application-desc>{arguments}</application-desc></jnlp>").as_bytes()).unwrap()
}
#[test]
fn login_mode_is_independent_of_network_location() {
for (value, mode) in [
("tunnel", crate::session::SessionMode::Tunnel),
("non-tunnel", crate::session::SessionMode::NonTunnel),
("internal", crate::session::SessionMode::NonTunnel),
] {
let authentication =
parse_gateway_authentication(&login_response(Some(value), "test-cookie"), "computer").unwrap();
assert_eq!(authentication.mode(), mode);
assert_eq!(authentication.connection_type(), value);
assert!(!format!("{authentication:?}").contains("test-cookie"));
}
}
#[test]
fn login_rejects_missing_mode_or_cookie() {
for mode in [None, Some(""), Some("(null)"), Some("-1"), Some(" ")] {
assert!(parse_gateway_authentication(&login_response(mode, "test-cookie"), "computer").is_err());
}
assert!(parse_gateway_authentication(&login_response(Some("tunnel"), ""), "computer").is_err());
let response = Element::parse(b"<response status='error'/>".as_slice()).unwrap();
assert!(parse_gateway_authentication(&response, "computer").is_err());
}
#[test]
fn mfa() {
let res = r#"var respStatus = "Challenge";
@@ -263,7 +765,9 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
let token = authentication.cookie();
assert_eq!(authentication.mode(), crate::session::SessionMode::Tunnel);
assert_eq!(
token,
@@ -300,7 +804,8 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
let token = authentication.cookie();
assert_eq!(
token,
+1 -1
View File
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
pub fn kind(&self) -> GatewayKind {
self.kind
}
+22 -29
View File
@@ -5,15 +5,13 @@ use std::{
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
gateway::login::{GatewayLogin, GatewayLoginClient},
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
utils::{parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
@@ -22,12 +20,18 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
client: GatewayLoginClient,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
Self { credential, client }
}
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
self.client.client_identity()
}
pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> {
self.client.binding()
}
}
@@ -35,7 +39,7 @@ impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.field("client", &"<redacted>")
.finish()
}
}
@@ -83,10 +87,15 @@ impl SessionContext {
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let client = auth.client.request_client();
let url = format!(
"{}/ssl-vpn/agentmessage.esp",
auth.client.origin().as_str().trim_end_matches('/')
);
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
@@ -108,33 +117,17 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
let login = auth.client.extend_lifetime(&auth.credential).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Authenticated(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = Client::builder();
if let Some(user_agent) = args.user_agent() {
builder = builder.user_agent(user_agent);
}
if let Some(cert) = args.certificate() {
info!("Using client certificate authentication...");
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
builder = builder.identity(identity);
}
Ok(builder.build()?)
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
+109 -14
View File
@@ -1,11 +1,12 @@
use log::info;
use reqwest::Client;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use specta::Type;
use zeroize::Zeroize;
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
utils::request::{ClientIdentity, create_identity},
};
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
@@ -43,6 +44,7 @@ pub struct GpParams {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
prepared_identity: Option<ClientIdentity>,
// Feature
csc_mode: CscMode,
// Per-request state
@@ -135,9 +137,49 @@ impl GpParams {
pub(crate) fn otp(&self) -> Option<&str> {
self.otp.as_deref()
}
pub fn prepare_client_identity(&mut self) -> anyhow::Result<()> {
if self.prepared_identity.is_none() {
if let Some(certificate) = self.certificate.as_deref() {
self.prepared_identity = Some(ClientIdentity::load(
certificate,
self.sslkey.as_deref(),
self.key_password.as_deref(),
)?);
}
}
self.certificate = None;
self.sslkey = None;
if let Some(mut passphrase) = self.key_password.take() {
passphrase.zeroize();
}
Ok(())
}
pub fn client_identity(&self) -> Option<&ClientIdentity> {
self.prepared_identity.as_ref()
}
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(self.ignore_tls_errors)
.user_agent(self.user_agent());
if let Some(identity) = &self.prepared_identity {
builder = builder.identity(identity.request_identity());
} else if let Some(cert) = self.certificate.as_deref() {
info!("Using client certificate authentication...");
builder = builder.identity(create_identity(
cert,
self.sslkey.as_deref(),
self.key_password.as_deref(),
)?);
}
Ok(builder)
}
}
pub struct GpParamsBuilder {
prepared_identity: Option<ClientIdentity>,
is_gateway: bool,
os_profile: OsProfile,
csc_mode: CscMode,
@@ -150,6 +192,7 @@ pub struct GpParamsBuilder {
impl GpParamsBuilder {
pub fn new(os_profile: OsProfile) -> Self {
Self {
prepared_identity: None,
is_gateway: false,
os_profile,
csc_mode: Default::default(),
@@ -176,22 +219,34 @@ impl GpParamsBuilder {
}
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
self.prepared_identity = None;
self.certificate = certificate.into();
self
}
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
self.prepared_identity = None;
self.sslkey = sslkey.into();
self
}
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut Self {
self.prepared_identity = None;
self.key_password = password.into();
self
}
pub fn client_identity(&mut self, identity: Option<ClientIdentity>) -> &mut Self {
self.prepared_identity = identity;
self.certificate = None;
self.sslkey = None;
self.key_password = None;
self
}
pub fn build(&self) -> GpParams {
GpParams {
prepared_identity: self.prepared_identity.clone(),
os_profile: self.os_profile.clone(),
ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(),
@@ -209,24 +264,64 @@ impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors)
.user_agent(value.user_agent());
if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication...");
let identity = create_identity(cert, value.sslkey.as_deref(), value.key_password.as_deref())?;
builder = builder.identity(identity);
}
let client = builder.build()?;
Ok(client)
Ok(value.client_builder()?.build()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_identity_settings_replace_a_prepared_snapshot() {
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
let setters: [fn(&mut GpParamsBuilder); 3] = [
|builder| {
builder.certificate(Some("missing-replacement-certificate.pem".into()));
},
|builder| {
builder.sslkey(Some("replacement-key.pem".into()));
},
|builder| {
builder.key_password(Some("replacement-password".into()));
},
];
for setter in setters {
let mut builder = GpParams::builder(profile(ClientOs::Linux));
builder.client_identity(Some(identity.clone()));
setter(&mut builder);
let params = builder.build();
assert!(
params.client_identity().is_none(),
"Path settings must not silently use the previous identity"
);
if params.certificate.is_some() {
assert!(
Client::try_from(&params).is_err(),
"The replacement certificate path must actually be loaded"
);
}
}
}
#[test]
fn prepared_identity_replaces_paths_and_can_be_explicitly_disabled() {
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
let mut builder = GpParams::builder(profile(ClientOs::Linux));
builder
.certificate(Some("missing-certificate.pem".into()))
.sslkey(Some("missing-key.pem".into()))
.key_password(Some("unused-password".into()))
.client_identity(Some(identity));
let params = builder.build();
assert!(params.client_identity().is_some());
assert!(params.certificate.is_none() && params.sslkey.is_none() && params.key_password.is_none());
assert!(Client::try_from(&params).is_ok());
builder.certificate(None);
let params = builder.build();
assert!(params.client_identity().is_none());
assert!(params.certificate.is_none());
}
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
+180 -56
View File
@@ -1,11 +1,11 @@
use std::collections::HashMap;
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
use tokio_util::sync::CancellationToken;
use xmltree::Element;
use crate::{
@@ -14,6 +14,7 @@ use crate::{
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
params,
session::{InternalSessionPolicy, network::InternalHostDetection},
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
@@ -35,6 +36,7 @@ pub struct PortalConfig {
* - Some(true): Internal host detection is supported and the user is connected to the internal network
*/
internal_host_detection: Option<bool>,
internal_detection: Option<InternalHostDetection>,
/**
* The version returned by the portal config, if any
*/
@@ -47,6 +49,7 @@ pub struct PortalConfig {
* Whether the portal policy enables default-browser authentication.
*/
default_browser: Option<bool>,
internal_session_policy: Option<InternalSessionPolicy>,
}
impl PortalConfig {
@@ -70,6 +73,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
self.internal_detection.as_ref()
}
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
@@ -86,6 +93,10 @@ impl PortalConfig {
self.default_browser
}
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
self.internal_session_policy
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -129,7 +140,14 @@ impl PortalConfig {
}
}
pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<PortalConfig> {
/// Cancellation is handled inside the request so a running native detection
/// helper is always cancelled and joined. Do not drop this future on disconnect.
pub async fn retrieve_config(
portal: &str,
cred: &Credential,
gp_params: &GpParams,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let portal = normalize_server(portal)?;
let server = remove_url_scheme(&portal);
@@ -146,29 +164,35 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_form_params(&body_pairs));
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = tokio::select! {
biased;
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = async {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal config error: {}", err.reason);
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})?;
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
} => result?,
};
if res_xml.is_empty() {
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response: {}", res_xml);
debug!("Portal config response received: {} bytes", res_xml.len());
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
@@ -178,14 +202,18 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
"Portal returned CSC criteria but CSC support is disabled".to_string()
));
}
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let csc_xml = tokio::select! {
biased;
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
};
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
return parse_portal_config(&server, cred, root, cancellation).await;
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
parse_portal_config(&server, cred, root, cancellation).await
}
async fn retrieve_csc_config(
@@ -245,12 +273,31 @@ fn present(value: Option<&str>) -> &'static str {
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false;
let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(ihd_node)
async fn parse_portal_config(
server: &str,
cred: &Credential,
root: Element,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let internal_detection = root
.descendant("internal-host-detection")
.map(parse_internal_detection)
.transpose()
.unwrap_or_else(|error| {
warn!("Internal host detection policy is unavailable: {error}");
None
})
.flatten();
let prefer_internal = match &internal_detection {
Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| {
warn!("Internal host detection failed: {error}");
false
}),
None => false,
};
if cancellation.is_cancelled() {
bail!("Portal configuration cancelled");
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -275,6 +322,7 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
let default_browser = parse_default_browser(&root);
let internal_session_policy = parse_internal_session_policy(&root).ok();
Ok(PortalConfig {
portal: server.to_string(),
@@ -283,13 +331,42 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
internal_detection,
version,
allow_extend_session,
default_browser,
internal_session_policy,
})
}
fn parse_internal_session_policy(root: &Element) -> anyhow::Result<InternalSessionPolicy> {
let hip = root.descendant("hip-collection");
let interval = hip
.and_then(|hip| hip.child("hip-report-interval"))
.map(|element| element.get_text().unwrap_or_default().into_owned());
let collect = hip
.and_then(|hip| hip.child("collect-hip-data"))
.map(|element| element.get_text().unwrap_or_default().into_owned());
let interval = parse_policy_number(interval, 3600, "hip-report-interval")?;
let collect = match collect.as_deref().map(str::trim) {
None | Some("yes") => true,
Some("no") => false,
Some(_) => bail!("Invalid portal collect-hip-data policy"),
};
InternalSessionPolicy::new(interval, collect)
}
fn parse_policy_number(value: Option<String>, default: u32, field: &str) -> anyhow::Result<u32> {
match value {
Some(value) => value
.trim()
.parse()
.map_err(|_| anyhow::anyhow!("Invalid portal {field} policy")),
None => Ok(default),
}
}
fn parse_default_browser(root: &Element) -> Option<bool> {
match root.descendant_text("default-browser")?.trim() {
"yes" => Some(true),
@@ -313,49 +390,94 @@ fn parse_connect_method(root: &Element) -> Option<String> {
.map(|s| s.to_string())
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool {
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
let ip_info = [
(element.child_text("ip-address"), element.child_text("host")),
(element.child_text("ipv6-address"), element.child_text("ipv6-host")),
];
info!("Found internal-host-detection, performing DNS lookup");
let mut targets = Vec::new();
for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
&& !ip_address.is_empty()
&& !host.is_empty()
{
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
let address = ip_address.as_deref().filter(|value| !value.is_empty());
let host = host.as_deref().filter(|value| !value.is_empty());
match (address, host) {
(None, None) => {}
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
_ => bail!("Incomplete internal host detection policy"),
}
}
false
if targets.is_empty() {
Ok(None)
} else {
Ok(Some(InternalHostDetection::new(targets)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() {
let root = parse_xml(
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
);
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new())
.await
.unwrap();
assert!(config.internal_session_policy().is_none());
assert_eq!(config.gateways()[0].server(), "vpn.example");
assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External);
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn parses_internal_maintenance_policy_with_explicit_units() {
let root = parse_xml(
"<policy><hip-collection><hip-report-interval>60</hip-report-interval><collect-hip-data>no</collect-hip-data></hip-collection><max-internal-gateway-connection-attempts>3</max-internal-gateway-connection-attempts></policy>",
);
let policy = parse_internal_session_policy(&root).unwrap();
assert_eq!(policy.hip_interval(), std::time::Duration::from_secs(60));
assert!(!policy.collect_hip_data());
assert_eq!(
parse_internal_session_policy(&parse_xml("<policy/>")).unwrap(),
InternalSessionPolicy::default()
);
}
#[test]
fn rejects_invalid_supplied_internal_policy() {
for interval in ["0", "-1", "", "4294967295", "not-a-number"] {
let root = parse_xml(&format!(
"<policy><hip-collection><hip-report-interval>{interval}</hip-report-interval></hip-collection></policy>"
));
assert!(parse_internal_session_policy(&root).is_err());
}
let root = parse_xml("<policy><hip-collection><collect-hip-data>true</collect-hip-data></hip-collection></policy>");
assert!(parse_internal_session_policy(&root).is_err());
}
#[tokio::test]
async fn accepts_existing_full_portal_fixture() {
let root = parse_xml(include_str!("../../tests/files/portal_config.xml"));
let cred = Credential::from(crate::credential::PasswordCredential::new(
"fixture-user",
"fixture-password",
));
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
assert_eq!(
config.internal_session_policy().unwrap().hip_interval(),
std::time::Duration::from_secs(3600)
);
assert!(!config.gateways().is_empty());
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
@@ -412,8 +534,8 @@ mod tests {
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
#[tokio::test]
async fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
@@ -431,7 +553,9 @@ mod tests {
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
+32 -11
View File
@@ -1,20 +1,23 @@
use std::{
net::IpAddr,
path::{Path, PathBuf},
process::Stdio,
};
use anyhow::bail;
use common::binary_paths;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
#[cfg(feature = "webview-auth")]
use crate::auth::AuthWindowTheme;
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
use super::command_traits::CommandExt;
use super::{command_runner::run_controlled, command_traits::CommandExt};
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
pub struct SamlAuthLauncher<'a> {
cancellation: CancellationToken,
server: &'a str,
auth_executable: Option<&'a str>,
gateway: bool,
@@ -46,6 +49,7 @@ pub struct SamlAuthLauncher<'a> {
impl<'a> SamlAuthLauncher<'a> {
pub fn new(server: &'a str) -> Self {
Self {
cancellation: CancellationToken::new(),
server,
auth_executable: None,
gateway: false,
@@ -176,6 +180,11 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
self.cancellation = cancellation.clone();
self
}
/// The command line this launcher will run.
///
/// Split out from `launch` so a test can observe the argv the child actually
@@ -273,18 +282,30 @@ impl<'a> SamlAuthLauncher<'a> {
.unwrap_or_else(binary_paths::gpauth);
let auth_cmd = self.build_command(&program);
let mut non_root_cmd = auth_cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
let child = match child {
Ok(child) => child,
Err(err) => {
bail!("Failed to spawn {}: {}", program.display(), err);
let command = auth_cmd.into_non_root()?.into_std();
let cancellation = self.cancellation;
let output = tokio::task::spawn_blocking(move || {
let check = || {
if cancellation.is_cancelled() {
Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"Authentication cancelled",
))
} else {
Ok(())
}
};
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
})
.await?;
let output = match output {
Ok(output) => output,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
return Err(crate::auth::AuthenticationCancelled.into());
}
Err(error) => return Err(error.into()),
};
let output = child.wait_with_output().await?;
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data")
};
+19 -76
View File
@@ -1,21 +1,12 @@
use std::{
fs,
io::{self, Read},
os::unix::{
fs::{MetadataExt, PermissionsExt},
process::CommandExt,
},
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::{Child, Command, Output, Stdio},
thread,
process::{Command, Output, Stdio},
time::{Duration, Instant},
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
use super::command_runner::run_controlled;
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
@@ -87,6 +78,16 @@ impl<'a> CollectorCommands<'a> {
self.run_path(&path, args)
}
/// Run an installed helper with the same trust checks as system collectors.
/// Root never executes a helper in a user-writable directory.
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
return Ok(None);
};
self.run_path(&path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let home = if uzers::get_effective_uid() == 0 {
@@ -106,59 +107,11 @@ impl<'a> CollectorCommands<'a> {
.env("LC_ALL", "C")
.env("HOME", home)
.current_dir("/")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.process_group(0);
let child = match command.spawn() {
Ok(child) => child,
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => {
return Ok(None);
}
Err(error) => return Err(error),
};
let mut child = CollectionChild(child);
let mut stdout = child.0.stdout.take().expect("collector stdout was piped");
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
fcntl(
&stdout,
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
)
.map_err(io::Error::from)?;
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
let mut eof = false;
let mut status = None;
loop {
self.control.check()?;
if !eof {
match stdout.read(&mut buffer) {
Ok(0) => eof = true,
Ok(length) => {
if output.len() + length > COMMAND_OUTPUT_LIMIT {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Device information collector output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
continue;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if status.is_none() {
status = child.0.try_wait()?;
}
if eof && let Some(status) = status {
return Ok(Some(Output {
status,
stdout: output,
stderr: Vec::new(),
}));
}
thread::sleep(Duration::from_millis(10));
.stderr(Stdio::null());
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
@@ -195,16 +148,6 @@ fn root_owned_path(path: &Path) -> bool {
})
}
struct CollectionChild(Child);
impl Drop for CollectionChild {
fn drop(&mut self) {
// Also stop descendants retaining the pipe after the direct child exits.
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,84 @@
use std::{
io::{self, Read},
os::unix::process::CommandExt,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
use super::collection::CollectionControl;
/// Execute an already configured command. Environment, identity and executable
/// trust belong to its caller. This worker owns the process group until reaped;
/// its asynchronous caller must cancel and await it instead of dropping it.
pub(crate) fn run_controlled(
mut command: Command,
control: &dyn CollectionControl,
output_limit: usize,
) -> io::Result<Output> {
control.check()?;
let child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.process_group(0)
.spawn()?;
let mut child = ControlledChild(child);
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
fcntl(
&stdout,
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
)
.map_err(io::Error::from)?;
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
let mut eof = false;
let mut status = None;
loop {
control.check()?;
if !eof {
match stdout.read(&mut buffer) {
Ok(0) => eof = true,
Ok(length) => {
if length > output_limit.saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
continue;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if status.is_none() {
status = child.0.try_wait()?;
}
if eof && let Some(status) = status {
return Ok(Output {
status,
stdout: output,
stderr: Vec::new(),
});
}
thread::sleep(Duration::from_millis(10));
}
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
// Reap the direct child and stop helpers retaining stdout after it exits.
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
+1
View File
@@ -1,3 +1,4 @@
mod command_runner;
mod command_traits;
mod desktop_session_env;
pub(crate) mod gui_helper_launcher;
+65 -17
View File
@@ -5,9 +5,9 @@ use specta::Type;
use zeroize::Zeroize;
use crate::{
gateway::Gateway,
hip::HipSource,
os_profile::{ClientOs, OsProfile},
os_profile::{ClientOs, HostIdentity, OsProfile},
session::ConnectionPlan,
};
use super::vpn_state::ConnectInfo;
@@ -58,8 +58,9 @@ impl LaunchGuiRequest {
#[derive(Deserialize, Serialize, Type, Clone)]
pub struct ConnectArgs {
cookie: String,
vpnc_script: Option<String>,
host_identity: Option<HostIdentity>,
ignore_tls_errors: bool,
user_agent: Option<String>,
os: Option<ClientOs>,
@@ -87,10 +88,11 @@ pub struct ConnectArgs {
}
impl ConnectArgs {
pub fn new(cookie: String) -> Self {
fn new() -> Self {
Self {
cookie,
vpnc_script: None,
host_identity: None,
ignore_tls_errors: false,
user_agent: None,
os: None,
os_version: None,
@@ -113,8 +115,12 @@ impl ConnectArgs {
}
}
pub fn cookie(&self) -> &str {
&self.cookie
pub fn host_identity(&self) -> Option<&HostIdentity> {
self.host_identity.as_ref()
}
pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
pub fn vpnc_script(&self) -> Option<String> {
@@ -213,7 +219,6 @@ impl ConnectArgs {
impl fmt::Debug for ConnectArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConnectArgs")
.field("cookie", &"<redacted>")
.field("vpnc_script", &self.vpnc_script)
.field(
"client_auth_path",
@@ -235,7 +240,6 @@ impl fmt::Debug for ConnectArgs {
impl Drop for ConnectArgs {
fn drop(&mut self) {
self.cookie.zeroize();
self.key_password.zeroize();
self.certificate_data.zeroize();
self.sslkey_data.zeroize();
@@ -245,14 +249,16 @@ impl Drop for ConnectArgs {
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectRequest {
info: ConnectInfo,
plan: ConnectionPlan,
args: ConnectArgs,
}
impl ConnectRequest {
pub fn new(info: ConnectInfo, cookie: String) -> Self {
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
Self {
info,
args: ConnectArgs::new(cookie),
plan,
args: ConnectArgs::new(),
}
}
@@ -267,6 +273,7 @@ impl ConnectRequest {
}
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
self.args.host_identity = Some(profile.host_identity().clone());
self.args.os = Some(profile.client_os());
self.args.os_version = Some(profile.os_version().to_string());
self.args.client_version = Some(profile.client_version().to_string());
@@ -275,6 +282,11 @@ impl ConnectRequest {
self
}
pub fn with_ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
self.args.ignore_tls_errors = ignore_tls_errors;
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.args.certificate = certificate.into();
self
@@ -340,8 +352,8 @@ impl ConnectRequest {
self
}
pub fn gateway(&self) -> &Gateway {
self.info.gateway()
pub fn plan(&self) -> &ConnectionPlan {
&self.plan
}
pub fn info(&self) -> &ConnectInfo {
@@ -370,6 +382,7 @@ pub struct UpdateLogLevelRequest(pub String);
pub enum WsRequest {
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
PreviewHipReport(PreviewHipReportRequest),
GetHipApprovalStatus { approval_id: String },
@@ -393,17 +406,52 @@ mod tests {
use super::*;
use crate::os_profile::OsProfileBuilder;
use crate::{
gateway::Gateway,
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
};
fn test_request(info: ConnectInfo) -> ConnectRequest {
let plan = ConnectionPlan::new(
vec![AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
.unwrap(),
}],
vec![],
InternalSessionPolicy::default(),
)
.unwrap();
ConnectRequest::new(info, plan)
}
fn test_connect_info() -> ConnectInfo {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
}
#[test]
fn connect_request_round_trips_a_validated_plan_and_rejects_cookie_only_wire_input() {
let request = test_request(test_connect_info());
let mut value = serde_json::to_value(&request).unwrap();
assert!(value["args"].get("cookie").is_none());
let decoded: ConnectRequest = serde_json::from_value(value.clone()).unwrap();
assert_eq!(decoded.plan().members().len(), 1);
assert_eq!(decoded.plan().members()[0].authentication.connection_type(), "tunnel");
value["plan"]["members"] = json!([]);
assert!(serde_json::from_value::<ConnectRequest>(value).is_err());
let mut legacy = serde_json::to_value(&request).unwrap();
legacy.as_object_mut().unwrap().remove("plan");
legacy["args"]["cookie"] = json!("authcookie=secret-cookie&user=user");
assert!(serde_json::from_value::<ConnectRequest>(legacy).is_err());
}
#[test]
fn connect_request_serializes_allow_extend_session() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
let req = test_request(info).with_allow_extend_session(true);
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["args"]["allowExtendSession"], json!(true));
@@ -413,7 +461,7 @@ mod tests {
fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
let req = test_request(test_connect_info()).with_os_profile(&profile);
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
}
@@ -422,7 +470,7 @@ mod tests {
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
let req = test_request(test_connect_info()).with_os_profile(&profile);
assert_eq!(
req.args().host_id(),
@@ -432,7 +480,7 @@ mod tests {
#[test]
fn client_identity_data_round_trips_without_debug_disclosure() {
let req = ConnectRequest::new(test_connect_info(), "secret-cookie".to_string())
let req = test_request(test_connect_info())
.with_certificate_data(Some(b"certificate".to_vec()))
.with_sslkey_data(Some(b"private-key".to_vec()));
let encoded = serde_json::to_vec(&req).unwrap();
+15 -1
View File
@@ -167,7 +167,21 @@ mod tests {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
let request = ConnectRequest::new(info, "cookie".to_string())
let plan = crate::session::ConnectionPlan::new(
vec![crate::session::AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
authentication: crate::session::GatewayAuthentication::new(
"authcookie=token&user=user".into(),
"tunnel".into(),
)
.unwrap(),
}],
vec![],
crate::session::InternalSessionPolicy::default(),
)
.unwrap();
let request = ConnectRequest::new(info, plan)
.with_certificate_data(Some(vec![b'c'; certificate_size]))
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
let message = ClientMessage::Request {
+23 -1
View File
@@ -3,7 +3,10 @@ use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{gateway::Gateway, session::SessionInfo};
use crate::{
gateway::Gateway,
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
};
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
@@ -18,6 +21,8 @@ pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
connected_at: u32,
members: Vec<GatewaySessionSummary>,
failures: Vec<GatewayFailureSummary>,
}
impl ConnectedInfo {
@@ -26,9 +31,25 @@ impl ConnectedInfo {
info: Box::new(info),
session_info,
connected_at: unix_timestamp(),
members: vec![],
failures: vec![],
}
}
pub fn with_members(mut self, members: Vec<GatewaySessionSummary>, failures: Vec<GatewayFailureSummary>) -> Self {
self.members = members;
self.failures = failures;
self
}
pub fn members(&self) -> &[GatewaySessionSummary] {
&self.members
}
pub fn failures(&self) -> &[GatewayFailureSummary] {
&self.failures
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
@@ -67,6 +88,7 @@ impl ConnectInfo {
#[serde(rename_all = "camelCase")]
pub enum VpnState {
Disconnected,
Failed(String),
Connecting(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>),
Disconnecting,
+8
View File
@@ -4,6 +4,14 @@ use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
mod connection;
mod gateway_sessions;
pub mod network;
pub mod non_tunnel;
pub mod transport;
pub use connection::*;
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
+335
View File
@@ -0,0 +1,335 @@
use std::{fmt, time::Duration};
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use zeroize::Zeroize;
use crate::gateway::Gateway;
/// Network location and session mode are independent: an internal gateway can
/// still require a tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SessionMode {
Tunnel,
NonTunnel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MaintenanceState {
Authenticated,
Healthy,
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GatewaySessionSummary {
pub gateway: Gateway,
pub mode: SessionMode,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub maintenance: MaintenanceState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SessionEndReason {
InvalidCookie,
NetworkChanged,
AllMembersFailed,
AuthorizationRevoked,
}
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "GatewayAuthenticationFields")]
pub struct GatewayAuthentication {
cookie: String,
connection_type: String,
}
#[derive(Deserialize)]
struct GatewayAuthenticationFields {
cookie: String,
connection_type: String,
}
impl TryFrom<GatewayAuthenticationFields> for GatewayAuthentication {
type Error = anyhow::Error;
fn try_from(fields: GatewayAuthenticationFields) -> Result<Self, Self::Error> {
Self::new(fields.cookie, fields.connection_type)
}
}
impl GatewayAuthentication {
pub fn new(cookie: String, connection_type: String) -> anyhow::Result<Self> {
let authentication = Self {
cookie,
connection_type,
};
ensure!(
!authentication.cookie.is_empty() && authentication.cookie.len() <= 64 * 1024,
"Gateway authentication cookie is missing or too large"
);
let params = url::form_urlencoded::parse(authentication.cookie.as_bytes()).collect::<Vec<_>>();
for key in ["authcookie", "user"] {
let mut values = params.iter().filter(|(name, _)| name == key).map(|(_, value)| value);
ensure!(
values.next().is_some_and(|value| !value.is_empty()) && values.next().is_none(),
"Gateway authentication requires one nonempty {key}"
);
}
ensure!(
!authentication.connection_type.trim().is_empty()
&& authentication.connection_type != "(null)"
&& authentication.connection_type != "-1",
"Gateway connection type is missing"
);
Ok(authentication)
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn connection_type(&self) -> &str {
&self.connection_type
}
pub fn mode(&self) -> SessionMode {
if self.connection_type == "tunnel" {
SessionMode::Tunnel
} else {
SessionMode::NonTunnel
}
}
}
impl fmt::Debug for GatewayAuthentication {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GatewayAuthentication")
.field("cookie", &"<redacted>")
.field("mode", &self.mode())
.finish()
}
}
impl Drop for GatewayAuthentication {
fn drop(&mut self) {
self.cookie.zeroize();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", try_from = "InternalSessionPolicyFields")]
pub struct InternalSessionPolicy {
hip_interval_secs: u32,
collect_hip_data: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct InternalSessionPolicyFields {
hip_interval_secs: u32,
collect_hip_data: bool,
}
impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
type Error = anyhow::Error;
fn try_from(fields: InternalSessionPolicyFields) -> Result<Self, Self::Error> {
Self::new(fields.hip_interval_secs, fields.collect_hip_data)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct AuthenticatedGateway {
pub gateway: Gateway,
pub authentication: GatewayAuthentication,
pub binding: Option<super::network::GatewayBinding>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GatewayFailure {
AuthenticationRejected,
Unreachable,
TunnelFailed,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct GatewayFailureSummary {
pub gateway: Gateway,
pub failure: GatewayFailure,
}
/// Credentials remain in the interactive authentication owner; only issued
/// gateway cookies cross the runtime/service boundary.
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "ConnectionPlanFields")]
pub struct ConnectionPlan {
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
internal_detection: Option<super::network::InternalHostDetection>,
}
#[derive(Deserialize)]
struct ConnectionPlanFields {
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
internal_detection: Option<super::network::InternalHostDetection>,
}
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
type Error = anyhow::Error;
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
}
}
impl ConnectionPlan {
pub fn new(
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
) -> anyhow::Result<Self> {
ensure!(!members.is_empty(), "Connection plan has no authenticated gateways");
ensure!(
members.len() <= 64 && failures.len() <= 64,
"Connection plan exceeds its gateway limit"
);
let mode = members[0].authentication.mode();
ensure!(
members.iter().all(|member| member.authentication.mode() == mode),
"Mixed tunnel and non-tunnel sessions are unsupported"
);
ensure!(
mode != SessionMode::NonTunnel
|| members
.iter()
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
"Non-tunnel sessions require freshly discovered internal gateways"
);
ensure!(
members.len() == 1
|| members
.iter()
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
"Multiple authenticated gateways require an internal connection"
);
let mut hosts = std::collections::HashSet::new();
for member in &members {
if mode == SessionMode::NonTunnel {
let binding = member
.binding
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?;
binding.validate_server(member.gateway.server())?;
}
let host = crate::utils::normalize_server(member.gateway.server())?;
ensure!(hosts.insert(host), "Connection plan has duplicate gateways");
}
Ok(Self {
members,
failures,
policy,
internal_detection: None,
})
}
pub fn members(&self) -> &[AuthenticatedGateway] {
&self.members
}
pub fn failures(&self) -> &[GatewayFailureSummary] {
&self.failures
}
pub fn policy(&self) -> InternalSessionPolicy {
self.policy
}
pub fn mode(&self) -> SessionMode {
self.members[0].authentication.mode()
}
pub fn with_internal_detection(mut self, detection: Option<super::network::InternalHostDetection>) -> Self {
self.internal_detection = detection;
self
}
pub fn internal_detection(&self) -> Option<&super::network::InternalHostDetection> {
self.internal_detection.as_ref()
}
}
impl Default for InternalSessionPolicy {
fn default() -> Self {
Self {
hip_interval_secs: 3600,
collect_hip_data: true,
}
}
}
impl InternalSessionPolicy {
pub fn new(hip_interval_secs: u32, collect_hip_data: bool) -> anyhow::Result<Self> {
ensure!(hip_interval_secs > 0, "HIP report interval must be positive");
ensure!(
hip_interval_secs.checked_mul(1000).is_some(),
"HIP report interval exceeds the supported range"
);
Ok(Self {
hip_interval_secs,
collect_hip_data,
})
}
pub fn hip_interval(&self) -> Duration {
Duration::from_secs(u64::from(self.hip_interval_secs))
}
pub fn collect_hip_data(&self) -> bool {
self.collect_hip_data
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialization_enforces_authentication_invariants() {
for (cookie, mode) in [
("", "tunnel"),
("not-a-cookie", "tunnel"),
("user=alice", "tunnel"),
("authcookie=token", "tunnel"),
("authcookie=token&user=alice&user=bob", "tunnel"),
("authcookie=token&user=alice", ""),
] {
let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode});
assert!(serde_json::from_value::<GatewayAuthentication>(serialized).is_err());
}
let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap();
let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap();
assert_eq!(decoded.mode(), SessionMode::NonTunnel);
}
#[test]
fn deserialization_enforces_schedule_invariants() {
for interval in [0, u32::MAX] {
let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false});
assert!(serde_json::from_value::<InternalSessionPolicy>(serialized).is_err());
}
let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap();
let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap();
assert_eq!(decoded.hip_interval(), Duration::from_secs(3600));
}
}
@@ -0,0 +1,103 @@
use std::{
net::{Ipv4Addr, Ipv6Addr},
sync::Arc,
time::Duration,
};
use crate::gateway::Gateway;
use super::transport::GatewayTransport;
const LOGOUT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct ClientAddresses {
pub ipv4: Option<Ipv4Addr>,
pub ipv6: Option<Ipv6Addr>,
}
/// One issued gateway authentication and its original request context. Session
/// mode governs execution, while every mode has the same cleanup owner.
pub struct GatewaySession {
pub gateway: Gateway,
pub transport: GatewayTransport,
pub addresses: ClientAddresses,
}
/// Owns issued gateway sessions independently of tunnel or HIP setup. Workers
/// borrow members; their owner joins them before consuming this ledger in logout.
/// This owner is deliberately not Clone: transfer or drain it exactly once.
#[derive(Default)]
pub struct GatewaySessions {
members: Vec<Arc<GatewaySession>>,
}
impl GatewaySessions {
pub fn new(members: Vec<GatewaySession>) -> Self {
Self {
members: members.into_iter().map(Arc::new).collect(),
}
}
pub fn register(&mut self, session: GatewaySession) {
self.members.push(Arc::new(session));
}
pub(crate) fn update(&mut self, session: GatewaySession) {
if let Some(member) = self
.members
.iter_mut()
.find(|member| member.gateway.server() == session.gateway.server())
{
*member = Arc::new(session);
}
}
pub fn is_empty(&self) -> bool {
self.members.is_empty()
}
/// Consume the local cleanup copies only after another owner has proved it
/// acquired responsibility for these issued sessions.
pub fn relinquish(self) {}
pub fn members(&self) -> &[Arc<GatewaySession>] {
&self.members
}
/// Transfer a selected tunnel login to OpenConnect immediately before its
/// native worker starts. OpenConnect owns the live reconnect cookie and logout.
pub fn relinquish_gateway(&mut self, server: &str) {
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
self.members.remove(index);
}
}
/// Call only after this member's worker has joined. Removing ownership before
/// awaiting logout prevents routine final cleanup from repeating the request.
pub async fn logout_gateway(&mut self, server: &str) {
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
logout(self.members.remove(index)).await;
}
}
pub async fn logout(self) {
let mut workers = tokio::task::JoinSet::new();
for session in self.members {
workers.spawn(logout(session));
}
while let Some(result) = workers.join_next().await {
if let Err(error) = result {
log::warn!("Gateway cleanup worker failed: {error}");
}
}
}
}
async fn logout(session: Arc<GatewaySession>) {
match tokio::time::timeout(LOGOUT_TIMEOUT, session.transport.logout()).await {
Ok(Ok(())) => {}
Ok(Err(error)) => log::warn!("Gateway logout failed: {error}"),
Err(_) => log::warn!("Gateway logout timed out"),
}
}
+223
View File
@@ -0,0 +1,223 @@
use std::net::{IpAddr, SocketAddr};
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use super::super::ClientAddresses;
/// Physical network context bound to the authenticated non-tunnel endpoint. Wire input is validated;
/// runtime transports use this context without performing another DNS lookup.
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "BindingFields", rename_all = "camelCase")]
pub struct GatewayBinding {
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct BindingFields {
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: Option<String>,
}
impl TryFrom<BindingFields> for GatewayBinding {
type Error = anyhow::Error;
fn try_from(fields: BindingFields) -> Result<Self, Self::Error> {
Self::new(
fields.endpoint,
fields.source,
fields.interface,
fields.interface_index,
fields.addresses,
fields.network_fingerprint,
)
}
}
impl GatewayBinding {
pub fn new(
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: impl Into<Option<String>>,
) -> anyhow::Result<Self> {
let network_fingerprint = network_fingerprint.into();
ensure!(
network_fingerprint
.as_ref()
.is_none_or(|value| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())),
"Physical network fingerprint is invalid"
);
ensure!(
endpoint.port() != 0 && !endpoint.ip().is_unspecified() && !endpoint.ip().is_multicast(),
"Gateway endpoint is invalid"
);
ensure!(
source.port() == 0 && !source.ip().is_unspecified() && !source.ip().is_multicast(),
"Gateway source is invalid"
);
ensure!(
endpoint.is_ipv4() == source.is_ipv4(),
"Gateway address families differ"
);
ensure!(
!interface.is_empty() && interface.len() < 64 && !interface.contains('\0') && interface_index != 0,
"Gateway interface is invalid"
);
for address in [endpoint, source] {
if let SocketAddr::V6(address) = address {
ensure!(address.flowinfo() == 0, "Gateway IPv6 flow information is invalid");
ensure!(
address.scope_id() == 0 || address.scope_id() == interface_index,
"Gateway IPv6 scope differs from its interface"
);
ensure!(
!address.ip().is_unicast_link_local() || address.scope_id() == interface_index,
"Gateway IPv6 scope is missing"
);
}
}
match source.ip() {
IpAddr::V4(ip) => ensure!(
addresses.ipv4 == Some(ip),
"Gateway IPv4 source differs from its identity"
),
IpAddr::V6(ip) => ensure!(
addresses.ipv6 == Some(ip),
"Gateway IPv6 source differs from its identity"
),
}
Ok(Self {
endpoint,
source,
interface,
interface_index,
addresses,
network_fingerprint,
})
}
pub fn endpoint(&self) -> SocketAddr {
self.endpoint
}
pub fn source(&self) -> SocketAddr {
self.source
}
pub fn interface(&self) -> &str {
&self.interface
}
pub fn interface_index(&self) -> u32 {
self.interface_index
}
pub fn addresses(&self) -> ClientAddresses {
self.addresses
}
pub fn network_fingerprint(&self) -> Option<&str> {
self.network_fingerprint.as_deref()
}
pub fn validate_server(&self, server: &str) -> anyhow::Result<()> {
let origin = super::super::transport::gateway_origin(server)?;
ensure!(
origin.port_or_known_default() == Some(self.endpoint.port()),
"Gateway endpoint port differs"
);
let literal = match origin.host() {
Some(url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)),
Some(url::Host::Ipv6(ip)) => Some(IpAddr::V6(ip)),
_ => None,
};
if let Some(ip) = literal {
ensure!(self.endpoint.ip() == ip, "Literal gateway endpoint differs");
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ipv4_binding() -> GatewayBinding {
GatewayBinding::new(
"192.0.2.10:443".parse().unwrap(),
"192.0.2.5:0".parse().unwrap(),
"fixture".into(),
7,
ClientAddresses {
ipv4: Some("192.0.2.5".parse().unwrap()),
ipv6: None,
},
"a".repeat(64),
)
.unwrap()
}
#[test]
fn wire_input_rejects_inconsistent_network_identity() {
let original = serde_json::to_value(ipv4_binding()).unwrap();
for (field, value) in [
("source", serde_json::json!("192.0.2.6:0")),
("source", serde_json::json!("192.0.2.5:1234")),
("endpoint", serde_json::json!("[2001:db8::10]:443")),
("interfaceIndex", serde_json::json!(0)),
("networkFingerprint", serde_json::json!("not-a-fingerprint")),
] {
let mut invalid = original.clone();
invalid[field] = value;
assert!(
serde_json::from_value::<GatewayBinding>(invalid).is_err(),
"accepted {field}"
);
}
assert!(serde_json::from_value::<GatewayBinding>(original).is_ok());
}
#[test]
fn link_local_scope_survives_wire_round_trip_and_must_match_interface() {
let addresses = ClientAddresses {
ipv4: None,
ipv6: Some("fe80::5".parse().unwrap()),
};
let binding = GatewayBinding::new(
"[fe80::10%7]:443".parse().unwrap(),
"[fe80::5%7]:0".parse().unwrap(),
"fixture".into(),
7,
addresses,
"a".repeat(64),
)
.unwrap();
let value = serde_json::to_value(&binding).unwrap();
let restored: GatewayBinding = serde_json::from_value(value.clone()).unwrap();
assert_eq!(restored.source(), binding.source());
assert_eq!(restored.endpoint(), binding.endpoint());
for source in ["[fe80::5]:0", "[fe80::5%8]:0"] {
let mut invalid = value.clone();
invalid["source"] = serde_json::json!(source);
assert!(serde_json::from_value::<GatewayBinding>(invalid).is_err());
}
}
#[test]
fn server_origin_must_match_endpoint_port_and_literal_address() {
let binding = ipv4_binding();
assert!(binding.validate_server("gateway.example.com").is_ok());
assert!(binding.validate_server("192.0.2.10").is_ok());
assert!(binding.validate_server("192.0.2.11").is_err());
assert!(binding.validate_server("gateway.example.com:444").is_err());
}
}
+6
View File
@@ -0,0 +1,6 @@
pub(super) use super::bsd_routes::routes;
use super::*;
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
resolv_conf(control)
}
@@ -0,0 +1,59 @@
use super::*;
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
let mut routes = Vec::new();
for family in ["inet", "inet6"] {
routes.extend(parse_routes(&command("netstat", &["-rn", "-f", family], control)?)?);
}
Ok(routes)
}
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
let mut interface_column = None;
let mut routes = Vec::new();
for line in contents.lines() {
let fields = line.split_whitespace().collect::<Vec<_>>();
if fields.first() == Some(&"Destination") {
interface_column = Some(
fields
.iter()
.position(|field| matches!(*field, "Netif" | "Iface"))
.context("Route table has no interface column")?,
);
continue;
}
let Some(column) = interface_column else {
continue;
};
if fields.len() <= column {
continue;
}
// L/W entries are neighbor-cache or cloned host routes. Their presence,
// gateway MAC and expiry depend on traffic and must not cause rediscovery.
if fields[2].contains('L') || fields[2].contains('W') {
continue;
}
routes.push(RouteContext {
destination: fields[0].into(),
gateway: fields[1].into(),
interface: fields[column].into(),
table: String::new(),
metric: String::new(),
});
}
ensure!(interface_column.is_some(), "Route table header is missing");
Ok(routes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ignores_route_use_expiry_and_platform_column_positions() {
let darwin = parse_routes("Routing tables\nInternet:\nDestination Gateway Flags Netif Expire\ndefault 192.0.2.1 UGScg en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHLWI en0 123").unwrap();
let bsd = parse_routes("Destination Gateway Flags Refs Use Mtu Netif Expire\ndefault 192.0.2.1 UGS 4 22 1500 en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHL 0 33 1500 en0 99").unwrap();
assert_eq!(darwin, bsd);
assert_eq!(darwin.len(), 1);
assert!(parse_routes("unrecognized table").is_err());
}
}
@@ -0,0 +1,94 @@
use std::net::IpAddr;
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "DetectionFields")]
pub struct InternalHostDetection {
targets: Vec<DetectionTarget>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
struct DetectionTarget {
address: IpAddr,
hostname: String,
}
#[derive(Deserialize)]
struct DetectionFields {
targets: Vec<DetectionTarget>,
}
impl TryFrom<DetectionFields> for InternalHostDetection {
type Error = anyhow::Error;
fn try_from(fields: DetectionFields) -> anyhow::Result<Self> {
Self::new(
fields
.targets
.into_iter()
.map(|target| (target.address, target.hostname))
.collect(),
)
}
}
impl InternalHostDetection {
pub fn new(targets: Vec<(IpAddr, String)>) -> anyhow::Result<Self> {
ensure!(
!targets.is_empty() && targets.len() <= 2,
"Invalid internal detection target count"
);
let targets = targets
.into_iter()
.map(|(address, hostname)| {
validate_target(address, &hostname)?;
Ok(DetectionTarget { address, hostname })
})
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(Self { targets })
}
pub async fn detect(&self, cancellation: &CancellationToken) -> anyhow::Result<bool> {
for target in &self.targets {
if super::native::detect(target.address, &target.hostname, cancellation).await? {
return Ok(true);
}
}
Ok(false)
}
}
pub(super) fn validate_target(address: IpAddr, hostname: &str) -> anyhow::Result<()> {
ensure!(
!address.is_unspecified() && !address.is_loopback() && !address.is_multicast(),
"Invalid internal detection address"
);
ensure!(
!hostname.is_empty()
&& hostname.len() <= 253
&& hostname.is_ascii()
&& hostname
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')),
"Invalid internal detection hostname"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detection_inputs_are_retained_and_validated_on_deserialization() {
let detection = InternalHostDetection::new(vec![("192.0.2.10".parse().unwrap(), "host.example".into())]).unwrap();
let value = serde_json::to_value(&detection).unwrap();
assert!(serde_json::from_value::<InternalHostDetection>(value).is_ok());
assert!(InternalHostDetection::new(vec![]).is_err());
assert!(InternalHostDetection::new(vec![("127.0.0.1".parse().unwrap(), "host.example".into())]).is_err());
}
}
+121
View File
@@ -0,0 +1,121 @@
use super::*;
#[cfg(target_os = "linux")]
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
let mut routes = Vec::new();
for family in ["-4", "-6"] {
routes.extend(parse_routes(&command(
"ip",
&[family, "-j", "route", "show", "table", "all"],
control,
)?)?);
}
Ok(routes)
}
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
let value: Vec<serde_json::Value> = serde_json::from_str(contents)?;
let mut routes = Vec::new();
for route in value {
// Kernel cache and neighbor lifetimes are traffic, not network changes.
if route.get("cache").is_some() {
continue;
}
let Some(interface) = route["dev"].as_str() else {
continue;
};
let field = |name| {
route
.get(name)
.map(|value| value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()))
.unwrap_or_default()
};
routes.push(RouteContext {
destination: field("dst"),
gateway: field("gateway"),
interface: interface.into(),
table: field("table"),
metric: field("metric"),
});
}
Ok(routes)
}
#[cfg(target_os = "linux")]
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
let path = std::fs::canonicalize("/etc/resolv.conf")?;
if path.starts_with("/run/systemd/resolve") {
let dns = command("resolvectl", &["dns"], control)?;
let domains = command("resolvectl", &["domain"], control)?;
return parse_resolved(&dns, &domains);
}
resolv_conf(control)
}
fn parse_resolved(dns: &str, domains: &str) -> anyhow::Result<Vec<ResolverContext>> {
let mut resolvers = std::collections::BTreeMap::<Option<String>, ResolverContext>::new();
for (contents, is_dns) in [(dns, true), (domains, false)] {
for line in contents.lines().filter(|line| !line.trim().is_empty()) {
let (label, values) = line.split_once(':').context("Invalid systemd resolver output")?;
let interface = if label == "Global" {
None
} else {
let (_, name) = label.split_once('(').context("Invalid systemd resolver interface")?;
Some(
name
.strip_suffix(')')
.context("Invalid systemd resolver interface")?
.to_owned(),
)
};
let resolver = resolvers.entry(interface.clone()).or_insert_with(|| ResolverContext {
interface,
servers: Vec::new(),
domains: Vec::new(),
});
if is_dns {
for server in values.split_whitespace() {
server
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid systemd resolver address")?;
resolver.servers.push(server.to_owned());
}
} else {
resolver
.domains
.extend(values.split_whitespace().map(|domain| domain.to_ascii_lowercase()));
}
}
}
Ok(resolvers.into_values().collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn route_identity_retains_ipv6_and_ignores_cache() {
let routes = parse_routes(r#"[{"dst":"default","gateway":"2001:db8::1","dev":"eth0","metric":600,"table":"main"},{"dst":"2001:db8::5","dev":"eth0","cache":[]}]"#).unwrap();
assert_eq!(routes.len(), 1);
assert_eq!(routes[0].gateway, "2001:db8::1");
assert_eq!(routes[0].metric, "600");
}
#[test]
fn resolved_preserves_interface_domains_and_empty_global_context() {
let resolvers = parse_resolved(
"Global:\nLink 2 (eth0): 192.0.2.53\n\nLink 3 (tun0): 198.51.100.53\n",
"Global:\nLink 2 (eth0): CORP.EXAMPLE\nLink 3 (tun0): ~.\n",
)
.unwrap();
assert_eq!(resolvers.len(), 3);
assert!(
resolvers
.iter()
.any(|resolver| resolver.interface.as_deref() == Some("eth0")
&& resolver.domains.iter().any(|domain| domain == "corp.example"))
);
}
}
+74
View File
@@ -0,0 +1,74 @@
pub(super) use super::bsd_routes::routes;
use super::*;
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
parse_resolvers(&command("scutil", &["--dns"], control)?)
}
fn parse_resolvers(contents: &str) -> anyhow::Result<Vec<ResolverContext>> {
let mut resolvers = Vec::new();
let mut current: Option<ResolverContext> = None;
for line in contents.lines().map(str::trim) {
if line.starts_with("resolver #") {
if let Some(resolver) = current.take() {
resolvers.push(resolver);
}
current = Some(ResolverContext {
interface: None,
servers: Vec::new(),
domains: Vec::new(),
});
continue;
}
let Some(resolver) = &mut current else {
continue;
};
let Some((field, value)) = line.split_once(':') else {
continue;
};
let field = field.trim();
let value = value.trim();
if field.starts_with("nameserver[") {
value
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid macOS resolver address")?;
resolver.servers.push(value.to_owned());
} else if field == "domain" || field.starts_with("search domain[") {
resolver.domains.push(value.to_ascii_lowercase());
} else if field == "if_index" {
if let Some((_, name)) = value.split_once('(') {
resolver.interface = Some(
name
.strip_suffix(')')
.context("Invalid macOS resolver interface")?
.to_owned(),
);
}
}
}
if let Some(resolver) = current {
resolvers.push(resolver);
}
Ok(resolvers)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolver_identity_is_scoped_and_ignores_reachability_counters() {
let a = parse_resolvers(
"resolver #1\n nameserver[0] : 192.0.2.53\n if_index : 4 (en0)\n search domain[0] : CORP.EXAMPLE\n reach : 2",
)
.unwrap();
let b = parse_resolvers(
"resolver #9\n search domain[0] : corp.example\n if_index : 4 (en0)\n nameserver[0] : 192.0.2.53\n reach : 3",
)
.unwrap();
assert_eq!(a, b);
assert_eq!(a[0].interface.as_deref(), Some("en0"));
}
}
+563
View File
@@ -0,0 +1,563 @@
use std::{
collections::BTreeSet,
io,
net::{IpAddr, SocketAddr},
time::Duration,
};
use anyhow::{Context, ensure};
use netdev::Interface;
use tokio_util::sync::CancellationToken;
use super::ClientAddresses;
use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
mod bsd;
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos", test))]
mod bsd_routes;
#[cfg(any(target_os = "linux", test))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
use bsd as platform;
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
mod binding;
mod detection;
pub mod native;
pub use binding::GatewayBinding;
pub use detection::InternalHostDetection;
const INSPECTION_TIMEOUT: Duration = Duration::from_secs(5);
const POLL_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct InterfaceIdentity {
index: u32,
name: String,
mac: Option<String>,
flags: u32,
addresses: BTreeSet<(String, u32)>,
}
impl From<&Interface> for InterfaceIdentity {
fn from(interface: &Interface) -> Self {
let mut addresses = interface
.ipv4
.iter()
.map(|ip| (ip.to_string(), 0))
.collect::<BTreeSet<_>>();
addresses.extend(interface.ipv6.iter().enumerate().map(|(index, ip)| {
(
ip.to_string(),
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
)
}));
Self {
index: interface.index,
name: interface.name.clone(),
mac: interface.mac_addr.map(|mac| mac.to_string()),
flags: interface.flags,
addresses,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct RouteContext {
destination: String,
gateway: String,
interface: String,
table: String,
metric: String,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct ResolverContext {
interface: Option<String>,
servers: Vec<String>,
domains: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
struct NetworkSnapshot {
interfaces: BTreeSet<InterfaceIdentity>,
routes: BTreeSet<RouteContext>,
resolvers: Vec<ResolverContext>,
}
/// Captured before this attempt installs a tunnel. Interface counters and
/// timestamps do not participate in identity; routes and resolver context do.
#[derive(Clone)]
pub struct PhysicalNetwork {
snapshot: NetworkSnapshot,
interfaces: Vec<Interface>,
}
impl PhysicalNetwork {
pub async fn bind_authenticated_endpoint(
&self,
server: &str,
endpoint: SocketAddr,
disable_ipv6: bool,
cancellation: &CancellationToken,
) -> anyhow::Result<GatewayBinding> {
self.ensure_current(cancellation).await?;
let binding = resolve_binding(
&self.interfaces,
Some(self.fingerprint()?),
server,
disable_ipv6,
cancellation,
endpoint,
)
.await?;
self.ensure_current(cancellation).await?;
Ok(binding)
}
pub async fn validate_internal_binding(
&self,
binding: &GatewayBinding,
detection: Option<&InternalHostDetection>,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.validate_binding(binding, cancellation).await?;
ensure!(
binding.interface() == self.physical_interface()?.name,
"Gateway uses a different physical uplink"
);
self.validate_internal(detection, cancellation).await
}
fn physical_interface(&self) -> anyhow::Result<&Interface> {
let defaults = self
.snapshot
.routes
.iter()
.filter(|route| matches!(route.destination.as_str(), "default" | "0.0.0.0/0" | "::/0"))
.map(|route| route.interface.as_str())
.collect::<BTreeSet<_>>();
ensure!(
defaults.len() == 1,
"Non-tunnel sessions require one unambiguous physical uplink"
);
let name = defaults.first().context("Physical default route is missing")?;
let interface = self
.interfaces
.iter()
.find(|interface| interface.name == *name)
.context("Physical interface is missing")?;
ensure!(
matches!(
interface.if_type,
netdev::prelude::InterfaceType::Ethernet
| netdev::prelude::InterfaceType::Wireless80211
| netdev::prelude::InterfaceType::FastEthernetT
| netdev::prelude::InterfaceType::FastEthernetFx
| netdev::prelude::InterfaceType::GigabitEthernet
),
"Unsupported physical interface type"
);
Ok(interface)
}
pub async fn validate_internal(
&self,
detection: Option<&InternalHostDetection>,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.ensure_current(cancellation).await?;
let interface = self.physical_interface()?;
let mut resolver_count = 0;
for resolver in &self.snapshot.resolvers {
if resolver.servers.is_empty() {
continue;
}
ensure!(
resolver.interface.as_deref().is_none_or(|name| name == interface.name),
"Split physical resolver attribution is unsupported"
);
for server in &resolver.servers {
let server = if server.contains(':') {
format!("[{server}]:53")
} else {
format!("{server}:53")
};
let endpoint: SocketAddr = server.parse().context("Scoped resolver attribution is unsupported")?;
ensure!(
!endpoint.ip().is_loopback() && !endpoint.ip().is_unspecified(),
"Unattributed local DNS stub is unsupported"
);
let socket = tokio::net::UdpSocket::bind(if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }).await?;
socket.connect(endpoint).await?;
let source = socket.local_addr()?.ip();
ensure!(
interface.ipv4.iter().any(|ip| IpAddr::V4(ip.addr()) == source)
|| interface.ipv6.iter().any(|ip| IpAddr::V6(ip.addr()) == source),
"Resolver does not use the physical uplink"
);
resolver_count += 1;
}
}
ensure!(resolver_count > 0, "Physical resolver context is unavailable");
if let Some(detection) = detection {
ensure!(
detection.detect(cancellation).await?,
"Internal host detection no longer matches"
);
}
self.ensure_current(cancellation).await
}
pub async fn capture_controlled(cancellation: &CancellationToken) -> anyhow::Result<Self> {
let cancellation = cancellation.clone();
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(io::ErrorKind::Interrupted, "Network capture cancelled"));
}
budget.check()
};
Self::capture(&check)
})
.await?
}
pub async fn validate_binding(
&self,
binding: &GatewayBinding,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.ensure_current(cancellation).await?;
ensure!(
binding.network_fingerprint() == Some(self.fingerprint()?.as_str()),
"Physical network changed since authentication"
);
let interface = self
.interfaces
.iter()
.find(|interface| interface.index == binding.interface_index() && interface.name == binding.interface())
.context("Authenticated gateway interface is no longer present")?;
let addresses = binding.addresses();
ensure!(
addresses
.ipv4
.is_none_or(|ip| interface.ipv4.iter().any(|address| address.addr() == ip)),
"Authenticated IPv4 address changed"
);
ensure!(
addresses
.ipv6
.is_none_or(|ip| interface.ipv6.iter().any(|address| address.addr() == ip)),
"Authenticated IPv6 address changed"
);
Ok(())
}
fn fingerprint(&self) -> anyhow::Result<String> {
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
}
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
control.check()?;
let mut interfaces = netdev::get_interfaces();
for interface in &mut interfaces {
interface.ipv4.sort();
// The address and its zone must move together when native enumeration
// order changes between captures.
let mut ipv6 = interface
.ipv6
.iter()
.copied()
.enumerate()
.map(|(index, address)| {
(
address,
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
)
})
.collect::<Vec<_>>();
ipv6.sort();
interface.ipv6 = ipv6.iter().map(|(address, _)| *address).collect();
interface.ipv6_scope_ids = ipv6.into_iter().map(|(_, scope)| scope).collect();
}
let snapshot = snapshot(&interfaces, control)?;
control.check()?;
Ok(Self { snapshot, interfaces })
}
/// Validate endpoint selection against the captured network. The inspection
/// is joined even when cancellation occurs, so native collectors cannot outlive
/// the connection attempt.
pub async fn ensure_current(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let current = inspect(cancellation.clone()).await?;
ensure!(
current == self.snapshot,
"Physical network changed during gateway setup"
);
Ok(())
}
/// The owner must cancel and await this monitor, including its blocking
/// inspection. Dropping a selected future would detach the native collector.
pub async fn wait_for_change(
&self,
detection: Option<InternalHostDetection>,
cancellation: CancellationToken,
) -> anyhow::Result<bool> {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => return Ok(false),
_ = tokio::time::sleep(POLL_INTERVAL) => {},
}
let current = self.validate_internal(detection.as_ref(), &cancellation).await;
if cancellation.is_cancelled() {
return Ok(false);
}
if current.is_err() {
return Ok(true);
}
}
}
}
async fn resolve_binding(
interfaces: &[Interface],
fingerprint: Option<String>,
server: &str,
disable_ipv6: bool,
cancellation: &CancellationToken,
authenticated_endpoint: SocketAddr,
) -> anyhow::Result<GatewayBinding> {
let origin = super::transport::gateway_origin(server)?;
let host = origin.host_str().context("Gateway host is missing")?;
let port = origin.port_or_known_default().context("Gateway port is missing")?;
let literal = literal_gateway_address(&origin)?;
let endpoints = if let Some(ip) = literal {
vec![SocketAddr::new(ip, port)]
} else {
native::resolve(host, port, disable_ipv6, cancellation).await?
};
ensure!(
endpoints.contains(&authenticated_endpoint),
"Authenticated peer is not a resolved gateway endpoint; proxied non-tunnel sessions are unsupported"
);
let endpoint = authenticated_endpoint;
ensure!(
!(disable_ipv6 && endpoint.is_ipv6()),
"Authenticated gateway uses disabled IPv6"
);
let bind = if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
let socket = tokio::net::UdpSocket::bind(bind).await?;
socket.connect(endpoint).await?;
let mut source_address = socket.local_addr()?;
source_address.set_port(0);
let source = source_address.ip();
let scope = [source_address, endpoint]
.into_iter()
.find_map(|address| match address {
SocketAddr::V6(address) if address.scope_id() != 0 => Some(address.scope_id()),
_ => None,
});
let mut matches = interfaces.iter().filter(|interface| {
scope.is_none_or(|scope| scope == interface.index)
&& (interface.ipv4.iter().any(|ip| IpAddr::V4(ip.addr()) == source)
|| interface.ipv6.iter().any(|ip| IpAddr::V6(ip.addr()) == source))
});
let interface = matches
.next()
.context("Gateway route has no matching physical interface")?;
ensure!(
matches.next().is_none(),
"Gateway route has ambiguous physical interfaces"
);
ensure!(
!source.is_unspecified() && !source.is_loopback(),
"Gateway route has no source address"
);
let ipv4 = match source {
IpAddr::V4(ip) => Some(ip),
_ => interface
.ipv4
.iter()
.map(|ip| ip.addr())
.find(|ip| !ip.is_loopback() && !ip.is_unspecified()),
};
let ipv6 = if disable_ipv6 {
None
} else {
match source {
IpAddr::V6(ip) => Some(ip),
_ => interface
.ipv6
.iter()
.map(|ip| ip.addr())
.find(|ip| !ip.is_loopback() && !ip.is_unspecified() && !ip.is_unicast_link_local()),
}
};
if let std::net::SocketAddr::V6(address) = &mut source_address {
if address.ip().is_unicast_link_local() && address.scope_id() == 0 {
address.set_scope_id(interface.index);
}
}
GatewayBinding::new(
endpoint,
source_address,
interface.name.clone(),
interface.index,
ClientAddresses { ipv4, ipv6 },
fingerprint.clone(),
)
}
async fn inspect(cancellation: CancellationToken) -> anyhow::Result<NetworkSnapshot> {
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Network inspection cancelled",
));
}
budget.check()
};
let result = snapshot(&netdev::get_interfaces(), &check)?;
check()?;
Ok(result)
})
.await?
}
fn literal_gateway_address(origin: &url::Url) -> anyhow::Result<Option<IpAddr>> {
Ok(match origin.host().context("Gateway host is missing")? {
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
url::Host::Domain(_) => None,
})
}
fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow::Result<NetworkSnapshot> {
control.check()?;
Ok(NetworkSnapshot {
interfaces: interfaces.iter().map(InterfaceIdentity::from).collect(),
routes: platform::routes(control)?.into_iter().collect(),
resolvers: platform::resolvers(control)?,
})
}
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
let output = CollectorCommands::new(control)
.run(name, args)?
.with_context(|| format!("Required network tool {name} is unavailable"))?;
ensure!(output.status.success(), "Network tool {name} failed");
String::from_utf8(output.stdout).context("Network tool output is not UTF-8")
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn resolv_conf(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
control.check()?;
let file = std::fs::File::open("/etc/resolv.conf")?;
use std::io::Read;
let mut contents = String::new();
file.take(64 * 1024 + 1).read_to_string(&mut contents)?;
ensure!(contents.len() <= 64 * 1024, "Resolver configuration is too large");
control.check()?;
Ok(vec![parse_resolv_conf(&contents)?])
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn parse_resolv_conf(contents: &str) -> anyhow::Result<ResolverContext> {
let mut resolver = ResolverContext {
interface: None,
servers: Vec::new(),
domains: Vec::new(),
};
for line in contents.lines() {
let line = line.split(['#', ';']).next().unwrap_or_default();
let mut fields = line.split_whitespace();
match fields.next() {
Some("nameserver") => {
if let Some(server) = fields.next() {
// IPv6 zone identifiers are retained for scoped physical resolvers.
server
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid resolver address")?;
resolver.servers.push(server.to_owned());
}
}
Some("search" | "domain") => resolver
.domains
.extend(fields.map(|domain| domain.to_ascii_lowercase())),
_ => {}
}
}
Ok(resolver)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bracketed_ipv6_gateway_is_a_literal_endpoint() {
let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap();
assert_eq!(
literal_gateway_address(&origin).unwrap(),
Some("2001:db8::1".parse().unwrap())
);
}
#[test]
fn resolver_order_comments_and_case_do_not_change_network_identity() {
assert_eq!(
parse_resolv_conf("nameserver 192.0.2.53\nsearch CORP.EXAMPLE\n# comment").unwrap(),
parse_resolv_conf("search corp.example\nnameserver 192.0.2.53 # DHCP\n").unwrap()
);
assert_ne!(
parse_resolv_conf("nameserver 192.0.2.53").unwrap(),
parse_resolv_conf("nameserver 192.0.2.54").unwrap()
);
}
#[test]
fn interface_identity_ignores_counters_and_address_enumeration_order() {
let mut interface = Interface::dummy();
interface.index = 7;
interface.name = "bridge0".into();
interface.ipv4 = vec!["192.0.2.10/24".parse().unwrap(), "192.0.2.11/24".parse().unwrap()];
let original = InterfaceIdentity::from(&interface);
interface.ipv4.reverse();
interface.mtu = Some(1200);
interface.default = !interface.default;
assert_eq!(original, InterfaceIdentity::from(&interface));
interface.index = 8;
assert_ne!(original, InterfaceIdentity::from(&interface));
}
}
#[cfg(test)]
pub(crate) fn test_binding() -> GatewayBinding {
GatewayBinding::new(
"192.0.2.10:443".parse().unwrap(),
"192.0.2.5:0".parse().unwrap(),
"fixture".into(),
1,
ClientAddresses {
ipv4: Some("192.0.2.5".parse().unwrap()),
ipv6: None,
},
"0".repeat(64),
)
.unwrap()
}
+245
View File
@@ -0,0 +1,245 @@
use std::{net::SocketAddr, path::PathBuf};
use anyhow::{Context, ensure};
use dns_lookup::{AddrFamily, AddrInfoHints, SockType, getaddrinfo};
use tokio_util::sync::CancellationToken;
use super::*;
const MAX_ADDRESSES: usize = 64;
#[doc(hidden)]
pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Result<bool> {
super::detection::validate_target(address, hostname)?;
Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname)))
}
pub(super) async fn detect(
address: std::net::IpAddr,
hostname: &str,
cancellation: &CancellationToken,
) -> anyhow::Result<bool> {
super::detection::validate_target(address, hostname)?;
let args = vec![
"detect-internal-host".into(),
"--address".into(),
address.to_string(),
"--hostname".into(),
hostname.into(),
];
let output = run_helper(common::binary_paths::gpclient(), args, cancellation.clone()).await?;
serde_json::from_slice(&output).context("Invalid internal detection helper response")
}
/// Entry point for gpclient's isolated native resolver helper. This blocking
/// function must run in the child process, never a connection runtime thread.
#[doc(hidden)]
pub fn lookup_in_helper(host: &str, port: u16, disable_ipv6: bool) -> anyhow::Result<Vec<SocketAddr>> {
validate_host(host, port)?;
let hints = AddrInfoHints {
address: if disable_ipv6 { AddrFamily::Inet.into() } else { 0 },
socktype: SockType::Stream.into(),
..AddrInfoHints::default()
};
let service = port.to_string();
let mut addresses = Vec::new();
for result in getaddrinfo(Some(host), Some(&service), Some(hints)).map_err(io::Error::from)? {
let address = result?.sockaddr;
if !addresses.contains(&address) {
ensure!(
addresses.len() < MAX_ADDRESSES,
"Native resolver returned too many gateway addresses"
);
addresses.push(address);
}
}
validate_addresses(&addresses, port, disable_ipv6)?;
Ok(addresses)
}
pub(super) async fn resolve(
host: &str,
port: u16,
disable_ipv6: bool,
cancellation: &CancellationToken,
) -> anyhow::Result<Vec<SocketAddr>> {
validate_host(host, port)?;
let mut args = vec!["resolve-gateway".into(), host.into(), "--port".into(), port.to_string()];
if disable_ipv6 {
args.push("--disable-ipv6".into());
}
run_resolver(
common::binary_paths::gpclient(),
args,
port,
disable_ipv6,
cancellation.clone(),
)
.await
}
async fn run_resolver(
executable: PathBuf,
args: Vec<String>,
port: u16,
disable_ipv6: bool,
cancellation: CancellationToken,
) -> anyhow::Result<Vec<SocketAddr>> {
let output = run_helper(executable, args, cancellation).await?;
let addresses: Vec<SocketAddr> = serde_json::from_slice(&output).context("Invalid resolver helper response")?;
validate_addresses(&addresses, port, disable_ipv6)?;
Ok(addresses)
}
async fn run_helper(
executable: PathBuf,
args: Vec<String>,
cancellation: CancellationToken,
) -> anyhow::Result<Vec<u8>> {
// Await the owned worker even on cancellation. CollectorCommands kills and
// waits for the helper process and any descendants before returning.
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Gateway resolution cancelled",
));
}
budget.check()
};
let args = args.iter().map(String::as_str).collect::<Vec<_>>();
let output = CollectorCommands::new(&check)
.run_executable(&executable, &args)?
.context("Native resolver helper is unavailable")?;
check()?;
ensure!(output.status.success(), "Native gateway resolution failed");
Ok(output.stdout)
})
.await?
}
fn validate_host(host: &str, port: u16) -> anyhow::Result<()> {
ensure!(port != 0, "Gateway port is zero");
ensure!(
!host.is_empty() && host.len() <= 253 && !host.contains('\0') && !host.contains(['/', ':']),
"Invalid gateway hostname"
);
Ok(())
}
fn validate_addresses(addresses: &[SocketAddr], port: u16, disable_ipv6: bool) -> anyhow::Result<()> {
ensure!(
!addresses.is_empty() && addresses.len() <= MAX_ADDRESSES,
"Invalid gateway address count"
);
ensure!(
addresses.iter().all(|address| {
address.port() == port && !address.ip().is_unspecified() && (!disable_ipv6 || address.is_ipv4())
}),
"Invalid gateway address from resolver helper"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn actual_helper_output_is_validated_before_admission() {
let addresses = run_resolver(
"/bin/sh".into(),
vec!["-c".into(), "printf '[\"192.0.2.1:443\"]'".into()],
443,
true,
CancellationToken::new(),
)
.await
.unwrap();
assert_eq!(addresses, vec!["192.0.2.1:443".parse::<SocketAddr>().unwrap()]);
assert!(
run_resolver(
"/bin/sh".into(),
vec!["-c".into(), "printf '[\"192.0.2.1:444\"]'".into()],
443,
true,
CancellationToken::new(),
)
.await
.is_err()
);
}
#[tokio::test]
async fn cancellation_kills_and_joins_the_running_resolver_process() {
let file = tempfile::NamedTempFile::new().unwrap();
let path = file.path().to_owned();
let cancellation = CancellationToken::new();
let worker = tokio::spawn(run_resolver(
"/bin/sh".into(),
vec![
"-c".into(),
"printf '%s' \"$$\" > \"$1\"; sleep 30 & wait".into(),
"resolver-test".into(),
path.to_string_lossy().into_owned(),
],
443,
false,
cancellation.clone(),
));
let pid = tokio::time::timeout(Duration::from_secs(2), async {
loop {
if let Ok(pid) = std::fs::read_to_string(&path).unwrap().parse::<i32>() {
break pid;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
cancellation.cancel();
let error = tokio::time::timeout(Duration::from_secs(1), worker)
.await
.unwrap()
.unwrap()
.unwrap_err();
assert_eq!(
error.downcast::<io::Error>().unwrap().kind(),
io::ErrorKind::Interrupted
);
assert_eq!(
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
Err(nix::errno::Errno::ESRCH)
);
}
#[test]
fn native_lookup_preserves_port_and_ipv4_policy() {
let addresses = lookup_in_helper("localhost", 444, true).unwrap();
assert!(
addresses
.iter()
.all(|address| address.is_ipv4() && address.ip().is_loopback() && address.port() == 444)
);
}
#[test]
fn helper_response_validation_retains_ipv6_scope_and_rejects_wrong_port() {
let addresses = vec!["[fe80::1%7]:443".parse().unwrap(), "192.0.2.1:443".parse().unwrap()];
validate_addresses(&addresses, 443, false).unwrap();
assert_eq!(
serde_json::from_str::<Vec<SocketAddr>>(&serde_json::to_string(&addresses).unwrap()).unwrap(),
addresses
);
assert!(validate_addresses(&addresses, 444, false).is_err());
assert!(validate_addresses(&addresses, 443, true).is_err());
}
#[test]
fn rejects_invalid_helper_requests_before_lookup() {
assert!(lookup_in_helper("gateway.example/path", 443, false).is_err());
assert!(lookup_in_helper("gateway.example", 0, false).is_err());
}
}
+316
View File
@@ -0,0 +1,316 @@
use std::{
future::Future,
io,
pin::Pin,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use zeroize::{Zeroize, Zeroizing};
use crate::{gateway::Gateway, process::collection::CollectionControl};
use super::{
GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason,
SessionMode, transport::GatewayRequestError,
};
const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60);
/// This request is deliberately independent of OpenConnect's callback/FFI types.
#[derive(Clone)]
pub struct SessionHipRequest {
pub gateway: Gateway,
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub collect_posture: bool,
}
impl Drop for SessionHipRequest {
fn drop(&mut self) {
self.cookie.zeroize();
}
}
pub struct SessionCollectionControl {
cancellation: CancellationToken,
deadline: Instant,
}
impl CollectionControl for SessionCollectionControl {
fn check(&self) -> io::Result<()> {
if self.cancellation.is_cancelled() {
Err(io::Error::new(io::ErrorKind::Interrupted, "HIP collection cancelled"))
} else if Instant::now() >= self.deadline {
Err(io::Error::new(io::ErrorKind::TimedOut, "HIP collection timed out"))
} else {
Ok(())
}
}
}
pub type SessionReportProducer =
dyn Fn(&SessionHipRequest, &SessionCollectionControl) -> io::Result<String> + Send + Sync;
pub type SessionReportObserver = dyn Fn(&SessionHipRequest, &str) + Send + Sync;
pub type SessionStatusObserver = dyn Fn(GatewaySessionSummary) + Send + Sync;
pub type SessionNetworkValidator =
dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> + Send + Sync;
#[derive(Clone)]
pub struct SessionCallbacks {
pub produce_report: Arc<SessionReportProducer>,
pub report_submitted: Arc<SessionReportObserver>,
pub status_changed: Arc<SessionStatusObserver>,
pub validate_network: Arc<SessionNetworkValidator>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionExit {
Disconnected,
Failed(SessionEndReason),
}
/// Owns maintenance workers until they have stopped. The session owner retains
/// its ledger and logs out after joining every worker. Interactive authentication
/// also belongs to that owner. Cancel and await this future, never abort/drop it:
/// blocking collectors must finish before cleanup releases their resources.
pub async fn maintain_non_tunnel_sessions(
sessions: &mut GatewaySessions,
policy: InternalSessionPolicy,
mut callbacks: SessionCallbacks,
cancellation: CancellationToken,
network_change: impl Future<Output = SessionEndReason>,
) -> anyhow::Result<SessionExit> {
anyhow::ensure!(!sessions.is_empty(), "Non-tunnel session set is empty");
anyhow::ensure!(
sessions
.members()
.iter()
.all(|session| session.transport.authentication().mode() == SessionMode::NonTunnel),
"Tunnel member supplied to non-tunnel runtime"
);
let workers_cancel = cancellation.child_token();
let observer = callbacks.status_changed.clone();
let status_gate = Arc::new(Mutex::new(()));
let gate = status_gate.clone();
let cancelled = workers_cancel.clone();
let worker_observer = observer.clone();
callbacks.status_changed = Arc::new(move |summary| {
let _guard = gate.lock().unwrap_or_else(|error| error.into_inner());
if !cancelled.is_cancelled() {
worker_observer(summary);
}
});
let mut workers = JoinSet::new();
for session in sessions.members() {
let session = session.clone();
let callbacks = callbacks.clone();
let cancellation = workers_cancel.clone();
workers.spawn(async move {
let server = session.gateway.server().to_owned();
(server, maintain_member(session, policy, callbacks, cancellation).await)
});
}
tokio::pin!(network_change);
let mut worker_failure = None;
let outcome = loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break SessionExit::Disconnected,
reason = &mut network_change => break SessionExit::Failed(reason),
result = workers.join_next() => match result {
Some(Ok((_, MemberExit::Terminal(reason)))) => break SessionExit::Failed(reason),
Some(Ok((server, MemberExit::Rejected))) => {
sessions.logout_gateway(&server).await;
if workers.is_empty() { break SessionExit::Failed(SessionEndReason::AllMembersFailed); }
},
Some(Ok((_, MemberExit::Cancelled))) => {},
Some(Err(error)) => { worker_failure = Some(error); break SessionExit::Disconnected; },
None => break SessionExit::Failed(SessionEndReason::AllMembersFailed),
},
}
};
workers_cancel.cancel();
if matches!(outcome, SessionExit::Failed(_)) || worker_failure.is_some() {
// Invalidate advertised health before waiting for collectors or remote
// cleanup. Cancellation prevents workers from publishing Healthy afterwards.
let _guard = status_gate.lock().unwrap_or_else(|error| error.into_inner());
for session in sessions.members() {
observer(GatewaySessionSummary {
gateway: session.gateway.clone(),
mode: SessionMode::NonTunnel,
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
maintenance: MaintenanceState::Rejected,
});
}
}
// Do not abort workers: a blocking collector must observe cancellation and be
// joined before approval/identity resources can be released by the caller.
while let Some(result) = workers.join_next().await {
if let Err(error) = result {
worker_failure.get_or_insert(error);
}
}
if let Some(error) = worker_failure {
return Err(error.into());
}
// Deliberate disconnect wins even when it arrives during coordinated cleanup.
if cancellation.is_cancelled() {
Ok(SessionExit::Disconnected)
} else {
Ok(outcome)
}
}
async fn maintain_member(
session: Arc<GatewaySession>,
policy: InternalSessionPolicy,
callbacks: SessionCallbacks,
cancellation: CancellationToken,
) -> MemberExit {
let request = SessionHipRequest {
gateway: session.gateway.clone(),
cookie: session.transport.authentication().cookie().into(),
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
md5: session.transport.hip_token(),
collect_posture: policy.collect_hip_data(),
};
let status = |maintenance| {
if !cancellation.is_cancelled() {
(callbacks.status_changed)(GatewaySessionSummary {
gateway: session.gateway.clone(),
mode: SessionMode::NonTunnel,
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
maintenance,
});
}
};
status(MaintenanceState::Authenticated);
loop {
if (callbacks.validate_network)(cancellation.clone()).await.is_err() {
return MemberExit::Terminal(SessionEndReason::NetworkChanged);
}
let sent_at = tokio::time::Instant::now();
let check = tokio::select! {
biased;
_ = cancellation.cancelled() => return MemberExit::Cancelled,
result = session.transport.check_hip(session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result,
};
let (result, delay) = match check {
Ok(check) => {
let result = if check.report_needed {
collect_and_submit(&session, &request, &callbacks, &cancellation).await
} else {
Ok(())
};
(result, check.delay)
}
Err(error) => (Err(MemberError::Gateway(error)), Duration::ZERO),
};
let next_check = match result {
Ok(()) => {
if cancellation.is_cancelled() {
return MemberExit::Cancelled;
}
status(MaintenanceState::Healthy);
let Some(next_check) = sent_at
.checked_add(policy.hip_interval())
.and_then(|time| time.checked_add(delay))
else {
status(MaintenanceState::Rejected);
return MemberExit::Rejected;
};
next_check
}
Err(MemberError::Gateway(GatewayRequestError::InvalidCookie)) => {
status(MaintenanceState::Rejected);
return MemberExit::Terminal(SessionEndReason::InvalidCookie);
}
Err(MemberError::Network) => return MemberExit::Terminal(SessionEndReason::NetworkChanged),
Err(MemberError::Authorization) => return MemberExit::Terminal(SessionEndReason::AuthorizationRevoked),
Err(error) => {
if cancellation.is_cancelled() {
return MemberExit::Cancelled;
}
status(MaintenanceState::Rejected);
log::warn!("Gateway maintenance failed: {error}");
return MemberExit::Rejected;
}
};
tokio::select! {
biased;
_ = cancellation.cancelled() => return MemberExit::Cancelled,
_ = tokio::time::sleep_until(next_check) => {},
}
}
}
enum MemberExit {
Cancelled,
Rejected,
Terminal(SessionEndReason),
}
#[derive(Debug, thiserror::Error)]
enum MemberError {
#[error("{0}")]
Gateway(#[from] GatewayRequestError),
// Collector/script errors can contain user-provided text. Do not log payloads.
#[error("HIP report collection failed")]
Collection,
#[error("Physical network validation failed")]
Network,
#[error("HIP report authorization was revoked")]
Authorization,
}
async fn collect_and_submit(
session: &GatewaySession,
request: &SessionHipRequest,
callbacks: &SessionCallbacks,
cancellation: &CancellationToken,
) -> Result<(), MemberError> {
let producer = callbacks.produce_report.clone();
let input = request.clone();
let control = SessionCollectionControl {
cancellation: cancellation.clone(),
deadline: Instant::now() + COLLECTION_TIMEOUT,
};
let report = tokio::task::spawn_blocking(move || {
control.check()?;
let report = Zeroizing::new(producer(&input, &control)?);
control.check()?;
Ok::<_, io::Error>(report)
})
.await
.map_err(|_| MemberError::Collection)?
.map_err(|error| {
if error.kind() == io::ErrorKind::PermissionDenied {
MemberError::Authorization
} else {
MemberError::Collection
}
})?;
(callbacks.validate_network)(cancellation.clone())
.await
.map_err(|_| MemberError::Network)?;
tokio::select! {
biased;
_ = cancellation.cancelled() => return Err(MemberError::Collection),
result = session.transport.submit_hip(&report, session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result?,
}
if !cancellation.is_cancelled() {
(callbacks.report_submitted)(request, &report);
}
Ok(())
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,415 @@
use std::{
future::pending,
sync::{
Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
use tokio::sync::Notify;
use super::*;
use crate::session::transport::GatewayTransport;
use crate::session::{
ClientAddresses, GatewaySessions,
transport::tests::{gateway, response},
};
async fn run_owned_sessions(
members: Vec<GatewaySession>,
policy: InternalSessionPolicy,
callbacks: SessionCallbacks,
cancellation: CancellationToken,
network_change: impl Future<Output = SessionEndReason>,
) -> anyhow::Result<SessionExit> {
let mut sessions = GatewaySessions::new(members);
let result =
maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation.clone(), network_change).await;
sessions.logout().await;
if cancellation.is_cancelled() {
Ok(SessionExit::Disconnected)
} else {
result
}
}
fn member(name: &str, transport: GatewayTransport) -> GatewaySession {
GatewaySession {
gateway: Gateway::new(name.into(), format!("{name}.example")),
transport,
addresses: ClientAddresses {
ipv4: Some("192.0.2.7".parse().unwrap()),
ipv6: None,
},
}
}
fn callbacks() -> SessionCallbacks {
SessionCallbacks {
produce_report: Arc::new(|_, _| Ok("<hip-report/>".into())),
report_submitted: Arc::new(|_, _| {}),
status_changed: Arc::new(|_| {}),
validate_network: Arc::new(|_| Box::pin(async { Ok(()) })),
}
}
#[tokio::test]
async fn network_uncertainty_prevents_hip_and_healthy_status() {
let (transport, server) = gateway(vec![response("<response status='success'/>")]).await;
let mut callbacks = callbacks();
callbacks.validate_network = Arc::new(|_| Box::pin(async { anyhow::bail!("Network changed") }));
callbacks.status_changed = Arc::new(|summary| assert_ne!(summary.maintenance, MaintenanceState::Healthy));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
assert_eq!(server.await.unwrap()[0].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn revoked_report_authorization_terminates_the_attempt() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.produce_report = Arc::new(|_, _| Err(io::ErrorKind::PermissionDenied.into()));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AuthorizationRevoked));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn invalid_cookie_terminates_only_after_logout() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
response("<response status='success'/>"),
])
.await;
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks(),
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
let requests = server.await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn rejection_preserves_healthy_members_and_cleanup_owns_all_members() {
let (rejected, rejected_server) = gateway(vec![
response("<response status='error'><error>Denied</error></response>"),
response("<response status='success'/>"),
])
.await;
let (healthy, healthy_server) = gateway(vec![
response("<response><hip-report-needed>no</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let ready = Arc::new(Notify::new());
let states = Arc::new(Mutex::new(Vec::new()));
let mut callbacks = callbacks();
let states_copy = states.clone();
let ready_copy = ready.clone();
callbacks.status_changed = Arc::new(move |summary| {
if summary.maintenance != MaintenanceState::Authenticated {
let mut states = states_copy.lock().unwrap();
states.push((summary.gateway.name().to_owned(), summary.maintenance));
if states.len() == 2 {
ready_copy.notify_one();
}
}
});
let exit = run_owned_sessions(
vec![member("rejected", rejected), member("healthy", healthy)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
async {
ready.notified().await;
SessionEndReason::NetworkChanged
},
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
let states = states.lock().unwrap();
assert!(states.contains(&("rejected".into(), MaintenanceState::Rejected)));
assert!(states.contains(&("healthy".into(), MaintenanceState::Healthy)));
assert_eq!(rejected_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn observes_reports_only_after_successful_submission() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
response("<response status='success'/>"),
])
.await;
let cancellation = CancellationToken::new();
let submitted = Arc::new(AtomicUsize::new(0));
let observed = submitted.clone();
let stop = cancellation.clone();
let mut callbacks = callbacks();
callbacks.report_submitted = Arc::new(move |request, report| {
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.7"));
assert_eq!(report, "<hip-report/>");
observed.fetch_add(1, Ordering::SeqCst);
stop.cancel();
});
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
cancellation,
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Disconnected);
assert_eq!(submitted.load(Ordering::SeqCst), 1);
assert_eq!(server.await.unwrap().len(), 3);
}
#[tokio::test]
async fn cancelled_collection_is_joined_before_runtime_returns() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let cancellation = CancellationToken::new();
let entered = Arc::new(Notify::new());
let stopped = Arc::new(AtomicBool::new(false));
let mut callbacks = callbacks();
let entered_copy = entered.clone();
let stopped_copy = stopped.clone();
callbacks.produce_report = Arc::new(move |_, control| {
entered_copy.notify_one();
loop {
if let Err(error) = control.check() {
stopped_copy.store(true, Ordering::SeqCst);
return Err(error);
}
std::thread::sleep(Duration::from_millis(10));
}
});
callbacks.report_submitted = Arc::new(|_, _| panic!("Cancelled report must not be observed"));
let stop = cancellation.clone();
let exit = tokio::time::timeout(
Duration::from_secs(2),
run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
cancellation,
async {
entered.notified().await;
stop.cancel();
pending().await
},
),
)
.await
.unwrap()
.unwrap();
assert_eq!(exit, SessionExit::Disconnected);
assert!(stopped.load(Ordering::SeqCst));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn all_rejected_members_are_logged_out_before_terminal_failure() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Denied</error></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.produce_report = Arc::new(|_, _| panic!("Rejected member cannot collect a report"));
let exit = run_owned_sessions(
vec![member("rejected", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn invalid_member_cookie_cancels_and_joins_another_members_collector() {
let arrived = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let collecting = Arc::new(Notify::new());
let stopped = Arc::new(AtomicBool::new(false));
let (expired, expired_server) = crate::session::transport::tests::gateway_with_first_response_gate(
vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
response("<response status='success'/>"),
],
arrived.clone(),
release.clone(),
)
.await;
let (healthy, healthy_server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
let collecting_copy = collecting.clone();
let stopped_copy = stopped.clone();
callbacks.produce_report = Arc::new(move |request, control| {
assert_eq!(request.gateway.name(), "collecting");
collecting_copy.notify_one();
loop {
if let Err(error) = control.check() {
stopped_copy.store(true, Ordering::SeqCst);
return Err(error);
}
std::thread::sleep(Duration::from_millis(10));
}
});
callbacks.report_submitted = Arc::new(|_, _| panic!("Interrupted collection must not submit"));
let exit = tokio::time::timeout(
Duration::from_secs(2),
run_owned_sessions(
vec![member("expired", expired), member("collecting", healthy)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
async {
arrived.notified().await;
collecting.notified().await;
release.notify_one();
pending().await
},
),
)
.await
.unwrap()
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
assert!(stopped.load(Ordering::SeqCst));
assert_eq!(expired_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn failed_submission_is_terminal_without_retry_or_observation() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.report_submitted = Arc::new(|_, _| panic!("Failed report must not be retained"));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
let requests = server.await.unwrap();
assert_eq!(
requests.iter().map(|request| request.0.as_str()).collect::<Vec<_>>(),
[
"/ssl-vpn/hipreportcheck.esp",
"/ssl-vpn/hipreport.esp",
"/ssl-vpn/logout.esp"
]
);
}
#[tokio::test]
async fn schedules_from_send_time_plus_interval_and_server_delay() {
let arrived = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let (transport, server) = crate::session::transport::tests::gateway_with_first_response_gate(
vec![
response("<response><hip-report-needed>no</hip-report-needed><delay>7</delay></response>"),
response("<response><hip-report-needed>no</hip-report-needed></response>"),
response("<response status='success'/>"),
],
arrived.clone(),
release.clone(),
)
.await;
let cancellation = CancellationToken::new();
let stop = cancellation.clone();
let (sent, mut received) = tokio::sync::mpsc::unbounded_channel();
let mut callbacks = callbacks();
callbacks.status_changed = Arc::new(move |summary| {
if summary.maintenance == MaintenanceState::Healthy {
sent.send(tokio::time::Instant::now()).unwrap();
}
});
let runtime = tokio::spawn(run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::new(10, false).unwrap(),
callbacks,
cancellation,
pending(),
));
arrived.notified().await;
// Simulate three seconds spent waiting for the first response. The interval
// must be anchored before that latency, rather than after completion.
tokio::time::pause();
tokio::time::advance(Duration::from_secs(3)).await;
tokio::time::resume();
release.notify_one();
let first = received.recv().await.unwrap();
tokio::time::pause();
tokio::time::advance(Duration::from_secs(13)).await;
tokio::time::resume();
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(received.try_recv().is_err(), "Server delay must extend the interval");
tokio::time::pause();
tokio::time::advance(Duration::from_secs(1)).await;
tokio::time::resume();
let second = tokio::time::timeout(Duration::from_millis(500), received.recv())
.await
.unwrap()
.unwrap();
let elapsed = second.duration_since(first);
assert!(
elapsed >= Duration::from_millis(13_900) && elapsed < Duration::from_millis(14_500),
"Unexpected anchored interval: {elapsed:?}"
);
stop.cancel();
assert_eq!(runtime.await.unwrap().unwrap(), SessionExit::Disconnected);
assert_eq!(server.await.unwrap().len(), 3);
}
+335
View File
@@ -0,0 +1,335 @@
use std::{net::IpAddr, time::Duration};
use reqwest::{Client, StatusCode, Url, redirect::Policy};
use xmltree::Element;
use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt};
use super::{GatewayAuthentication, network::GatewayBinding};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const MAX_GATEWAY_RESPONSE_BYTES: usize = 1024 * 1024;
pub const MAX_HIP_REPORT_BYTES: usize = 1024 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum GatewayRequestError {
#[error("Gateway authentication cookie expired")]
InvalidCookie,
#[error("Gateway request failed: {0}")]
Transport(#[from] reqwest::Error),
#[error("Gateway returned HTTP {0}")]
Http(StatusCode),
#[error("Gateway rejected the request")]
Rejected,
#[error("Gateway returned a malformed response")]
MalformedResponse,
#[error("Gateway response exceeds its size limit")]
ResponseTooLarge,
#[error("HIP report is empty, contains NUL, or exceeds its size limit")]
InvalidReport,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HipCheck {
pub report_needed: bool,
pub delay: Duration,
}
/// Authenticated HTTP requests retain the login identity. Non-tunnel maintenance
/// uses a validated physical binding; pre-tunnel cleanup uses ordinary HTTP.
pub struct GatewayTransport {
client: Client,
origin: Url,
authentication: GatewayAuthentication,
profile: OsProfile,
}
impl GatewayTransport {
pub fn new(
server: &str,
authentication: GatewayAuthentication,
params: &GpParams,
binding: Option<&GatewayBinding>,
) -> anyhow::Result<Self> {
let origin = Url::parse(&crate::utils::normalize_server(server)?)?;
let client = match binding {
Some(binding) => bound_client(server, params, binding)?,
None => Client::try_from(params)?,
};
Ok(Self {
client,
origin,
authentication,
profile: params.os_profile().clone(),
})
}
/// The login client already validated and built this transport before issuing
/// authentication. Registering its cleanup context cannot fail afterwards.
pub(crate) fn from_authenticated_login(
client: Client,
origin: Url,
authentication: GatewayAuthentication,
profile: OsProfile,
) -> Self {
Self {
client,
origin,
authentication,
profile,
}
}
pub fn authentication(&self) -> &GatewayAuthentication {
&self.authentication
}
pub fn hip_token(&self) -> String {
hip_token(self.authentication.cookie())
}
pub async fn check_hip(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Result<HipCheck, GatewayRequestError> {
let mut form = self.hip_form(ipv4, ipv6);
form.push(("md5".into(), self.hip_token()));
parse_hip_check(&self.post("hipreportcheck.esp", &form).await?)
}
pub async fn submit_hip(
&self,
report: &str,
ipv4: Option<IpAddr>,
ipv6: Option<IpAddr>,
) -> Result<(), GatewayRequestError> {
if report.is_empty() || report.len() > MAX_HIP_REPORT_BYTES || report.contains('\0') {
return Err(GatewayRequestError::InvalidReport);
}
let mut form = self.hip_form(ipv4, ipv6);
form.push(("report".into(), report.into()));
self.post("hipreport.esp", &form).await?;
Ok(())
}
pub async fn logout(&self) -> Result<(), GatewayRequestError> {
logout_cookie(&self.client, &self.origin, self.authentication.cookie(), &self.profile).await
}
fn cookie_form(&self) -> Vec<(String, String)> {
url::form_urlencoded::parse(self.authentication.cookie().as_bytes())
.into_owned()
.collect()
}
fn hip_form(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Vec<(String, String)> {
let mut form = self.cookie_form();
set_form(&mut form, "client-role", "global-protect-full");
set_form(&mut form, "computer", self.profile.computer());
set_form(&mut form, "host-id", self.profile.host_id());
set_form(&mut form, "serialno", self.profile.serialno());
if let Some(ip) = ipv4 {
set_form(&mut form, "client-ip", &ip.to_string());
}
if let Some(ip) = ipv6 {
set_form(&mut form, "client-ipv6", &ip.to_string());
}
form
}
async fn post(&self, endpoint: &str, form: &[(String, String)]) -> Result<Element, GatewayRequestError> {
post(&self.client, &self.origin, endpoint, form).await
}
}
/// Cleanup uses trustworthy issued cookie fields even when execution mode is
/// invalid. It never creates a runnable authentication with a fabricated mode.
pub(crate) async fn logout_cookie(
client: &Client,
origin: &Url,
cookie: &str,
profile: &OsProfile,
) -> Result<(), GatewayRequestError> {
let mut form = url::form_urlencoded::parse(cookie.as_bytes()).into_owned().collect();
set_form(&mut form, "computer", profile.computer());
set_form(&mut form, "clientos", profile.client_os().as_str());
set_form(&mut form, "os-version", profile.os_version());
post(client, origin, "logout.esp", &form).await?;
Ok(())
}
async fn post(
client: &Client,
origin: &Url,
endpoint: &str,
form: &[(String, String)],
) -> Result<Element, GatewayRequestError> {
let mut url = origin.clone();
url.set_path(&format!("/ssl-vpn/{endpoint}"));
let response = client.post(url).form(form).send().await?;
let status = response.status();
let invalid_cookie = status.as_u16() == 512
|| response
.headers()
.get("x-private-pan-globalprotect")
.is_some_and(|value| value == "Invalid authentication cookie");
if invalid_cookie {
return Err(GatewayRequestError::InvalidCookie);
}
if !status.is_success() {
return Err(GatewayRequestError::Http(status));
}
let body = crate::utils::request::read_bounded_response(response, MAX_GATEWAY_RESPONSE_BYTES)
.await
.map_err(|error| match error {
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
})?;
parse_response(&body)
}
pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result<Client> {
binding.validate_server(server)?;
let origin = gateway_origin(server)?;
let host = origin
.host_str()
.ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?;
let builder = params
.client_builder()?
.redirect(Policy::none())
.no_proxy()
.local_address(binding.source().ip())
.resolve(host, binding.endpoint())
.timeout(REQUEST_TIMEOUT);
let builder = bind_interface(builder, binding)?;
Ok(builder.build()?)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
Ok(builder.interface(binding.interface()))
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!(
source.scope_id() == 0,
"Scoped IPv6 source requires a native socket connector"
);
}
Ok(builder)
}
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
let server = if server.starts_with("https://") {
server.to_owned()
} else {
format!("https://{server}")
};
let origin = Url::parse(&server)?;
anyhow::ensure!(
origin.scheme() == "https"
&& origin.username().is_empty()
&& origin.password().is_none()
&& origin.path() == "/"
&& origin.query().is_none()
&& origin.fragment().is_none(),
"Gateway endpoint must be an HTTPS origin"
);
Ok(origin)
}
fn set_form(form: &mut Vec<(String, String)>, key: &str, value: &str) {
form.retain(|(name, _)| name != key);
form.push((key.into(), value.into()));
}
/// Match gpst.c::build_csd_token without decoding or reordering cookie fields.
pub fn hip_token(cookie: &str) -> String {
let stable = cookie
.split('&')
.filter(|field| {
let key = field.split('=').next().unwrap_or_default();
!matches!(key, "authcookie" | "preferred-ip" | "preferred-ipv6")
})
.collect::<Vec<_>>()
.join("&");
format!("{:x}", md5::compute(stable.as_bytes()))
}
fn parse_response(body: &[u8]) -> Result<Element, GatewayRequestError> {
let text = std::str::from_utf8(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
let lower = text.to_ascii_lowercase();
if lower.contains("<!doctype") || lower.contains("<!entity") {
return Err(GatewayRequestError::MalformedResponse);
}
if let Some(error) = javascript_error(text) {
return Err(error);
}
let root = Element::parse(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
if root.name == "html" {
return Err(
root
.descendant_text("body")
.as_deref()
.and_then(javascript_error)
.unwrap_or(GatewayRequestError::MalformedResponse),
);
}
if root.name == "prelogin-response" && root.child_text("status").as_deref() == Some("Error") {
return Err(message_error(root.child_text("msg").as_deref()));
}
if root.name != "response" {
return Err(GatewayRequestError::MalformedResponse);
}
match root.attr("status") {
Some("error") => Err(message_error(root.child_text("error").as_deref())),
None | Some("success") => Ok(root),
_ => Err(GatewayRequestError::Rejected),
}
}
fn message_error(message: Option<&str>) -> GatewayRequestError {
if message == Some("Invalid authentication cookie") {
GatewayRequestError::InvalidCookie
} else {
GatewayRequestError::Rejected
}
}
fn javascript_error(text: &str) -> Option<GatewayRequestError> {
static ERROR: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let regex = ERROR.get_or_init(|| {
regex::Regex::new(r#"(?s)^\s*var\s+respStatus\s*=\s*"Error"\s*;\s*var\s+respMsg\s*=\s*("(?:\\.|[^"\\])*")"#)
.expect("valid GlobalProtect error pattern")
});
let captures = regex.captures(text)?;
match serde_json::from_str::<String>(&captures[1]) {
Ok(message) => Some(message_error(Some(&message))),
Err(_) => Some(GatewayRequestError::MalformedResponse),
}
}
fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
let report_needed = match root.child_text("hip-report-needed").as_deref() {
Some("yes") => true,
Some("no") => false,
_ => return Err(GatewayRequestError::MalformedResponse),
};
let delay = match root.child_text("delay") {
Some(value) => value
.parse::<u32>()
.map_err(|_| GatewayRequestError::MalformedResponse)?,
None => 0,
};
// Limit this client's supported response delay to one hour. The official
// registry scheduling cap is not evidence of a wire-protocol maximum.
if delay > 3600 {
return Err(GatewayRequestError::MalformedResponse);
}
Ok(HipCheck {
report_needed,
delay: Duration::from_secs(u64::from(delay)),
})
}
#[cfg(test)]
pub(crate) mod tests;
+246
View File
@@ -0,0 +1,246 @@
use super::*;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
task::JoinHandle,
};
pub(crate) async fn gateway(responses: Vec<String>) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
gateway_fixture(responses, None).await
}
pub(crate) async fn login_gateway(responses: Vec<String>) -> (Client, Url, JoinHandle<Vec<(String, String)>>) {
let (transport, server) = gateway(responses).await;
(transport.client, transport.origin, server)
}
pub(crate) async fn gateway_with_first_response_gate(
responses: Vec<String>,
arrived: std::sync::Arc<tokio::sync::Notify>,
release: std::sync::Arc<tokio::sync::Notify>,
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
gateway_fixture(responses, Some((arrived, release))).await
}
async fn gateway_fixture(
responses: Vec<String>,
gate: Option<(std::sync::Arc<tokio::sync::Notify>, std::sync::Arc<tokio::sync::Notify>)>,
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
let server = tokio::spawn(async move {
let mut requests = Vec::new();
for (index, response) in responses.into_iter().enumerate() {
let (mut stream, _) = listener.accept().await.unwrap();
let mut bytes = Vec::new();
let (headers_end, length) = loop {
let mut chunk = [0; 1024];
let count = stream.read(&mut chunk).await.unwrap();
assert_ne!(count, 0);
bytes.extend_from_slice(&chunk[..count]);
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
let length = headers
.lines()
.find_map(|line| {
let (key, value) = line.split_once(':')?;
key
.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().unwrap())
})
.unwrap();
break (position + 4, length);
}
};
while bytes.len() < headers_end + length {
let mut chunk = [0; 1024];
let count = stream.read(&mut chunk).await.unwrap();
assert_ne!(count, 0);
bytes.extend_from_slice(&chunk[..count]);
}
let path = std::str::from_utf8(&bytes[..headers_end])
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.to_owned();
let body = String::from_utf8(bytes[headers_end..headers_end + length].to_vec()).unwrap();
requests.push((path, body));
if index == 0
&& let Some((arrived, release)) = &gate
{
arrived.notify_one();
release.notified().await;
}
stream.write_all(response.as_bytes()).await.unwrap();
}
requests
});
let transport = GatewayTransport {
client: Client::builder()
.redirect(Policy::none())
.no_proxy()
.timeout(REQUEST_TIMEOUT)
.build()
.unwrap(),
origin,
authentication: GatewayAuthentication::new(
"authcookie=test-cookie&portal=portal&user=alice&domain=example&computer=test".into(),
"non-tunnel".into(),
)
.unwrap(),
profile: OsProfile::builder(crate::os_profile::ClientOs::Linux)
.computer_name_override("test")
.build(),
};
(transport, server)
}
pub(crate) fn response(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
#[test]
fn checksum_matches_c_protocol_golden_fixture() {
for volatile in [
"authcookie=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1",
"authcookie=refreshed&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2",
] {
let cookie =
format!("user=test&{volatile}&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&computer=test");
assert_eq!(hip_token(&cookie), "20f30054f721fd212925866b5778447d");
}
assert_ne!(hip_token("user=alice%20bob"), hip_token("user=alice+bob"));
assert_ne!(hip_token("user=alice&portal=a"), hip_token("portal=a&user=alice"));
}
#[tokio::test]
async fn maintenance_uses_only_hip_and_logout_with_physical_identity() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed><delay>7</delay></response>"),
response("<response status='success'/>"),
response("<response status='success'/>"),
])
.await;
let ipv4 = Some("192.0.2.7".parse().unwrap());
let ipv6 = Some("2001:db8::7".parse().unwrap());
let check = transport.check_hip(ipv4, ipv6).await.unwrap();
assert_eq!(
check,
HipCheck {
report_needed: true,
delay: Duration::from_secs(7)
}
);
transport.submit_hip("<hip-report/>", ipv4, ipv6).await.unwrap();
transport.logout().await.unwrap();
let requests = server.await.unwrap();
assert_eq!(
requests.iter().map(|(path, _)| path.as_str()).collect::<Vec<_>>(),
[
"/ssl-vpn/hipreportcheck.esp",
"/ssl-vpn/hipreport.esp",
"/ssl-vpn/logout.esp"
]
);
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[0].1).unwrap();
assert_eq!(form["authcookie"], "test-cookie");
assert_eq!(form["client-ip"], "192.0.2.7");
assert_eq!(form["client-ipv6"], "2001:db8::7");
assert_eq!(form["md5"], transport.hip_token());
}
#[tokio::test]
async fn rejects_redirects_without_forwarding_authentication() {
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
let (transport, server) = gateway(vec![format!(
"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{}/stolen\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
destination.local_addr().unwrap()
)])
.await;
assert!(
matches!(transport.check_hip(None, None).await, Err(GatewayRequestError::Http(status)) if status.as_u16() == 307)
);
assert!(
tokio::time::timeout(Duration::from_millis(100), destination.accept())
.await
.is_err()
);
assert_eq!(server.await.unwrap().len(), 1);
}
#[tokio::test]
async fn distinguishes_expired_cookie_from_transport_and_protocol_errors() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
"HTTP/1.1 512 Invalid Cookie\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
response("<response><hip-report-needed>maybe</hip-report-needed></response>"),
response("<response status='error'><error>server-private-payload</error></response>"),
])
.await;
for _ in 0..2 {
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::InvalidCookie)
));
}
assert!(matches!(
transport.check_hip(None, None).await.unwrap_err(),
GatewayRequestError::Http(StatusCode::SERVICE_UNAVAILABLE)
));
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::MalformedResponse)
));
let error = transport.check_hip(None, None).await.unwrap_err();
assert!(!format!("{error:?}").contains("server-private-payload"));
server.await.unwrap();
}
#[tokio::test]
async fn bounds_response_size_before_reading_body() {
let (transport, server) = gateway(vec![format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
MAX_GATEWAY_RESPONSE_BYTES + 1
)])
.await;
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::ResponseTooLarge)
));
server.await.unwrap();
}
#[test]
fn rejects_invalid_delays_and_unsafe_response_xml() {
for delay in ["-1", "3601", "4294967296", "invalid"] {
let root = parse_response(
format!("<response><hip-report-needed>no</hip-report-needed><delay>{delay}</delay></response>").as_bytes(),
)
.unwrap();
assert!(parse_hip_check(&root).is_err());
}
assert!(parse_response(b"<!DOCTYPE response><response/>").is_err());
}
#[test]
fn recognizes_cookie_expiry_in_official_error_formats() {
for body in [
r#"var respStatus = "Error"; var respMsg = "Invalid authentication\u0020cookie"; thisForm.inputStr.value = "";"#,
r#"<html><head/><body>var respStatus = "Error"; var respMsg = "Invalid authentication cookie";</body></html>"#,
"<prelogin-response><status>Error</status><msg>Invalid authentication cookie</msg></prelogin-response>",
] {
assert!(matches!(
parse_response(body.as_bytes()),
Err(GatewayRequestError::InvalidCookie)
));
}
assert!(matches!(
parse_response(b"<response status='error'><error>Denied</error></response>"),
Err(GatewayRequestError::Rejected)
));
}
+427 -56
View File
@@ -1,10 +1,9 @@
use std::{borrow::Cow, fs};
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::bail;
use log::warn;
use openssl::pkey::PKey;
use pem::parse_many;
use anyhow::{Context, ensure};
use openssl::{pkey::PKey, x509::X509};
use reqwest::Identity;
use zeroize::Zeroizing;
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
@@ -16,72 +15,419 @@ pub enum RequestIdentityError {
DecryptError(&'static str),
}
/// Create an identity object from a certificate and key
/// The file is expected to be the PKCS#8 PEM or PKCS#12 format
/// When using a PKCS#12 file, the key is NOT required, but a passphrase is required
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
if cert.ends_with(".p12") || cert.ends_with(".pfx") {
create_identity_from_pkcs12(cert, passphrase)
} else {
create_identity_from_pem(cert, key, passphrase)
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
/// retains its original bytes and passphrase so each native backend imports the
/// same identity and chain. Debug never exposes retained material.
#[derive(Clone)]
pub struct ClientIdentity {
material: Arc<IdentityMaterial>,
identity: Identity,
}
struct IdentityMaterial {
certificate: Zeroizing<Vec<u8>>,
key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<Zeroizing<String>>,
}
impl fmt::Debug for ClientIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientIdentity")
.field("material", &"<redacted>")
.finish()
}
}
fn create_identity_from_pem(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
let cert_pem = fs::read(cert).map_err(|err| anyhow::anyhow!("Failed to read certificate file: {}", err))?;
impl ClientIdentity {
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
let certificate_bytes = read_identity_file(certificate)?;
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
return Self::from_data(certificate_bytes, None, Some(passphrase));
}
let key_bytes = match key {
Some(path) => read_identity_file(path)?,
None => certificate_bytes.clone(),
};
// Keep the previous first-private-key rule: unrelated later blocks must not
// change which key is selected or whether the caller is prompted.
let key = pem::parse_many(&*key_bytes)?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
let key_pem = Zeroizing::new(pem::encode(&key));
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
} else {
Zeroizing::new(key_pem.as_bytes().to_vec())
};
// Strip private-key blocks before importing the certificate chain: macOS
// otherwise imports the same key twice for combined PEM files.
let mut certificate = Zeroizing::new(Vec::new());
for cert in X509::stack_from_pem(&certificate_bytes)? {
certificate.extend(cert.to_pem()?);
}
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
key: Some(key),
passphrase: None,
}),
identity,
})
}
// Use the certificate as the key if no key is provided
let key_pem_file = match key {
Some(key) => Cow::Owned(fs::read(key).map_err(|err| anyhow::anyhow!("Failed to read key file: {}", err))?),
None => Cow::Borrowed(&cert_pem),
};
/// A separate key denotes decrypted PEM; no separate key denotes original
/// PKCS#12 bytes. Input-size limits belong to the service transport boundary.
pub fn from_data(
certificate: Zeroizing<Vec<u8>>,
key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key {
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
None => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
(
Identity::from_pkcs12_der(&certificate, passphrase)?,
Some(Zeroizing::new(passphrase.to_owned())),
)
}
};
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
key,
passphrase,
}),
identity,
})
}
// Find the private key in the pem file
let key_pem = parse_many(key_pem_file.as_ref())?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
pub fn certificate_data(&self) -> &[u8] {
&self.material.certificate
}
pub fn key_data(&self) -> Option<&[u8]> {
self.material.key.as_ref().map(|key| key.as_slice())
}
pub fn key_password(&self) -> Option<&str> {
self.material.passphrase.as_ref().map(|value| value.as_str())
}
pub(crate) fn request_identity(&self) -> Identity {
self.identity.clone()
}
// The key pem could be encrypted, so we need to decrypt it
let decrypted_key_pem = if key_pem.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or_else(|| {
warn!("Key is encrypted but no passphrase provided");
RequestIdentityError::NoPassphrase("PEM")
})?;
let pem_content = pem::encode(&key_pem);
let key = PKey::private_key_from_pem_passphrase(pem_content.as_bytes(), passphrase.as_bytes()).map_err(|err| {
warn!("Failed to decrypt key: {}", err);
RequestIdentityError::DecryptError("PEM")
})?;
key.private_key_to_pem_pkcs8()?
} else {
pem::encode(&key_pem).into()
};
let identity = Identity::from_pkcs8_pem(&cert_pem, &decrypted_key_pem)?;
Ok(identity)
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
let suffix = if self.material.key.is_some() { ".pem" } else { ".p12" };
let certificate = write_identity_file(self.certificate_data(), directory, suffix)?;
let key = self
.key_data()
.map(|key| write_identity_file(key, directory, ".pem"))
.transpose()?;
Ok(ClientIdentityFiles { certificate, key })
}
}
fn create_identity_from_pkcs12(pkcs12: &str, passphrase: Option<&str>) -> anyhow::Result<Identity> {
let pkcs12 = fs::read(pkcs12)?;
/// Named files are private and remain owned until native workers and logout
/// finish. The original configured files are never reopened by these workers.
pub struct ClientIdentityFiles {
certificate: tempfile::NamedTempFile,
key: Option<tempfile::NamedTempFile>,
}
let Some(passphrase) = passphrase else {
bail!(RequestIdentityError::NoPassphrase("PKCS#12"));
impl ClientIdentityFiles {
pub fn certificate(&self) -> &str {
self.certificate.path().to_str().expect("identity path is UTF-8")
}
pub fn key(&self) -> Option<&str> {
self
.key
.as_ref()
.map(|key| key.path().to_str().expect("identity path is UTF-8"))
}
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?,
))
}
fn write_identity_file(
bytes: &[u8],
directory: Option<&Path>,
suffix: &str,
) -> anyhow::Result<tempfile::NamedTempFile> {
let mut builder = tempfile::Builder::new();
builder.prefix("gp-identity-").suffix(suffix);
let mut file = match directory {
Some(directory) => builder.tempfile_in(directory)?,
None => builder.tempfile()?,
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
}
ensure!(file.path().to_str().is_some(), "Client identity path is not UTF-8");
file.write_all(bytes)?;
file.flush()?;
Ok(file)
}
let identity = Identity::from_pkcs12_der(&pkcs12, passphrase)?;
Ok(identity)
/// General request clients may load an identity directly. Session owners call
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::pkcs12::Pkcs12;
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "identity-fixture").unwrap();
let name = name.build();
let mut certificate = X509::builder().unwrap();
certificate.set_version(2).unwrap();
certificate.set_subject_name(&name).unwrap();
certificate.set_issuer_name(&name).unwrap();
certificate.set_pubkey(&key).unwrap();
certificate
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
.unwrap();
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
certificate.sign(&key, MessageDigest::sha256()).unwrap();
(
certificate.build().to_pem().unwrap(),
key.private_key_to_pem_pkcs8().unwrap(),
)
}
#[test]
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
let (certificate, key) = generated_identity();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
.unwrap();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&encrypted).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.key_data().unwrap(), key);
}
#[test]
fn pem_without_key_reports_missing_key_even_with_passphrase() {
let (certificate, _) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
for passphrase in [None, Some("unused")] {
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
assert!(matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::NoKey)
));
}
}
#[test]
fn local_identity_loading_is_not_limited_by_service_message_size() {
let (certificate, key) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
}
#[test]
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
let (certificate, key) = generated_identity();
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
cert_file.write_all(&certificate).unwrap();
let mut key_file = tempfile::NamedTempFile::new().unwrap();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
.unwrap();
key_file.write_all(&encrypted).unwrap();
let cert = cert_file.path().to_str().unwrap();
let key_path = Some(key_file.path().to_str().unwrap());
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
match error.downcast_ref::<RequestIdentityError>().unwrap() {
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
other => panic!("Unexpected identity error: {other}"),
}
}
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
assert_eq!(loaded.key_data().unwrap(), key);
fs::write(key_file.path(), &key).unwrap();
for passphrase in [None, Some("ignored for unencrypted key")] {
assert_eq!(
ClientIdentity::load(cert, key_path, passphrase)
.unwrap()
.key_data()
.unwrap(),
key
);
}
}
#[test]
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
use std::os::unix::fs::PermissionsExt;
let (certificate, key) = generated_identity();
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("combined.pem");
let mut combined = certificate.clone();
combined.extend(&key);
fs::write(&source, &combined).unwrap();
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
fs::write(&source, "changed after authentication").unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
let files = identity.write_files(Some(directory.path())).unwrap();
let certificate_path = files.certificate().to_owned();
let key_path = files.key().unwrap().to_owned();
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
assert_eq!(fs::read(&key_path).unwrap(), key);
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&certificate_path).exists());
assert!(!Path::new(&key_path).exists());
// The request identity remains valid after its original files disappear.
fs::remove_file(&source).unwrap();
reqwest::Client::builder()
.identity(identity.request_identity())
.build()
.unwrap();
}
#[test]
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
let (certificate, key) = generated_identity();
let certificate = X509::from_pem(&certificate).unwrap();
let key = PKey::private_key_from_pem(&key).unwrap();
let mut builder = Pkcs12::builder();
builder.name("identity-fixture").pkey(&key).cert(&certificate);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
for suffix in [".p12", ".pfx"] {
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
source.write_all(&encoded).unwrap();
let path = source.path().to_str().unwrap();
assert!(ClientIdentity::load(path, None, None).is_err());
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
// PKCS#12 has always ignored a separately configured key path.
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
fs::write(source.path(), b"replaced after login").unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
assert_eq!(identity.key_password(), Some("fixture-password"));
assert!(!format!("{identity:?}").contains("fixture-password"));
let files = identity.write_files(None).unwrap();
assert!(files.certificate().ends_with(".p12"));
assert!(files.key().is_none());
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
let owned_path = files.certificate().to_owned();
drop(files);
assert!(!Path::new(&owned_path).exists());
}
let empty_password = builder.build2("").unwrap().to_der().unwrap();
// Empty-password support varies by native backend and PKCS#12 algorithms.
// Match the previous native import instead of introducing another parser.
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
assert_eq!(
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
previously_accepted
);
}
#[test]
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
rsa::Rsa,
stack::Stack,
x509::{X509NameBuilder, extension::BasicConstraints},
};
fn certificate(
name: &str,
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
ca: bool,
) -> (X509, PKey<openssl::pkey::Private>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut subject = X509NameBuilder::new().unwrap();
subject.append_entry_by_text("CN", name).unwrap();
let subject = subject.build();
let mut cert = X509::builder().unwrap();
cert.set_version(2).unwrap();
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
.unwrap()
.to_asn1_integer()
.unwrap();
cert.set_serial_number(&serial).unwrap();
cert.set_subject_name(&subject).unwrap();
cert
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
.unwrap();
cert.set_pubkey(&key).unwrap();
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
if ca {
cert
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
.unwrap();
}
cert
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
.unwrap();
(cert.build(), key)
}
let (root, root_key) = certificate("root", None, true);
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
// This is the reverse CA stack consumed by the previous native-tls path.
let mut ca = Stack::new().unwrap();
ca.push(root.clone()).unwrap();
ca.push(intermediate.clone()).unwrap();
let mut builder = Pkcs12::builder();
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
source.write_all(&encoded).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
ClientIdentity::from_data(
Zeroizing::new(identity.certificate_data().to_vec()),
None,
identity.key_password(),
)
.unwrap();
}
#[test]
fn create_identity_from_pem_requires_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let identity = create_identity_from_pem(cert, None, None);
let identity = create_identity(cert, None, None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
@@ -93,7 +439,7 @@ mod tests {
let cert = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity_from_pem(cert, None, Some(passphrase));
let identity = create_identity(cert, None, Some(passphrase));
assert!(identity.is_ok());
}
@@ -102,7 +448,7 @@ mod tests {
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_unencrypted_key() {
let cert = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity_from_pem(cert, None, None);
let identity = create_identity(cert, None, None);
println!("{:?}", identity);
assert!(identity.is_ok());
@@ -115,7 +461,7 @@ mod tests {
let key = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity_from_pem(cert, Some(key), Some(passphrase));
let identity = create_identity(cert, Some(key), Some(passphrase));
assert!(identity.is_ok());
}
@@ -125,7 +471,7 @@ mod tests {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let identity = create_identity_from_pem(cert, Some(key), None);
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
@@ -137,8 +483,33 @@ mod tests {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity_from_pem(cert, Some(key), None);
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_ok());
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ResponseBodyError {
#[error("Response read failed: {0}")]
Transport(#[from] reqwest::Error),
#[error("Response exceeds its size limit")]
TooLarge,
}
pub(crate) async fn read_bounded_response(
mut response: reqwest::Response,
limit: usize,
) -> Result<Vec<u8>, ResponseBodyError> {
if response.content_length().is_some_and(|length| length > limit as u64) {
return Err(ResponseBodyError::TooLarge);
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await? {
if chunk.len() > limit.saturating_sub(body.len()) {
return Err(ResponseBodyError::TooLarge);
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
+64
View File
@@ -212,6 +212,33 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
generate_report_with_control(input, &budget)
}
/// Identity-only maintenance report. This deliberately does not enumerate the
/// machine or execute posture collectors; addresses come from the session owner.
pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
let params = cookie_params(input);
let mut report = Element::new("hip-report");
for (name, value) in [
("md5-sum", input.context.md5()),
("user-name", report_user_name(input, &params)),
("domain", params.get("domain").map(String::as_str).unwrap_or_default()),
("host-name", input.profile.computer()),
("host-id", input.profile.host_id()),
("ip-address", input.context.client_ip().unwrap_or_default()),
("ipv6-address", input.context.client_ipv6().unwrap_or_default()),
("hip-report-version", "4"),
] {
let mut field = Element::new(name);
field.children.push(xmltree::XMLNode::Text(value.to_owned()));
report.children.push(xmltree::XMLNode::Element(field));
}
let mut timestamp = Element::new("generate-time");
timestamp
.children
.push(xmltree::XMLNode::Text(get_current_time_components().0));
report.children.push(xmltree::XMLNode::Element(timestamp));
write_xml(&report)
}
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
control.check()?;
let cookie_params = cookie_params(input);
@@ -727,6 +754,43 @@ mod tests {
OsProfileBuilder::new(client_os).build()
}
#[test]
fn identity_report_contains_session_identity_without_posture() {
for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
let mut input = make_input(make_profile(os));
input.context = ReportContext::Connected {
cookie: "user=alice%26bob&domain=example".into(),
client_ip: Some("192.0.2.7".into()),
client_ipv6: Some("2001:db8::7".into()),
md5: "identity-token".into(),
};
let xml = generate_identity_report(&input).unwrap();
let root = Element::parse(xml.as_bytes()).unwrap();
assert_eq!(
unique_child(&root, "user-name").unwrap().get_text().unwrap(),
"alice&bob"
);
assert_eq!(
unique_child(&root, "ip-address").unwrap().get_text().unwrap(),
"192.0.2.7"
);
assert_eq!(
unique_child(&root, "ipv6-address").unwrap().get_text().unwrap(),
"2001:db8::7"
);
assert_eq!(
unique_child(&root, "host-id").unwrap().get_text().unwrap(),
input.profile.host_id()
);
assert_eq!(
unique_child(&root, "md5-sum").unwrap().get_text().unwrap(),
"identity-token"
);
assert!(root.get_child("categories").is_none());
assert!(!xml.contains("ProductInfo"));
}
}
#[test]
fn host_info_os_vendor_is_linux_for_linux_profile() {
let input = make_input(make_profile(ClientOs::Linux));
+87 -11
View File
@@ -127,10 +127,29 @@ pub(crate) extern "C" fn generate_hip_report(
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let vpn = unsafe { &*(data as *const Vpn) };
generate_source_report(
vpn.hip_source.as_ref() as *const HipSource as *mut _,
request,
control,
output,
capacity,
written,
)
}
extern "C" fn generate_source_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
let vpn = unsafe { &*(data as *const Vpn) };
let HipSource::Generator(generate) = &vpn.hip_source else {
let source = unsafe { &*(data as *const HipSource) };
let HipSource::Generator(generate) = source else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
};
let request = unsafe { read_hip_request(&*request)? };
@@ -175,7 +194,28 @@ extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlR
Err(_) => -libc::EIO,
}
}
pub(crate) fn preview_hip_script(
pub(crate) fn collect_hip_source(
source: &HipSource,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
match source {
HipSource::Disabled => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP collection is disabled",
)),
HipSource::Script(script) => collect_hip_script(script, request, check),
HipSource::Generator(_) => collect_hip_report(
&HipScriptRaw::default(),
Some(generate_source_report),
source as *const _ as *mut _,
request,
check,
),
}
}
pub(crate) fn collect_hip_script(
script: &HipScript,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
@@ -224,7 +264,7 @@ fn collect_hip_report(
};
let control = HipControlRaw {
data: &check as *const _ as *mut _,
check: preview_check,
check: collection_check,
};
let mut output = vec![0u8; 1024 * 1024 + 1];
let mut written = 0;
@@ -246,7 +286,7 @@ fn collect_hip_report(
output.truncate(written);
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
}
unsafe extern "C" fn preview_check(data: *mut c_void) -> c_int {
unsafe extern "C" fn collection_check(data: *mut c_void) -> c_int {
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
match catch_unwind(AssertUnwindSafe(check)) {
Ok(Ok(())) => 0,
@@ -305,6 +345,42 @@ mod hip_tests {
}
}
#[test]
fn standalone_source_uses_bounded_executor_without_a_vpn() {
let source = HipSource::Generator(std::sync::Arc::new(|request, control| {
control.check()?;
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.42"));
assert_eq!(request.md5, "physical-session-token");
Ok("<hip-report/>".into())
}));
let request = HipRequest {
client_ip: Some("192.0.2.42".into()),
md5: "physical-session-token".into(),
..Default::default()
};
assert_eq!(source.collect(&request, &|| Ok(())).unwrap(), "<hip-report/>");
let too_large = HipSource::Generator(std::sync::Arc::new(|_, _| Ok("x".repeat(1024 * 1024 + 1))));
assert_eq!(
too_large.collect(&request, &|| Ok(())).unwrap_err().raw_os_error(),
Some(libc::E2BIG)
);
assert!(HipSource::Disabled.collect(&request, &|| Ok(())).is_err());
}
#[test]
fn standalone_source_checks_cancellation_before_generation() {
let source = HipSource::Generator(std::sync::Arc::new(|_, _| panic!("Cancelled source must not run")));
assert_eq!(
source
.collect(&HipRequest::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn callback_outputs_are_bounded_and_validated_by_c() {
let raw = HipScriptRaw::default();
@@ -355,7 +431,7 @@ mod hip_tests {
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
let script = fixture.script(Some(unsafe { libc::getuid() }));
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
assert_eq!(script.preview(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
assert_eq!(script.collect(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
}
#[test]
fn validator_refusal_prevents_execution_and_errors_propagate() {
@@ -365,7 +441,7 @@ mod hip_tests {
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EPERM)
@@ -374,7 +450,7 @@ mod hip_tests {
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
assert_eq!(
script
.preview(&HipRequest::default(), &|| Ok(()))
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
@@ -392,7 +468,7 @@ mod hip_tests {
})
.unwrap();
assert_eq!(
script.preview(&HipRequest::default(), &|| Ok(())).unwrap(),
script.collect(&HipRequest::default(), &|| Ok(())).unwrap(),
format!("child:{cwd}")
);
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
@@ -404,7 +480,7 @@ mod hip_tests {
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &|| Ok(()))
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EINVAL)
@@ -426,7 +502,7 @@ mod hip_tests {
assert_eq!(
fixture
.script(None)
.preview(&HipRequest::default(), &check)
.collect(&HipRequest::default(), &check)
.unwrap_err()
.raw_os_error(),
Some(errno)
+3 -1
View File
@@ -1,7 +1,9 @@
mod hip;
use crate::Vpn;
use hip::HipGenerateFn;
pub(crate) use hip::{HipControlRaw, HipScriptRaw, generate_hip_report, preview_hip_script, script_environment};
pub(crate) use hip::{
HipControlRaw, HipScriptRaw, collect_hip_script, collect_hip_source, generate_hip_report, script_environment,
};
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
+10 -2
View File
@@ -13,6 +13,14 @@ pub enum HipSource {
Script(HipScript),
}
impl HipSource {
/// Collect through the same bounded executor used by tunnel submissions.
/// Disabled posture is a caller policy; this method never invents a report.
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_source(self, request, check)
}
}
/// Current gateway and negotiated identity inputs for one report invocation.
#[derive(Clone, Default)]
pub struct HipRequest {
@@ -105,8 +113,8 @@ impl HipScript {
}
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
pub fn preview(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::preview_hip_script(self, request, check)
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_script(self, request, check)
}
}
+10 -10
View File
@@ -119,7 +119,7 @@ pub struct Vpn {
key_password: Option<CString>,
servercert: Option<CString>,
pub(crate) hip_source: HipSource,
pub(crate) hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -139,7 +139,7 @@ impl Vpn {
}
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
match &self.hip_source {
match self.hip_source.as_ref() {
HipSource::Disabled => info!("HIP reporting: disabled"),
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
HipSource::Script(script) => {
@@ -157,7 +157,7 @@ impl Vpn {
}
self.callback.write().unwrap().replace(Box::new(on_connected));
let mut options = self.build_connect_options();
let environment = match &self.hip_source {
let environment = match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
};
@@ -226,11 +226,11 @@ impl Vpn {
key_password: Self::option_to_ptr(&self.key_password),
servercert: Self::option_to_ptr(&self.servercert),
hip_script: match &self.hip_source {
hip_script: match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
_ => Default::default(),
},
generate_hip: match &self.hip_source {
generate_hip: match self.hip_source.as_ref() {
HipSource::Generator(_) => Some(ffi::generate_hip_report),
_ => None,
},
@@ -290,7 +290,7 @@ pub struct VpnBuilder {
sslkey: Option<String>,
key_password: Option<String>,
hip_source: HipSource,
hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -322,7 +322,7 @@ impl VpnBuilder {
sslkey: None,
key_password: None,
hip_source: HipSource::Disabled,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
@@ -400,8 +400,8 @@ impl VpnBuilder {
self
}
pub fn hip_source(mut self, hip_source: HipSource) -> Self {
self.hip_source = hip_source;
pub fn hip_source(mut self, hip_source: impl Into<Arc<HipSource>>) -> Self {
self.hip_source = hip_source.into();
self
}
@@ -605,7 +605,7 @@ mod tests {
sslkey: None,
key_password: None,
servercert: None,
hip_source: HipSource::Disabled,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
+35 -2
View File
@@ -20,6 +20,8 @@ static int generate(void *data, const struct openconnect_gp_hip_request *request
assert(!strcmp(request->client_version, "6.3.3"));
assert(!strcmp(request->host_id, "test-host"));
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
/* Shared golden fixture with gpapi's non-tunnel HIP transport. */
assert(!strcmp(request->md5, "20f30054f721fd212925866b5778447d"));
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
state->generated++;
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
@@ -87,10 +89,41 @@ static void script_registration_lifecycle(struct openconnect_info *vpninfo)
assert(!vpninfo->csd_wrapper);
}
static int close_count;
static int count_session_close(struct openconnect_info *vpninfo, const char *reason)
{
assert(!strcmp(reason, "fixture exit"));
close_count++;
return 0;
}
static void native_session_logout(void)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("logout owner test",
accept_cert, NULL, NULL, progress, NULL);
const struct vpn_proto *original;
struct vpn_proto protocol;
assert(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
original = vpninfo->proto;
protocol = *original;
protocol.vpn_close_session = count_session_close;
vpninfo->proto = &protocol;
vpninfo->quit_reason = "fixture exit";
/* All exit causes use this same mainloop cleanup path. */
openconnect_mainloop(vpninfo, 0, 0);
assert(close_count == 1);
openconnect_mainloop(vpninfo, 0, 0);
assert(close_count == 2);
vpninfo->proto = original;
openconnect_vpninfo_free(vpninfo);
}
int main(int argc, char **argv) {
struct state state = {0};
struct openconnect_info *vpninfo;
assert(argc == 2);
native_session_logout();
openconnect_init_ssl();
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
assert(vpninfo);
@@ -98,7 +131,7 @@ int main(int argc, char **argv) {
assert(!openconnect_set_protocol(vpninfo, "gp"));
assert(!openconnect_set_reported_os(vpninfo, "linux"));
assert(!openconnect_parse_url(vpninfo, argv[1]));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&portal=test&domain=test&computer=test"));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1&computer=test"));
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
openconnect_disable_dtls(vpninfo);
@@ -110,7 +143,7 @@ int main(int argc, char **argv) {
assert(state.generated == 2 && state.accepted == 2);
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
openconnect_close_https(vpninfo, 0);
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&portal=test&domain=test&computer=test"));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2&computer=test"));
assert(!openconnect_make_cstp_connection(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fourth gateway check says no report needed. */