mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: release GP Connect 3.3.0 with Native Shell support
This commit is contained in:
226 files changed
+7700
-5225
No files matched your search
@@ -145,130 +145,6 @@ impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[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 {
|
||||
@@ -299,37 +175,3 @@ impl InternalSessionPolicy {
|
||||
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,159 @@
|
||||
use super::*;
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct AuthenticatedGateway {
|
||||
pub gateway: Gateway,
|
||||
pub authentication: GatewayAuthentication,
|
||||
pub binding: Option<crate::session::desktop::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<crate::session::InternalHostDetection>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConnectionPlanFields {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<crate::session::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<crate::session::InternalHostDetection>) -> Self {
|
||||
self.internal_detection = detection;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&crate::session::InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
+71
@@ -39,6 +39,74 @@ impl GatewaySessions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Register cleanup ownership before any fallible native network work.
|
||||
pub fn register_login(
|
||||
&mut self,
|
||||
gateway: Gateway,
|
||||
authentication: super::GatewayAuthentication,
|
||||
client: &crate::gateway::GatewayLoginClient,
|
||||
) {
|
||||
self.register(GatewaySession {
|
||||
gateway,
|
||||
transport: GatewayTransport::from_authenticated_login(
|
||||
client.request_client().clone(),
|
||||
client.origin().clone(),
|
||||
authentication,
|
||||
client.params().os_profile().clone(),
|
||||
),
|
||||
addresses: ClientAddresses::default(),
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn bind_non_tunnel(
|
||||
&mut self,
|
||||
gateway: &Gateway,
|
||||
client: &crate::gateway::GatewayLoginClient,
|
||||
disable_ipv6: bool,
|
||||
detection: Option<&super::InternalHostDetection>,
|
||||
cancellation: &tokio_util::sync::CancellationToken,
|
||||
) -> anyhow::Result<super::network::GatewayBinding> {
|
||||
use super::{
|
||||
network::PhysicalNetwork,
|
||||
transport::binding::{bound_client, gateway_origin},
|
||||
};
|
||||
let member = self
|
||||
.members
|
||||
.iter()
|
||||
.find(|member| member.gateway.server() == gateway.server())
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway must be registered before network binding"))?;
|
||||
let origin = gateway_origin(client.origin().as_str())?;
|
||||
let response_url = client
|
||||
.authenticated_url()
|
||||
.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 = client
|
||||
.login_endpoint()
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
|
||||
let 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 maintenance = bound_client(origin.as_str(), client.params(), &binding)?;
|
||||
self.update(GatewaySession {
|
||||
gateway: gateway.clone(),
|
||||
transport: GatewayTransport::from_authenticated_login(
|
||||
maintenance,
|
||||
client.origin().clone(),
|
||||
member.transport.authentication().clone(),
|
||||
client.params().os_profile().clone(),
|
||||
),
|
||||
addresses: binding.addresses(),
|
||||
});
|
||||
Ok(binding)
|
||||
}
|
||||
|
||||
pub fn register(&mut self, session: GatewaySession) {
|
||||
self.members.push(Arc::new(session));
|
||||
}
|
||||
@@ -101,3 +169,6 @@ async fn logout(session: Arc<GatewaySession>) {
|
||||
Err(_) => log::warn!("Gateway logout timed out"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,65 @@
|
||||
use super::*;
|
||||
use crate::{
|
||||
gateway::{GatewayLogin, GatewayLoginClient},
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_binding_retains_issued_session_for_exactly_once_logout() {
|
||||
use crate::session::transport::tests::{login_gateway, response};
|
||||
let mut arguments = [""; 19];
|
||||
arguments[1] = "issued-cookie";
|
||||
arguments[4] = "alice";
|
||||
arguments[12] = "non-tunnel";
|
||||
let xml = format!(
|
||||
"<jnlp><application-desc>{}</application-desc></jnlp>",
|
||||
arguments
|
||||
.iter()
|
||||
.map(|value| format!("<argument>{value}</argument>"))
|
||||
.collect::<String>()
|
||||
);
|
||||
let (_, origin, server) = login_gateway(vec![response(&xml), response("<response status='success'/>")]).await;
|
||||
let params = GpParams::builder(
|
||||
OsProfile::builder(ClientOs::Linux)
|
||||
.computer_name_override("original-computer")
|
||||
.build(crate::os_profile::test_snapshot()),
|
||||
)
|
||||
.build();
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), params).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let GatewayLogin::Authenticated(authentication) = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("expected issued authentication")
|
||||
};
|
||||
let gateway = Gateway::new(origin.to_string(), origin.to_string());
|
||||
let mut sessions = GatewaySessions::default();
|
||||
sessions.register_login(gateway.clone(), authentication, &client);
|
||||
// HTTP is accepted by the protocol fixture but rejected by native binding validation.
|
||||
assert!(
|
||||
sessions
|
||||
.bind_non_tunnel(&gateway, &client, false, None, &CancellationToken::new())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(sessions.members().len(), 1);
|
||||
assert!(
|
||||
sessions.members()[0]
|
||||
.transport
|
||||
.authentication()
|
||||
.cookie()
|
||||
.contains("issued-cookie")
|
||||
);
|
||||
sessions.logout_gateway(gateway.server()).await;
|
||||
assert!(sessions.is_empty());
|
||||
sessions.logout().await;
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
assert!(requests[1].1.contains("authcookie=issued-cookie"));
|
||||
assert!(requests[1].1.contains("computer=original-computer"));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use super::{GatewayAuthentication, InternalHostDetection, InternalSessionPolicy, SessionMode, detection, transport};
|
||||
use crate::gateway::Gateway;
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
mod connection_plan;
|
||||
mod gateway_sessions;
|
||||
pub mod network;
|
||||
pub mod non_tunnel;
|
||||
pub mod tunnel;
|
||||
pub use connection_plan::{AuthenticatedGateway, ConnectionPlan, GatewayFailure, GatewayFailureSummary};
|
||||
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
|
||||
+1
-1
@@ -130,7 +130,7 @@ impl GatewayBinding {
|
||||
}
|
||||
|
||||
pub fn validate_server(&self, server: &str) -> anyhow::Result<()> {
|
||||
let origin = super::super::transport::gateway_origin(server)?;
|
||||
let origin = super::super::transport::binding::gateway_origin(server)?;
|
||||
ensure!(
|
||||
origin.port_or_known_default() == Some(self.endpoint.port()),
|
||||
"Gateway endpoint port differs"
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+19
-7
@@ -9,8 +9,9 @@ use anyhow::{Context, ensure};
|
||||
use netdev::Interface;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::ClientAddresses;
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
|
||||
use super::{ClientAddresses, InternalHostDetection};
|
||||
use crate::collection::{CollectionBudget, CollectionControl};
|
||||
use crate::process::collection::CollectorCommands;
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
mod bsd;
|
||||
@@ -29,10 +30,9 @@ use linux as platform;
|
||||
use macos as platform;
|
||||
|
||||
mod binding;
|
||||
mod detection;
|
||||
use super::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);
|
||||
@@ -170,7 +170,7 @@ impl PhysicalNetwork {
|
||||
ensure!(resolver_count > 0, "Physical resolver context is unavailable");
|
||||
if let Some(detection) = detection {
|
||||
ensure!(
|
||||
detection.detect(cancellation).await?,
|
||||
detect(detection, cancellation).await?,
|
||||
"Internal host detection no longer matches"
|
||||
);
|
||||
}
|
||||
@@ -298,7 +298,7 @@ async fn resolve_binding(
|
||||
cancellation: &CancellationToken,
|
||||
authenticated_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<GatewayBinding> {
|
||||
let origin = super::transport::gateway_origin(server)?;
|
||||
let origin = super::transport::binding::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)?;
|
||||
@@ -628,7 +628,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn bracketed_ipv6_gateway_is_a_literal_endpoint() {
|
||||
let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap();
|
||||
let origin = super::super::transport::binding::gateway_origin("https://[2001:db8::1]:444").unwrap();
|
||||
assert_eq!(
|
||||
literal_gateway_address(&origin).unwrap(),
|
||||
Some("2001:db8::1".parse().unwrap())
|
||||
@@ -678,3 +678,15 @@ pub(crate) fn test_binding() -> GatewayBinding {
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub async fn detect(
|
||||
policy: &super::InternalHostDetection,
|
||||
cancellation: &tokio_util::sync::CancellationToken,
|
||||
) -> anyhow::Result<bool> {
|
||||
for (address, hostname) in policy.targets() {
|
||||
if native::detect(address, hostname, cancellation).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Re
|
||||
Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname)))
|
||||
}
|
||||
|
||||
pub(super) async fn detect(
|
||||
pub(in crate::session) async fn detect(
|
||||
address: std::net::IpAddr,
|
||||
hostname: &str,
|
||||
cancellation: &CancellationToken,
|
||||
+3
-5
@@ -1,3 +1,4 @@
|
||||
use crate::session::{GatewaySessionSummary, MaintenanceState, SessionEndReason};
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
@@ -10,12 +11,9 @@ use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::{gateway::Gateway, process::collection::CollectionControl};
|
||||
use crate::{collection::CollectionControl, gateway::Gateway};
|
||||
|
||||
use super::{
|
||||
GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason,
|
||||
SessionMode, transport::GatewayRequestError,
|
||||
};
|
||||
use super::{GatewaySession, GatewaySessions, InternalSessionPolicy, SessionMode, transport::GatewayRequestError};
|
||||
|
||||
const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
+2
-1
@@ -11,7 +11,8 @@ use tokio::sync::Notify;
|
||||
use super::*;
|
||||
use crate::session::transport::GatewayTransport;
|
||||
use crate::session::{
|
||||
ClientAddresses, GatewaySessions,
|
||||
desktop::ClientAddresses,
|
||||
desktop::GatewaySessions,
|
||||
transport::tests::{gateway, response},
|
||||
};
|
||||
|
||||
File renamed without changes.
+5
-8
@@ -3,7 +3,6 @@ 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")]
|
||||
@@ -52,13 +51,11 @@ impl InternalHostDetection {
|
||||
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(crate) fn targets(&self) -> impl Iterator<Item = (IpAddr, &str)> {
|
||||
self
|
||||
.targets
|
||||
.iter()
|
||||
.map(|target| (target.address, target.hostname.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
use super::*;
|
||||
use crate::{gp_params::GpParams, session::desktop::network::GatewayBinding};
|
||||
use reqwest::redirect::Policy;
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
#[cfg(feature = "desktop")]
|
||||
pub(crate) mod binding;
|
||||
use std::{net::IpAddr, time::Duration};
|
||||
|
||||
use reqwest::{Client, StatusCode, Url, redirect::Policy};
|
||||
use reqwest::{Client, StatusCode, Url};
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt};
|
||||
use crate::{os_profile::OsProfile, utils::xml::ElementExt};
|
||||
|
||||
use super::{GatewayAuthentication, network::GatewayBinding};
|
||||
use super::GatewayAuthentication;
|
||||
|
||||
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;
|
||||
|
||||
@@ -45,25 +46,6 @@ pub struct GatewayTransport {
|
||||
}
|
||||
|
||||
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(
|
||||
@@ -185,58 +167,6 @@ async fn post(
|
||||
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()));
|
||||
@@ -1,3 +1,6 @@
|
||||
use reqwest::redirect::Policy;
|
||||
use std::time::Duration;
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
use super::*;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
@@ -77,7 +80,7 @@ async fn gateway_fixture(
|
||||
requests
|
||||
});
|
||||
let transport = GatewayTransport {
|
||||
client: Client::builder()
|
||||
client: crate::utils::request::client_builder()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
@@ -91,7 +94,7 @@ async fn gateway_fixture(
|
||||
.unwrap(),
|
||||
profile: OsProfile::builder(crate::os_profile::ClientOs::Linux)
|
||||
.computer_name_override("test")
|
||||
.build(),
|
||||
.build(crate::os_profile::test_snapshot()),
|
||||
};
|
||||
(transport, server)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user