mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
feat: support internal non-tunnel gateway sessions
This commit is contained in:
58 files changed
+7897
-949
No files matched your search
Generated
+4
@@ -1865,6 +1865,7 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
"url",
|
"url",
|
||||||
"urlencoding",
|
"urlencoding",
|
||||||
"uuid",
|
"uuid",
|
||||||
@@ -1915,6 +1916,7 @@ dependencies = [
|
|||||||
"sysinfo",
|
"sysinfo",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
"uzers",
|
"uzers",
|
||||||
"whoami",
|
"whoami",
|
||||||
]
|
]
|
||||||
@@ -1976,6 +1978,7 @@ dependencies = [
|
|||||||
"mac_address",
|
"mac_address",
|
||||||
"nix 0.31.3",
|
"nix 0.31.3",
|
||||||
"openconnect",
|
"openconnect",
|
||||||
|
"openssl",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha256",
|
"sha256",
|
||||||
@@ -4654,6 +4657,7 @@ checksum = "4ccbb212565d2dc177bc15ecb7b039d66c4490da892436a4eee5b394d620c9bc"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"specta-macros",
|
"specta-macros",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ env_logger.workspace = true
|
|||||||
inquire = "0.9"
|
inquire = "0.9"
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
tokio = { workspace = true, features = ["rt-multi-thread"] }
|
||||||
|
tokio-util.workspace = true
|
||||||
sysinfo.workspace = true
|
sysinfo.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
|||||||
@@ -50,6 +50,21 @@ enum CliCommand {
|
|||||||
LaunchGui(LaunchGuiArgs),
|
LaunchGui(LaunchGuiArgs),
|
||||||
#[command(about = "Generate HIP report")]
|
#[command(about = "Generate HIP report")]
|
||||||
Hip(HipArgs),
|
Hip(HipArgs),
|
||||||
|
#[command(hide = true)]
|
||||||
|
DetectInternalHost {
|
||||||
|
#[arg(long)]
|
||||||
|
address: std::net::IpAddr,
|
||||||
|
#[arg(long)]
|
||||||
|
hostname: String,
|
||||||
|
},
|
||||||
|
#[command(hide = true)]
|
||||||
|
ResolveGateway {
|
||||||
|
host: String,
|
||||||
|
#[arg(long, default_value_t = 443)]
|
||||||
|
port: u16,
|
||||||
|
#[arg(long)]
|
||||||
|
disable_ipv6: bool,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
@@ -118,10 +133,9 @@ impl Args for Cli {
|
|||||||
impl Cli {
|
impl Cli {
|
||||||
fn can_run_alongside_client(&self) -> bool {
|
fn can_run_alongside_client(&self) -> bool {
|
||||||
match &self.command {
|
match &self.command {
|
||||||
CliCommand::Disconnect(_) => true,
|
CliCommand::Connect(_) => false,
|
||||||
CliCommand::Hip(_) => true,
|
|
||||||
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
CliCommand::LaunchGui(args) => args.is_auth_callback(),
|
||||||
_ => false,
|
_ => true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,6 +193,20 @@ impl Cli {
|
|||||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
||||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||||
|
CliCommand::DetectInternalHost { address, hostname } => {
|
||||||
|
let internal = gpapi::session::network::native::detect_in_helper(*address, hostname)?;
|
||||||
|
println!("{}", serde_json::to_string(&internal)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CliCommand::ResolveGateway {
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
disable_ipv6,
|
||||||
|
} => {
|
||||||
|
let addresses = gpapi::session::network::native::lookup_in_helper(host, *port, *disable_ipv6)?;
|
||||||
|
println!("{}", serde_json::to_string(&addresses)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -220,6 +248,23 @@ mod tests {
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolver_helper_runs_alongside_client_and_is_hidden_from_help() {
|
||||||
|
let cli = Cli::try_parse_from([
|
||||||
|
"gpclient",
|
||||||
|
"resolve-gateway",
|
||||||
|
"localhost",
|
||||||
|
"--port",
|
||||||
|
"444",
|
||||||
|
"--disable-ipv6",
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
assert!(cli.can_run_alongside_client());
|
||||||
|
use clap::CommandFactory;
|
||||||
|
let help = Cli::command().render_help().to_string();
|
||||||
|
assert!(!help.contains("resolve-gateway"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn lock_file_defaults_to_standard_path() {
|
fn lock_file_defaults_to_standard_path() {
|
||||||
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
|
||||||
|
|||||||
@@ -116,7 +116,8 @@ impl ConnectHandler<'_> {
|
|||||||
.clean(clean_auth)
|
.clean(clean_auth)
|
||||||
.default_browser(use_default_browser);
|
.default_browser(use_default_browser);
|
||||||
|
|
||||||
let cred = auth_launcher.launch().await?;
|
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
|
||||||
|
self.check_cancelled()?;
|
||||||
Ok(cred)
|
Ok(cred)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use clap::Parser;
|
||||||
|
use gpapi::{
|
||||||
|
cookie_store::{self, StoredCookie},
|
||||||
|
credential::AuthCookieCredential,
|
||||||
|
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||||
|
log_format::LogFormat,
|
||||||
|
session::SessionMode,
|
||||||
|
};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
use super::{ConnectArgs, ConnectHandler};
|
||||||
|
use crate::cli::SharedArgs;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
struct TestArgs {
|
||||||
|
#[command(flatten)]
|
||||||
|
connect: ConnectArgs,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn login_response() -> String {
|
||||||
|
let mut fields = [""; 20];
|
||||||
|
fields[1] = "issued-cookie";
|
||||||
|
fields[3] = "gateway";
|
||||||
|
fields[4] = "alice";
|
||||||
|
fields[5] = "fixture-auth";
|
||||||
|
fields[6] = "vsys1";
|
||||||
|
fields[12] = "tunnel";
|
||||||
|
format!(
|
||||||
|
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||||
|
fields
|
||||||
|
.iter()
|
||||||
|
.map(|field| format!("<argument>{field}</argument>"))
|
||||||
|
.collect::<String>()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let worker = tokio::spawn(async move {
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||||
|
let mut requests = Vec::new();
|
||||||
|
for (status, body) in responses {
|
||||||
|
let (mut stream, _) = listener.accept().await.unwrap();
|
||||||
|
let mut request = Vec::new();
|
||||||
|
loop {
|
||||||
|
let mut buf = [0; 4096];
|
||||||
|
let count = stream.read(&mut buf).await.unwrap();
|
||||||
|
assert_ne!(count, 0, "Request ended before its body");
|
||||||
|
request.extend_from_slice(&buf[..count]);
|
||||||
|
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||||
|
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||||
|
let length = headers
|
||||||
|
.lines()
|
||||||
|
.find_map(|line| line.strip_prefix("content-length:"))
|
||||||
|
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||||
|
.unwrap_or(0);
|
||||||
|
if request.len() >= end + 4 + length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requests.push(String::from_utf8(request).unwrap());
|
||||||
|
stream
|
||||||
|
.write_all(
|
||||||
|
format!(
|
||||||
|
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.as_bytes(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
requests
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("Gateway fixture timed out")
|
||||||
|
});
|
||||||
|
(origin, worker)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||||
|
let (gateway, worker) = gateway(vec![("200 OK", login_response())]).await;
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let cache = directory.path().join("cookie.json");
|
||||||
|
let args = TestArgs::parse_from([
|
||||||
|
"test",
|
||||||
|
"http://unavailable-portal.invalid",
|
||||||
|
"--cookie-only",
|
||||||
|
"--cookie-cache",
|
||||||
|
cache.to_str().unwrap(),
|
||||||
|
])
|
||||||
|
.connect;
|
||||||
|
let lock = directory.path().join("client.pid");
|
||||||
|
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||||
|
let shared = SharedArgs {
|
||||||
|
fix_openssl: false,
|
||||||
|
ignore_tls_errors: true,
|
||||||
|
lock_file: &lock,
|
||||||
|
verbose: &verbose,
|
||||||
|
log_format: LogFormat::Text,
|
||||||
|
};
|
||||||
|
let handler = ConnectHandler::new(&args, &shared);
|
||||||
|
cookie_store::save(
|
||||||
|
&cache,
|
||||||
|
&StoredCookie::new(
|
||||||
|
args.server.clone(),
|
||||||
|
"alice".into(),
|
||||||
|
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||||
|
gateway,
|
||||||
|
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
handler.handle_impl().await.unwrap();
|
||||||
|
let requests = worker.await.unwrap();
|
||||||
|
assert_eq!(requests.len(), 1);
|
||||||
|
assert!(requests[0].starts_with("POST /ssl-vpn/login.esp "));
|
||||||
|
assert!(requests[0].contains("portal-cookie"));
|
||||||
|
assert_eq!(
|
||||||
|
handler.sessions.borrow().members()[0].transport.authentication().mode(),
|
||||||
|
SessionMode::Tunnel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||||
|
let (origin, worker) = gateway(vec![
|
||||||
|
(
|
||||||
|
"200 OK",
|
||||||
|
"<prelogin-response><status>Success</status></prelogin-response>".into(),
|
||||||
|
),
|
||||||
|
("403 Forbidden", "<response><error>rejected</error></response>".into()),
|
||||||
|
("200 OK", login_response()),
|
||||||
|
])
|
||||||
|
.await;
|
||||||
|
let args = TestArgs::parse_from(["test", &origin, "--user", "alice", "--passwd-on-stdin"]).connect;
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let lock = directory.path().join("client.pid");
|
||||||
|
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||||
|
let shared = SharedArgs {
|
||||||
|
fix_openssl: false,
|
||||||
|
ignore_tls_errors: true,
|
||||||
|
lock_file: &lock,
|
||||||
|
verbose: &verbose,
|
||||||
|
log_format: LogFormat::Text,
|
||||||
|
};
|
||||||
|
let handler = ConnectHandler::new(&args, &shared);
|
||||||
|
handler.password_from_stdin.replace(Some("gateway-password".into()));
|
||||||
|
let mut value = serde_json::to_value(Gateway::new("internal".into(), origin.clone())).unwrap();
|
||||||
|
value["kind"] = serde_json::json!("internal");
|
||||||
|
let gateway: Gateway = serde_json::from_value(value).unwrap();
|
||||||
|
let session = handler
|
||||||
|
.authenticate_gateway(
|
||||||
|
&origin,
|
||||||
|
&origin,
|
||||||
|
&AuthCookieCredential::new("alice", "rejected-cookie", ""),
|
||||||
|
false,
|
||||||
|
GatewayLoginContext::new(&gateway, GatewaySelection::Auto),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(session.authentication.mode(), SessionMode::Tunnel);
|
||||||
|
assert!(session.extension_auth.binding().is_none());
|
||||||
|
let requests = worker.await.unwrap();
|
||||||
|
assert_eq!(requests.len(), 3);
|
||||||
|
assert!(requests[1].contains("rejected-cookie"));
|
||||||
|
assert!(requests[2].contains("gateway-password"));
|
||||||
|
}
|
||||||
@@ -11,12 +11,12 @@ use gpapi::{
|
|||||||
clap::report,
|
clap::report,
|
||||||
cookie_store,
|
cookie_store,
|
||||||
credential::{AuthCookieCredential, Credential},
|
credential::{AuthCookieCredential, Credential},
|
||||||
gateway::{GatewayLogin, GatewayLoginContext, SessionExtensionAuth, gateway_login, gateway_login_with_context},
|
gateway::{Gateway, GatewayLogin, GatewayLoginClient, GatewayLoginContext, GatewaySelection, SessionExtensionAuth},
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
os_profile::OsProfile,
|
os_profile::OsProfile,
|
||||||
portal::prelogin,
|
portal::{PortalConfig, prelogin},
|
||||||
process::users::get_user_by_name,
|
process::users::get_user_by_name,
|
||||||
utils::shutdown_signal,
|
session::{GatewayAuthentication, SessionMode},
|
||||||
};
|
};
|
||||||
use inquire::Text;
|
use inquire::Text;
|
||||||
use log::{Level, info, warn};
|
use log::{Level, info, warn};
|
||||||
@@ -31,15 +31,15 @@ use super::{ConnectHandler, args::cookie_cache_path};
|
|||||||
|
|
||||||
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
|
||||||
|
|
||||||
struct GatewayLoginSession {
|
pub(super) struct GatewayLoginSession {
|
||||||
cookie: String,
|
pub(super) authentication: GatewayAuthentication,
|
||||||
extension_auth: SessionExtensionAuth,
|
pub(super) extension_auth: SessionExtensionAuth,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
enum GatewayConnectFailureStage {
|
enum GatewayConnectFailureStage {
|
||||||
BeforeTunnel,
|
BeforeEstablishment,
|
||||||
AfterTunnel,
|
AfterEstablishment,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -49,22 +49,22 @@ pub(super) struct GatewayConnectError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GatewayConnectError {
|
impl GatewayConnectError {
|
||||||
fn before_tunnel(error: anyhow::Error) -> Self {
|
fn before_establishment(error: anyhow::Error) -> Self {
|
||||||
Self {
|
Self {
|
||||||
stage: GatewayConnectFailureStage::BeforeTunnel,
|
stage: GatewayConnectFailureStage::BeforeEstablishment,
|
||||||
error,
|
error,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn after_tunnel(error: anyhow::Error) -> Self {
|
fn after_establishment(error: anyhow::Error) -> Self {
|
||||||
Self {
|
Self {
|
||||||
stage: GatewayConnectFailureStage::AfterTunnel,
|
stage: GatewayConnectFailureStage::AfterEstablishment,
|
||||||
error,
|
error,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn is_before_tunnel(&self) -> bool {
|
pub(super) fn is_before_establishment(&self) -> bool {
|
||||||
self.stage == GatewayConnectFailureStage::BeforeTunnel
|
self.stage == GatewayConnectFailureStage::BeforeEstablishment
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn as_error(&self) -> &anyhow::Error {
|
pub(super) fn as_error(&self) -> &anyhow::Error {
|
||||||
@@ -77,59 +77,81 @@ impl GatewayConnectError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ConnectHandler<'_> {
|
impl ConnectHandler<'_> {
|
||||||
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<()> {
|
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
|
||||||
let path = cookie_cache_path(self.args)?;
|
let path = cookie_cache_path(self.args)?;
|
||||||
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||||
let stored = cookie_store::load(&path, server, &host_id)?;
|
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||||
|
|
||||||
if !stored.auth_cookie.can_authenticate_gateway() {
|
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||||
warn!(
|
|
||||||
"Cached portal cookie for {} is not usable for gateway authentication. Clearing cache.",
|
|
||||||
stored.server
|
|
||||||
);
|
|
||||||
cookie_store::clear(&path);
|
cookie_store::clear(&path);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
let credential = (&stored.auth_cookie).into();
|
||||||
info!(
|
let mut params = self.build_gp_params();
|
||||||
"Using cached portal cookie for {} (saved_at={}, gateway={})",
|
params.set_is_gateway(true);
|
||||||
stored.server, stored.saved_at, stored.last_gateway
|
let session = match self
|
||||||
);
|
.login_gateway(&stored.last_gateway, &credential, ¶ms, None)
|
||||||
|
.await
|
||||||
let cred: Credential = (&stored.auth_cookie).into();
|
{
|
||||||
let mut gp_params = self.build_gp_params();
|
|
||||||
gp_params.set_is_gateway(true);
|
|
||||||
|
|
||||||
let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params, None).await {
|
|
||||||
Ok(session) => session,
|
Ok(session) => session,
|
||||||
Err(err) => {
|
Err(error) => {
|
||||||
warn!(
|
if self.cancellation.is_cancelled()
|
||||||
"Cached portal cookie rejected by gateway {}: {}. Clearing cache and falling back to portal auth.",
|
|| error
|
||||||
stored.last_gateway, err
|
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||||
);
|
.is_some()
|
||||||
|
{
|
||||||
|
return Some(Err(error));
|
||||||
|
}
|
||||||
cookie_store::clear(&path);
|
cookie_store::clear(&path);
|
||||||
|
warn!("Cached gateway authentication failed: {error}");
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if session.authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||||
match self
|
self.logout_gateway(&stored.last_gateway).await;
|
||||||
|
info!("Cached non-tunnel login requires fresh portal discovery");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let result = self
|
||||||
.connect_gateway(
|
.connect_gateway(
|
||||||
server,
|
server,
|
||||||
&stored.last_gateway,
|
&stored.last_gateway,
|
||||||
&login_session.cookie,
|
&session.authentication,
|
||||||
false,
|
false,
|
||||||
login_session.extension_auth,
|
session.extension_auth,
|
||||||
)
|
)
|
||||||
.await
|
.await;
|
||||||
{
|
match result {
|
||||||
Ok(()) => Some(()),
|
Ok(()) => Some(Ok(())),
|
||||||
Err(err) => {
|
Err(error) if self.cancellation.is_cancelled() => Some(Err(error.into_error())),
|
||||||
warn!("Gateway connect failed after cached-cookie login: {}", err.as_error());
|
Err(error) => {
|
||||||
|
self.logout_gateway(&stored.last_gateway).await;
|
||||||
|
warn!("Cached gateway connection failed: {}", error.as_error());
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn cached_portal_credential(&self, server: &str) -> Option<Credential> {
|
||||||
|
if self.args.cookie_on_stdin {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let path = cookie_cache_path(self.args)?;
|
||||||
|
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
|
||||||
|
let stored = cookie_store::load(&path, server, &host_id)?;
|
||||||
|
if !stored.auth_cookie.can_authenticate_gateway() {
|
||||||
|
cookie_store::clear(&path);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
info!("Using cached credential for fresh portal discovery");
|
||||||
|
Some((&stored.auth_cookie).into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn clear_cookie_cache(&self) {
|
||||||
|
if let Some(path) = cookie_cache_path(self.args) {
|
||||||
|
cookie_store::clear(&path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) async fn connect_gateway_with_prelogin(
|
pub(super) async fn connect_gateway_with_prelogin(
|
||||||
&self,
|
&self,
|
||||||
portal: &str,
|
portal: &str,
|
||||||
@@ -143,7 +165,11 @@ impl ConnectHandler<'_> {
|
|||||||
gp_params.set_is_gateway(true);
|
gp_params.set_is_gateway(true);
|
||||||
|
|
||||||
let gateway_browser_auth_allowed = true;
|
let gateway_browser_auth_allowed = true;
|
||||||
let prelogin = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()).await?;
|
let prelogin = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||||
|
result = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()) => result?,
|
||||||
|
};
|
||||||
let cred = self
|
let cred = self
|
||||||
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
|
.obtain_credential(&prelogin, gateway, gateway_browser_auth_allowed)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -156,7 +182,7 @@ impl ConnectHandler<'_> {
|
|||||||
.connect_gateway(
|
.connect_gateway(
|
||||||
portal,
|
portal,
|
||||||
gateway,
|
gateway,
|
||||||
&login_session.cookie,
|
&login_session.authentication,
|
||||||
allow_extend_session,
|
allow_extend_session,
|
||||||
login_session.extension_auth,
|
login_session.extension_auth,
|
||||||
)
|
)
|
||||||
@@ -164,94 +190,101 @@ impl ConnectHandler<'_> {
|
|||||||
.map_err(GatewayConnectError::into_error)
|
.map_err(GatewayConnectError::into_error)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connect to a gateway using the official client's auth flow:
|
|
||||||
///
|
|
||||||
/// 1. Call gateway prelogin and retain the response (SAML data is held as a fallback).
|
|
||||||
/// 2. If the portal provided auth cookies, attempt gateway login using them.
|
|
||||||
/// 3. If that login succeeds, proceed directly to the VPN connection.
|
|
||||||
/// 4. If no portal auth cookies exist or portal-cookie login fails, use the retained gateway prelogin response to authenticate
|
|
||||||
/// against the gateway (SAML or username/password) and obtain a gateway-issued
|
|
||||||
/// credential.
|
|
||||||
/// 5. Retry gateway login with the gateway credential (now carrying the gateway's
|
|
||||||
/// `prelogin-cookie`) and connect on success.
|
|
||||||
pub(super) async fn connect_gateway_with_fallback(
|
pub(super) async fn connect_gateway_with_fallback(
|
||||||
|
&self,
|
||||||
|
portal: &str,
|
||||||
|
gateway: &Gateway,
|
||||||
|
portal_cred: &AuthCookieCredential,
|
||||||
|
config: &PortalConfig,
|
||||||
|
selection: GatewaySelection,
|
||||||
|
remaining: &[&Gateway],
|
||||||
|
) -> Result<(), GatewayConnectError> {
|
||||||
|
let session = self
|
||||||
|
.authenticate_gateway(
|
||||||
|
portal,
|
||||||
|
gateway.server(),
|
||||||
|
portal_cred,
|
||||||
|
config.default_browser().unwrap_or(false),
|
||||||
|
GatewayLoginContext::new(gateway, selection).with_connect_method(config.connect_method()),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(GatewayConnectError::before_establishment)?;
|
||||||
|
if !self.args.cookie_only && session.authentication.mode() == SessionMode::NonTunnel {
|
||||||
|
if gateway.kind() != gpapi::gateway::GatewayKind::Internal {
|
||||||
|
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||||
|
"Non-tunnel authentication requires freshly discovered internal gateways"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
return self
|
||||||
|
.connect_internal_gateways(portal, config, portal_cred, gateway, session, remaining)
|
||||||
|
.await
|
||||||
|
.map_err(GatewayConnectError::after_establishment);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
.connect_gateway(
|
||||||
|
portal,
|
||||||
|
gateway.server(),
|
||||||
|
&session.authentication,
|
||||||
|
config.allow_extend_session().unwrap_or(false),
|
||||||
|
session.extension_auth,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn authenticate_gateway(
|
||||||
&self,
|
&self,
|
||||||
portal: &str,
|
portal: &str,
|
||||||
gateway: &str,
|
gateway: &str,
|
||||||
portal_cred: &AuthCookieCredential,
|
portal_cred: &AuthCookieCredential,
|
||||||
allow_extend_session: bool,
|
|
||||||
portal_config_default_browser: bool,
|
portal_config_default_browser: bool,
|
||||||
gateway_context: GatewayLoginContext,
|
gateway_context: GatewayLoginContext,
|
||||||
) -> Result<(), GatewayConnectError> {
|
) -> anyhow::Result<GatewayLoginSession> {
|
||||||
info!("Connecting to gateway with portal-cookie first, gateway prelogin fallback...");
|
self.check_cancelled()?;
|
||||||
|
|
||||||
let mut gp_params = self.build_gp_params();
|
let mut gp_params = self.build_gp_params();
|
||||||
gp_params.set_is_gateway(true);
|
gp_params.set_is_gateway(true);
|
||||||
let gateway_browser_auth_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
let browser_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
|
||||||
|
let gateway_prelogin = tokio::select! {
|
||||||
let gateway_prelogin = prelogin(gateway, &gp_params, self.prelogin_options(gateway_browser_auth_allowed))
|
biased;
|
||||||
.await
|
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||||
.map_err(GatewayConnectError::before_tunnel)?;
|
result = prelogin(gateway, &gp_params, self.prelogin_options(browser_allowed)) => result?,
|
||||||
|
};
|
||||||
|
self.check_cancelled()?;
|
||||||
|
|
||||||
if portal_cred.can_authenticate_gateway() {
|
if portal_cred.can_authenticate_gateway() {
|
||||||
let portal_cred_for_login: Credential = portal_cred.into();
|
let credential: Credential = portal_cred.into();
|
||||||
match self
|
match self
|
||||||
.login_gateway(gateway, &portal_cred_for_login, &gp_params, Some(&gateway_context))
|
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(login_session) => {
|
Ok(session) => {
|
||||||
info!("Gateway login with portal auth cookies succeeded");
|
|
||||||
self.save_cookie_cache(portal, gateway, portal_cred);
|
self.save_cookie_cache(portal, gateway, portal_cred);
|
||||||
return self
|
return Ok(session);
|
||||||
.connect_gateway(
|
|
||||||
portal,
|
|
||||||
gateway,
|
|
||||||
&login_session.cookie,
|
|
||||||
allow_extend_session,
|
|
||||||
login_session.extension_auth,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(error) => {
|
||||||
info!("Gateway login with portal auth cookies failed: {}", err);
|
self.check_cancelled()?;
|
||||||
info!("Falling back to gateway prelogin authentication...");
|
if error
|
||||||
|
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
info!("Portal cookie login failed; using gateway prelogin authentication: {error}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let gateway_cred = match self
|
let credential = self
|
||||||
.obtain_credential(&gateway_prelogin, gateway, gateway_browser_auth_allowed)
|
.obtain_credential(&gateway_prelogin, gateway, browser_allowed)
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(cred) => cred,
|
|
||||||
Err(err) => {
|
|
||||||
self.print_direct_gateway_recommendation(gateway);
|
|
||||||
return Err(GatewayConnectError::before_tunnel(err));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let login_session = match self
|
|
||||||
.login_gateway(gateway, &gateway_cred, &gp_params, Some(&gateway_context))
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(login_session) => login_session,
|
|
||||||
Err(err) => {
|
|
||||||
self.print_direct_gateway_recommendation(gateway);
|
|
||||||
return Err(GatewayConnectError::before_tunnel(err));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
self
|
|
||||||
.connect_gateway(
|
|
||||||
portal,
|
|
||||||
gateway,
|
|
||||||
&login_session.cookie,
|
|
||||||
allow_extend_session,
|
|
||||||
login_session.extension_auth,
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
|
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
|
||||||
|
self.check_cancelled()?;
|
||||||
|
let result = self
|
||||||
|
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
|
||||||
|
.await;
|
||||||
|
if result.is_err() {
|
||||||
|
self.print_direct_gateway_recommendation(gateway);
|
||||||
|
}
|
||||||
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
|
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
|
||||||
@@ -308,24 +341,39 @@ impl ConnectHandler<'_> {
|
|||||||
gateway_context: Option<&GatewayLoginContext>,
|
gateway_context: Option<&GatewayLoginContext>,
|
||||||
) -> anyhow::Result<GatewayLoginSession> {
|
) -> anyhow::Result<GatewayLoginSession> {
|
||||||
let mut gp_params = gp_params.clone();
|
let mut gp_params = gp_params.clone();
|
||||||
|
gp_params.prepare_client_identity()?;
|
||||||
|
let cancellation = self.cancellation.clone();
|
||||||
|
let internal = gateway_context.is_some_and(|context| context.kind() == gpapi::gateway::GatewayKind::Internal);
|
||||||
|
let mut client = GatewayLoginClient::new(gateway, gp_params)?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let login = match gateway_context {
|
self.check_cancelled()?;
|
||||||
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?,
|
let login = client.login(cred, gateway_context, &cancellation).await?;
|
||||||
None => gateway_login(gateway, cred, &gp_params).await?,
|
|
||||||
};
|
|
||||||
|
|
||||||
match login {
|
match login {
|
||||||
GatewayLogin::Cookie(cookie) => {
|
GatewayLogin::Authenticated(authentication) => {
|
||||||
|
let descriptor = Gateway::new(gateway.to_string(), gateway.to_string());
|
||||||
|
client.register_session(
|
||||||
|
descriptor.clone(),
|
||||||
|
authentication.clone(),
|
||||||
|
&mut self.sessions.borrow_mut(),
|
||||||
|
);
|
||||||
|
self.check_cancelled()?;
|
||||||
|
if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
|
||||||
|
client
|
||||||
|
.bind_non_tunnel(self.args.disable_ipv6, None, &cancellation)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?;
|
||||||
|
client.update_registered_session(&descriptor, &authentication, &mut self.sessions.borrow_mut());
|
||||||
|
}
|
||||||
return Ok(GatewayLoginSession {
|
return Ok(GatewayLoginSession {
|
||||||
cookie,
|
authentication,
|
||||||
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
|
extension_auth: SessionExtensionAuth::new(cred.clone(), client),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
GatewayLogin::Mfa(message, input_str) => {
|
GatewayLogin::Mfa(message, input_str) => {
|
||||||
let otp = Text::new(&message).prompt()?;
|
let otp = Text::new(&message).prompt()?;
|
||||||
gp_params.set_input_str(&input_str);
|
client.respond_mfa(&input_str, &otp);
|
||||||
gp_params.set_otp(&otp);
|
|
||||||
|
|
||||||
info!("Retrying gateway login with MFA...");
|
info!("Retrying gateway login with MFA...");
|
||||||
}
|
}
|
||||||
@@ -333,14 +381,15 @@ impl ConnectHandler<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn connect_gateway(
|
pub(super) async fn connect_gateway(
|
||||||
&self,
|
&self,
|
||||||
portal: &str,
|
portal: &str,
|
||||||
gateway: &str,
|
gateway: &str,
|
||||||
cookie: &str,
|
authentication: &GatewayAuthentication,
|
||||||
allow_extend_session: bool,
|
allow_extend_session: bool,
|
||||||
extension_auth: SessionExtensionAuth,
|
extension_auth: SessionExtensionAuth,
|
||||||
) -> Result<(), GatewayConnectError> {
|
) -> Result<(), GatewayConnectError> {
|
||||||
|
let cookie = authentication.cookie();
|
||||||
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
|
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
|
||||||
// No tun device is allocated, no root is required, and no logout is issued
|
// No tun device is allocated, no root is required, and no logout is issued
|
||||||
// against the gateway — the cookie remains valid for subsequent use.
|
// against the gateway — the cookie remains valid for subsequent use.
|
||||||
@@ -351,20 +400,39 @@ impl ConnectHandler<'_> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if authentication.mode() != SessionMode::Tunnel {
|
||||||
|
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
|
||||||
|
"Non-tunnel authentication requires fresh internal portal discovery"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
self
|
||||||
|
.check_cancelled()
|
||||||
|
.map_err(GatewayConnectError::after_establishment)?;
|
||||||
|
let identity_files = extension_auth
|
||||||
|
.client_identity()
|
||||||
|
.map(|identity| identity.write_files(None))
|
||||||
|
.transpose()
|
||||||
|
.map_err(GatewayConnectError::before_establishment)?;
|
||||||
|
let certificate = identity_files.as_ref().map(|files| files.certificate().to_owned());
|
||||||
|
let sslkey = identity_files.as_ref().and_then(|files| files.key().map(str::to_owned));
|
||||||
|
let key_password = extension_auth
|
||||||
|
.client_identity()
|
||||||
|
.and_then(|identity| identity.key_password())
|
||||||
|
.map(str::to_owned);
|
||||||
let mtu = self.args.mtu.unwrap_or(0);
|
let mtu = self.args.mtu.unwrap_or(0);
|
||||||
let os_profile = self.os_profile.borrow().clone();
|
let os_profile = self.os_profile.borrow().clone();
|
||||||
let hip_source = self
|
let hip_source = self
|
||||||
.hip_source(os_profile.clone())
|
.hip_source(os_profile.clone())
|
||||||
.map_err(GatewayConnectError::before_tunnel)?;
|
.map_err(GatewayConnectError::before_establishment)?;
|
||||||
|
|
||||||
let session_ctx = build_session_context(SessionContextInput {
|
let session_ctx = build_session_context(SessionContextInput {
|
||||||
portal: portal.to_string(),
|
portal: portal.to_string(),
|
||||||
gateway: gateway.to_string(),
|
gateway: gateway.to_string(),
|
||||||
cookie: cookie.to_string(),
|
cookie: cookie.to_string(),
|
||||||
os_profile: os_profile.clone(),
|
os_profile: os_profile.clone(),
|
||||||
certificate: self.args.certificate.clone(),
|
certificate: certificate.clone(),
|
||||||
sslkey: self.args.sslkey.clone(),
|
sslkey: sslkey.clone(),
|
||||||
key_password: self.latest_key_password.borrow().clone(),
|
key_password: key_password.clone(),
|
||||||
disable_ipv6: self.args.disable_ipv6,
|
disable_ipv6: self.args.disable_ipv6,
|
||||||
extension_auth: Some(extension_auth),
|
extension_auth: Some(extension_auth),
|
||||||
});
|
});
|
||||||
@@ -372,9 +440,9 @@ impl ConnectHandler<'_> {
|
|||||||
.script(self.args.script.clone())
|
.script(self.args.script.clone())
|
||||||
.interface(self.args.interface.clone())
|
.interface(self.args.interface.clone())
|
||||||
.script_tun(self.args.script_tun)
|
.script_tun(self.args.script_tun)
|
||||||
.certificate(self.args.certificate.clone())
|
.certificate(certificate)
|
||||||
.sslkey(self.args.sslkey.clone())
|
.sslkey(sslkey)
|
||||||
.key_password(self.latest_key_password.borrow().clone())
|
.key_password(key_password)
|
||||||
.hip_source(hip_source)
|
.hip_source(hip_source)
|
||||||
.reconnect_timeout(self.args.reconnect_timeout)
|
.reconnect_timeout(self.args.reconnect_timeout)
|
||||||
.mtu(mtu)
|
.mtu(mtu)
|
||||||
@@ -385,7 +453,7 @@ impl ConnectHandler<'_> {
|
|||||||
.no_xmlpost(self.args.no_xmlpost);
|
.no_xmlpost(self.args.no_xmlpost);
|
||||||
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
let vpn = apply_os_profile(vpn_builder, &os_profile)
|
||||||
.build()
|
.build()
|
||||||
.map_err(|err| GatewayConnectError::before_tunnel(err.into()))?;
|
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
|
||||||
|
|
||||||
let vpn = Arc::new(vpn);
|
let vpn = Arc::new(vpn);
|
||||||
let vpn_clone = vpn.clone();
|
let vpn_clone = vpn.clone();
|
||||||
@@ -398,46 +466,72 @@ impl ConnectHandler<'_> {
|
|||||||
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
|
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
|
||||||
let disconnect_requested = Arc::new(AtomicBool::new(false));
|
let disconnect_requested = Arc::new(AtomicBool::new(false));
|
||||||
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
|
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
|
||||||
|
let cancellation = self.cancellation.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
let disconnect_task = tokio::spawn(async move {
|
||||||
shutdown_signal().await;
|
cancellation.cancelled().await;
|
||||||
info!("Received the interrupt signal, disconnecting...");
|
info!("Received the interrupt signal, disconnecting...");
|
||||||
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
|
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
|
||||||
vpn_clone.disconnect();
|
vpn_clone.disconnect();
|
||||||
});
|
});
|
||||||
|
|
||||||
let lock_file = self.shared_args.lock_file.to_path_buf();
|
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
|
||||||
let lock_file_on_connect = lock_file.clone();
|
let pid_written = self.pid_written.clone();
|
||||||
let log_format = self.shared_args.log_format;
|
let log_format = self.shared_args.log_format;
|
||||||
let connect_result = vpn.connect(move |vpn_session_info| {
|
let session_cancellation = self.cancellation.clone();
|
||||||
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
|
||||||
write_pid_file(&lock_file_on_connect);
|
self.sessions.borrow_mut().relinquish_gateway(gateway);
|
||||||
|
let worker = tokio::task::spawn_blocking(move || {
|
||||||
|
vpn.connect(move |vpn_session_info| {
|
||||||
|
if session_cancellation.is_cancelled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tunnel_established_on_connect.store(true, Ordering::SeqCst);
|
||||||
|
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
|
||||||
|
let _ = established_tx.send(());
|
||||||
|
|
||||||
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
||||||
info!("VPN session info: {}", session_info.log_summary());
|
info!("VPN session info: {}", session_info.log_summary());
|
||||||
|
|
||||||
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info, log_format);
|
||||||
session_task_on_connect.lock().unwrap().replace(task);
|
session_task_on_connect.lock().unwrap().replace(task);
|
||||||
|
})
|
||||||
});
|
});
|
||||||
|
tokio::pin!(worker);
|
||||||
|
let connect_result = tokio::select! {
|
||||||
|
result = &mut worker => result,
|
||||||
|
established = established_rx => {
|
||||||
|
if established.is_ok() {
|
||||||
|
let unused = self.sessions.borrow().members().iter()
|
||||||
|
.filter(|session| session.gateway.server() != gateway)
|
||||||
|
.map(|session| session.gateway.server().to_owned())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
for server in unused {
|
||||||
|
self.logout_gateway(&server).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(&mut worker).await
|
||||||
|
}
|
||||||
|
};
|
||||||
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
|
||||||
|
disconnect_task.abort();
|
||||||
|
let _ = disconnect_task.await;
|
||||||
|
|
||||||
if let Some(task) = session_task.lock().unwrap().take() {
|
let session_task = { session_task.lock().unwrap().take() };
|
||||||
|
if let Some(task) = session_task {
|
||||||
task.abort();
|
task.abort();
|
||||||
}
|
let _ = task.await;
|
||||||
|
|
||||||
if fs::metadata(&lock_file).is_ok() {
|
|
||||||
info!("Removing PID file");
|
|
||||||
fs::remove_file(&lock_file).map_err(|err| GatewayConnectError::after_tunnel(err.into()))?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
|
||||||
|
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
|
||||||
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
|
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
|
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
|
||||||
let user = self.determine_hip_user();
|
let user = self.determine_hip_user();
|
||||||
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
|
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
|
||||||
match script {
|
match script {
|
||||||
@@ -489,9 +583,9 @@ fn classify_openconnect_result(
|
|||||||
|
|
||||||
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
|
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
|
||||||
if tunnel_established {
|
if tunnel_established {
|
||||||
Err(GatewayConnectError::after_tunnel(error))
|
Err(GatewayConnectError::after_establishment(error))
|
||||||
} else {
|
} else {
|
||||||
Err(GatewayConnectError::before_tunnel(error))
|
Err(GatewayConnectError::before_establishment(error))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -499,13 +593,15 @@ fn direct_gateway_command(gateway: &str) -> String {
|
|||||||
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_pid_file(lock_file: &Path) {
|
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
|
|
||||||
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
if let Err(err) = fs::write(lock_file, pid.to_string()) {
|
||||||
warn!("Failed to write PID file: {}", err);
|
warn!("Failed to write PID file: {}", err);
|
||||||
|
false
|
||||||
} else {
|
} else {
|
||||||
info!("Wrote PID {} to {}", pid, lock_file.display());
|
info!("Wrote PID {} to {}", pid, lock_file.display());
|
||||||
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -556,14 +652,14 @@ mod tests {
|
|||||||
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
|
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
|
||||||
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
|
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
|
||||||
|
|
||||||
assert!(err.is_before_tunnel());
|
assert!(err.is_before_establishment());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
|
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
|
||||||
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
|
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
|
||||||
|
|
||||||
assert!(!err.is_before_tunnel());
|
assert!(!err.is_before_establishment());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -576,7 +672,7 @@ mod tests {
|
|||||||
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
|
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
|
||||||
.expect_err("unexpected interrupt should fail");
|
.expect_err("unexpected interrupt should fail");
|
||||||
|
|
||||||
assert!(!err.is_before_tunnel());
|
assert!(!err.is_before_establishment());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use gpapi::{
|
||||||
|
credential::AuthCookieCredential,
|
||||||
|
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
|
||||||
|
portal::PortalConfig,
|
||||||
|
process::collection::CollectionControl,
|
||||||
|
session::{
|
||||||
|
MaintenanceState, SessionEndReason, SessionMode,
|
||||||
|
network::PhysicalNetwork,
|
||||||
|
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use log::{info, warn};
|
||||||
|
|
||||||
|
use super::ConnectHandler;
|
||||||
|
|
||||||
|
impl ConnectHandler<'_> {
|
||||||
|
pub(super) async fn connect_internal_gateways(
|
||||||
|
&self,
|
||||||
|
portal: &str,
|
||||||
|
config: &PortalConfig,
|
||||||
|
credential: &AuthCookieCredential,
|
||||||
|
first_gateway: &Gateway,
|
||||||
|
first_session: super::gateway::GatewayLoginSession,
|
||||||
|
remaining: &[&Gateway],
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
ensure!(remaining.len() < 64, "Too many internal non-tunnel candidates");
|
||||||
|
let mut hosts = std::collections::HashSet::new();
|
||||||
|
for gateway in std::iter::once(first_gateway).chain(remaining.iter().copied()) {
|
||||||
|
ensure!(
|
||||||
|
gateway.kind() == gpapi::gateway::GatewayKind::Internal,
|
||||||
|
"Non-tunnel candidates must be internal"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
hosts.insert(gpapi::utils::normalize_server(gateway.server())?),
|
||||||
|
"Duplicate internal gateway"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut authenticated = vec![(first_gateway, first_session)];
|
||||||
|
for gateway in remaining.iter().copied() {
|
||||||
|
self.check_cancelled()?;
|
||||||
|
let context =
|
||||||
|
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(config.connect_method());
|
||||||
|
match self
|
||||||
|
.authenticate_gateway(
|
||||||
|
portal,
|
||||||
|
gateway.server(),
|
||||||
|
credential,
|
||||||
|
config.default_browser().unwrap_or(false),
|
||||||
|
context,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(session) => authenticated.push((gateway, session)),
|
||||||
|
Err(error) => {
|
||||||
|
self.logout_gateway(gateway.server()).await;
|
||||||
|
self.check_cancelled()?;
|
||||||
|
warn!("Internal gateway {gateway} authentication failed: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.check_cancelled()?;
|
||||||
|
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
|
||||||
|
ensure!(
|
||||||
|
internal_session_mode(modes)? == SessionMode::NonTunnel,
|
||||||
|
"Expected non-tunnel authentication"
|
||||||
|
);
|
||||||
|
self.run_internal_session(config, &authenticated).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_internal_session(
|
||||||
|
&self,
|
||||||
|
config: &PortalConfig,
|
||||||
|
authenticated: &[(&gpapi::gateway::Gateway, super::gateway::GatewayLoginSession)],
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let cancellation = self.cancellation.clone();
|
||||||
|
let network = Arc::new(PhysicalNetwork::capture_controlled(&cancellation).await?);
|
||||||
|
let detection = config.internal_detection().cloned();
|
||||||
|
let bindings = authenticated
|
||||||
|
.iter()
|
||||||
|
.map(|(_, session)| {
|
||||||
|
session
|
||||||
|
.extension_auth
|
||||||
|
.binding()
|
||||||
|
.cloned()
|
||||||
|
.context("Non-tunnel binding is missing")
|
||||||
|
})
|
||||||
|
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||||
|
for binding in &bindings {
|
||||||
|
network
|
||||||
|
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
let policy = config
|
||||||
|
.internal_session_policy()
|
||||||
|
.context("Invalid internal session policy")?;
|
||||||
|
let profile = self.os_profile.borrow().clone();
|
||||||
|
let source = if policy.collect_hip_data() {
|
||||||
|
self.hip_source(profile.clone())?
|
||||||
|
} else {
|
||||||
|
openconnect::HipSource::Disabled
|
||||||
|
};
|
||||||
|
let source = Arc::new(source);
|
||||||
|
let validate_network = network.clone();
|
||||||
|
let validate_detection = detection.clone();
|
||||||
|
let callbacks = SessionCallbacks {
|
||||||
|
produce_report: Arc::new(move |request, control| {
|
||||||
|
control.check()?;
|
||||||
|
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
|
||||||
|
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||||
|
profile: profile.clone(),
|
||||||
|
context: gphip::ReportContext::Connected {
|
||||||
|
cookie: request.cookie.clone(),
|
||||||
|
client_ip: request.client_ip.clone(),
|
||||||
|
client_ipv6: request.client_ipv6.clone(),
|
||||||
|
md5: request.md5.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.map_err(std::io::Error::other);
|
||||||
|
}
|
||||||
|
source.collect(
|
||||||
|
&openconnect::HipRequest {
|
||||||
|
cookie: request.cookie.clone(),
|
||||||
|
client_ip: request.client_ip.clone(),
|
||||||
|
client_ipv6: request.client_ipv6.clone(),
|
||||||
|
md5: request.md5.clone(),
|
||||||
|
client_version: profile.client_version().into(),
|
||||||
|
client_os: profile.client_os().as_str().into(),
|
||||||
|
os_version: profile.os_version().into(),
|
||||||
|
host_id: Some(profile.host_id().into()),
|
||||||
|
local_hostname: Some(profile.computer().into()),
|
||||||
|
},
|
||||||
|
&|| control.check(),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
report_submitted: Arc::new(|_, _| {}),
|
||||||
|
status_changed: Arc::new(|member| match member.maintenance {
|
||||||
|
MaintenanceState::Healthy => info!(
|
||||||
|
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
|
||||||
|
member.gateway, member.client_ip, member.client_ipv6
|
||||||
|
),
|
||||||
|
state => info!("Internal gateway {}: {state:?}", member.gateway),
|
||||||
|
}),
|
||||||
|
validate_network: Arc::new(move |cancellation| {
|
||||||
|
let network = validate_network.clone();
|
||||||
|
let detection = validate_detection.clone();
|
||||||
|
let bindings = bindings.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
for binding in &bindings {
|
||||||
|
network
|
||||||
|
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let monitor_cancel = cancellation.child_token();
|
||||||
|
let monitor_token = monitor_cancel.clone();
|
||||||
|
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||||
|
let monitor = tokio::spawn(async move {
|
||||||
|
match network.wait_for_change(detection, monitor_token).await {
|
||||||
|
Ok(false) => {}
|
||||||
|
Ok(true) | Err(_) => {
|
||||||
|
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The PID spans maintenance and cleanup, including initialization before the
|
||||||
|
// first successful HIP exchange. The outer handler owns final session logout.
|
||||||
|
self.pid_written.store(
|
||||||
|
super::gateway::write_pid_file(self.shared_args.lock_file),
|
||||||
|
std::sync::atomic::Ordering::SeqCst,
|
||||||
|
);
|
||||||
|
let mut sessions = self.sessions.take();
|
||||||
|
let result = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
|
||||||
|
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
self.sessions.replace(sessions);
|
||||||
|
monitor_cancel.cancel();
|
||||||
|
monitor.await.context("Internal network monitor failed")?;
|
||||||
|
match result? {
|
||||||
|
SessionExit::Disconnected => Ok(()),
|
||||||
|
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn logout_gateway(&self, gateway: &str) {
|
||||||
|
let mut sessions = self.sessions.take();
|
||||||
|
sessions.logout_gateway(gateway).await;
|
||||||
|
self.sessions.replace(sessions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
|
||||||
|
let mut modes = modes;
|
||||||
|
let mode = modes.next().context("No internal gateway authenticated successfully")?;
|
||||||
|
ensure!(
|
||||||
|
modes.all(|candidate| candidate == mode),
|
||||||
|
"Mixed tunnel and non-tunnel internal gateways are unsupported; select a gateway explicitly"
|
||||||
|
);
|
||||||
|
Ok(mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn internal_modes_reject_mixed_and_empty_sets() {
|
||||||
|
assert!(internal_session_mode([].into_iter()).is_err());
|
||||||
|
assert!(internal_session_mode([SessionMode::Tunnel, SessionMode::NonTunnel].into_iter()).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
|
||||||
|
SessionMode::NonTunnel
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
|
||||||
|
SessionMode::Tunnel
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,25 @@
|
|||||||
mod args;
|
mod args;
|
||||||
mod credential;
|
mod credential;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod flow_tests;
|
||||||
mod gateway;
|
mod gateway;
|
||||||
|
mod internal;
|
||||||
|
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
|
use std::sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
};
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
clap::report,
|
clap::report,
|
||||||
error::PortalError,
|
error::PortalError,
|
||||||
gateway::{GatewayLoginContext, GatewaySelection},
|
gateway::GatewaySelection,
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
os_profile::OsProfile,
|
os_profile::OsProfile,
|
||||||
portal::{PreloginOptions, prelogin, retrieve_config},
|
portal::{PreloginOptions, prelogin, retrieve_config},
|
||||||
|
session::GatewaySessions,
|
||||||
utils::request::RequestIdentityError,
|
utils::request::RequestIdentityError,
|
||||||
};
|
};
|
||||||
use inquire::{Password, PasswordDisplayMode, Select};
|
use inquire::{Password, PasswordDisplayMode, Select};
|
||||||
@@ -25,6 +33,7 @@ use credential::CleanAuthState;
|
|||||||
use gateway::GatewayConnectError;
|
use gateway::GatewayConnectError;
|
||||||
|
|
||||||
pub(crate) struct ConnectHandler<'a> {
|
pub(crate) struct ConnectHandler<'a> {
|
||||||
|
cancellation: tokio_util::sync::CancellationToken,
|
||||||
args: &'a ConnectArgs,
|
args: &'a ConnectArgs,
|
||||||
shared_args: &'a SharedArgs<'a>,
|
shared_args: &'a SharedArgs<'a>,
|
||||||
os_profile: RefCell<OsProfile>,
|
os_profile: RefCell<OsProfile>,
|
||||||
@@ -32,6 +41,8 @@ pub(crate) struct ConnectHandler<'a> {
|
|||||||
password_from_stdin: RefCell<Option<String>>,
|
password_from_stdin: RefCell<Option<String>>,
|
||||||
cookie_from_stdin: RefCell<Option<String>>,
|
cookie_from_stdin: RefCell<Option<String>>,
|
||||||
clean_auth_state: RefCell<CleanAuthState>,
|
clean_auth_state: RefCell<CleanAuthState>,
|
||||||
|
sessions: RefCell<GatewaySessions>,
|
||||||
|
pid_written: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ConnectHandler<'a> {
|
impl<'a> ConnectHandler<'a> {
|
||||||
@@ -44,6 +55,7 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
let clean_auth = false;
|
let clean_auth = false;
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
|
cancellation: tokio_util::sync::CancellationToken::new(),
|
||||||
args,
|
args,
|
||||||
shared_args,
|
shared_args,
|
||||||
os_profile: RefCell::new(build_os_profile(args)),
|
os_profile: RefCell::new(build_os_profile(args)),
|
||||||
@@ -51,6 +63,8 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
password_from_stdin: Default::default(),
|
password_from_stdin: Default::default(),
|
||||||
cookie_from_stdin: Default::default(),
|
cookie_from_stdin: Default::default(),
|
||||||
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
|
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
|
||||||
|
sessions: RefCell::default(),
|
||||||
|
pid_written: Arc::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +107,37 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
||||||
|
let cancellation = self.cancellation.clone();
|
||||||
|
let signal = tokio::spawn(async move {
|
||||||
|
gpapi::utils::shutdown_signal().await;
|
||||||
|
cancellation.cancel();
|
||||||
|
});
|
||||||
|
let result = self.handle_attempt().await;
|
||||||
|
let sessions = self.sessions.take();
|
||||||
|
if self.args.cookie_only && result.is_ok() {
|
||||||
|
sessions.relinquish();
|
||||||
|
} else {
|
||||||
|
sessions.logout().await;
|
||||||
|
}
|
||||||
|
if self.pid_written.load(Ordering::SeqCst) {
|
||||||
|
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
|
||||||
|
warn!("Failed to remove PID file: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
signal.abort();
|
||||||
|
let _ = signal.await;
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_cancelled(&self) -> anyhow::Result<()> {
|
||||||
|
if self.cancellation.is_cancelled() {
|
||||||
|
Err(gpapi::auth::AuthenticationCancelled.into())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_attempt(&self) -> anyhow::Result<()> {
|
||||||
if self.args.browser_listen.is_some()
|
if self.args.browser_listen.is_some()
|
||||||
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
|
||||||
{
|
{
|
||||||
@@ -107,6 +152,7 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
self.latest_key_password.replace(self.args.key_password.clone());
|
self.latest_key_password.replace(self.args.key_password.clone());
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
self.check_cancelled()?;
|
||||||
let Err(err) = self.handle_impl().await else {
|
let Err(err) = self.handle_impl().await else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -144,6 +190,7 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
||||||
|
self.check_cancelled()?;
|
||||||
let server = self.args.server.as_str();
|
let server = self.args.server.as_str();
|
||||||
let as_gateway = self.args.as_gateway;
|
let as_gateway = self.args.as_gateway;
|
||||||
|
|
||||||
@@ -155,10 +202,11 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !self.args.cookie_on_stdin {
|
if !self.args.cookie_on_stdin {
|
||||||
if let Some(()) = self.try_cached_cookie(server).await {
|
if let Some(result) = self.try_cached_cookie(server).await {
|
||||||
return Ok(());
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.check_cancelled()?;
|
||||||
|
|
||||||
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -190,10 +238,35 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
||||||
let gp_params = self.build_gp_params();
|
let gp_params = self.build_gp_params();
|
||||||
|
|
||||||
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
|
let prelogin = tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
|
||||||
|
result = prelogin(portal, &gp_params, self.prelogin_options(false)) => result?,
|
||||||
|
};
|
||||||
|
|
||||||
let cred = self.obtain_credential(&prelogin, portal, false).await?;
|
let cached = self.cached_portal_credential(portal);
|
||||||
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
let cached_config = match cached {
|
||||||
|
Some(cred) => match retrieve_config(portal, &cred, &gp_params, &self.cancellation).await {
|
||||||
|
Ok(config) => Some((cred, config)),
|
||||||
|
Err(error) => {
|
||||||
|
self.check_cancelled()?;
|
||||||
|
warn!("Cached portal authentication failed: {error}");
|
||||||
|
self.clear_cookie_cache();
|
||||||
|
None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let (cred, mut portal_config) = match cached_config {
|
||||||
|
Some(result) => result,
|
||||||
|
None => {
|
||||||
|
let cred = self.obtain_credential(&prelogin, portal, false).await?;
|
||||||
|
self.check_cancelled()?;
|
||||||
|
let config = retrieve_config(portal, &cred, &gp_params, &self.cancellation).await?;
|
||||||
|
(cred, config)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.check_cancelled()?;
|
||||||
|
|
||||||
portal_config.sort_gateways(prelogin.region());
|
portal_config.sort_gateways(prelogin.region());
|
||||||
|
|
||||||
@@ -201,7 +274,6 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
Some(password) => portal_config.auth_cookie().clone().with_password(password),
|
Some(password) => portal_config.auth_cookie().clone().with_password(password),
|
||||||
None => portal_config.auth_cookie().clone(),
|
None => portal_config.auth_cookie().clone(),
|
||||||
};
|
};
|
||||||
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
|
|
||||||
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
|
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
|
||||||
info!("Portal config default-browser: {}", portal_config_default_browser);
|
info!("Portal config default-browser: {}", portal_config_default_browser);
|
||||||
|
|
||||||
@@ -217,29 +289,27 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let mut last_err: Option<anyhow::Error> = None;
|
let mut last_err: Option<anyhow::Error> = None;
|
||||||
for gateway in &gateways {
|
for (index, gateway) in gateways.iter().enumerate() {
|
||||||
info!("Auto-gateway: attempting gateway {}", gateway);
|
info!("Auto-gateway: attempting gateway {}", gateway);
|
||||||
let gateway_context =
|
|
||||||
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(portal_config.connect_method());
|
|
||||||
|
|
||||||
match self
|
match self
|
||||||
.connect_gateway_with_fallback(
|
.connect_gateway_with_fallback(
|
||||||
portal,
|
portal,
|
||||||
gateway.server(),
|
gateway,
|
||||||
&auth_cookie,
|
&auth_cookie,
|
||||||
allow_extend_session,
|
&portal_config,
|
||||||
portal_config_default_browser,
|
GatewaySelection::Auto,
|
||||||
gateway_context,
|
&gateways[index + 1..],
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(()) => return Ok(()),
|
Ok(()) => return Ok(()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if !err.is_before_tunnel() {
|
self.logout_gateway(gateway.server()).await;
|
||||||
|
if !err.is_before_establishment() {
|
||||||
return Err(err.into_error());
|
return Err(err.into_error());
|
||||||
}
|
}
|
||||||
warn!(
|
warn!(
|
||||||
"Auto-gateway: gateway {} failed before tunnel setup: {}",
|
"Auto-gateway: gateway {} failed before session establishment: {}",
|
||||||
gateway,
|
gateway,
|
||||||
err.as_error()
|
err.as_error()
|
||||||
);
|
);
|
||||||
@@ -270,6 +340,9 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
None => {
|
None => {
|
||||||
let gateways = portal_config.gateways();
|
let gateways = portal_config.gateways();
|
||||||
|
|
||||||
|
if gateways.is_empty() {
|
||||||
|
bail!("No gateways available in portal configuration");
|
||||||
|
}
|
||||||
if gateways.len() > 1 {
|
if gateways.len() > 1 {
|
||||||
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
||||||
.with_vim_mode(true)
|
.with_vim_mode(true)
|
||||||
@@ -283,18 +356,14 @@ impl<'a> ConnectHandler<'a> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let gateway = selected_gateway.server();
|
|
||||||
let gateway_context =
|
|
||||||
GatewayLoginContext::new(selected_gateway, gateway_selection).with_connect_method(portal_config.connect_method());
|
|
||||||
|
|
||||||
self
|
self
|
||||||
.connect_gateway_with_fallback(
|
.connect_gateway_with_fallback(
|
||||||
portal,
|
portal,
|
||||||
gateway,
|
selected_gateway,
|
||||||
&auth_cookie,
|
&auth_cookie,
|
||||||
allow_extend_session,
|
&portal_config,
|
||||||
portal_config_default_browser,
|
gateway_selection,
|
||||||
gateway_context,
|
&[],
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(GatewayConnectError::into_error)
|
.map_err(GatewayConnectError::into_error)
|
||||||
|
|||||||
@@ -35,4 +35,5 @@ mac_address = "1"
|
|||||||
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
nix = { version = "0.31", features = ["fs", "socket", "user"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
openssl.workspace = true
|
||||||
tokio-tungstenite = "0.29"
|
tokio-tungstenite = "0.29"
|
||||||
@@ -301,7 +301,7 @@ async fn wait_for_brokered_idle(
|
|||||||
_ = interval.tick() => {},
|
_ = interval.tick() => {},
|
||||||
}
|
}
|
||||||
|
|
||||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected) && registry.is_empty();
|
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected | VpnState::Failed(_)) && registry.is_empty();
|
||||||
if !idle {
|
if !idle {
|
||||||
idle_since = None;
|
idle_since = None;
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ fn generate(
|
|||||||
let openconnect::HipSource::Script(script) = execution.source else {
|
let openconnect::HipSource::Script(script) = execution.source else {
|
||||||
bail!("HIP preview executable is unavailable");
|
bail!("HIP preview executable is unavailable");
|
||||||
};
|
};
|
||||||
let xml = script.preview(&input, &check)?;
|
let xml = script.collect(&input, &check)?;
|
||||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
||||||
xml
|
xml
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,16 +24,12 @@ pub(crate) struct HipApproval {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl HipApproval {
|
impl HipApproval {
|
||||||
pub(crate) fn approval_id(&self) -> Option<&str> {
|
|
||||||
self.identity.as_ref().map(|(id, _)| id.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn approval_is_valid(&self) -> bool {
|
pub(crate) fn approval_is_valid(&self) -> bool {
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||||
if let Some((id, uid)) = &self.identity {
|
if let Some((id, uid)) = &self.identity {
|
||||||
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
||||||
}
|
}
|
||||||
true
|
self.identity.is_none()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,54 @@ const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
|||||||
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
||||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||||
|
|
||||||
|
pub(crate) struct SessionAuthority {
|
||||||
|
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
|
pub session_id: uuid::Uuid,
|
||||||
|
pub generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) enum PendingDispatch {
|
||||||
|
Connect {
|
||||||
|
preparation: ConnectionPreparation,
|
||||||
|
request: Box<gpapi::service::request::ConnectRequest>,
|
||||||
|
desktop_uid: Option<u32>,
|
||||||
|
edited_report: Option<Arc<str>>,
|
||||||
|
},
|
||||||
|
Drain(Option<crate::vpn_task::AttemptDrain>),
|
||||||
|
Other(WsRequest),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct ConnectionPreparation {
|
||||||
|
authority: SessionAuthority,
|
||||||
|
non_tunnel: bool,
|
||||||
|
reservation: Option<crate::vpn_task::ConnectReservation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConnectionPreparation {
|
||||||
|
fn cancellation(&self) -> tokio_util::sync::CancellationToken {
|
||||||
|
self
|
||||||
|
.reservation
|
||||||
|
.as_ref()
|
||||||
|
.expect("preparation retains reservation")
|
||||||
|
.cancellation()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit(
|
||||||
|
mut self,
|
||||||
|
connection: crate::vpn_task::PreparedConnection,
|
||||||
|
desktop_uid: Option<u32>,
|
||||||
|
edited_report: Option<Arc<str>>,
|
||||||
|
) -> ServiceResult {
|
||||||
|
let reservation = self.reservation.take().expect("preparation retains reservation");
|
||||||
|
self.authority.registry.commit_connection(
|
||||||
|
self.authority.session_id,
|
||||||
|
self.authority.generation,
|
||||||
|
self.non_tunnel,
|
||||||
|
|| reservation.commit(connection, desktop_uid, edited_report, Some(self.authority.session_id)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct RequestDispatcher {
|
pub struct RequestDispatcher {
|
||||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
gui_restart_requested: Arc<AtomicBool>,
|
||||||
@@ -56,38 +104,123 @@ impl RequestDispatcher {
|
|||||||
request: WsRequest,
|
request: WsRequest,
|
||||||
desktop_uid: Option<u32>,
|
desktop_uid: Option<u32>,
|
||||||
edited_report: Option<Arc<str>>,
|
edited_report: Option<Arc<str>>,
|
||||||
session_id: Option<uuid::Uuid>,
|
authority: Option<SessionAuthority>,
|
||||||
) -> Result<WsRequest, ServiceResult> {
|
) -> Result<PendingDispatch, ServiceResult> {
|
||||||
match request {
|
match request {
|
||||||
WsRequest::Connect(request) => {
|
WsRequest::Connect(request) => {
|
||||||
if let Err(message) = self.validate_connect_paths(&request) {
|
if let Err(message) = self.validate_connect_paths(&request) {
|
||||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||||
}
|
}
|
||||||
if let Err(err) = self
|
let redaction_values = request
|
||||||
.redaction
|
.plan()
|
||||||
.add_values(&[request.gateway().server(), request.args().cookie()])
|
.members()
|
||||||
{
|
.iter()
|
||||||
|
.flat_map(|member| [member.gateway.server(), member.authentication.cookie()])
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if let Err(err) = self.redaction.add_values(&redaction_values) {
|
||||||
warn!("Failed to update log redaction: {err}");
|
warn!("Failed to update log redaction: {err}");
|
||||||
return Err(ServiceResult::rejected(
|
return Err(ServiceResult::rejected(
|
||||||
ServiceErrorCode::Internal,
|
ServiceErrorCode::Internal,
|
||||||
"Request could not be accepted",
|
"Request could not be accepted",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Err(
|
let authority = authority
|
||||||
self
|
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||||
.lifecycle
|
let non_tunnel = request
|
||||||
.submit_connect(*request, desktop_uid, edited_report, session_id),
|
.plan()
|
||||||
)
|
.members()
|
||||||
|
.iter()
|
||||||
|
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||||
|
let reservation =
|
||||||
|
authority
|
||||||
|
.registry
|
||||||
|
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
|
||||||
|
self.lifecycle.reserve_connect()
|
||||||
|
})?;
|
||||||
|
let preparation = ConnectionPreparation {
|
||||||
|
authority,
|
||||||
|
non_tunnel,
|
||||||
|
reservation: Some(reservation),
|
||||||
|
};
|
||||||
|
let edited_report = if let gpapi::hip::HipSource::Edited { report_id } = request.args().hip_source() {
|
||||||
|
let report_id = uuid::Uuid::parse_str(report_id)
|
||||||
|
.map_err(|_| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"))?;
|
||||||
|
Some(
|
||||||
|
preparation
|
||||||
|
.authority
|
||||||
|
.registry
|
||||||
|
.edited_hip_report(preparation.authority.session_id, report_id)
|
||||||
|
.map_err(|_| {
|
||||||
|
ServiceResult::rejected(
|
||||||
|
ServiceErrorCode::InvalidRequest,
|
||||||
|
"HIP report is unavailable for this session",
|
||||||
|
)
|
||||||
|
})?,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
edited_report
|
||||||
|
};
|
||||||
|
Ok(PendingDispatch::Connect {
|
||||||
|
preparation,
|
||||||
|
request,
|
||||||
|
desktop_uid,
|
||||||
|
edited_report,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
WsRequest::StopNonTunnelAttachment { connection_id } => {
|
||||||
|
let authority = authority
|
||||||
|
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||||
|
let drain =
|
||||||
|
authority
|
||||||
|
.registry
|
||||||
|
.stop_non_tunnel_attachment(authority.session_id, authority.generation, connection_id)?;
|
||||||
|
Ok(PendingDispatch::Drain(drain))
|
||||||
}
|
}
|
||||||
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
||||||
request => Ok(request),
|
request => Ok(PendingDispatch::Other(request)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||||
let request = match self.dispatch_lifecycle(request, None, None, None) {
|
match self.dispatch_lifecycle(request, None, None, None) {
|
||||||
Ok(request) => request,
|
Ok(request) => self.dispatch_pending(request).await,
|
||||||
Err(result) => return result,
|
Err(result) => result,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn dispatch_pending(&self, request: PendingDispatch) -> ServiceResult {
|
||||||
|
let request = match request {
|
||||||
|
PendingDispatch::Connect {
|
||||||
|
preparation,
|
||||||
|
request,
|
||||||
|
desktop_uid,
|
||||||
|
edited_report,
|
||||||
|
} => {
|
||||||
|
let prepared = crate::vpn_task::prepare_connection(
|
||||||
|
*request,
|
||||||
|
self.brokered_scripts_dir.is_some(),
|
||||||
|
preparation.cancellation(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return match prepared {
|
||||||
|
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Connection preparation failed: {error:#}");
|
||||||
|
ServiceResult::rejected(
|
||||||
|
ServiceErrorCode::InvalidRequest,
|
||||||
|
"Connection resources could not be prepared",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
PendingDispatch::Drain(drain) => {
|
||||||
|
if let Some(drain) = drain {
|
||||||
|
drain.wait().await;
|
||||||
|
}
|
||||||
|
return ServiceResult::Accepted;
|
||||||
|
}
|
||||||
|
PendingDispatch::Other(request) => request,
|
||||||
};
|
};
|
||||||
|
|
||||||
match request {
|
match request {
|
||||||
@@ -132,6 +265,7 @@ impl RequestDispatcher {
|
|||||||
ServiceResult::Accepted
|
ServiceResult::Accepted
|
||||||
}
|
}
|
||||||
WsRequest::Connect(_)
|
WsRequest::Connect(_)
|
||||||
|
| WsRequest::StopNonTunnelAttachment { .. }
|
||||||
| WsRequest::Disconnect(_)
|
| WsRequest::Disconnect(_)
|
||||||
| WsRequest::StoreEditedHipReportChunk(_)
|
| WsRequest::StoreEditedHipReportChunk(_)
|
||||||
| WsRequest::PreviewHipReport(_)
|
| WsRequest::PreviewHipReport(_)
|
||||||
@@ -296,14 +430,12 @@ fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<N
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use crate::vpn_task::test_connect_request as test_request;
|
||||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||||
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
gateway::Gateway,
|
gateway::Gateway,
|
||||||
service::{
|
service::transport::{ServiceErrorCode, ServiceResult},
|
||||||
request::ConnectRequest,
|
|
||||||
transport::{ServiceErrorCode, ServiceResult},
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use tar::{Builder, EntryType, Header};
|
use tar::{Builder, EntryType, Header};
|
||||||
use xz2::write::XzEncoder;
|
use xz2::write::XzEncoder;
|
||||||
@@ -426,7 +558,7 @@ mod tests {
|
|||||||
|
|
||||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||||
let request = ConnectRequest::new(info, "cookie".into())
|
let request = test_request(info)
|
||||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||||
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
||||||
@@ -446,18 +578,17 @@ mod tests {
|
|||||||
);
|
);
|
||||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||||
let bundled = ConnectRequest::new(info.clone(), "cookie".into())
|
let bundled =
|
||||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||||
|
|
||||||
let old_layout = ConnectRequest::new(info.clone(), "cookie".into())
|
let old_layout = test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||||
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
dispatcher.validate_connect_paths(&old_layout),
|
dispatcher.validate_connect_paths(&old_layout),
|
||||||
Err("macOS VPN script must be the bundled script")
|
Err("macOS VPN script must be the bundled script")
|
||||||
);
|
);
|
||||||
|
|
||||||
let custom = ConnectRequest::new(info, "cookie".into())
|
let custom = test_request(info)
|
||||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||||
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||||
path: "/tmp/hip.sh".into(),
|
path: "/tmp/hip.sh".into(),
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::{
|
|||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
use gpapi::service::transport::SessionCredential;
|
use gpapi::service::transport::{ServiceErrorCode, ServiceResult, SessionCredential};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
@@ -62,6 +62,8 @@ enum SessionStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct SessionRecord {
|
struct SessionRecord {
|
||||||
|
non_tunnel: Option<AttachmentAttempt>,
|
||||||
|
closed_attachment: Option<Uuid>,
|
||||||
secret: Zeroizing<[u8; 32]>,
|
secret: Zeroizing<[u8; 32]>,
|
||||||
product_version: String,
|
product_version: String,
|
||||||
desktop_uid: Option<u32>,
|
desktop_uid: Option<u32>,
|
||||||
@@ -72,12 +74,120 @@ struct SessionRecord {
|
|||||||
status: SessionStatus,
|
status: SessionStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Only live preparation/execution is retained, never acceptance history.
|
||||||
|
struct AttachmentAttempt {
|
||||||
|
generation: u64,
|
||||||
|
connection_id: Uuid,
|
||||||
|
drain: crate::vpn_task::AttemptDrain,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct SessionRegistry {
|
pub struct SessionRegistry {
|
||||||
service_instance_id: Uuid,
|
service_instance_id: Uuid,
|
||||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn unavailable_connection() -> ServiceResult {
|
||||||
|
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection attachment is unavailable")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_connection(record: &SessionRecord, expected: u64) -> Result<Uuid, ServiceResult> {
|
||||||
|
match &record.status {
|
||||||
|
SessionStatus::Active {
|
||||||
|
generation,
|
||||||
|
connection: Some(connection),
|
||||||
|
..
|
||||||
|
} if *generation == expected && !connection.is_closed() => Ok(connection.connection_id()),
|
||||||
|
_ => Err(unavailable_connection()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl SessionRegistry {
|
impl SessionRegistry {
|
||||||
|
pub(crate) fn reserve_connection(
|
||||||
|
&self,
|
||||||
|
session_id: Uuid,
|
||||||
|
generation: u64,
|
||||||
|
non_tunnel: bool,
|
||||||
|
reserve: impl FnOnce() -> Result<crate::vpn_task::ConnectReservation, ServiceResult>,
|
||||||
|
) -> Result<crate::vpn_task::ConnectReservation, ServiceResult> {
|
||||||
|
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||||
|
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||||
|
let connection_id = current_connection(record, generation)?;
|
||||||
|
if non_tunnel && record.closed_attachment == Some(connection_id) {
|
||||||
|
return Err(ServiceResult::rejected(
|
||||||
|
ServiceErrorCode::InvalidRequest,
|
||||||
|
"Non-tunnel attachment is closing",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if record
|
||||||
|
.non_tunnel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|attempt| attempt.drain.is_complete())
|
||||||
|
{
|
||||||
|
record.non_tunnel = None;
|
||||||
|
}
|
||||||
|
let reservation = reserve()?;
|
||||||
|
if non_tunnel {
|
||||||
|
record.non_tunnel = Some(AttachmentAttempt {
|
||||||
|
generation,
|
||||||
|
connection_id,
|
||||||
|
drain: reservation.drain(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(reservation)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn commit_connection(
|
||||||
|
&self,
|
||||||
|
session_id: Uuid,
|
||||||
|
generation: u64,
|
||||||
|
non_tunnel: bool,
|
||||||
|
commit: impl FnOnce() -> ServiceResult,
|
||||||
|
) -> ServiceResult {
|
||||||
|
let Ok(sessions) = self.sessions.lock() else {
|
||||||
|
return unavailable_connection();
|
||||||
|
};
|
||||||
|
let Some(record) = sessions.get(&session_id) else {
|
||||||
|
return unavailable_connection();
|
||||||
|
};
|
||||||
|
if non_tunnel {
|
||||||
|
let connection_id = match current_connection(record, generation) {
|
||||||
|
Ok(id) => id,
|
||||||
|
Err(result) => return result,
|
||||||
|
};
|
||||||
|
if record.closed_attachment == Some(connection_id) {
|
||||||
|
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Non-tunnel attachment is closing");
|
||||||
|
}
|
||||||
|
} else if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||||
|
return unavailable_connection();
|
||||||
|
}
|
||||||
|
// Non-tunnel attachment invalidation takes this same lock. An authorized
|
||||||
|
// tunnel reservation survives attachment loss as before; revoked sessions
|
||||||
|
// cannot commit either mode. Queue insertion transfers cleanup ownership.
|
||||||
|
commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn stop_non_tunnel_attachment(
|
||||||
|
&self,
|
||||||
|
session_id: Uuid,
|
||||||
|
generation: u64,
|
||||||
|
connection_id: Uuid,
|
||||||
|
) -> Result<Option<crate::vpn_task::AttemptDrain>, ServiceResult> {
|
||||||
|
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||||
|
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||||
|
let current_id = current_connection(record, generation)?;
|
||||||
|
if current_id == connection_id {
|
||||||
|
record.closed_attachment = Some(connection_id);
|
||||||
|
}
|
||||||
|
if let Some(attempt) = &record.non_tunnel {
|
||||||
|
if attempt.connection_id == connection_id {
|
||||||
|
attempt.drain.cancel();
|
||||||
|
return Ok(Some(attempt.drain.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No retained live work belongs to that attachment. Never stop a successor.
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new(service_instance_id: Uuid) -> Self {
|
pub fn new(service_instance_id: Uuid) -> Self {
|
||||||
Self {
|
Self {
|
||||||
service_instance_id,
|
service_instance_id,
|
||||||
@@ -120,6 +230,8 @@ impl SessionRegistry {
|
|||||||
sessions.insert(
|
sessions.insert(
|
||||||
credential.session_id(),
|
credential.session_id(),
|
||||||
SessionRecord {
|
SessionRecord {
|
||||||
|
non_tunnel: None,
|
||||||
|
closed_attachment: None,
|
||||||
secret: Zeroizing::new(*credential.secret()),
|
secret: Zeroizing::new(*credential.secret()),
|
||||||
product_version: credential.product_version().to_owned(),
|
product_version: credential.product_version().to_owned(),
|
||||||
desktop_uid,
|
desktop_uid,
|
||||||
@@ -258,6 +370,10 @@ impl SessionRegistry {
|
|||||||
connection: current,
|
connection: current,
|
||||||
reconnect_token,
|
reconnect_token,
|
||||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||||
|
if let Some(attempt) = &record.non_tunnel {
|
||||||
|
attempt.drain.cancel();
|
||||||
|
}
|
||||||
|
record.closed_attachment = None;
|
||||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
||||||
*reconnect_token = None;
|
*reconnect_token = None;
|
||||||
Ok(current.replace(connection))
|
Ok(current.replace(connection))
|
||||||
@@ -418,6 +534,13 @@ impl SessionRegistry {
|
|||||||
let Ok(mut sessions) = self.sessions.lock() else {
|
let Ok(mut sessions) = self.sessions.lock() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
if let Some(record) = sessions.get_mut(&session_id) {
|
||||||
|
if let Some(attempt) = &record.non_tunnel {
|
||||||
|
if attempt.generation == generation {
|
||||||
|
attempt.drain.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if let Some(SessionRecord {
|
if let Some(SessionRecord {
|
||||||
status: SessionStatus::Active {
|
status: SessionStatus::Active {
|
||||||
generation: current,
|
generation: current,
|
||||||
@@ -438,9 +561,14 @@ impl SessionRegistry {
|
|||||||
.lock()
|
.lock()
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
.and_then(|mut sessions| sessions.remove(&session_id))
|
||||||
.and_then(|record| match record.status {
|
.and_then(|record| {
|
||||||
SessionStatus::Active { connection, .. } => connection,
|
if let Some(attempt) = &record.non_tunnel {
|
||||||
SessionStatus::Pending { .. } => None,
|
attempt.drain.cancel();
|
||||||
|
}
|
||||||
|
match record.status {
|
||||||
|
SessionStatus::Active { connection, .. } => connection,
|
||||||
|
SessionStatus::Pending { .. } => None,
|
||||||
|
}
|
||||||
});
|
});
|
||||||
if let Some(connection) = connection {
|
if let Some(connection) = connection {
|
||||||
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
||||||
@@ -468,6 +596,140 @@ mod tests {
|
|||||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
ConnectionControl::new(Uuid::new_v4(), tx).0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn attachment_replacement_cancels_preparation_and_retains_drain_until_release() {
|
||||||
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
|
let credential = registry.issue("fixture", None).unwrap();
|
||||||
|
let session = credential.session_id();
|
||||||
|
let first = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _rx) = mpsc::channel(4);
|
||||||
|
let first_control = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||||
|
let old_id = first_control.connection_id();
|
||||||
|
registry.commit_attach(&first, first_control).unwrap();
|
||||||
|
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||||
|
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||||
|
let reservation = registry
|
||||||
|
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
let drain = reservation.drain();
|
||||||
|
let cancel = reservation.cancellation();
|
||||||
|
|
||||||
|
let next = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _next_rx) = mpsc::channel(4);
|
||||||
|
registry
|
||||||
|
.commit_attach(&next, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||||
|
.unwrap();
|
||||||
|
assert!(cancel.is_cancelled());
|
||||||
|
assert!(!drain.is_complete());
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
registry.commit_connection(session, 1, true, || panic!("stale start committed")),
|
||||||
|
ServiceResult::Rejected(_)
|
||||||
|
));
|
||||||
|
drop(reservation);
|
||||||
|
drain.wait().await;
|
||||||
|
|
||||||
|
let next_reservation = registry
|
||||||
|
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.stop_non_tunnel_attachment(session, 2, old_id)
|
||||||
|
.unwrap()
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
assert!(!next_reservation.cancellation().is_cancelled());
|
||||||
|
registry.disconnect_if_current(session, 1);
|
||||||
|
assert!(!next_reservation.cancellation().is_cancelled());
|
||||||
|
registry.disconnect_if_current(session, 2);
|
||||||
|
assert!(next_reservation.cancellation().is_cancelled());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn scoped_stop_closes_attachment_to_delayed_starts_without_receipt_history() {
|
||||||
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
|
let credential = registry.issue("fixture", None).unwrap();
|
||||||
|
let session = credential.session_id();
|
||||||
|
let permit = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _rx) = mpsc::channel(4);
|
||||||
|
let connection = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||||
|
let id = connection.connection_id();
|
||||||
|
registry.commit_attach(&permit, connection).unwrap();
|
||||||
|
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||||
|
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||||
|
let reservation = registry
|
||||||
|
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
|
||||||
|
assert!(reservation.cancellation().is_cancelled());
|
||||||
|
assert!(matches!(
|
||||||
|
registry.commit_connection(session, 1, true, || panic!("closing start committed")),
|
||||||
|
ServiceResult::Rejected(_)
|
||||||
|
));
|
||||||
|
assert!(!drain.is_complete());
|
||||||
|
drop(reservation);
|
||||||
|
drain.wait().await;
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.reserve_connection(session, 1, true, || panic!("closed attachment reserved"))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tunnel_reservation_survives_attachment_loss_but_non_tunnel_revocation_cancels() {
|
||||||
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
|
let credential = registry.issue("fixture", None).unwrap();
|
||||||
|
let session = credential.session_id();
|
||||||
|
let permit = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _rx) = mpsc::channel(4);
|
||||||
|
registry
|
||||||
|
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||||
|
.unwrap();
|
||||||
|
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||||
|
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||||
|
let tunnel = registry
|
||||||
|
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
registry.disconnect_if_current(session, 1);
|
||||||
|
assert!(!tunnel.cancellation().is_cancelled());
|
||||||
|
assert_eq!(
|
||||||
|
registry.commit_connection(session, 1, false, || ServiceResult::Accepted),
|
||||||
|
ServiceResult::Accepted
|
||||||
|
);
|
||||||
|
drop(tunnel);
|
||||||
|
let permit = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _next_rx) = mpsc::channel(4);
|
||||||
|
registry
|
||||||
|
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||||
|
.unwrap();
|
||||||
|
let session_work = registry
|
||||||
|
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
registry.revoke(session);
|
||||||
|
assert!(session_work.cancellation().is_cancelled());
|
||||||
|
assert!(!session_work.drain().is_complete());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn credential_retains_verified_desktop_user_across_reconnect() {
|
fn credential_retains_verified_desktop_user_across_reconnect() {
|
||||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
|
|||||||
+774
-329
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,192 @@
|
|||||||
|
use std::{sync::Arc, time::Duration};
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use gpapi::process::collection::CollectionControl;
|
||||||
|
use gpapi::session::{
|
||||||
|
GatewaySessionSummary, MaintenanceState, SessionEndReason,
|
||||||
|
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||||
|
};
|
||||||
|
use log::warn;
|
||||||
|
use tokio::sync::{mpsc, watch};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
LifecycleEvent,
|
||||||
|
runtime::{AttemptInput, stop_for_revoked_approval},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Borrow the accepted ledger. The outer attempt owner retains identity/source
|
||||||
|
/// resources and joins this runtime before draining the remaining members.
|
||||||
|
pub(super) async fn run(
|
||||||
|
input: &mut AttemptInput,
|
||||||
|
source: Arc<openconnect::HipSource>,
|
||||||
|
approval: &crate::hip_source::HipApproval,
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
|
) -> anyhow::Result<SessionExit> {
|
||||||
|
let request = &input.connection.request;
|
||||||
|
let args = request.args();
|
||||||
|
let resources = &input.connection.resources;
|
||||||
|
let sessions = &mut input.connection.sessions;
|
||||||
|
let network = resources
|
||||||
|
.network
|
||||||
|
.as_ref()
|
||||||
|
.context("Physical network context is missing")?;
|
||||||
|
let posture_enabled =
|
||||||
|
request.plan().policy().collect_hip_data() && !matches!(args.hip_source(), gpapi::hip::HipSource::Disabled);
|
||||||
|
let profile = resources.profile.clone();
|
||||||
|
let initial = sessions
|
||||||
|
.members()
|
||||||
|
.iter()
|
||||||
|
.map(|session| GatewaySessionSummary {
|
||||||
|
gateway: session.gateway.clone(),
|
||||||
|
mode: gpapi::session::SessionMode::NonTunnel,
|
||||||
|
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||||
|
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||||
|
maintenance: MaintenanceState::Authenticated,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let (status, mut changed) = watch::channel(initial);
|
||||||
|
let registry = input.registry.clone();
|
||||||
|
let session_id = input.session_id;
|
||||||
|
let validation_network = network.clone();
|
||||||
|
let validation_detection = request.plan().internal_detection().cloned();
|
||||||
|
let callbacks = SessionCallbacks {
|
||||||
|
validate_network: Arc::new(move |cancel| {
|
||||||
|
let network = validation_network.clone();
|
||||||
|
let detection = validation_detection.clone();
|
||||||
|
Box::pin(async move { network.validate_internal(detection.as_ref(), &cancel).await })
|
||||||
|
}),
|
||||||
|
produce_report: Arc::new(move |request, control| {
|
||||||
|
control.check()?;
|
||||||
|
let context = gphip::ReportContext::Connected {
|
||||||
|
cookie: request.cookie.clone(),
|
||||||
|
client_ip: request.client_ip.clone(),
|
||||||
|
client_ipv6: request.client_ipv6.clone(),
|
||||||
|
md5: request.md5.clone(),
|
||||||
|
};
|
||||||
|
if !posture_enabled {
|
||||||
|
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||||
|
profile: profile.clone(),
|
||||||
|
context,
|
||||||
|
})
|
||||||
|
.map_err(std::io::Error::other);
|
||||||
|
}
|
||||||
|
source.collect(
|
||||||
|
&openconnect::HipRequest {
|
||||||
|
cookie: request.cookie.clone(),
|
||||||
|
client_ip: request.client_ip.clone(),
|
||||||
|
client_ipv6: request.client_ipv6.clone(),
|
||||||
|
md5: request.md5.clone(),
|
||||||
|
client_version: profile.client_version().into(),
|
||||||
|
client_os: profile.client_os().as_str().into(),
|
||||||
|
os_version: profile.os_version().into(),
|
||||||
|
host_id: Some(profile.host_id().into()),
|
||||||
|
local_hostname: Some(profile.computer().into()),
|
||||||
|
},
|
||||||
|
&|| control.check(),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
report_submitted: Arc::new(move |_, xml| {
|
||||||
|
if let Some(session_id) = session_id {
|
||||||
|
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||||
|
warn!("Could not retain submitted HIP report: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
status_changed: Arc::new(move |summary| {
|
||||||
|
status.send_modify(|members| {
|
||||||
|
if let Some(member) = members
|
||||||
|
.iter_mut()
|
||||||
|
.find(|member| member.gateway.server() == summary.gateway.server())
|
||||||
|
{
|
||||||
|
*member = summary;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let monitor_cancel = cancellation.child_token();
|
||||||
|
let monitor_token = monitor_cancel.clone();
|
||||||
|
let network = network.clone();
|
||||||
|
let detection = request.plan().internal_detection().cloned();
|
||||||
|
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||||
|
let monitor = tokio::spawn(async move {
|
||||||
|
match network.wait_for_change(detection, monitor_token).await {
|
||||||
|
Ok(false) => {}
|
||||||
|
Ok(true) => {
|
||||||
|
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Physical network inspection failed: {error}");
|
||||||
|
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let mut approval_revoked = false;
|
||||||
|
let result = {
|
||||||
|
let lifecycle_cancel = cancellation.clone();
|
||||||
|
let maintenance = maintain_non_tunnel_sessions(
|
||||||
|
sessions,
|
||||||
|
request.plan().policy(),
|
||||||
|
callbacks,
|
||||||
|
lifecycle_cancel,
|
||||||
|
async move { network_signal.await.unwrap_or(SessionEndReason::NetworkChanged) },
|
||||||
|
);
|
||||||
|
tokio::pin!(maintenance);
|
||||||
|
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||||
|
let mut publish = true;
|
||||||
|
let result = loop {
|
||||||
|
if publish && !cancellation.is_cancelled() {
|
||||||
|
let members = changed.borrow_and_update().clone();
|
||||||
|
let _ = events
|
||||||
|
.send(LifecycleEvent::MembersChanged {
|
||||||
|
attempt: input.attempt,
|
||||||
|
members,
|
||||||
|
failures: request.plan().failures().to_vec(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
publish = false;
|
||||||
|
}
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
result = &mut maintenance => break result,
|
||||||
|
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||||
|
approval_revoked = true;
|
||||||
|
stop_for_revoked_approval(&input.lifecycle, &cancellation);
|
||||||
|
},
|
||||||
|
result = changed.changed() => { if result.is_ok() { publish = true; } },
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Maintenance can invalidate every member and finish in the same poll.
|
||||||
|
// Forward that last snapshot before monitor/remote cleanup, even when the
|
||||||
|
// completed maintenance branch won over the watch notification.
|
||||||
|
if !cancellation.is_cancelled() {
|
||||||
|
let members = changed.borrow_and_update().clone();
|
||||||
|
let _ = events
|
||||||
|
.send(LifecycleEvent::MembersChanged {
|
||||||
|
attempt: input.attempt,
|
||||||
|
members,
|
||||||
|
failures: request.plan().failures().to_vec(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
};
|
||||||
|
monitor_cancel.cancel();
|
||||||
|
monitor.await.context("Network monitor worker failed")?;
|
||||||
|
if approval_revoked {
|
||||||
|
let _ = events
|
||||||
|
.send(LifecycleEvent::Failed {
|
||||||
|
attempt: input.attempt,
|
||||||
|
reason: "HIP script approval was revoked".into(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
// resources and approval remain owned until maintenance/logout and monitor
|
||||||
|
// inspection are drained. Deliberate disconnect wins throughout cleanup.
|
||||||
|
if cancellation.is_cancelled() {
|
||||||
|
Ok(SessionExit::Disconnected)
|
||||||
|
} else {
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
use std::{
|
||||||
|
io::{Read, Write},
|
||||||
|
sync::Arc,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use gpapi::{
|
||||||
|
gateway::Gateway,
|
||||||
|
gp_params::GpParams,
|
||||||
|
service::{
|
||||||
|
transport::ServiceResult,
|
||||||
|
vpn_state::{ConnectInfo, VpnState},
|
||||||
|
},
|
||||||
|
session::{ClientAddresses, GatewayAuthentication, GatewaySession, GatewaySessions, transport::GatewayTransport},
|
||||||
|
};
|
||||||
|
use openssl::{
|
||||||
|
asn1::Asn1Time,
|
||||||
|
hash::MessageDigest,
|
||||||
|
pkey::PKey,
|
||||||
|
rsa::Rsa,
|
||||||
|
ssl::{SslAcceptor, SslMethod},
|
||||||
|
x509::{X509, X509NameBuilder},
|
||||||
|
};
|
||||||
|
use tokio::sync::{oneshot, watch};
|
||||||
|
|
||||||
|
use super::{LifecycleEvent, PreparedConnection, VpnTask, test_connect_request};
|
||||||
|
|
||||||
|
fn tls_acceptor() -> SslAcceptor {
|
||||||
|
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||||
|
let mut name = X509NameBuilder::new().unwrap();
|
||||||
|
name.append_entry_by_text("CN", "localhost").unwrap();
|
||||||
|
let name = name.build();
|
||||||
|
let mut cert = X509::builder().unwrap();
|
||||||
|
cert.set_version(2).unwrap();
|
||||||
|
cert.set_subject_name(&name).unwrap();
|
||||||
|
cert.set_issuer_name(&name).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();
|
||||||
|
cert.sign(&key, MessageDigest::sha256()).unwrap();
|
||||||
|
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||||
|
acceptor.set_private_key(&key).unwrap();
|
||||||
|
acceptor.set_certificate(&cert.build()).unwrap();
|
||||||
|
acceptor.check_private_key().unwrap();
|
||||||
|
acceptor.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exercise the real HTTPS logout transport without any production network,
|
||||||
|
/// host collectors, or user identity files. The response gate proves admission
|
||||||
|
/// stays owned until the server request finishes.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response() {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let endpoint = listener.local_addr().unwrap();
|
||||||
|
let server_name = format!("https://{endpoint}");
|
||||||
|
let mut gateway = serde_json::to_value(Gateway::new("fixture".into(), server_name.clone())).unwrap();
|
||||||
|
gateway["kind"] = serde_json::json!("internal");
|
||||||
|
let gateway: Gateway = serde_json::from_value(gateway).unwrap();
|
||||||
|
let registry = Arc::new(crate::session_registry::SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||||
|
let credential = registry.issue("fixture", None).unwrap();
|
||||||
|
let session_id = credential.session_id();
|
||||||
|
let permit = registry
|
||||||
|
.begin_handshake(credential.service_instance_id(), session_id, "fixture")
|
||||||
|
.unwrap();
|
||||||
|
let (tx, _rx) = tokio::sync::mpsc::channel(4);
|
||||||
|
let control = crate::ws_connection::ConnectionControl::new(uuid::Uuid::new_v4(), tx).0;
|
||||||
|
let connection_id = control.connection_id();
|
||||||
|
registry.commit_attach(&permit, control).unwrap();
|
||||||
|
let fixture = test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]));
|
||||||
|
let mut member = fixture.plan().members()[0].clone();
|
||||||
|
member.authentication =
|
||||||
|
GatewayAuthentication::new("authcookie=fixture&user=fixture".into(), "internal".into()).unwrap();
|
||||||
|
let plan = gpapi::session::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap();
|
||||||
|
let request = gpapi::service::request::ConnectRequest::new(fixture.info().clone(), plan);
|
||||||
|
let mut prepared = PreparedConnection::lifecycle_fixture(request);
|
||||||
|
let mut params = GpParams::builder(prepared.resources.profile.clone());
|
||||||
|
params.ignore_tls_errors(true);
|
||||||
|
prepared.sessions = GatewaySessions::new(vec![GatewaySession {
|
||||||
|
gateway,
|
||||||
|
transport: GatewayTransport::new(
|
||||||
|
&server_name,
|
||||||
|
prepared.request.plan().members()[0].authentication.clone(),
|
||||||
|
¶ms.build(),
|
||||||
|
prepared.request.plan().members()[0].binding.as_ref(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
addresses: ClientAddresses::default(),
|
||||||
|
}]);
|
||||||
|
let acceptor = tls_acceptor();
|
||||||
|
let (arrived, arrival) = oneshot::channel();
|
||||||
|
let (release, response_gate) = oneshot::channel();
|
||||||
|
let server = tokio::spawn(async move {
|
||||||
|
let (socket, _) = tokio::time::timeout(Duration::from_secs(3), listener.accept())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
let socket = socket.into_std().unwrap();
|
||||||
|
socket.set_nonblocking(false).unwrap();
|
||||||
|
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||||
|
socket.set_write_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||||
|
let request = tokio::task::spawn_blocking(move || {
|
||||||
|
let mut stream = acceptor.accept(socket).unwrap();
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
let (headers_end, body_len) = loop {
|
||||||
|
let mut chunk = [0; 1024];
|
||||||
|
let count = stream.read(&mut chunk).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 + body_len {
|
||||||
|
let mut chunk = [0; 1024];
|
||||||
|
let count = stream.read(&mut chunk).unwrap();
|
||||||
|
assert_ne!(count, 0);
|
||||||
|
bytes.extend_from_slice(&chunk[..count]);
|
||||||
|
}
|
||||||
|
arrived.send(()).unwrap();
|
||||||
|
response_gate.blocking_recv().unwrap();
|
||||||
|
let body = "<response status=\"success\"/>";
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
stream.flush().unwrap();
|
||||||
|
String::from_utf8(bytes).unwrap()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// A single accepted authentication must produce a single logout.
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(Duration::from_millis(100), listener.accept())
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
request
|
||||||
|
});
|
||||||
|
let (state, state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
|
||||||
|
let reservation = registry
|
||||||
|
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
registry.commit_connection(session_id, 1, true, || reservation.commit(
|
||||||
|
prepared,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Some(session_id)
|
||||||
|
)),
|
||||||
|
ServiceResult::Accepted
|
||||||
|
);
|
||||||
|
let drain = registry
|
||||||
|
.stop_non_tunnel_attachment(session_id, 1, connection_id)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
let drain_waiter = tokio::spawn(async move {
|
||||||
|
drain.wait().await;
|
||||||
|
});
|
||||||
|
let start = task.events.recv().await.unwrap();
|
||||||
|
assert!(matches!(&start, LifecycleEvent::Start { .. }));
|
||||||
|
task.handle_event(start).await;
|
||||||
|
tokio::time::timeout(Duration::from_secs(3), arrival)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert!(lifecycle.has_attempt(0));
|
||||||
|
assert!(!drain_waiter.is_finished());
|
||||||
|
assert!(lifecycle.reserve_connect().is_err());
|
||||||
|
assert!(!task.active.as_ref().unwrap().task.is_finished());
|
||||||
|
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||||
|
release.send(()).unwrap();
|
||||||
|
while task.active.is_some() {
|
||||||
|
let event = tokio::time::timeout(Duration::from_secs(3), task.events.recv())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
task.handle_event(event).await;
|
||||||
|
}
|
||||||
|
assert!(!lifecycle.has_attempt(0));
|
||||||
|
drain_waiter.await.unwrap();
|
||||||
|
assert!(lifecycle.reserve_connect().is_ok());
|
||||||
|
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||||
|
let request = server.await.unwrap();
|
||||||
|
assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
|
||||||
|
let form = request.split_once("\r\n\r\n").unwrap().1;
|
||||||
|
let fields = url_form(form);
|
||||||
|
assert_eq!(fields.get("user").map(String::as_str), Some("fixture"));
|
||||||
|
assert_eq!(fields.get("computer").map(String::as_str), Some("fixture"));
|
||||||
|
assert_eq!(fields.get("clientos").map(String::as_str), Some("Linux"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url_form(form: &str) -> std::collections::HashMap<String, String> {
|
||||||
|
form
|
||||||
|
.split('&')
|
||||||
|
.map(|field| {
|
||||||
|
let (key, value) = field.split_once('=').unwrap();
|
||||||
|
(key.to_owned(), value.to_owned())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
use std::{sync::Arc, time::Duration};
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use gpapi::{
|
||||||
|
gp_params::GpParams,
|
||||||
|
os_profile::OsProfile,
|
||||||
|
process::collection::{CollectionBudget, CollectionControl},
|
||||||
|
service::request::ConnectRequest,
|
||||||
|
session::{GatewaySession, GatewaySessions, network::PhysicalNetwork, transport::GatewayTransport},
|
||||||
|
};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
pub(crate) struct PreparedConnection {
|
||||||
|
pub(super) request: ConnectRequest,
|
||||||
|
pub(super) resources: Arc<ConnectionResources>,
|
||||||
|
pub(super) sessions: GatewaySessions,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct ConnectionResources {
|
||||||
|
pub profile: OsProfile,
|
||||||
|
pub identity: Option<gpapi::utils::request::ClientIdentity>,
|
||||||
|
pub identity_files: Option<gpapi::utils::request::ClientIdentityFiles>,
|
||||||
|
pub network: Option<PhysicalNetwork>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Preparation sends no authenticated gateway requests. Rejection leaves the
|
||||||
|
/// authentication owner responsible for logout; only queued admission transfers
|
||||||
|
/// the complete ledger and its retained identity resources to the service.
|
||||||
|
pub(crate) async fn prepare_connection(
|
||||||
|
request: ConnectRequest,
|
||||||
|
brokered_macos: bool,
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
) -> anyhow::Result<PreparedConnection> {
|
||||||
|
let args = request.args();
|
||||||
|
let non_tunnel = request
|
||||||
|
.plan()
|
||||||
|
.members()
|
||||||
|
.iter()
|
||||||
|
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||||
|
anyhow::ensure!(
|
||||||
|
non_tunnel || request.plan().members().len() == 1,
|
||||||
|
"Only one selected tunnel gateway can execute"
|
||||||
|
);
|
||||||
|
for member in request.plan().members() {
|
||||||
|
if non_tunnel {
|
||||||
|
let binding = member.binding.as_ref().context("Internal gateway binding is missing")?;
|
||||||
|
anyhow::ensure!(
|
||||||
|
!args.disable_ipv6() || (binding.endpoint().is_ipv4() && binding.addresses().ipv6.is_none()),
|
||||||
|
"IPv6 gateway transport or identity is disabled"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let setup_request = request.clone();
|
||||||
|
let setup_cancel = cancellation.clone();
|
||||||
|
let resources = tokio::task::spawn_blocking(move || {
|
||||||
|
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||||
|
let check = || {
|
||||||
|
if setup_cancel.is_cancelled() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::Interrupted,
|
||||||
|
"Connection preparation cancelled",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
budget.check()
|
||||||
|
};
|
||||||
|
check()?;
|
||||||
|
let args = setup_request.args();
|
||||||
|
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||||
|
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||||
|
let identity_files = identity
|
||||||
|
.as_ref()
|
||||||
|
.map(|identity| identity.write_files(directory))
|
||||||
|
.transpose()?;
|
||||||
|
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||||
|
let profile = crate::hip_source::profile(
|
||||||
|
host,
|
||||||
|
args.os().context("Authenticated client OS is missing")?,
|
||||||
|
args.client_version(),
|
||||||
|
args.os_version(),
|
||||||
|
args.host_id(),
|
||||||
|
args.local_hostname(),
|
||||||
|
&check,
|
||||||
|
)?;
|
||||||
|
let network = if non_tunnel {
|
||||||
|
Some(PhysicalNetwork::capture(&check)?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
check()?;
|
||||||
|
Ok::<_, anyhow::Error>(Arc::new(ConnectionResources {
|
||||||
|
profile,
|
||||||
|
identity,
|
||||||
|
identity_files,
|
||||||
|
network,
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
.await??;
|
||||||
|
let args = request.args();
|
||||||
|
let mut builder = GpParams::builder(resources.profile.clone());
|
||||||
|
builder
|
||||||
|
.ignore_tls_errors(args.ignore_tls_errors())
|
||||||
|
.client_identity(resources.identity.clone());
|
||||||
|
let params = builder.build();
|
||||||
|
let mut sessions = Vec::new();
|
||||||
|
for member in request.plan().members() {
|
||||||
|
let binding = if non_tunnel {
|
||||||
|
Some(member.binding.as_ref().context("Internal gateway binding is missing")?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(network) = &resources.network {
|
||||||
|
network
|
||||||
|
.validate_internal_binding(
|
||||||
|
binding.context("Internal gateway binding is missing")?,
|
||||||
|
request.plan().internal_detection(),
|
||||||
|
&cancellation,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
let transport = GatewayTransport::new(member.gateway.server(), member.authentication.clone(), ¶ms, binding)?;
|
||||||
|
sessions.push(GatewaySession {
|
||||||
|
gateway: member.gateway.clone(),
|
||||||
|
transport,
|
||||||
|
addresses: binding.map(|binding| binding.addresses()).unwrap_or_default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(network) = &resources.network {
|
||||||
|
network.ensure_current(&cancellation).await?;
|
||||||
|
}
|
||||||
|
Ok(PreparedConnection {
|
||||||
|
request,
|
||||||
|
resources,
|
||||||
|
sessions: GatewaySessions::new(sessions),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
impl PreparedConnection {
|
||||||
|
/// Lifecycle-only fixtures own no issued server sessions. Protocol ownership
|
||||||
|
/// checks use actual gateway transports rather than this actor-state fixture.
|
||||||
|
pub(crate) fn lifecycle_fixture(request: ConnectRequest) -> Self {
|
||||||
|
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||||
|
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||||
|
"fixture".into(),
|
||||||
|
"fixture-host".into(),
|
||||||
|
"fixture-serial".into(),
|
||||||
|
"02:00:00:00:00:01".into(),
|
||||||
|
))
|
||||||
|
.build();
|
||||||
|
Self {
|
||||||
|
request,
|
||||||
|
resources: Arc::new(ConnectionResources {
|
||||||
|
profile,
|
||||||
|
identity: None,
|
||||||
|
identity_files: None,
|
||||||
|
network: None,
|
||||||
|
}),
|
||||||
|
sessions: GatewaySessions::new(vec![]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||||
|
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||||
|
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||||
|
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||||
|
.with_certificate(Some("/identity.pem".into()));
|
||||||
|
let mut wire = serde_json::to_value(request).unwrap();
|
||||||
|
if non_tunnel {
|
||||||
|
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||||
|
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||||
|
}
|
||||||
|
let request = serde_json::from_value(wire).unwrap();
|
||||||
|
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||||
|
.await
|
||||||
|
.err()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(error.to_string(), "Client identity must be a protected snapshot");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disabled_ipv6_rejects_ipv6_report_identity_before_setup() {
|
||||||
|
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||||
|
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||||
|
.with_disable_ipv6(true);
|
||||||
|
let mut wire = serde_json::to_value(request).unwrap();
|
||||||
|
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||||
|
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||||
|
wire["plan"]["members"][0]["binding"]["addresses"]["ipv6"] = serde_json::json!("2001:db8::5");
|
||||||
|
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||||
|
// The fixture has no host identity or usable physical interface. Policy
|
||||||
|
// rejection must happen before those collectors or transport setup run.
|
||||||
|
let error = prepare_connection(request, false, CancellationToken::new())
|
||||||
|
.await
|
||||||
|
.err()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(error.to_string(), "IPv6 gateway transport or identity is disabled");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn ordinary_tunnel_preparation_needs_no_physical_binding_or_resolver() {
|
||||||
|
let gateway = Gateway::new("fixture".into(), "does-not-resolve.invalid".into());
|
||||||
|
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||||
|
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||||
|
"fixture".into(),
|
||||||
|
"fixture-host".into(),
|
||||||
|
"fixture-serial".into(),
|
||||||
|
"02:00:00:00:00:01".into(),
|
||||||
|
))
|
||||||
|
.build();
|
||||||
|
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||||
|
.with_os_profile(&profile)
|
||||||
|
.with_disable_ipv6(true);
|
||||||
|
let mut wire = serde_json::to_value(request).unwrap();
|
||||||
|
wire["plan"]["members"][0]["binding"] = serde_json::Value::Null;
|
||||||
|
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||||
|
let prepared = prepare_connection(request, false, CancellationToken::new())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(prepared.resources.network.is_none());
|
||||||
|
assert_eq!(prepared.sessions.members().len(), 1);
|
||||||
|
assert!(prepared.sessions.members()[0].addresses.ipv4.is_none());
|
||||||
|
assert!(prepared.sessions.members()[0].addresses.ipv6.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
use std::{sync::Arc, time::Duration};
|
||||||
|
|
||||||
|
use anyhow::{Context, ensure};
|
||||||
|
use gpapi::{
|
||||||
|
process::collection::{CollectionBudget, CollectionControl},
|
||||||
|
service::request::ConnectRequest,
|
||||||
|
session::SessionMode,
|
||||||
|
};
|
||||||
|
use log::warn;
|
||||||
|
use openconnect::Vpn;
|
||||||
|
use tokio::{sync::mpsc, task::JoinHandle};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{LifecycleEvent, LifecycleHandle, PreparedConnection, preparation::ConnectionResources};
|
||||||
|
|
||||||
|
pub(super) struct AttemptInput {
|
||||||
|
pub attempt: u64,
|
||||||
|
pub connection: PreparedConnection,
|
||||||
|
pub desktop_uid: Option<u32>,
|
||||||
|
pub edited_report: Option<Arc<str>>,
|
||||||
|
pub session_id: Option<Uuid>,
|
||||||
|
pub brokered_macos: bool,
|
||||||
|
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
|
pub lifecycle: LifecycleHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TunnelInput {
|
||||||
|
request: ConnectRequest,
|
||||||
|
resources: Arc<ConnectionResources>,
|
||||||
|
source: Arc<openconnect::HipSource>,
|
||||||
|
session_id: Option<Uuid>,
|
||||||
|
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PreparedTunnel {
|
||||||
|
vpn: Arc<Vpn>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
|
||||||
|
/// borrow that ledger; a native tunnel takes its cleanup ownership when started.
|
||||||
|
/// Cancellation joins execution before draining any remaining issued sessions.
|
||||||
|
pub(super) fn spawn(
|
||||||
|
mut input: AttemptInput,
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
|
) -> JoinHandle<()> {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let attempt = input.attempt;
|
||||||
|
let non_tunnel = input
|
||||||
|
.connection
|
||||||
|
.request
|
||||||
|
.plan()
|
||||||
|
.members()
|
||||||
|
.iter()
|
||||||
|
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||||
|
let mut failure = None;
|
||||||
|
let mut approval = None;
|
||||||
|
if !cancellation.is_cancelled() {
|
||||||
|
let request = input.connection.request.clone();
|
||||||
|
let resources = input.connection.resources.clone();
|
||||||
|
let desktop_uid = input.desktop_uid;
|
||||||
|
let brokered = input.brokered_macos;
|
||||||
|
let edited = input.edited_report.clone();
|
||||||
|
let setup_cancel = cancellation.clone();
|
||||||
|
let execution = tokio::task::spawn_blocking(move || {
|
||||||
|
prepare_execution(request, resources, desktop_uid, brokered, edited, &setup_cancel)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match execution {
|
||||||
|
Ok(Ok(execution)) => {
|
||||||
|
let (source, guard) = execution.into_parts();
|
||||||
|
approval = Some(guard);
|
||||||
|
let source = Arc::new(source);
|
||||||
|
let guard = approval.as_ref().expect("execution approval is retained");
|
||||||
|
if input
|
||||||
|
.connection
|
||||||
|
.request
|
||||||
|
.plan()
|
||||||
|
.members()
|
||||||
|
.iter()
|
||||||
|
.all(|member| member.authentication.mode() == SessionMode::NonTunnel)
|
||||||
|
{
|
||||||
|
match super::non_tunnel::run(&mut input, source, guard, cancellation.clone(), events.clone()).await {
|
||||||
|
Ok(gpapi::session::non_tunnel::SessionExit::Disconnected) => {}
|
||||||
|
Ok(gpapi::session::non_tunnel::SessionExit::Failed(reason)) => {
|
||||||
|
let message = match reason {
|
||||||
|
gpapi::session::SessionEndReason::InvalidCookie => {
|
||||||
|
"Internal gateway authentication expired; connect again"
|
||||||
|
}
|
||||||
|
gpapi::session::SessionEndReason::NetworkChanged => {
|
||||||
|
"Physical network changed or could not be verified; connect again"
|
||||||
|
}
|
||||||
|
gpapi::session::SessionEndReason::AllMembersFailed => {
|
||||||
|
"All internal gateway sessions failed; connect again"
|
||||||
|
}
|
||||||
|
gpapi::session::SessionEndReason::AuthorizationRevoked => "HIP execution authorization was revoked",
|
||||||
|
};
|
||||||
|
failure = Some(message.into());
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("Non-tunnel maintenance failed: {error:#}");
|
||||||
|
failure = Some("Internal session maintenance failed".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let tunnel_input = TunnelInput {
|
||||||
|
request: input.connection.request.clone(),
|
||||||
|
resources: input.connection.resources.clone(),
|
||||||
|
source,
|
||||||
|
session_id: input.session_id,
|
||||||
|
registry: input.registry.clone(),
|
||||||
|
};
|
||||||
|
let setup_cancel = cancellation.clone();
|
||||||
|
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
|
||||||
|
match prepared {
|
||||||
|
Ok(Ok(prepared)) => {
|
||||||
|
run_tunnel(
|
||||||
|
attempt,
|
||||||
|
&prepared,
|
||||||
|
guard,
|
||||||
|
&input.lifecycle,
|
||||||
|
&mut input.connection.sessions,
|
||||||
|
cancellation.clone(),
|
||||||
|
events.clone(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
|
||||||
|
Err(error) => warn!("Tunnel setup worker failed: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
warn!("Failed to prepare HIP execution: {error:#}");
|
||||||
|
failure = Some("HIP execution could not be prepared".into());
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
warn!("HIP setup worker failed: {error}");
|
||||||
|
failure = Some("HIP setup worker failed".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input.connection.sessions.logout().await;
|
||||||
|
// Identity and approval remain alive through worker drain and logout. Ended
|
||||||
|
// only releases admission after the actor also joins this task.
|
||||||
|
drop(approval);
|
||||||
|
if non_tunnel && !cancellation.is_cancelled() {
|
||||||
|
if let Some(reason) = failure {
|
||||||
|
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = events.send(LifecycleEvent::Ended { attempt }).await;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_execution(
|
||||||
|
request: ConnectRequest,
|
||||||
|
resources: Arc<ConnectionResources>,
|
||||||
|
desktop_uid: Option<u32>,
|
||||||
|
brokered: bool,
|
||||||
|
edited: Option<Arc<str>>,
|
||||||
|
cancellation: &CancellationToken,
|
||||||
|
) -> anyhow::Result<crate::hip_source::HipExecution> {
|
||||||
|
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||||
|
let check = || {
|
||||||
|
if cancellation.is_cancelled() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::Interrupted,
|
||||||
|
"HIP setup cancelled",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
budget.check()
|
||||||
|
};
|
||||||
|
check()?;
|
||||||
|
let args = request.args();
|
||||||
|
let pure_non_tunnel = request
|
||||||
|
.plan()
|
||||||
|
.members()
|
||||||
|
.iter()
|
||||||
|
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||||
|
let disabled = pure_non_tunnel && !request.plan().policy().collect_hip_data();
|
||||||
|
let source = if disabled {
|
||||||
|
&gpapi::hip::HipSource::Disabled
|
||||||
|
} else {
|
||||||
|
args.hip_source()
|
||||||
|
};
|
||||||
|
let execution = crate::hip_source::resolve(source, desktop_uid, brokered, edited, Some(resources.profile.clone()))?;
|
||||||
|
check()?;
|
||||||
|
Ok(execution)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyhow::Result<PreparedTunnel> {
|
||||||
|
let args = input.request.args();
|
||||||
|
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||||
|
let check = || {
|
||||||
|
if cancellation.is_cancelled() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::Interrupted,
|
||||||
|
"Tunnel setup cancelled",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
budget.check()
|
||||||
|
};
|
||||||
|
check()?;
|
||||||
|
ensure!(
|
||||||
|
input.request.plan().members().len() == 1
|
||||||
|
&& input.request.plan().members()[0].authentication.mode() == SessionMode::Tunnel,
|
||||||
|
"Tunnel execution requires one selected tunnel gateway"
|
||||||
|
);
|
||||||
|
let member = &input.request.plan().members()[0];
|
||||||
|
let identity_files = &input.resources.identity_files;
|
||||||
|
let vpn = Arc::new(
|
||||||
|
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?
|
||||||
|
.user_agent(args.user_agent())
|
||||||
|
.os(args.openconnect_os())
|
||||||
|
.os_version(args.os_version())
|
||||||
|
.client_version(args.client_version())
|
||||||
|
.host_id(args.host_id())
|
||||||
|
.certificate(identity_files.as_ref().map(|files| files.certificate().to_owned()))
|
||||||
|
.sslkey(identity_files.as_ref().and_then(|files| files.key()).map(str::to_owned))
|
||||||
|
.key_password(
|
||||||
|
input
|
||||||
|
.resources
|
||||||
|
.identity
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|identity| identity.key_password())
|
||||||
|
.map(str::to_owned),
|
||||||
|
)
|
||||||
|
.hip_source(input.source)
|
||||||
|
.reconnect_timeout(args.reconnect_timeout())
|
||||||
|
.mtu(args.mtu())
|
||||||
|
.disable_ipv6(args.disable_ipv6())
|
||||||
|
.no_dtls(args.no_dtls())
|
||||||
|
.local_hostname(args.local_hostname())
|
||||||
|
.dpd_interval(args.force_dpd())
|
||||||
|
.no_xmlpost(args.no_xmlpost())
|
||||||
|
.build()
|
||||||
|
.context("Failed to create tunnel worker")?,
|
||||||
|
);
|
||||||
|
check()?;
|
||||||
|
if let Some(session_id) = input.session_id {
|
||||||
|
let registry = input.registry;
|
||||||
|
vpn.set_hip_report_callback(move |xml| {
|
||||||
|
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||||
|
warn!("Could not retain submitted HIP report: {error}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(PreparedTunnel { vpn })
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_tunnel(
|
||||||
|
attempt: u64,
|
||||||
|
prepared: &PreparedTunnel,
|
||||||
|
approval: &crate::hip_source::HipApproval,
|
||||||
|
lifecycle: &LifecycleHandle,
|
||||||
|
sessions: &mut gpapi::session::GatewaySessions,
|
||||||
|
cancellation: CancellationToken,
|
||||||
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
|
) {
|
||||||
|
if cancellation.is_cancelled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let vpn = prepared.vpn.clone();
|
||||||
|
// The native tunnel keeps its reconnect endpoint and cookie current and owns
|
||||||
|
// normal logout. The ledger remains responsible only before native execution.
|
||||||
|
// Service admission permits exactly one tunnel member.
|
||||||
|
std::mem::take(sessions).relinquish();
|
||||||
|
let worker = tokio::task::spawn_blocking(move || {
|
||||||
|
vpn.connect(move |session| {
|
||||||
|
let _ = events.blocking_send(LifecycleEvent::Established { attempt, session });
|
||||||
|
})
|
||||||
|
});
|
||||||
|
tokio::pin!(worker);
|
||||||
|
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||||
|
let result = loop {
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
_ = cancellation.cancelled() => { prepared.vpn.disconnect(); break (&mut worker).await; },
|
||||||
|
result = &mut worker => break result,
|
||||||
|
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||||
|
stop_for_revoked_approval(lifecycle, &cancellation);
|
||||||
|
prepared.vpn.disconnect();
|
||||||
|
break (&mut worker).await;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(0 | -4) => {}
|
||||||
|
Ok(code) => warn!("Tunnel worker exited with status {code}"),
|
||||||
|
Err(error) => warn!("Tunnel worker failed: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn stop_for_revoked_approval(lifecycle: &LifecycleHandle, cancellation: &CancellationToken) {
|
||||||
|
let result = lifecycle.request_disconnect();
|
||||||
|
if !matches!(result, gpapi::service::transport::ServiceResult::Accepted) {
|
||||||
|
warn!("Could not enqueue approval revocation stop: {result:?}");
|
||||||
|
}
|
||||||
|
cancellation.cancel();
|
||||||
|
}
|
||||||
@@ -58,11 +58,11 @@ impl ConnectionControl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_closed(&self) -> bool {
|
pub fn is_closed(&self) -> bool {
|
||||||
self.tx.is_closed()
|
self.tx.is_closed() || self.close_tx.borrow().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn close(&self, reason: CloseReason) {
|
pub fn close(&self, reason: CloseReason) {
|
||||||
let _ = self.close_tx.send(Some(reason));
|
self.close_tx.send_replace(Some(reason));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||||
@@ -185,11 +185,11 @@ impl WsConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ctx
|
ctx
|
||||||
.hip_previews
|
.remove_connection(control.connection_id(), permit.session_id, generation)
|
||||||
.cancel_connection(permit.session_id, control.connection_id())
|
|
||||||
.await;
|
.await;
|
||||||
ctx
|
ctx
|
||||||
.remove_connection(control.connection_id(), permit.session_id, generation)
|
.hip_previews
|
||||||
|
.cancel_connection(permit.session_id, control.connection_id())
|
||||||
.await;
|
.await;
|
||||||
info!("GUI connection {} closed", control.connection_id());
|
info!("GUI connection {} closed", control.connection_id());
|
||||||
}
|
}
|
||||||
@@ -487,44 +487,17 @@ async fn handle_client_message(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let edited_report = if let WsRequest::Connect(connect) = &request {
|
|
||||||
if let HipSource::Edited { report_id } = connect.args().hip_source() {
|
|
||||||
let report_id = match Uuid::parse_str(report_id) {
|
|
||||||
Ok(id) => id,
|
|
||||||
Err(_) => {
|
|
||||||
control
|
|
||||||
.send(ConnectionCommand::Reply {
|
|
||||||
id,
|
|
||||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"),
|
|
||||||
})
|
|
||||||
.map_err(|_| ())?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
match ctx.registry().edited_hip_report(session_id, report_id) {
|
|
||||||
Ok(report) => Some(report),
|
|
||||||
Err(_) => {
|
|
||||||
control
|
|
||||||
.send(ConnectionCommand::Reply {
|
|
||||||
id,
|
|
||||||
result: ServiceResult::rejected(
|
|
||||||
ServiceErrorCode::InvalidRequest,
|
|
||||||
"HIP report is unavailable for this session",
|
|
||||||
),
|
|
||||||
})
|
|
||||||
.map_err(|_| ())?;
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let dispatcher = ctx.dispatcher();
|
let dispatcher = ctx.dispatcher();
|
||||||
let request = match dispatcher.dispatch_lifecycle(request, desktop_uid, edited_report, Some(session_id)) {
|
let request = match dispatcher.dispatch_lifecycle(
|
||||||
|
request,
|
||||||
|
desktop_uid,
|
||||||
|
None,
|
||||||
|
Some(crate::request_dispatcher::SessionAuthority {
|
||||||
|
registry: Arc::clone(ctx.registry()),
|
||||||
|
session_id,
|
||||||
|
generation,
|
||||||
|
}),
|
||||||
|
) {
|
||||||
Ok(request) => request,
|
Ok(request) => request,
|
||||||
Err(result) => {
|
Err(result) => {
|
||||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||||
@@ -536,7 +509,7 @@ async fn handle_client_message(
|
|||||||
};
|
};
|
||||||
let control = control.clone();
|
let control = control.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let result = dispatcher.dispatch(request).await;
|
let result = dispatcher.dispatch_pending(request).await;
|
||||||
control.send_reply(id, result).await;
|
control.send_reply(id, result).await;
|
||||||
});
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -151,8 +151,8 @@ impl WsServerContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||||
self.state.lock().await.connections.remove(&connection_id);
|
|
||||||
self.registry.disconnect_if_current(session_id, generation);
|
self.registry.disconnect_if_current(session_id, generation);
|
||||||
|
self.state.lock().await.connections.remove(&connection_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_event(&self, event: WsEvent) {
|
pub async fn send_event(&self, event: WsEvent) {
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
use std::process::{Command, Stdio};
|
use std::{
|
||||||
|
os::unix::process::CommandExt,
|
||||||
|
process::{Command, Stdio},
|
||||||
|
};
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use log::{debug, info, warn};
|
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}");
|
info!("Launching Flatpak browser: {app_id}");
|
||||||
Command::new(executable)
|
Command::new(executable)
|
||||||
.args(["run", app_id, url])
|
.args(["run", app_id, url])
|
||||||
|
.process_group(0)
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::null())
|
||||||
|
|||||||
@@ -81,8 +81,27 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
|
|||||||
let current_exe = env::current_exe().ok()?;
|
let current_exe = env::current_exe().ok()?;
|
||||||
let bin_dir = current_exe.parent()?;
|
let bin_dir = current_exe.parent()?;
|
||||||
let binary = bin_dir.join(binary_name);
|
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(¤t_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 {
|
fn is_file(path: &Path) -> bool {
|
||||||
@@ -93,6 +112,20 @@ fn is_file(path: &Path) -> bool {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn default_path_is_used_when_no_sibling_exists() {
|
fn default_path_is_used_when_no_sibling_exists() {
|
||||||
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
|
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
|
||||||
|
|||||||
@@ -18,9 +18,10 @@ version-compare = "0.2"
|
|||||||
pem.workspace = true
|
pem.workspace = true
|
||||||
xmltree.workspace = true
|
xmltree.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
specta = { workspace = true, features = ["derive"] }
|
specta = { workspace = true, features = ["derive", "uuid"] }
|
||||||
urlencoding.workspace = true
|
urlencoding.workspace = true
|
||||||
tokio = { workspace = true, features = ["process", "signal", "macros"] }
|
tokio = { workspace = true, features = ["process", "signal", "macros"] }
|
||||||
|
tokio-util.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
whoami.workspace = true
|
whoami.workspace = true
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
@@ -59,6 +60,7 @@ gtk = { version = "0.18", optional = true }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
proptest.workspace = true
|
proptest.workspace = true
|
||||||
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
tauri = ["dep:tauri", "dep:gtk"]
|
tauri = ["dep:tauri", "dep:gtk"]
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
use std::{borrow::Cow, net::UdpSocket};
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
|
net::{SocketAddr, UdpSocket},
|
||||||
|
};
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, warn};
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
use urlencoding::{decode, encode};
|
use urlencoding::{decode, encode};
|
||||||
use xmltree::Element;
|
use xmltree::Element;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
credential::Credential,
|
credential::Credential,
|
||||||
@@ -12,68 +17,238 @@ use crate::{
|
|||||||
gateway::GatewayLoginContext,
|
gateway::GatewayLoginContext,
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
params::gateway_login::{self, GatewayLoginInput},
|
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},
|
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub enum GatewayLogin {
|
pub enum GatewayLogin {
|
||||||
Cookie(String),
|
Authenticated(GatewayAuthentication),
|
||||||
Mfa(String, String),
|
Mfa(String, String),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
|
/// Protocol failures cannot be repaired by repeating login with different
|
||||||
gateway_login_with_options(gateway, cred, gp_params, None, false).await
|
/// 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(
|
impl GatewayLoginClient {
|
||||||
gateway: &str,
|
pub fn register_session(
|
||||||
cred: &Credential,
|
&self,
|
||||||
gp_params: &GpParams,
|
gateway: crate::gateway::Gateway,
|
||||||
context: &GatewayLoginContext,
|
authentication: GatewayAuthentication,
|
||||||
) -> anyhow::Result<GatewayLogin> {
|
sessions: &mut crate::session::GatewaySessions,
|
||||||
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
|
) {
|
||||||
|
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(¶ms)?;
|
||||||
|
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(
|
struct LoginResponse {
|
||||||
gateway: &str,
|
login: GatewayLogin,
|
||||||
cred: &Credential,
|
endpoint: Option<SocketAddr>,
|
||||||
gp_params: &GpParams,
|
url: reqwest::Url,
|
||||||
) -> anyhow::Result<GatewayLogin> {
|
|
||||||
gateway_login_with_options(gateway, cred, gp_params, None, true).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn gateway_login_with_options(
|
struct ReceivedLogin {
|
||||||
gateway: &str,
|
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,
|
cred: &Credential,
|
||||||
gp_params: &GpParams,
|
gp_params: &GpParams,
|
||||||
context: Option<&GatewayLoginContext>,
|
context: Option<&GatewayLoginContext>,
|
||||||
|
client_ip: Option<&str>,
|
||||||
extend_lifetime: bool,
|
extend_lifetime: bool,
|
||||||
) -> anyhow::Result<GatewayLogin> {
|
) -> anyhow::Result<ReceivedLogin> {
|
||||||
let url = normalize_server(gateway)?;
|
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
|
||||||
let gateway = remove_url_scheme(&url);
|
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
|
||||||
|
|
||||||
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()))
|
|
||||||
});
|
|
||||||
let request_params = gateway_login::build(&GatewayLoginInput {
|
let request_params = gateway_login::build(&GatewayLoginInput {
|
||||||
gp_params,
|
gp_params,
|
||||||
cred,
|
cred,
|
||||||
gateway_host: &gateway,
|
gateway_host: &gateway,
|
||||||
context,
|
context,
|
||||||
client_ip: client_ip.as_deref(),
|
client_ip,
|
||||||
extend_lifetime,
|
extend_lifetime,
|
||||||
});
|
});
|
||||||
|
|
||||||
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
|
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
|
let res = client
|
||||||
.post(&login_url)
|
.post(login_url)
|
||||||
.form(&request_params.body)
|
.form(&request_params.body)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
@@ -82,11 +257,32 @@ async fn gateway_login_with_options(
|
|||||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
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| {
|
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)
|
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
|
// It's possible to get an empty response, log the response headers for debugging
|
||||||
if res.trim().is_empty() {
|
if res.trim().is_empty() {
|
||||||
info!("Empty gateway login response headers: {:?}", res);
|
info!("Empty gateway login response headers: {:?}", res);
|
||||||
@@ -96,27 +292,47 @@ async fn gateway_login_with_options(
|
|||||||
// MFA detected
|
// MFA detected
|
||||||
if res.contains("Challenge") {
|
if res.contains("Challenge") {
|
||||||
let Some((message, input_str)) = parse_mfa(&res) else {
|
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 lower = res.to_ascii_lowercase();
|
||||||
|
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||||
let root = Element::parse(res.as_bytes())?;
|
return Err(GatewayLoginProtocolError.into());
|
||||||
|
}
|
||||||
let cookie = build_gateway_token(&root, gp_params.computer())?;
|
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
|
||||||
|
let (cookie, connection_type) =
|
||||||
Ok(GatewayLogin::Cookie(cookie))
|
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));
|
||||||
fn detect_local_ipv4(host: &str) -> Option<String> {
|
let authentication = match authentication {
|
||||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
Ok(authentication) => authentication,
|
||||||
socket.connect((host, 443)).ok()?;
|
Err(_) => {
|
||||||
let ip = socket.local_addr().ok()?.ip();
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(5),
|
||||||
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
|
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) {
|
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> {
|
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
|
||||||
let args = element
|
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
|
||||||
.descendants("argument")
|
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()
|
.iter()
|
||||||
.map(|e| e.get_text().unwrap_or_default())
|
.map(|e| e.get_text().unwrap_or_default())
|
||||||
.collect::<Vec<_>>();
|
.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![
|
let mut params = vec![
|
||||||
read_required_arg(&args, 1, "authcookie")?,
|
read_required_arg(&args, 1, "authcookie")?,
|
||||||
read_optional_arg(&args, 2, "persistent-cookie")?,
|
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>> {
|
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
|
||||||
|
let value = decode(value)?;
|
||||||
if value.is_empty() || value == "(null)" || value == "-1" {
|
if value.is_empty() || value == "(null)" || value == "-1" {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
anyhow::ensure!(
|
||||||
Ok(Some(decode(value)?.into_owned()))
|
!value.chars().any(char::is_control),
|
||||||
|
"Gateway argument contains control characters"
|
||||||
|
);
|
||||||
|
Ok(Some(value.into_owned()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_mfa(res: &str) -> Option<(String, String)> {
|
fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||||
@@ -223,6 +463,268 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn mfa() {
|
fn mfa() {
|
||||||
let res = r#"var respStatus = "Challenge";
|
let res = r#"var respStatus = "Challenge";
|
||||||
@@ -263,7 +765,9 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
|||||||
"#;
|
"#;
|
||||||
|
|
||||||
let root = Element::parse(res.as_bytes()).unwrap();
|
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!(
|
assert_eq!(
|
||||||
token,
|
token,
|
||||||
@@ -300,7 +804,8 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
|||||||
"#;
|
"#;
|
||||||
|
|
||||||
let root = Element::parse(res.as_bytes()).unwrap();
|
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!(
|
assert_eq!(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
|
|||||||
&self.name
|
&self.name
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn kind(&self) -> GatewayKind {
|
pub fn kind(&self) -> GatewayKind {
|
||||||
self.kind
|
self.kind
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,15 +5,13 @@ use std::{
|
|||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use reqwest::Client;
|
|
||||||
use xmltree::Element;
|
use xmltree::Element;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
credential::Credential,
|
credential::Credential,
|
||||||
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
|
gateway::login::{GatewayLogin, GatewayLoginClient},
|
||||||
gp_params::GpParams,
|
|
||||||
session::SessionRequestArgs,
|
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";
|
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
|
||||||
@@ -22,12 +20,18 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SessionExtensionAuth {
|
pub struct SessionExtensionAuth {
|
||||||
credential: Credential,
|
credential: Credential,
|
||||||
gp_params: GpParams,
|
client: GatewayLoginClient,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionExtensionAuth {
|
impl SessionExtensionAuth {
|
||||||
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
|
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
|
||||||
Self { credential, gp_params }
|
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 {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
f.debug_struct("SessionExtensionAuth")
|
f.debug_struct("SessionExtensionAuth")
|
||||||
.field("username", &self.credential.username())
|
.field("username", &self.credential.username())
|
||||||
.field("gp_params", &"<redacted>")
|
.field("client", &"<redacted>")
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,10 +87,15 @@ impl SessionContext {
|
|||||||
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||||
extend_session_lifetime(ctx).await?;
|
extend_session_lifetime(ctx).await?;
|
||||||
|
|
||||||
let base_url = normalize_server(ctx.server())?;
|
let auth = ctx
|
||||||
let client = build_session_client(ctx.session_args())?;
|
.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 form = build_extend_session_form(ctx)?;
|
||||||
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
|
|
||||||
|
|
||||||
info!("Sending extend-session request");
|
info!("Sending extend-session request");
|
||||||
|
|
||||||
@@ -108,33 +117,17 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
|
|||||||
.extension_auth()
|
.extension_auth()
|
||||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
.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)
|
validate_extension_login(login)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
|
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
|
||||||
match login {
|
match login {
|
||||||
GatewayLogin::Cookie(_) => Ok(()),
|
GatewayLogin::Authenticated(_) => Ok(()),
|
||||||
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
|
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>> {
|
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
|
||||||
Ok(serde_urlencoded::from_str(args.cookie())?)
|
Ok(serde_urlencoded::from_str(args.cookie())?)
|
||||||
}
|
}
|
||||||
|
|||||||
+109
-14
@@ -1,11 +1,12 @@
|
|||||||
use log::info;
|
use log::info;
|
||||||
use reqwest::Client;
|
use reqwest::{Client, ClientBuilder};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||||
utils::request::create_identity,
|
utils::request::{ClientIdentity, create_identity},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||||
@@ -43,6 +44,7 @@ pub struct GpParams {
|
|||||||
certificate: Option<String>,
|
certificate: Option<String>,
|
||||||
sslkey: Option<String>,
|
sslkey: Option<String>,
|
||||||
key_password: Option<String>,
|
key_password: Option<String>,
|
||||||
|
prepared_identity: Option<ClientIdentity>,
|
||||||
// Feature
|
// Feature
|
||||||
csc_mode: CscMode,
|
csc_mode: CscMode,
|
||||||
// Per-request state
|
// Per-request state
|
||||||
@@ -135,9 +137,49 @@ impl GpParams {
|
|||||||
pub(crate) fn otp(&self) -> Option<&str> {
|
pub(crate) fn otp(&self) -> Option<&str> {
|
||||||
self.otp.as_deref()
|
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 {
|
pub struct GpParamsBuilder {
|
||||||
|
prepared_identity: Option<ClientIdentity>,
|
||||||
is_gateway: bool,
|
is_gateway: bool,
|
||||||
os_profile: OsProfile,
|
os_profile: OsProfile,
|
||||||
csc_mode: CscMode,
|
csc_mode: CscMode,
|
||||||
@@ -150,6 +192,7 @@ pub struct GpParamsBuilder {
|
|||||||
impl GpParamsBuilder {
|
impl GpParamsBuilder {
|
||||||
pub fn new(os_profile: OsProfile) -> Self {
|
pub fn new(os_profile: OsProfile) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
prepared_identity: None,
|
||||||
is_gateway: false,
|
is_gateway: false,
|
||||||
os_profile,
|
os_profile,
|
||||||
csc_mode: Default::default(),
|
csc_mode: Default::default(),
|
||||||
@@ -176,22 +219,34 @@ impl GpParamsBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
|
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
|
||||||
|
self.prepared_identity = None;
|
||||||
self.certificate = certificate.into();
|
self.certificate = certificate.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
|
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
|
||||||
|
self.prepared_identity = None;
|
||||||
self.sslkey = sslkey.into();
|
self.sslkey = sslkey.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut 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.key_password = password.into();
|
||||||
self
|
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 {
|
pub fn build(&self) -> GpParams {
|
||||||
GpParams {
|
GpParams {
|
||||||
|
prepared_identity: self.prepared_identity.clone(),
|
||||||
os_profile: self.os_profile.clone(),
|
os_profile: self.os_profile.clone(),
|
||||||
ignore_tls_errors: self.ignore_tls_errors,
|
ignore_tls_errors: self.ignore_tls_errors,
|
||||||
certificate: self.certificate.clone(),
|
certificate: self.certificate.clone(),
|
||||||
@@ -209,24 +264,64 @@ impl TryFrom<&GpParams> for Client {
|
|||||||
type Error = anyhow::Error;
|
type Error = anyhow::Error;
|
||||||
|
|
||||||
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
|
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
|
||||||
let mut builder = Client::builder()
|
Ok(value.client_builder()?.build()?)
|
||||||
.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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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(¶ms).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(¶ms).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;
|
use crate::os_profile::runtime_client_os;
|
||||||
|
|
||||||
fn profile(client_os: ClientOs) -> OsProfile {
|
fn profile(client_os: ClientOs) -> OsProfile {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use dns_lookup::lookup_addr;
|
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, warn};
|
||||||
use reqwest::{Client, StatusCode};
|
use reqwest::{Client, StatusCode};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
use xmltree::Element;
|
use xmltree::Element;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -14,6 +14,7 @@ use crate::{
|
|||||||
gateway::{Gateway, parse_gateways},
|
gateway::{Gateway, parse_gateways},
|
||||||
gp_params::GpParams,
|
gp_params::GpParams,
|
||||||
params,
|
params,
|
||||||
|
session::{InternalSessionPolicy, network::InternalHostDetection},
|
||||||
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
|
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
|
* - Some(true): Internal host detection is supported and the user is connected to the internal network
|
||||||
*/
|
*/
|
||||||
internal_host_detection: Option<bool>,
|
internal_host_detection: Option<bool>,
|
||||||
|
internal_detection: Option<InternalHostDetection>,
|
||||||
/**
|
/**
|
||||||
* The version returned by the portal config, if any
|
* The version returned by the portal config, if any
|
||||||
*/
|
*/
|
||||||
@@ -47,6 +49,7 @@ pub struct PortalConfig {
|
|||||||
* Whether the portal policy enables default-browser authentication.
|
* Whether the portal policy enables default-browser authentication.
|
||||||
*/
|
*/
|
||||||
default_browser: Option<bool>,
|
default_browser: Option<bool>,
|
||||||
|
internal_session_policy: Option<InternalSessionPolicy>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PortalConfig {
|
impl PortalConfig {
|
||||||
@@ -70,6 +73,10 @@ impl PortalConfig {
|
|||||||
self.internal_host_detection
|
self.internal_host_detection
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
|
||||||
|
self.internal_detection.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn connect_method(&self) -> Option<&str> {
|
pub fn connect_method(&self) -> Option<&str> {
|
||||||
self.connect_method.as_deref()
|
self.connect_method.as_deref()
|
||||||
}
|
}
|
||||||
@@ -86,6 +93,10 @@ impl PortalConfig {
|
|||||||
self.default_browser
|
self.default_browser
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
|
||||||
|
self.internal_session_policy
|
||||||
|
}
|
||||||
|
|
||||||
/// In-place sort the gateways by region
|
/// In-place sort the gateways by region
|
||||||
pub fn sort_gateways(&mut self, region: &str) {
|
pub fn sort_gateways(&mut self, region: &str) {
|
||||||
let preferred_gateway = self.find_preferred_gateway(region);
|
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 portal = normalize_server(portal)?;
|
||||||
let server = remove_url_scheme(&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!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
|
||||||
info!("Portal config request params: {}", redact_form_params(&body_pairs));
|
info!("Portal config request params: {}", redact_form_params(&body_pairs));
|
||||||
|
|
||||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
let res_xml = tokio::select! {
|
||||||
warn!("Network error: {:?}", e);
|
biased;
|
||||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
_ = 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| {
|
parse_gp_response(res).await.or_else(|err| {
|
||||||
if err.status == StatusCode::NOT_FOUND {
|
if err.status == StatusCode::NOT_FOUND {
|
||||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if err.is_status_error() {
|
if err.is_status_error() {
|
||||||
warn!("{err}");
|
warn!("{err}");
|
||||||
bail!("Portal config error: {}", err.reason);
|
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() {
|
if res_xml.is_empty() {
|
||||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
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()))?;
|
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||||
|
|
||||||
if csc::is_config_criteria(&root) {
|
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()
|
"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?;
|
let csc_xml = tokio::select! {
|
||||||
debug!("Portal CSC config response: {}", csc_xml);
|
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()))?;
|
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");
|
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(
|
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> {
|
async fn parse_portal_config(
|
||||||
let mut ihd_enabled = false;
|
server: &str,
|
||||||
let mut prefer_internal = false;
|
cred: &Credential,
|
||||||
if let Some(ihd_node) = root.descendant("internal-host-detection") {
|
root: Element,
|
||||||
ihd_enabled = true;
|
cancellation: &CancellationToken,
|
||||||
prefer_internal = internal_host_detect(ihd_node)
|
) -> 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(|| {
|
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);
|
info!("Detected portal version: {:?}", version);
|
||||||
let allow_extend_session = parse_allow_extend_session(&root);
|
let allow_extend_session = parse_allow_extend_session(&root);
|
||||||
let default_browser = parse_default_browser(&root);
|
let default_browser = parse_default_browser(&root);
|
||||||
|
let internal_session_policy = parse_internal_session_policy(&root).ok();
|
||||||
|
|
||||||
Ok(PortalConfig {
|
Ok(PortalConfig {
|
||||||
portal: server.to_string(),
|
portal: server.to_string(),
|
||||||
@@ -283,13 +331,42 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
|
|||||||
gateways,
|
gateways,
|
||||||
connect_method,
|
connect_method,
|
||||||
config_digest: config_digest.map(|s| s.to_string()),
|
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,
|
version,
|
||||||
allow_extend_session,
|
allow_extend_session,
|
||||||
default_browser,
|
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> {
|
fn parse_default_browser(root: &Element) -> Option<bool> {
|
||||||
match root.descendant_text("default-browser")?.trim() {
|
match root.descendant_text("default-browser")?.trim() {
|
||||||
"yes" => Some(true),
|
"yes" => Some(true),
|
||||||
@@ -313,49 +390,94 @@ fn parse_connect_method(root: &Element) -> Option<String> {
|
|||||||
.map(|s| s.to_string())
|
.map(|s| s.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Perform DNS lookup and compare the result with the expected hostname
|
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
|
||||||
fn internal_host_detect(element: &Element) -> bool {
|
|
||||||
let ip_info = [
|
let ip_info = [
|
||||||
(element.child_text("ip-address"), element.child_text("host")),
|
(element.child_text("ip-address"), element.child_text("host")),
|
||||||
(element.child_text("ipv6-address"), element.child_text("ipv6-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() {
|
for (ip_address, host) in ip_info.iter() {
|
||||||
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
|
let address = ip_address.as_deref().filter(|value| !value.is_empty());
|
||||||
&& !ip_address.is_empty()
|
let host = host.as_deref().filter(|value| !value.is_empty());
|
||||||
&& !host.is_empty()
|
match (address, host) {
|
||||||
{
|
(None, None) => {}
|
||||||
match ip_address.parse::<std::net::IpAddr>() {
|
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
|
||||||
Ok(ip) => match lookup_addr(&ip) {
|
_ => bail!("Incomplete internal host detection policy"),
|
||||||
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),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if targets.is_empty() {
|
||||||
false
|
Ok(None)
|
||||||
|
} else {
|
||||||
|
Ok(Some(InternalHostDetection::new(targets)?))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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 {
|
fn parse_xml(xml: &str) -> Element {
|
||||||
Element::parse(xml.as_bytes()).unwrap()
|
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]
|
#[test]
|
||||||
fn parses_allow_extend_session_yes() {
|
fn parses_allow_extend_session_yes() {
|
||||||
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
|
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"));
|
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[tokio::test]
|
||||||
fn parses_csc_policy_response_as_portal_config() {
|
async fn parses_csc_policy_response_as_portal_config() {
|
||||||
let root = parse_xml(
|
let root = parse_xml(
|
||||||
r#"<policy>
|
r#"<policy>
|
||||||
<portal-userauthcookie>user-cookie</portal-userauthcookie>
|
<portal-userauthcookie>user-cookie</portal-userauthcookie>
|
||||||
@@ -431,7 +553,9 @@ mod tests {
|
|||||||
);
|
);
|
||||||
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
|
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().user_auth_cookie(), "user-cookie");
|
||||||
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
|
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
|
||||||
|
|||||||
@@ -1,20 +1,23 @@
|
|||||||
use std::{
|
use std::{
|
||||||
net::IpAddr,
|
net::IpAddr,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
process::Stdio,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use common::binary_paths;
|
use common::binary_paths;
|
||||||
use tokio::process::Command;
|
use tokio::process::Command;
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
#[cfg(feature = "webview-auth")]
|
#[cfg(feature = "webview-auth")]
|
||||||
use crate::auth::AuthWindowTheme;
|
use crate::auth::AuthWindowTheme;
|
||||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
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> {
|
pub struct SamlAuthLauncher<'a> {
|
||||||
|
cancellation: CancellationToken,
|
||||||
server: &'a str,
|
server: &'a str,
|
||||||
auth_executable: Option<&'a str>,
|
auth_executable: Option<&'a str>,
|
||||||
gateway: bool,
|
gateway: bool,
|
||||||
@@ -46,6 +49,7 @@ pub struct SamlAuthLauncher<'a> {
|
|||||||
impl<'a> SamlAuthLauncher<'a> {
|
impl<'a> SamlAuthLauncher<'a> {
|
||||||
pub fn new(server: &'a str) -> Self {
|
pub fn new(server: &'a str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
cancellation: CancellationToken::new(),
|
||||||
server,
|
server,
|
||||||
auth_executable: None,
|
auth_executable: None,
|
||||||
gateway: false,
|
gateway: false,
|
||||||
@@ -176,6 +180,11 @@ impl<'a> SamlAuthLauncher<'a> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
|
||||||
|
self.cancellation = cancellation.clone();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// The command line this launcher will run.
|
/// The command line this launcher will run.
|
||||||
///
|
///
|
||||||
/// Split out from `launch` so a test can observe the argv the child actually
|
/// 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);
|
.unwrap_or_else(binary_paths::gpauth);
|
||||||
let auth_cmd = self.build_command(&program);
|
let auth_cmd = self.build_command(&program);
|
||||||
|
|
||||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
let command = auth_cmd.into_non_root()?.into_std();
|
||||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
let cancellation = self.cancellation;
|
||||||
|
let output = tokio::task::spawn_blocking(move || {
|
||||||
let child = match child {
|
let check = || {
|
||||||
Ok(child) => child,
|
if cancellation.is_cancelled() {
|
||||||
Err(err) => {
|
Err(std::io::Error::new(
|
||||||
bail!("Failed to spawn {}: {}", program.display(), err);
|
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 {
|
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||||
bail!("Failed to parse auth data")
|
bail!("Failed to parse auth data")
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,21 +1,12 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs,
|
fs, io,
|
||||||
io::{self, Read},
|
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||||
os::unix::{
|
|
||||||
fs::{MetadataExt, PermissionsExt},
|
|
||||||
process::CommandExt,
|
|
||||||
},
|
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
process::{Child, Command, Output, Stdio},
|
process::{Command, Output, Stdio},
|
||||||
thread,
|
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
use nix::{
|
use super::command_runner::run_controlled;
|
||||||
fcntl::{FcntlArg, OFlag, fcntl},
|
|
||||||
sys::signal::{Signal, killpg},
|
|
||||||
unistd::Pid,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Invocation control borrowed by collection; interruption must never be treated
|
/// Invocation control borrowed by collection; interruption must never be treated
|
||||||
/// as an unavailable optional product.
|
/// as an unavailable optional product.
|
||||||
@@ -87,6 +78,16 @@ impl<'a> CollectorCommands<'a> {
|
|||||||
self.run_path(&path, args)
|
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>> {
|
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||||
self.control.check()?;
|
self.control.check()?;
|
||||||
let home = if uzers::get_effective_uid() == 0 {
|
let home = if uzers::get_effective_uid() == 0 {
|
||||||
@@ -106,59 +107,11 @@ impl<'a> CollectorCommands<'a> {
|
|||||||
.env("LC_ALL", "C")
|
.env("LC_ALL", "C")
|
||||||
.env("HOME", home)
|
.env("HOME", home)
|
||||||
.current_dir("/")
|
.current_dir("/")
|
||||||
.stdin(Stdio::null())
|
.stderr(Stdio::null());
|
||||||
.stdout(Stdio::piped())
|
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
|
||||||
.stderr(Stdio::null())
|
Ok(output) => Ok(Some(output)),
|
||||||
.process_group(0);
|
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||||
let child = match command.spawn() {
|
Err(error) => Err(error),
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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,3 +1,4 @@
|
|||||||
|
mod command_runner;
|
||||||
mod command_traits;
|
mod command_traits;
|
||||||
mod desktop_session_env;
|
mod desktop_session_env;
|
||||||
pub(crate) mod gui_helper_launcher;
|
pub(crate) mod gui_helper_launcher;
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ use specta::Type;
|
|||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
gateway::Gateway,
|
|
||||||
hip::HipSource,
|
hip::HipSource,
|
||||||
os_profile::{ClientOs, OsProfile},
|
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||||
|
session::ConnectionPlan,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::vpn_state::ConnectInfo;
|
use super::vpn_state::ConnectInfo;
|
||||||
@@ -58,8 +58,9 @@ impl LaunchGuiRequest {
|
|||||||
|
|
||||||
#[derive(Deserialize, Serialize, Type, Clone)]
|
#[derive(Deserialize, Serialize, Type, Clone)]
|
||||||
pub struct ConnectArgs {
|
pub struct ConnectArgs {
|
||||||
cookie: String,
|
|
||||||
vpnc_script: Option<String>,
|
vpnc_script: Option<String>,
|
||||||
|
host_identity: Option<HostIdentity>,
|
||||||
|
ignore_tls_errors: bool,
|
||||||
|
|
||||||
user_agent: Option<String>,
|
user_agent: Option<String>,
|
||||||
os: Option<ClientOs>,
|
os: Option<ClientOs>,
|
||||||
@@ -87,10 +88,11 @@ pub struct ConnectArgs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ConnectArgs {
|
impl ConnectArgs {
|
||||||
pub fn new(cookie: String) -> Self {
|
fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
cookie,
|
|
||||||
vpnc_script: None,
|
vpnc_script: None,
|
||||||
|
host_identity: None,
|
||||||
|
ignore_tls_errors: false,
|
||||||
user_agent: None,
|
user_agent: None,
|
||||||
os: None,
|
os: None,
|
||||||
os_version: None,
|
os_version: None,
|
||||||
@@ -113,8 +115,12 @@ impl ConnectArgs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cookie(&self) -> &str {
|
pub fn host_identity(&self) -> Option<&HostIdentity> {
|
||||||
&self.cookie
|
self.host_identity.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ignore_tls_errors(&self) -> bool {
|
||||||
|
self.ignore_tls_errors
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn vpnc_script(&self) -> Option<String> {
|
pub fn vpnc_script(&self) -> Option<String> {
|
||||||
@@ -213,7 +219,6 @@ impl ConnectArgs {
|
|||||||
impl fmt::Debug for ConnectArgs {
|
impl fmt::Debug for ConnectArgs {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("ConnectArgs")
|
f.debug_struct("ConnectArgs")
|
||||||
.field("cookie", &"<redacted>")
|
|
||||||
.field("vpnc_script", &self.vpnc_script)
|
.field("vpnc_script", &self.vpnc_script)
|
||||||
.field(
|
.field(
|
||||||
"client_auth_path",
|
"client_auth_path",
|
||||||
@@ -235,7 +240,6 @@ impl fmt::Debug for ConnectArgs {
|
|||||||
|
|
||||||
impl Drop for ConnectArgs {
|
impl Drop for ConnectArgs {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.cookie.zeroize();
|
|
||||||
self.key_password.zeroize();
|
self.key_password.zeroize();
|
||||||
self.certificate_data.zeroize();
|
self.certificate_data.zeroize();
|
||||||
self.sslkey_data.zeroize();
|
self.sslkey_data.zeroize();
|
||||||
@@ -245,14 +249,16 @@ impl Drop for ConnectArgs {
|
|||||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||||
pub struct ConnectRequest {
|
pub struct ConnectRequest {
|
||||||
info: ConnectInfo,
|
info: ConnectInfo,
|
||||||
|
plan: ConnectionPlan,
|
||||||
args: ConnectArgs,
|
args: ConnectArgs,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ConnectRequest {
|
impl ConnectRequest {
|
||||||
pub fn new(info: ConnectInfo, cookie: String) -> Self {
|
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
|
||||||
Self {
|
Self {
|
||||||
info,
|
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 {
|
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 = Some(profile.client_os());
|
||||||
self.args.os_version = Some(profile.os_version().to_string());
|
self.args.os_version = Some(profile.os_version().to_string());
|
||||||
self.args.client_version = Some(profile.client_version().to_string());
|
self.args.client_version = Some(profile.client_version().to_string());
|
||||||
@@ -275,6 +282,11 @@ impl ConnectRequest {
|
|||||||
self
|
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 {
|
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
|
||||||
self.args.certificate = certificate.into();
|
self.args.certificate = certificate.into();
|
||||||
self
|
self
|
||||||
@@ -340,8 +352,8 @@ impl ConnectRequest {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn gateway(&self) -> &Gateway {
|
pub fn plan(&self) -> &ConnectionPlan {
|
||||||
self.info.gateway()
|
&self.plan
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn info(&self) -> &ConnectInfo {
|
pub fn info(&self) -> &ConnectInfo {
|
||||||
@@ -370,6 +382,7 @@ pub struct UpdateLogLevelRequest(pub String);
|
|||||||
pub enum WsRequest {
|
pub enum WsRequest {
|
||||||
Connect(Box<ConnectRequest>),
|
Connect(Box<ConnectRequest>),
|
||||||
Disconnect(DisconnectRequest),
|
Disconnect(DisconnectRequest),
|
||||||
|
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||||
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
|
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
|
||||||
PreviewHipReport(PreviewHipReportRequest),
|
PreviewHipReport(PreviewHipReportRequest),
|
||||||
GetHipApprovalStatus { approval_id: String },
|
GetHipApprovalStatus { approval_id: String },
|
||||||
@@ -393,17 +406,52 @@ mod tests {
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::os_profile::OsProfileBuilder;
|
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 {
|
fn test_connect_info() -> ConnectInfo {
|
||||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||||
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
|
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]
|
#[test]
|
||||||
fn connect_request_serializes_allow_extend_session() {
|
fn connect_request_serializes_allow_extend_session() {
|
||||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
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 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();
|
let value = serde_json::to_value(req).unwrap();
|
||||||
|
|
||||||
assert_eq!(value["args"]["allowExtendSession"], json!(true));
|
assert_eq!(value["args"]["allowExtendSession"], json!(true));
|
||||||
@@ -413,7 +461,7 @@ mod tests {
|
|||||||
fn with_os_profile_sets_user_agent_from_profile() {
|
fn with_os_profile_sets_user_agent_from_profile() {
|
||||||
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
|
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()));
|
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() {
|
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
|
||||||
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
|
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!(
|
assert_eq!(
|
||||||
req.args().host_id(),
|
req.args().host_id(),
|
||||||
@@ -432,7 +480,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_identity_data_round_trips_without_debug_disclosure() {
|
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_certificate_data(Some(b"certificate".to_vec()))
|
||||||
.with_sslkey_data(Some(b"private-key".to_vec()));
|
.with_sslkey_data(Some(b"private-key".to_vec()));
|
||||||
let encoded = serde_json::to_vec(&req).unwrap();
|
let encoded = serde_json::to_vec(&req).unwrap();
|
||||||
|
|||||||
@@ -167,7 +167,21 @@ mod tests {
|
|||||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
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 info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||||
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
|
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_certificate_data(Some(vec![b'c'; certificate_size]))
|
||||||
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
||||||
let message = ClientMessage::Request {
|
let message = ClientMessage::Request {
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
|
|
||||||
use crate::{gateway::Gateway, session::SessionInfo};
|
use crate::{
|
||||||
|
gateway::Gateway,
|
||||||
|
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||||
pub struct ConnectInfo {
|
pub struct ConnectInfo {
|
||||||
@@ -18,6 +21,8 @@ pub struct ConnectedInfo {
|
|||||||
info: Box<ConnectInfo>,
|
info: Box<ConnectInfo>,
|
||||||
session_info: Option<SessionInfo>,
|
session_info: Option<SessionInfo>,
|
||||||
connected_at: u32,
|
connected_at: u32,
|
||||||
|
members: Vec<GatewaySessionSummary>,
|
||||||
|
failures: Vec<GatewayFailureSummary>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ConnectedInfo {
|
impl ConnectedInfo {
|
||||||
@@ -26,9 +31,25 @@ impl ConnectedInfo {
|
|||||||
info: Box::new(info),
|
info: Box::new(info),
|
||||||
session_info,
|
session_info,
|
||||||
connected_at: unix_timestamp(),
|
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 {
|
pub fn info(&self) -> &ConnectInfo {
|
||||||
&self.info
|
&self.info
|
||||||
}
|
}
|
||||||
@@ -67,6 +88,7 @@ impl ConnectInfo {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub enum VpnState {
|
pub enum VpnState {
|
||||||
Disconnected,
|
Disconnected,
|
||||||
|
Failed(String),
|
||||||
Connecting(Box<ConnectInfo>),
|
Connecting(Box<ConnectInfo>),
|
||||||
Connected(Box<ConnectedInfo>),
|
Connected(Box<ConnectedInfo>),
|
||||||
Disconnecting,
|
Disconnecting,
|
||||||
|
|||||||
@@ -4,6 +4,14 @@ use chrono::{Local, TimeZone};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use specta::Type;
|
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)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||||
pub struct SessionWarning {
|
pub struct SessionWarning {
|
||||||
pub prior_secs: u32,
|
pub prior_secs: u32,
|
||||||
|
|||||||
@@ -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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -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)
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
use std::{borrow::Cow, fs};
|
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::{Context, ensure};
|
||||||
use log::warn;
|
use openssl::{pkey::PKey, x509::X509};
|
||||||
use openssl::pkey::PKey;
|
|
||||||
use pem::parse_many;
|
|
||||||
use reqwest::Identity;
|
use reqwest::Identity;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum RequestIdentityError {
|
pub enum RequestIdentityError {
|
||||||
@@ -16,72 +15,419 @@ pub enum RequestIdentityError {
|
|||||||
DecryptError(&'static str),
|
DecryptError(&'static str),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create an identity object from a certificate and key
|
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||||
/// The file is expected to be the PKCS#8 PEM or PKCS#12 format
|
/// retains its original bytes and passphrase so each native backend imports the
|
||||||
/// When using a PKCS#12 file, the key is NOT required, but a passphrase is required
|
/// same identity and chain. Debug never exposes retained material.
|
||||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
#[derive(Clone)]
|
||||||
if cert.ends_with(".p12") || cert.ends_with(".pfx") {
|
pub struct ClientIdentity {
|
||||||
create_identity_from_pkcs12(cert, passphrase)
|
material: Arc<IdentityMaterial>,
|
||||||
} else {
|
identity: Identity,
|
||||||
create_identity_from_pem(cert, key, passphrase)
|
}
|
||||||
|
|
||||||
|
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> {
|
impl ClientIdentity {
|
||||||
let cert_pem = fs::read(cert).map_err(|err| anyhow::anyhow!("Failed to read certificate file: {}", err))?;
|
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
|
/// A separate key denotes decrypted PEM; no separate key denotes original
|
||||||
let key_pem_file = match key {
|
/// PKCS#12 bytes. Input-size limits belong to the service transport boundary.
|
||||||
Some(key) => Cow::Owned(fs::read(key).map_err(|err| anyhow::anyhow!("Failed to read key file: {}", err))?),
|
pub fn from_data(
|
||||||
None => Cow::Borrowed(&cert_pem),
|
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
|
pub fn certificate_data(&self) -> &[u8] {
|
||||||
let key_pem = parse_many(key_pem_file.as_ref())?
|
&self.material.certificate
|
||||||
.into_iter()
|
}
|
||||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
pub fn key_data(&self) -> Option<&[u8]> {
|
||||||
.ok_or(RequestIdentityError::NoKey)?;
|
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
|
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
|
||||||
let decrypted_key_pem = if key_pem.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
let suffix = if self.material.key.is_some() { ".pem" } else { ".p12" };
|
||||||
let passphrase = passphrase.ok_or_else(|| {
|
let certificate = write_identity_file(self.certificate_data(), directory, suffix)?;
|
||||||
warn!("Key is encrypted but no passphrase provided");
|
let key = self
|
||||||
RequestIdentityError::NoPassphrase("PEM")
|
.key_data()
|
||||||
})?;
|
.map(|key| write_identity_file(key, directory, ".pem"))
|
||||||
let pem_content = pem::encode(&key_pem);
|
.transpose()?;
|
||||||
let key = PKey::private_key_from_pem_passphrase(pem_content.as_bytes(), passphrase.as_bytes()).map_err(|err| {
|
Ok(ClientIdentityFiles { certificate, key })
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_identity_from_pkcs12(pkcs12: &str, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
/// Named files are private and remain owned until native workers and logout
|
||||||
let pkcs12 = fs::read(pkcs12)?;
|
/// 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 {
|
impl ClientIdentityFiles {
|
||||||
bail!(RequestIdentityError::NoPassphrase("PKCS#12"));
|
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)?;
|
/// General request clients may load an identity directly. Session owners call
|
||||||
Ok(identity)
|
/// 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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn create_identity_from_pem_requires_passphrase() {
|
fn create_identity_from_pem_requires_passphrase() {
|
||||||
let cert = "tests/files/badssl.com-client.pem";
|
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.is_err());
|
||||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
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 cert = "tests/files/badssl.com-client.pem";
|
||||||
let passphrase = "badssl.com";
|
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());
|
assert!(identity.is_ok());
|
||||||
}
|
}
|
||||||
@@ -102,7 +448,7 @@ mod tests {
|
|||||||
#[cfg(not(target_os = "macos"))]
|
#[cfg(not(target_os = "macos"))]
|
||||||
fn create_identity_from_pem_unencrypted_key() {
|
fn create_identity_from_pem_unencrypted_key() {
|
||||||
let cert = "tests/files/badssl.com-client-unencrypted.pem";
|
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);
|
println!("{:?}", identity);
|
||||||
|
|
||||||
assert!(identity.is_ok());
|
assert!(identity.is_ok());
|
||||||
@@ -115,7 +461,7 @@ mod tests {
|
|||||||
let key = "tests/files/badssl.com-client.pem";
|
let key = "tests/files/badssl.com-client.pem";
|
||||||
let passphrase = "badssl.com";
|
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());
|
assert!(identity.is_ok());
|
||||||
}
|
}
|
||||||
@@ -125,7 +471,7 @@ mod tests {
|
|||||||
let cert = "tests/files/badssl.com-client.pem";
|
let cert = "tests/files/badssl.com-client.pem";
|
||||||
let key = "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.is_err());
|
||||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
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 cert = "tests/files/badssl.com-client.pem";
|
||||||
let key = "tests/files/badssl.com-client-unencrypted.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());
|
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)
|
||||||
|
}
|
||||||
@@ -212,6 +212,33 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
|
|||||||
generate_report_with_control(input, &budget)
|
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, ¶ms)),
|
||||||
|
("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> {
|
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||||
control.check()?;
|
control.check()?;
|
||||||
let cookie_params = cookie_params(input);
|
let cookie_params = cookie_params(input);
|
||||||
@@ -727,6 +754,43 @@ mod tests {
|
|||||||
OsProfileBuilder::new(client_os).build()
|
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]
|
#[test]
|
||||||
fn host_info_os_vendor_is_linux_for_linux_profile() {
|
fn host_info_os_vendor_is_linux_for_linux_profile() {
|
||||||
let input = make_input(make_profile(ClientOs::Linux));
|
let input = make_input(make_profile(ClientOs::Linux));
|
||||||
|
|||||||
@@ -127,10 +127,29 @@ pub(crate) extern "C" fn generate_hip_report(
|
|||||||
output: *mut c_char,
|
output: *mut c_char,
|
||||||
capacity: usize,
|
capacity: usize,
|
||||||
written: *mut 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 {
|
) -> c_int {
|
||||||
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
|
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
|
||||||
let vpn = unsafe { &*(data as *const Vpn) };
|
let source = unsafe { &*(data as *const HipSource) };
|
||||||
let HipSource::Generator(generate) = &vpn.hip_source else {
|
let HipSource::Generator(generate) = source else {
|
||||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
|
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
|
||||||
};
|
};
|
||||||
let request = unsafe { read_hip_request(&*request)? };
|
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,
|
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,
|
script: &HipScript,
|
||||||
request: &HipRequest,
|
request: &HipRequest,
|
||||||
check: &dyn Fn() -> io::Result<()>,
|
check: &dyn Fn() -> io::Result<()>,
|
||||||
@@ -224,7 +264,7 @@ fn collect_hip_report(
|
|||||||
};
|
};
|
||||||
let control = HipControlRaw {
|
let control = HipControlRaw {
|
||||||
data: &check as *const _ as *mut _,
|
data: &check as *const _ as *mut _,
|
||||||
check: preview_check,
|
check: collection_check,
|
||||||
};
|
};
|
||||||
let mut output = vec![0u8; 1024 * 1024 + 1];
|
let mut output = vec![0u8; 1024 * 1024 + 1];
|
||||||
let mut written = 0;
|
let mut written = 0;
|
||||||
@@ -246,7 +286,7 @@ fn collect_hip_report(
|
|||||||
output.truncate(written);
|
output.truncate(written);
|
||||||
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
|
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<()>) };
|
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
|
||||||
match catch_unwind(AssertUnwindSafe(check)) {
|
match catch_unwind(AssertUnwindSafe(check)) {
|
||||||
Ok(Ok(())) => 0,
|
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]
|
#[test]
|
||||||
fn callback_outputs_are_bounded_and_validated_by_c() {
|
fn callback_outputs_are_bounded_and_validated_by_c() {
|
||||||
let raw = HipScriptRaw::default();
|
let raw = HipScriptRaw::default();
|
||||||
@@ -355,7 +431,7 @@ mod hip_tests {
|
|||||||
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
|
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
|
||||||
let script = fixture.script(Some(unsafe { libc::getuid() }));
|
let script = fixture.script(Some(unsafe { libc::getuid() }));
|
||||||
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
|
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]
|
#[test]
|
||||||
fn validator_refusal_prevents_execution_and_errors_propagate() {
|
fn validator_refusal_prevents_execution_and_errors_propagate() {
|
||||||
@@ -365,7 +441,7 @@ mod hip_tests {
|
|||||||
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
|
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
script
|
script
|
||||||
.preview(&HipRequest::default(), &|| Ok(()))
|
.collect(&HipRequest::default(), &|| Ok(()))
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.raw_os_error(),
|
.raw_os_error(),
|
||||||
Some(libc::EPERM)
|
Some(libc::EPERM)
|
||||||
@@ -374,7 +450,7 @@ mod hip_tests {
|
|||||||
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
|
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
script
|
script
|
||||||
.preview(&HipRequest::default(), &|| Ok(()))
|
.collect(&HipRequest::default(), &|| Ok(()))
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.raw_os_error(),
|
.raw_os_error(),
|
||||||
Some(libc::EIO)
|
Some(libc::EIO)
|
||||||
@@ -392,7 +468,7 @@ mod hip_tests {
|
|||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
script.preview(&HipRequest::default(), &|| Ok(())).unwrap(),
|
script.collect(&HipRequest::default(), &|| Ok(())).unwrap(),
|
||||||
format!("child:{cwd}")
|
format!("child:{cwd}")
|
||||||
);
|
);
|
||||||
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
|
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
|
||||||
@@ -404,7 +480,7 @@ mod hip_tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
fixture
|
fixture
|
||||||
.script(None)
|
.script(None)
|
||||||
.preview(&HipRequest::default(), &|| Ok(()))
|
.collect(&HipRequest::default(), &|| Ok(()))
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.raw_os_error(),
|
.raw_os_error(),
|
||||||
Some(libc::EINVAL)
|
Some(libc::EINVAL)
|
||||||
@@ -426,7 +502,7 @@ mod hip_tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
fixture
|
fixture
|
||||||
.script(None)
|
.script(None)
|
||||||
.preview(&HipRequest::default(), &check)
|
.collect(&HipRequest::default(), &check)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.raw_os_error(),
|
.raw_os_error(),
|
||||||
Some(errno)
|
Some(errno)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
mod hip;
|
mod hip;
|
||||||
use crate::Vpn;
|
use crate::Vpn;
|
||||||
use hip::HipGenerateFn;
|
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 log::{debug, info, trace, warn};
|
||||||
use std::ffi::{c_char, c_int, c_long, c_void};
|
use std::ffi::{c_char, c_int, c_long, c_void};
|
||||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ pub enum HipSource {
|
|||||||
Script(HipScript),
|
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.
|
/// Current gateway and negotiated identity inputs for one report invocation.
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct HipRequest {
|
pub struct HipRequest {
|
||||||
@@ -105,8 +113,8 @@ impl HipScript {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
|
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
|
||||||
pub fn preview(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
||||||
ffi::preview_hip_script(self, request, check)
|
ffi::collect_hip_script(self, request, check)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ pub struct Vpn {
|
|||||||
key_password: Option<CString>,
|
key_password: Option<CString>,
|
||||||
servercert: Option<CString>,
|
servercert: Option<CString>,
|
||||||
|
|
||||||
pub(crate) hip_source: HipSource,
|
pub(crate) hip_source: Arc<HipSource>,
|
||||||
|
|
||||||
reconnect_timeout: u32,
|
reconnect_timeout: u32,
|
||||||
mtu: u32,
|
mtu: u32,
|
||||||
@@ -139,7 +139,7 @@ impl Vpn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
|
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::Disabled => info!("HIP reporting: disabled"),
|
||||||
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
|
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
|
||||||
HipSource::Script(script) => {
|
HipSource::Script(script) => {
|
||||||
@@ -157,7 +157,7 @@ impl Vpn {
|
|||||||
}
|
}
|
||||||
self.callback.write().unwrap().replace(Box::new(on_connected));
|
self.callback.write().unwrap().replace(Box::new(on_connected));
|
||||||
let mut options = self.build_connect_options();
|
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),
|
HipSource::Script(script) => ffi::script_environment(script),
|
||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
@@ -226,11 +226,11 @@ impl Vpn {
|
|||||||
key_password: Self::option_to_ptr(&self.key_password),
|
key_password: Self::option_to_ptr(&self.key_password),
|
||||||
servercert: Self::option_to_ptr(&self.servercert),
|
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),
|
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
|
||||||
_ => Default::default(),
|
_ => Default::default(),
|
||||||
},
|
},
|
||||||
generate_hip: match &self.hip_source {
|
generate_hip: match self.hip_source.as_ref() {
|
||||||
HipSource::Generator(_) => Some(ffi::generate_hip_report),
|
HipSource::Generator(_) => Some(ffi::generate_hip_report),
|
||||||
_ => None,
|
_ => None,
|
||||||
},
|
},
|
||||||
@@ -290,7 +290,7 @@ pub struct VpnBuilder {
|
|||||||
sslkey: Option<String>,
|
sslkey: Option<String>,
|
||||||
key_password: Option<String>,
|
key_password: Option<String>,
|
||||||
|
|
||||||
hip_source: HipSource,
|
hip_source: Arc<HipSource>,
|
||||||
|
|
||||||
reconnect_timeout: u32,
|
reconnect_timeout: u32,
|
||||||
mtu: u32,
|
mtu: u32,
|
||||||
@@ -322,7 +322,7 @@ impl VpnBuilder {
|
|||||||
sslkey: None,
|
sslkey: None,
|
||||||
key_password: None,
|
key_password: None,
|
||||||
|
|
||||||
hip_source: HipSource::Disabled,
|
hip_source: Arc::new(HipSource::Disabled),
|
||||||
|
|
||||||
reconnect_timeout: 300,
|
reconnect_timeout: 300,
|
||||||
mtu: 0,
|
mtu: 0,
|
||||||
@@ -400,8 +400,8 @@ impl VpnBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn hip_source(mut self, hip_source: HipSource) -> Self {
|
pub fn hip_source(mut self, hip_source: impl Into<Arc<HipSource>>) -> Self {
|
||||||
self.hip_source = hip_source;
|
self.hip_source = hip_source.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -605,7 +605,7 @@ mod tests {
|
|||||||
sslkey: None,
|
sslkey: None,
|
||||||
key_password: None,
|
key_password: None,
|
||||||
servercert: None,
|
servercert: None,
|
||||||
hip_source: HipSource::Disabled,
|
hip_source: Arc::new(HipSource::Disabled),
|
||||||
reconnect_timeout: 300,
|
reconnect_timeout: 300,
|
||||||
mtu: 0,
|
mtu: 0,
|
||||||
disable_ipv6: false,
|
disable_ipv6: false,
|
||||||
|
|||||||
@@ -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->client_version, "6.3.3"));
|
||||||
assert(!strcmp(request->host_id, "test-host"));
|
assert(!strcmp(request->host_id, "test-host"));
|
||||||
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
|
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"));
|
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
|
||||||
state->generated++;
|
state->generated++;
|
||||||
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
|
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);
|
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) {
|
int main(int argc, char **argv) {
|
||||||
struct state state = {0};
|
struct state state = {0};
|
||||||
struct openconnect_info *vpninfo;
|
struct openconnect_info *vpninfo;
|
||||||
assert(argc == 2);
|
assert(argc == 2);
|
||||||
|
native_session_logout();
|
||||||
openconnect_init_ssl();
|
openconnect_init_ssl();
|
||||||
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
|
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
|
||||||
assert(vpninfo);
|
assert(vpninfo);
|
||||||
@@ -98,7 +131,7 @@ int main(int argc, char **argv) {
|
|||||||
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
||||||
assert(!openconnect_set_reported_os(vpninfo, "linux"));
|
assert(!openconnect_set_reported_os(vpninfo, "linux"));
|
||||||
assert(!openconnect_parse_url(vpninfo, argv[1]));
|
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_app_version(vpninfo, "6.3.3"));
|
||||||
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
|
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
|
||||||
openconnect_disable_dtls(vpninfo);
|
openconnect_disable_dtls(vpninfo);
|
||||||
@@ -110,7 +143,7 @@ int main(int argc, char **argv) {
|
|||||||
assert(state.generated == 2 && state.accepted == 2);
|
assert(state.generated == 2 && state.accepted == 2);
|
||||||
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
|
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
|
||||||
openconnect_close_https(vpninfo, 0);
|
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(!openconnect_make_cstp_connection(vpninfo));
|
||||||
assert(state.generated == 3 && state.accepted == 3);
|
assert(state.generated == 3 && state.accepted == 3);
|
||||||
/* Fourth gateway check says no report needed. */
|
/* Fourth gateway check says no report needed. */
|
||||||
|
|||||||
Reference in new issue
Block a user