feat: release GP Connect 3.3.0 with Native Shell support

This commit is contained in:
Kevin Yue committed 2026-11-05 23:05:14 +08:00
1 parent d12d677208
commit fd08cdbe66
226 files changed
+7700 -5225

No files matched your search

+38 -14
View File
@@ -12,6 +12,16 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
/// Validates an explicit GlobalProtect SAML completion status.
/// A missing status means the page has not supplied an authentication result.
pub fn validate_saml_auth_status(status: Option<&str>) -> Result<(), AuthDataParseError> {
match status {
Some("1") => Ok(()),
Some(status) => Err(AuthDataParseError::AuthenticationFailed(status.to_owned())),
None => Err(AuthDataParseError::NotFound),
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum AuthWindowTheme {
@@ -121,21 +131,15 @@ impl SamlAuthData {
}
pub fn from_html(html: &str) -> AuthDataParseResult {
match parse_xml_tag(html, "saml-auth-status") {
Some(status) if status == "1" => {
let username = parse_xml_tag(html, "saml-username");
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
validate_saml_auth_status(parse_xml_tag(html, "saml-auth-status").as_deref())?;
let username = parse_xml_tag(html, "saml-username");
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
let auth_data =
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
}
Some(status) => Err(AuthDataParseError::AuthenticationFailed(status)),
None => Err(AuthDataParseError::NotFound),
}
let auth_data =
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
}
pub fn from_gpcallback(data: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> {
@@ -217,6 +221,26 @@ fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
mod tests {
use super::*;
#[test]
fn saml_status_distinguishes_rejection_from_an_unfinished_page() {
assert!(validate_saml_auth_status(Some("1")).is_ok());
assert!(matches!(
validate_saml_auth_status(None),
Err(AuthDataParseError::NotFound)
));
for status in ["0", "2", "", "unknown"] {
assert!(matches!(
validate_saml_auth_status(Some(status)),
Err(AuthDataParseError::AuthenticationFailed(_))
));
let html = format!("<saml-auth-status>{status}</saml-auth-status>");
assert!(matches!(
SamlAuthData::from_html(&html),
Err(AuthDataParseError::AuthenticationFailed(_))
));
}
}
#[test]
fn auth_data_from_gpcallback_cas() {
let auth_data = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";
+2 -1
View File
@@ -2,7 +2,7 @@ use clap::{ValueEnum, builder::PossibleValue};
use crate::{
gp_params::CscMode,
os_profile::{ClientOs, runtime_client_os},
os_profile::{ClientOs, desktop::runtime_client_os},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
@@ -31,6 +31,7 @@ impl Default for Os {
ClientOs::Linux => Os::Linux,
ClientOs::Windows => Os::Windows,
ClientOs::Mac => Os::Mac,
ClientOs::Ios => unreachable!("The desktop CLI is not available on iOS"),
}
}
}
+3 -39
View File
@@ -11,8 +11,6 @@ use crate::{
pub mod args;
pub trait Args {
#[cfg(not(target_os = "macos"))]
fn fix_openssl(&self) -> bool;
fn ignore_tls_errors(&self) -> bool;
/// How this program renders its logs.
@@ -43,14 +41,6 @@ fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
// users already see; keep it exactly.
let mut hints = Vec::new();
#[cfg(not(target_os = "macos"))]
if kind == ServerTlsErrorKind::LegacyRenegotiation && !args.fix_openssl() {
let (program, rest) = command_line();
hints.push(format!(
"Re-run it with the `--fix-openssl` option to work around this issue, e.g.:\n\n{program} --fix-openssl {rest}"
));
}
if kind == ServerTlsErrorKind::Certificate && !args.ignore_tls_errors() {
let (program, rest) = command_line();
hints.push(format!(
@@ -204,18 +194,11 @@ mod tests {
#[derive(Default)]
struct TestArgs {
#[cfg(not(target_os = "macos"))]
fix_openssl: bool,
ignore_tls_errors: bool,
log_format: LogFormat,
}
impl Args for TestArgs {
#[cfg(not(target_os = "macos"))]
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
@@ -260,31 +243,12 @@ mod tests {
}
#[test]
fn hints_distinguish_legacy_and_unknown_tls_and_respect_both_flags() {
let legacy = ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::LegacyRenegotiation,
};
let hints = retry_hints(&anyhow!(legacy.clone()), &TestArgs::default());
if cfg!(target_os = "macos") {
assert!(hints.is_empty());
} else {
assert_eq!(hints.len(), 1);
assert!(hints[0].contains("--fix-openssl"));
}
let args = TestArgs {
#[cfg(not(target_os = "macos"))]
fix_openssl: true,
ignore_tls_errors: true,
..Default::default()
};
assert!(retry_hints(&anyhow!(legacy), &args).is_empty());
assert!(retry_hints(&anyhow!(certificate_error()), &args).is_empty());
let other = ServerTlsError {
fn unknown_tls_failure_does_not_suggest_bypassing_certificate_validation() {
let error = ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::Other,
};
assert!(retry_hints(&anyhow!(other), &TestArgs::default()).is_empty());
assert!(retry_hints(&anyhow!(error), &TestArgs::default()).is_empty());
}
/// Suggesting an option the user already passed is noise, and in JSON mode it
+41
View File
@@ -0,0 +1,41 @@
use std::{
io,
time::{Duration, Instant},
};
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
pub trait CollectionControl {
fn check(&self) -> io::Result<()>;
}
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
fn check(&self) -> io::Result<()> {
self()
}
}
pub struct CollectionBudget {
deadline: Instant,
}
impl CollectionBudget {
pub fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
}
impl CollectionControl for CollectionBudget {
fn check(&self) -> io::Result<()> {
if Instant::now() >= self.deadline {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Device information collection timed out",
))
} else {
Ok(())
}
}
}
+5
View File
@@ -3,6 +3,11 @@ use thiserror::Error;
mod server_tls;
pub use server_tls::{ServerTlsError, ServerTlsErrorKind};
/// An explicit server rejection, distinct from transport, TLS, and parsing failures.
#[derive(Error, Debug)]
#[error("Authentication was rejected")]
pub struct AuthenticationRejected;
#[derive(Error, Debug)]
pub enum PortalError {
#[error("Prelogin error: {0}")]
+112 -176
View File
@@ -4,13 +4,6 @@ use serde::{Deserialize, Serialize};
use super::PortalError;
#[cfg(target_os = "macos")]
#[path = "server_tls/macos.rs"]
mod backend;
#[cfg(not(target_os = "macos"))]
#[path = "server_tls/openssl.rs"]
mod backend;
/// A VPN HTTP TLS failure. The server identifies the configured VPN origin,
/// not necessarily the peer that failed after an HTTP redirect.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -25,7 +18,6 @@ pub struct ServerTlsError {
pub enum ServerTlsErrorKind {
Certificate,
ClientCertificateRequired,
LegacyRenegotiation,
Other,
}
@@ -43,7 +35,6 @@ impl fmt::Display for ServerTlsError {
let message = match self.kind {
ServerTlsErrorKind::Certificate => "The server's certificate could not be verified",
ServerTlsErrorKind::ClientCertificateRequired => "The server requires a client certificate",
ServerTlsErrorKind::LegacyRenegotiation => "The server requires unsafe legacy TLS renegotiation",
ServerTlsErrorKind::Other => "A secure connection to the server could not be established",
};
write!(f, "{message}: {}", self.server)
@@ -70,122 +61,25 @@ impl ServerTlsErrorKind {
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
let mut source = Some(error);
let mut fallback = None;
while let Some(error) = source {
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
return Some(tls.kind);
}
if let Some(kind) = backend::classify(error) {
return Some(kind);
}
if let Some(tls) = error.downcast_ref::<native_tls::Error>() {
let kind = classify_native(tls);
if kind != ServerTlsErrorKind::Other {
return Some(kind);
}
fallback = Some(kind);
if let Some(tls) = error.downcast_ref::<rustls::Error>() {
return Some(match tls {
rustls::Error::InvalidCertificate(_) => ServerTlsErrorKind::Certificate,
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
ServerTlsErrorKind::ClientCertificateRequired
}
_ => ServerTlsErrorKind::Other,
});
}
source = error
.downcast_ref::<std::io::Error>()
.and_then(|error| error.get_ref().map(|inner| inner as &(dyn Error + 'static)))
.or_else(|| error.source());
}
fallback
}
fn classify_native(error: &native_tls::Error) -> ServerTlsErrorKind {
// native-tls hides some backend reason codes and verification results. Keep
// backend text matching here, scoped to a confirmed native TLS error.
let detail = format!("{error:?}").to_ascii_lowercase();
classify_native_detail(&detail)
}
fn classify_native_detail(detail: &str) -> ServerTlsErrorKind {
// native-tls forwards Security.framework's Debug representation, but hides
// its OSStatus from the public error chain. Prefer that status to localized
// text, including for peer alerts that can mention a rejected client cert.
if let Some(code) = detail
.strip_prefix("error { code: ")
.and_then(|detail| detail.split_once(','))
.and_then(|(code, _)| code.parse::<i32>().ok())
{
return classify_macos_status(code);
}
if detail.contains("unsafe legacy renegotiation") {
return ServerTlsErrorKind::LegacyRenegotiation;
}
if detail.contains("alert certificate required") {
return ServerTlsErrorKind::ClientCertificateRequired;
}
let certificate = [
"certificate verify failed",
"certificate verification failed",
"certificate was not trusted",
"certificate is not trusted",
"self signed certificate",
"hostname mismatch",
"certificate has expired",
"certificate is not yet valid",
"certificate has been revoked",
]
.iter()
.any(|reason| detail.contains(reason));
if certificate {
ServerTlsErrorKind::Certificate
} else {
ServerTlsErrorKind::Other
}
}
fn classify_macos_status(code: i32) -> ServerTlsErrorKind {
if code == -9863 {
return ServerTlsErrorKind::ClientCertificateRequired;
}
// Local server-certificate validation failures from Security/SecBase.h.
// Peer alerts (errSSLPeer*) reject our client certificate; protocol/cipher,
// keychain, and internal errors also cannot be fixed by skipping server trust.
let certificate = matches!(
code,
-9807 // errSSLXCertChainInvalid
| -9812 // errSSLUnknownRootCert
| -9813 // errSSLNoRootCert
| -9814 // errSSLCertExpired
| -9815 // errSSLCertNotYetValid
| -9843 // errSSLHostNameMismatch
| -9884 // errSSLATSLeafCertificateHashAlgorithmViolation
| -9885 // errSSLATSCertificateHashAlgorithmViolation
| -9886 // errSSLATSCertificateTrustViolation
| -67602 // errSecHostNameMismatch
| -67603 // errSecUnknownCriticalExtensionFlag
| -67604 // errSecNoBasicConstraints
| -67605 // errSecNoBasicConstraintsCA
| -67606 // errSecInvalidAuthorityKeyID
| -67607 // errSecInvalidSubjectKeyID
| -67608 // errSecInvalidKeyUsageForPolicy
| -67609 // errSecInvalidExtendedKeyUsage
| -67610 // errSecInvalidIDLinkage
| -67611 // errSecPathLengthConstraintExceeded
| -67612 // errSecInvalidRoot
| -67629 // errSecSSLBadExtendedKeyUsage
| -67654 // errSecTrustSettingDeny
| -67818 // errSecCertificateExpired
| -67819 // errSecCertificateNotValidYet
| -67820 // errSecCertificateRevoked
| -67821 // errSecCertificateSuspended
| -67826 // errSecInvalidCertAuthority
| -67843 // errSecNotTrusted
| -67899 // errSecCertificatePolicyNotAllowed
| -67900 // errSecCertificateNameNotAllowed
| -67901 // errSecCertificateValidityPeriodTooLong
| -67902 // errSecCertificateIsCA
| -67903 // errSecCertificateDuplicateExtension
| -67904 // errSecMissingQualifiedCertStatement
);
if certificate {
ServerTlsErrorKind::Certificate
} else {
ServerTlsErrorKind::Other
}
None
}
#[cfg(test)]
@@ -207,39 +101,26 @@ mod tests {
};
#[test]
fn explicit_client_certificate_requirement_has_a_distinct_kind() {
let kind = classify_native_detail("error { code: -9863, message: \"localized message\" }");
assert_eq!(serde_json::to_value(kind).unwrap(), "clientCertificateRequired");
assert_eq!(
classify_native_detail("error { code: -9842, message: \"client cert requested\" }"),
ServerTlsErrorKind::Other
);
}
#[test]
fn macos_certificate_statuses_do_not_depend_on_the_error_message() {
for code in [-67818, -67819, -67820, -67843, -67602, -67629, -67899, -67901] {
let detail = format!("error {{ code: {code}, message: \"localized message\" }}");
fn typed_tls_causes_distinguish_local_trust_from_peer_alerts() {
for reason in [
rustls::CertificateError::Expired,
rustls::CertificateError::UnknownIssuer,
] {
let error = std::io::Error::other(std::io::Error::other(rustls::Error::InvalidCertificate(reason)));
assert_eq!(classify(&error), Some(ServerTlsErrorKind::Certificate));
}
for alert in [
rustls::AlertDescription::UnknownCA,
rustls::AlertDescription::BadCertificate,
] {
assert_eq!(
classify_native_detail(&detail),
ServerTlsErrorKind::Certificate,
"{code}"
classify(&rustls::Error::AlertReceived(alert)),
Some(ServerTlsErrorKind::Other)
);
}
}
#[test]
fn macos_peer_alerts_and_handshake_errors_are_not_certificate_validation_failures() {
for (code, message) in [
(-9800, "SSL protocol error"),
(-9801, "Cipher Suite negotiation failure"),
(-9828, "peer certificate has expired"),
(-9831, "unknown certificate authority"),
(-9850, "weak ephemeral DH key"),
] {
let detail = format!("error {{ code: {code}, message: \"{message}\" }}").to_ascii_lowercase();
assert_eq!(classify_native_detail(&detail), ServerTlsErrorKind::Other, "{code}");
}
let required = rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired);
assert_eq!(classify(&required), Some(ServerTlsErrorKind::ClientCertificateRequired));
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
}
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
@@ -303,7 +184,7 @@ mod tests {
portal::{PreloginOptions, prelogin},
};
let (address, worker) = server(true);
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
let error = prelogin(&address, &params, PreloginOptions::default())
.await
@@ -324,7 +205,7 @@ mod tests {
portal::{PreloginOptions, prelogin},
};
let (address, worker) = server(true);
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
.ignore_tls_errors(true)
.build();
let result = prelogin(&address, &params, PreloginOptions::default()).await;
@@ -335,7 +216,7 @@ mod tests {
#[tokio::test]
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
let (address, worker) = server(false);
let error = reqwest::Client::builder()
let error = crate::utils::request::client_builder()
.no_proxy()
.danger_accept_invalid_certs(true)
.build()
@@ -354,7 +235,7 @@ mod tests {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("https://{}", listener.local_addr().unwrap());
drop(listener);
let error = reqwest::Client::builder()
let error = crate::utils::request::client_builder()
.no_proxy()
.build()
.unwrap()
@@ -365,17 +246,7 @@ mod tests {
assert_eq!(classify(&error), None);
}
#[cfg(target_os = "macos")]
#[test]
fn wrapped_macos_io_status_retains_the_client_certificate_requirement() {
let error = std::io::Error::other(std::io::Error::other(security_framework::base::Error::from(-9863)));
let server = url::Url::parse("https://vpn.example.com/login?token=secret").unwrap();
let tls = ServerTlsError::from_request(&server, &error).unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::ClientCertificateRequired);
assert_eq!(tls.server, "https://vpn.example.com");
assert_eq!(classify(&std::io::Error::other("alert certificate required")), None);
}
#[cfg(feature = "desktop")]
#[test]
fn rendering_recovery_retains_client_certificate_requirement() {
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
@@ -409,7 +280,7 @@ mod tests {
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()))
.ignore_tls_errors(true)
.build();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
@@ -435,19 +306,11 @@ mod tests {
worker.join().unwrap();
let kind =
ServerTlsErrorKind::from_error(&error).unwrap_or_else(|| panic!("{operation}: unclassified: {error:?}"));
// Secure Transport's TLS 1.2 handshake can return only a generic peer alert.
if cfg!(target_os = "macos") {
assert!(matches!(
kind,
ServerTlsErrorKind::ClientCertificateRequired | ServerTlsErrorKind::Other
));
} else {
assert_eq!(
kind,
ServerTlsErrorKind::ClientCertificateRequired,
"{operation}: {error:?}"
);
}
assert_eq!(
kind,
ServerTlsErrorKind::ClientCertificateRequired,
"{operation}: {error:?}"
);
}
}
@@ -465,7 +328,8 @@ mod tests {
SslVerifyMode::PEER
};
let (address, worker) = server_with_client_auth(true, verify);
let mut builder = GpParams::builder(OsProfile::builder(ClientOs::Linux).build());
let mut builder =
GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()));
builder.ignore_tls_errors(true);
if required {
builder
@@ -482,6 +346,78 @@ mod tests {
}
}
#[tokio::test]
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
let fixture = |name: &str| format!("{}/tests/files/client-identity/{name}", env!("CARGO_MANIFEST_DIR"));
for (certificate, key, password) in [
(
"rsa-cert.pem",
Some("rsa-traditional-aes256.pem"),
Some("fixture-password"),
),
("ec-cert.pem", Some("ec-traditional-des3.pem"), Some("fixture-password")),
("rsa-cert.pem", Some("rsa-pbes1-3des.pem"), Some("fixture-password")),
("rsa-cert.pem", Some("rsa-pbes2-scrypt.pem"), Some("fixture-password")),
("ec-cert.pem", Some("ec-sec1.pem"), None),
("modern.p12", None, Some("fixture-password")),
("legacy-rc2.p12", None, Some("fixture-password")),
("empty-password.p12", None, None),
("no-bag-ids.p12", None, None),
] {
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
let mut builder =
GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()));
builder
.ignore_tls_errors(true)
.certificate(Some(fixture(certificate)))
.sslkey(key.map(fixture))
.key_password(password.map(str::to_owned));
let mut params = builder.build();
params
.prepare_client_identity()
.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}"));
let result = prelogin(&address, &params, PreloginOptions::default()).await;
worker.join().unwrap();
assert!(matches!(
result.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}")),
crate::portal::Prelogin::Saml(_)
));
}
}
/// Point at the GnuTLS fixture configured without RFC 5746, with a trusted test root.
#[tokio::test]
#[ignore = "requires GP_TLS_TEST_SERVER and GP_TLS_TEST_CA for the external GnuTLS fixture"]
async fn tls12_peer_without_renegotiation_extension_uses_default_policy() {
let server = std::env::var("GP_TLS_TEST_SERVER").unwrap();
let root = std::fs::read(std::env::var("GP_TLS_TEST_CA").unwrap()).unwrap();
let client = crate::utils::request::client_builder()
.no_proxy()
.add_root_certificate(reqwest::Certificate::from_pem(&root).unwrap())
.build()
.unwrap();
assert!(client.get(&server).send().await.unwrap().status().is_success());
let error = crate::utils::request::client_builder()
.no_proxy()
.build()
.unwrap()
.get(&server)
.send()
.await
.unwrap_err();
assert_eq!(
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
.unwrap()
.kind,
ServerTlsErrorKind::Certificate
);
}
#[tokio::test]
async fn failed_response_reads_preserve_the_transport_cause() {
for status in [200, 403] {
@@ -498,7 +434,7 @@ mod tests {
)
.unwrap();
});
let response = reqwest::Client::builder()
let response = crate::utils::request::client_builder()
.no_proxy()
.build()
.unwrap()
@@ -1,9 +0,0 @@
use std::error::Error;
use super::{ServerTlsErrorKind, classify_macos_status};
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
error
.downcast_ref::<security_framework::base::Error>()
.map(|error| classify_macos_status(error.code()))
}
@@ -1,17 +0,0 @@
use std::error::Error;
use super::ServerTlsErrorKind;
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
let stack = error.downcast_ref::<openssl::error::ErrorStack>().or_else(|| {
error
.downcast_ref::<openssl::ssl::Error>()
.and_then(openssl::ssl::Error::ssl_error)
})?;
// ERR_LIB_SSL and SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED from sslerr.h.
stack
.errors()
.iter()
.any(|error| error.library_code() == 20 && error.reason_code() == 1116)
.then_some(ServerTlsErrorKind::ClientCertificateRequired)
}
+44 -95
View File
@@ -17,11 +17,7 @@ use crate::{
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
session::{
GatewayAuthentication,
network::GatewayBinding,
transport::{bound_client, gateway_origin},
},
session::GatewayAuthentication,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
@@ -41,29 +37,12 @@ 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>,
peer_certificate: Option<Vec<u8>>,
}
impl GatewayLoginClient {
pub fn register_session(
&self,
gateway: crate::gateway::Gateway,
authentication: GatewayAuthentication,
sessions: &mut crate::session::GatewaySessions,
) {
sessions.register(crate::session::GatewaySession {
gateway,
transport: self.authenticated_transport(authentication),
addresses: self
.binding
.as_ref()
.map(|binding| binding.addresses())
.unwrap_or_default(),
});
}
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
let client = Client::try_from(&params)?;
@@ -71,78 +50,19 @@ impl GatewayLoginClient {
origin,
client,
params,
binding: None,
login_endpoint: None,
login_url: None,
maintenance_client: None,
peer_certificate: 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(crate) fn login_endpoint(&self) -> Option<SocketAddr> {
self.login_endpoint
}
pub(crate) fn params(&self) -> &GpParams {
&self.params
}
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()
}
@@ -153,6 +73,16 @@ impl GatewayLoginClient {
&self.origin
}
/// DER certificate from the TLS connection that returned the login response.
/// Callers must retain normal certificate verification when using it as a pin.
pub fn authenticated_url(&self) -> Option<&reqwest::Url> {
self.login_url.as_ref()
}
pub fn peer_certificate(&self) -> Option<&[u8]> {
self.peer_certificate.as_deref()
}
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
self.params.set_input_str(input);
self.params.set_otp(otp);
@@ -171,7 +101,7 @@ impl GatewayLoginClient {
context
.client_ip()
.map(str::to_owned)
.or_else(|| detect_local_ipv4(context.host()))
.or_else(|| self.origin.host_str().and_then(detect_local_ipv4))
});
let request = receive_gateway_login(
&self.origin,
@@ -190,6 +120,7 @@ impl GatewayLoginClient {
// 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.peer_certificate = response.peer_certificate;
self.login_endpoint = response.endpoint;
self.login_url = Some(response.url);
Ok(response.login)
@@ -206,12 +137,14 @@ impl GatewayLoginClient {
}
struct LoginResponse {
peer_certificate: Option<Vec<u8>>,
login: GatewayLogin,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
}
struct ReceivedLogin {
peer_certificate: Option<Vec<u8>>,
body: String,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
@@ -260,17 +193,26 @@ async fn receive_gateway_login(
}
})?;
let peer_certificate = res
.extensions()
.get::<reqwest::tls::TlsInfo>()
.and_then(|info| info.peer_certificate())
.map(<[u8]>::to_vec);
let endpoint = res.remote_addr();
let url = res.url().clone();
let res = parse_gp_response(res).await.map_err(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
return anyhow::anyhow!(tls);
}
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return anyhow::anyhow!(crate::error::AuthenticationRejected);
}
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason)
})?;
Ok(ReceivedLogin {
peer_certificate,
body: res,
endpoint,
url,
@@ -284,6 +226,7 @@ async fn parse_login_response(
gp_params: &GpParams,
) -> anyhow::Result<LoginResponse> {
let ReceivedLogin {
peer_certificate,
body: res,
endpoint,
url,
@@ -302,6 +245,7 @@ async fn parse_login_response(
};
return Ok(LoginResponse {
peer_certificate,
login: GatewayLogin::Mfa(message, input_str),
endpoint,
url,
@@ -335,6 +279,7 @@ async fn parse_login_response(
};
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
Ok(LoginResponse {
peer_certificate,
login: GatewayLogin::Authenticated(authentication),
endpoint,
url,
@@ -477,7 +422,11 @@ mod tests {
}
fn test_params() -> GpParams {
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
GpParams::builder(
crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux)
.build(crate::os_profile::test_snapshot()),
)
.build()
}
#[tokio::test]
@@ -578,7 +527,6 @@ mod tests {
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(_)
@@ -619,7 +567,6 @@ mod tests {
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(server.await.unwrap().len(), 1);
}
@@ -642,7 +589,6 @@ mod tests {
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(
server.await.unwrap()[0].0,
"http://unresolvable.invalid/ssl-vpn/login.esp"
@@ -660,8 +606,11 @@ mod tests {
response("<response status='success'/>"),
])
.await;
let params =
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
let params = GpParams::builder(
crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux)
.build(crate::os_profile::test_snapshot()),
)
.build();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let mut client = GatewayLoginClient {
client,
+4
View File
@@ -1,9 +1,11 @@
mod login;
mod parse_gateways;
#[cfg(feature = "desktop")]
pub mod session;
pub use login::*;
pub(crate) use parse_gateways::*;
#[cfg(feature = "desktop")]
pub use session::*;
use serde::{Deserialize, Serialize};
@@ -24,7 +26,9 @@ pub struct Gateway {
pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
#[serde(default)]
pub(crate) priority: u32,
#[serde(default)]
pub(crate) priority_rules: Vec<PriorityRule>,
}
+14 -5
View File
@@ -21,17 +21,26 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
pub struct SessionExtensionAuth {
credential: Credential,
client: GatewayLoginClient,
binding: Option<crate::session::desktop::network::GatewayBinding>,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
Self { credential, client }
Self {
credential,
client,
binding: None,
}
}
pub fn with_binding(mut self, binding: Option<crate::session::desktop::network::GatewayBinding>) -> Self {
self.binding = binding;
self
}
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()
pub fn binding(&self) -> Option<&crate::session::desktop::network::GatewayBinding> {
self.binding.as_ref()
}
}
@@ -170,14 +179,14 @@ mod tests {
fn build_session_args() -> SessionRequestArgs {
let profile = OsProfile::builder(ClientOs::Mac)
.host_identity(HostIdentity::new(
.host_identity(HostIdentity::from_parts(
"test-mac".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.client_version("6.3.1-12".to_string())
.build();
.build(crate::os_profile::test_snapshot());
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_user_agent(profile.user_agent().to_string())
.with_disable_ipv6(true)
+43 -28
View File
@@ -161,7 +161,8 @@ impl GpParams {
}
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
let mut builder = Client::builder()
let mut builder = crate::utils::request::client_builder()
.tls_info(true)
.danger_accept_invalid_certs(self.ignore_tls_errors)
.user_agent(self.user_agent());
if let Some(identity) = &self.prepared_identity {
@@ -322,10 +323,9 @@ mod tests {
assert!(params.client_identity().is_none());
assert!(params.certificate.is_none());
}
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
OsProfile::builder(client_os).build()
OsProfile::builder(client_os).build(crate::os_profile::test_snapshot())
}
#[test]
@@ -346,7 +346,7 @@ mod tests {
fn builder_keeps_explicit_client_version() {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.2.9-1".to_string())
.build();
.build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
assert_eq!(params.client_version(), Some("6.2.9-1"));
@@ -355,7 +355,7 @@ mod tests {
#[test]
fn builder_uses_os_profile_version_when_unspecified() {
let params = GpParams::builder(profile(ClientOs::Mac)).build();
let default_os_version = ClientOs::Mac.default_os_version();
let default_os_version = crate::os_profile::defaults::os_version(ClientOs::Mac);
assert_eq!(params.os_version(), Some(default_os_version.as_str()));
}
@@ -370,13 +370,18 @@ mod tests {
#[test]
fn delegates_identity_to_os_profile() {
let identity = HostIdentity::new(
let identity = HostIdentity::from_parts(
"test-computer".to_string(),
"test-host-id".to_string(),
"test-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).host_identity(identity).build()).build();
let params = GpParams::builder(
OsProfile::builder(ClientOs::Linux)
.host_identity(identity)
.build(crate::os_profile::test_snapshot()),
)
.build();
assert!(!params.host_id().is_empty());
assert_eq!(params.host_identity().host_id(), "test-host-id");
@@ -388,7 +393,7 @@ mod tests {
fn builder_accepts_pre_built_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyMac")
.build();
.build(crate::os_profile::test_snapshot());
let expected_os_version = profile.os_version().to_string();
let params = GpParams::builder(profile).build();
@@ -404,7 +409,7 @@ mod tests {
fn delegates_computer_to_os_profile() {
let profile = OsProfile::builder(ClientOs::Mac)
.computer_name_override("MyComputer")
.build();
.build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
assert_eq!(params.computer(), "MyComputer");
@@ -421,7 +426,7 @@ mod tests {
#[test]
fn delegates_host_identity_to_os_profile() {
let identity = HostIdentity::new(
let identity = HostIdentity::from_parts(
"delegated-computer".to_string(),
"delegated-host".to_string(),
"delegated-serial".to_string(),
@@ -430,7 +435,7 @@ mod tests {
let params = GpParams::builder(
OsProfile::builder(ClientOs::Linux)
.host_identity(identity.clone())
.build(),
.build(crate::os_profile::test_snapshot()),
)
.build();
@@ -445,7 +450,7 @@ mod tests {
#[test]
fn builder_uses_provided_os_profile() {
let identity = HostIdentity::new(
let identity = HostIdentity::from_parts(
"identity-host".to_string(),
"host-7".to_string(),
"serial-7".to_string(),
@@ -455,13 +460,16 @@ mod tests {
.computer_name_override("linux-host")
.client_version("6.0.0-1".to_string())
.host_identity(identity)
.build();
.build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
let profile = params.os_profile();
assert_eq!(profile.client_os(), ClientOs::Linux);
assert_eq!(profile.computer(), "linux-host");
assert_eq!(profile.os_version(), ClientOs::Linux.default_os_version());
assert_eq!(
profile.os_version(),
crate::os_profile::defaults::os_version(ClientOs::Linux)
);
assert_eq!(profile.client_version(), "6.0.0-1");
assert_eq!(profile.host_identity().host_id(), "host-7");
assert_eq!(profile.host_identity().serialno(), "serial-7");
@@ -475,7 +483,7 @@ mod tests {
#[test]
fn try_from_gp_params_constructs_reqwest_client() {
let params = GpParams::builder(profile(runtime_client_os())).build();
let params = GpParams::builder(profile(ClientOs::Mac)).build();
let client = Client::try_from(&params);
assert!(client.is_ok(), "Client construction should succeed with default params");
@@ -483,7 +491,7 @@ mod tests {
#[test]
fn try_from_gp_params_with_ignore_tls_errors() {
let params = GpParams::builder(profile(runtime_client_os()))
let params = GpParams::builder(profile(ClientOs::Mac))
.ignore_tls_errors(true)
.build();
let client = Client::try_from(&params);
@@ -497,9 +505,9 @@ mod tests {
#[test]
fn try_from_gp_params_with_custom_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
OsProfile::builder(ClientOs::Mac)
.user_agent("custom-agent/1.0")
.build(),
.build(crate::os_profile::test_snapshot()),
)
.build();
let client = Client::try_from(&params);
@@ -511,7 +519,7 @@ mod tests {
fn try_from_gp_params_with_invalid_certificate_returns_error() {
// When a certificate path is provided but the file does not exist or is malformed,
// Client construction should fail rather than silently succeed.
let params = GpParams::builder(profile(runtime_client_os()))
let params = GpParams::builder(profile(ClientOs::Mac))
.certificate("/nonexistent/path/to/cert.pem".to_string())
.build();
let client = Client::try_from(&params);
@@ -526,7 +534,7 @@ mod tests {
#[test]
fn user_agent_delegates_to_os_profile_for_default_build() {
let params = GpParams::builder(profile(runtime_client_os())).build();
let params = GpParams::builder(profile(ClientOs::Mac)).build();
assert_eq!(
params.user_agent(),
@@ -537,14 +545,21 @@ mod tests {
#[test]
fn builder_uses_profile_user_agent() {
let params = GpParams::builder(OsProfile::builder(runtime_client_os()).user_agent("custom").build()).build();
let params = GpParams::builder(
OsProfile::builder(ClientOs::Mac)
.user_agent("custom")
.build(crate::os_profile::test_snapshot()),
)
.build();
assert_eq!(params.user_agent(), "custom");
}
#[test]
fn builder_os_profile_without_user_agent_delegates_to_profile() {
let profile = OsProfile::builder(ClientOs::Mac).client_version("6.1.0").build();
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.1.0")
.build(crate::os_profile::test_snapshot());
let expected_ua = profile.user_agent().to_string();
let params = GpParams::builder(profile).build();
@@ -557,7 +572,7 @@ mod tests {
let profile = OsProfile::builder(ClientOs::Mac)
.client_version("6.1.0")
.user_agent("override")
.build();
.build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
assert_eq!(params.user_agent(), "override");
@@ -566,9 +581,9 @@ mod tests {
#[test]
fn try_from_gp_params_succeeds_with_delegated_user_agent() {
let params = GpParams::builder(
OsProfile::builder(runtime_client_os())
OsProfile::builder(ClientOs::Mac)
.user_agent("delegated-agent/2.0")
.build(),
.build(crate::os_profile::test_snapshot()),
)
.build();
let client = Client::try_from(&params);
@@ -602,7 +617,7 @@ mod tests {
client_os in arb_client_os(),
user_agent_override in proptest::option::of("[a-zA-Z0-9/_.-]{1,30}"),
) {
let identity = HostIdentity::new(
let identity = HostIdentity::from_parts(
"prop-computer".to_string(),
"prop-host".to_string(),
"prop-serial".to_string(),
@@ -616,7 +631,7 @@ mod tests {
if let Some(ref ua) = user_agent_override {
profile_builder = profile_builder.user_agent(ua);
}
let params = GpParams::builder(profile_builder.build()).build();
let params = GpParams::builder(profile_builder.build(crate::os_profile::test_snapshot())).build();
prop_assert_eq!(
params.user_agent(),
@@ -634,7 +649,7 @@ mod tests {
proptest! {
#[test]
fn builder_uses_profile_user_agent(ua in "[^\\s]{1,50}") {
let profile = OsProfile::builder(runtime_client_os()).user_agent(&ua).build();
let profile = OsProfile::builder(ClientOs::Mac).user_agent(&ua).build(crate::os_profile::test_snapshot());
let params = GpParams::builder(profile).build();
prop_assert_eq!(params.user_agent(), ua.as_str());
+124
View File
@@ -0,0 +1,124 @@
//! Desktop GUI selection shared by launchers, installers and settings.
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum GuiVariant {
#[default]
Tauri,
Nsh,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
pub enum GuiTheme {
#[default]
System,
Light,
Dark,
}
impl GuiTheme {
pub fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GuiSwitchRequest {
pub variant: GuiVariant,
/// Permit a download only after the user accepts the confirmation dialog.
pub allow_download: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum GuiSwitchOutcome {
Switched,
DownloadRequired,
}
impl GuiVariant {
pub fn binary_name(self) -> &'static str {
match self {
Self::Tauri => "gpgui",
Self::Nsh => "gpgui-nsh",
}
}
pub fn update_target(self) -> PathBuf {
let target = common::binary_paths::gpgui_update_target();
match self {
Self::Tauri => target,
Self::Nsh => target.with_file_name(self.binary_name()),
}
}
pub fn primary(self) -> PathBuf {
match self {
Self::Tauri => common::binary_paths::gpgui(),
Self::Nsh => common::binary_paths::gpgui().with_file_name(self.binary_name()),
}
}
}
#[cfg(target_os = "linux")]
fn preference_path() -> anyhow::Result<PathBuf> {
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
Ok(dirs.config_dir().join("gui"))
}
pub fn preferred() -> anyhow::Result<GuiVariant> {
#[cfg(target_os = "linux")]
{
match std::fs::read_to_string(preference_path()?) {
Ok(value) => match value.trim() {
"gpgui" => Ok(GuiVariant::Tauri),
"gpgui-nsh" => Ok(GuiVariant::Nsh),
_ => anyhow::bail!("Invalid GUI preference"),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(GuiVariant::Tauri),
Err(error) => Err(error.into()),
}
}
#[cfg(not(target_os = "linux"))]
Ok(GuiVariant::Tauri)
}
#[cfg(target_os = "linux")]
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
use std::io::Write;
let path = preference_path()?;
let directory = path.parent().unwrap();
std::fs::create_dir_all(directory)?;
let mut file = tempfile::NamedTempFile::new_in(directory)?;
writeln!(file, "{}", variant.binary_name())?;
file.persist(path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nsh_selection_keeps_both_launch_and_upgrade_paths_on_nsh() {
let variant = GuiVariant::Nsh;
assert_eq!(variant.primary().file_name().unwrap(), "gpgui-nsh");
assert_eq!(variant.update_target().file_name().unwrap(), "gpgui-nsh");
assert_eq!(
variant.update_target().parent(),
GuiVariant::Tauri.update_target().parent()
);
assert_eq!(serde_json::to_string(&variant).unwrap(), "\"nsh\"");
}
}
+9
View File
@@ -1,16 +1,24 @@
pub mod auth;
pub mod collection;
#[cfg(feature = "desktop")]
pub mod cookie_store;
pub mod credential;
#[cfg(feature = "desktop")]
pub mod device_anchor;
pub mod error;
pub mod gateway;
pub mod gp_params;
#[cfg(feature = "desktop")]
pub mod gui;
#[cfg(feature = "desktop")]
pub mod hip;
pub mod log_format;
pub mod os_profile;
pub mod params;
pub mod portal;
#[cfg(feature = "desktop")]
pub mod process;
#[cfg(feature = "desktop")]
pub mod service;
pub mod session;
pub mod utils;
@@ -21,4 +29,5 @@ pub mod logger;
#[cfg(feature = "clap")]
pub mod clap;
#[cfg(feature = "desktop")]
pub mod script_tun;
+163
View File
@@ -0,0 +1,163 @@
use super::*;
// ─── ClientOs ────────────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type)]
pub enum ClientOs {
Linux,
Windows,
Mac,
Ios,
}
impl From<&str> for ClientOs {
fn from(os: &str) -> Self {
match os {
"Linux" => ClientOs::Linux,
"Windows" => ClientOs::Windows,
"Mac" => ClientOs::Mac,
"iOS" => ClientOs::Ios,
_ => ClientOs::Linux,
}
}
}
impl ClientOs {
pub fn as_str(&self) -> &'static str {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
ClientOs::Ios => "iOS",
}
}
pub fn to_openconnect_os(&self) -> &str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
ClientOs::Ios => "apple-ios",
}
}
pub fn default_client_version(&self) -> &'static str {
match self {
ClientOs::Linux => GP_CLIENT_VERSION_LINUX,
ClientOs::Windows => GP_CLIENT_VERSION_WINDOWS,
ClientOs::Mac => GP_CLIENT_VERSION_MACOS,
ClientOs::Ios => "6.3.5-28",
}
}
pub(crate) fn default_csc_support(&self) -> bool {
match self {
ClientOs::Linux | ClientOs::Ios => false,
ClientOs::Mac | ClientOs::Windows => true,
}
}
}
// ─── PreloginParamLocation ───────────────────────────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PreloginParamLocation {
Body,
Query,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreloginBrowserMode {
Embedded,
External,
}
// ─── WebviewUserAgent ───────────────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebviewUserAgent {
Native {
prefix: String,
transform: WebviewUserAgentTransform,
},
Projected {
prefix: String,
default_user_agent: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebviewUserAgentTransform {
None,
LinuxPanGpuiVersion,
}
// ─── Target behavior ────────────────────────────────────────────────────────
pub(super) mod target {
use super::*;
pub(in crate::os_profile) fn prelogin_param_location(client_os: ClientOs) -> PreloginParamLocation {
match client_os {
ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => PreloginParamLocation::Body,
ClientOs::Windows => PreloginParamLocation::Query,
}
}
pub(in crate::os_profile) fn saml_password(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "SAMLPASS",
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => "",
}
}
pub(in crate::os_profile) fn external_browser_os_value(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "4",
ClientOs::Mac => "3",
ClientOs::Windows => "2",
ClientOs::Ios => "0",
}
}
pub(in crate::os_profile) fn supports_macos_plist_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Mac)
}
pub(in crate::os_profile) fn supports_linux_process_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Linux)
}
pub(in crate::os_profile) fn supports_windows_registry_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Windows)
}
pub(in crate::os_profile) fn kerberos_support_in_query(client_os: ClientOs) -> bool {
match client_os {
ClientOs::Linux | ClientOs::Ios => false,
ClientOs::Mac | ClientOs::Windows => true,
}
}
pub(in crate::os_profile) fn os_vendor(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "Linux",
ClientOs::Mac | ClientOs::Ios => "Apple",
ClientOs::Windows => "Microsoft",
}
}
pub(in crate::os_profile) fn webview_user_agent_default(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => DEFAULT_LINUX_WEBVIEW_USER_AGENT,
ClientOs::Mac | ClientOs::Ios => DEFAULT_MACOS_WEBVIEW_USER_AGENT,
ClientOs::Windows => DEFAULT_WINDOWS_WEBVIEW_USER_AGENT,
}
}
pub(in crate::os_profile) fn webview_user_agent_transform(client_os: ClientOs) -> WebviewUserAgentTransform {
match client_os {
ClientOs::Linux => WebviewUserAgentTransform::LinuxPanGpuiVersion,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => WebviewUserAgentTransform::None,
}
}
}
+26
View File
@@ -0,0 +1,26 @@
use super::ClientOs;
pub(super) const DEFAULT_MACOS_VERSION: &str = "13.4.0";
pub(super) const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
pub(super) const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
pub(super) const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
pub(super) const DEFAULT_LINUX_WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1";
pub(super) const DEFAULT_MACOS_WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
pub(super) const DEFAULT_WINDOWS_WEBVIEW_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0";
pub(crate) fn os_version(os: ClientOs) -> String {
match os {
ClientOs::Linux => format!("Linux {DEFAULT_LINUX_DISTRO}"),
ClientOs::Mac => format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
ClientOs::Windows => format!("Microsoft {DEFAULT_WINDOWS_DISTRO} , 64-bit"),
ClientOs::Ios => "Apple iOS".into(),
}
}
pub(crate) fn software_version(os: ClientOs) -> String {
match os {
ClientOs::Mac => DEFAULT_MACOS_VERSION.into(),
ClientOs::Windows => DEFAULT_WINDOWS_VERSION.into(),
ClientOs::Linux | ClientOs::Ios => String::new(),
}
}
@@ -0,0 +1,136 @@
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon, primary_mac_colon,
resolve_host_id,
};
use crate::collection::CollectionControl;
use crate::process::collection::CollectorCommands;
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer,
serial_number,
mac_address: native_mac,
})
}
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
return Ok(Some(value));
}
}
Ok(None)
}
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return Ok(normalize_mac_colon(mac));
}
}
Ok(None)
}
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
}))
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
let commands = crate::process::collection::CollectorCommands::new(control);
let version = commands
.run("sw_vers", &["-productVersion"])?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|version| version.trim().to_string())
.filter(|version| !version.is_empty())
.unwrap_or_else(|| super::DEFAULT_MACOS_VERSION.into());
control.check()?;
Ok((format!("Apple Mac OS X {version}"), version))
}
pub(super) fn fallback_versions() -> (String, String) {
(
super::defaults::os_version(ClientOs::Mac),
super::defaults::software_version(ClientOs::Mac),
)
}
}
+242
View File
@@ -0,0 +1,242 @@
use super::*;
use crate::collection::{CollectionBudget, CollectionControl};
use std::{io, time::Duration};
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
mod unix;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "macos")]
use macos::RuntimeNativeHostIdentity;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use unix::RuntimeNativeHostIdentity;
#[cfg(target_os = "windows")]
use windows::RuntimeNativeHostIdentity;
#[cfg(not(any(
target_os = "macos",
target_os = "windows",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
compile_error!("gpapi desktop collection is unsupported on this target; disable the desktop feature");
pub fn collect_identity() -> HostIdentity {
collect_with_host_id(None)
}
pub fn collect_identity_with_control(control: &dyn CollectionControl) -> io::Result<HostIdentity> {
collect_with_host_id_and_control(None, control)
}
pub(super) fn collect_with_host_id(host_id: Option<&str>) -> HostIdentity {
match collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(super) fn default_with_host_id(host_id: Option<&str>) -> HostIdentity {
identity_from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(super) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<HostIdentity> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
pub fn identity_from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> HostIdentity {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
HostIdentity::from_parts(computer, host_id, serial_number, mac_address)
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
identity_from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
pub fn runtime_client_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
/// Strict native collection, followed by deterministic profile projection.
pub fn collect_profile_with_control(
builder: OsProfileBuilder,
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<OsProfile> {
control.check()?;
let identity = match &builder.host_identity {
Some(identity) => identity.clone(),
None => collect_with_host_id_and_control(host_id_override, control)?,
};
let runtime_os = runtime_client_os();
// Preserve the old behavior: only probe the native version when reporting it.
let (os_version, software_version) = if builder.client_os == runtime_os {
RuntimeNativeHostIdentity::versions(control)?
} else {
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
};
control.check()?;
Ok(builder.build(HostSnapshot {
runtime_os,
identity,
os_version,
software_version,
}))
}
/// Existing desktop best-effort policy; strict HIP callers use the controlled entry point.
pub fn collect_profile(builder: OsProfileBuilder, host_id_override: Option<&str>) -> OsProfile {
match collect_profile_with_control(
builder.clone(),
host_id_override,
&CollectionBudget::new(Duration::from_secs(60)),
) {
Ok(profile) => profile,
Err(error) => {
log::warn!("OS profile collection was unavailable: {error}");
let identity = builder
.host_identity
.clone()
.unwrap_or_else(|| default_with_host_id(host_id_override));
let runtime_os = runtime_client_os();
let (os_version, software_version) = RuntimeNativeHostIdentity::fallback_versions();
builder.build(HostSnapshot {
runtime_os,
identity,
os_version,
software_version,
})
}
}
}
pub fn default_computer_name(client_os: &ClientOs) -> String {
projection::project(runtime_client_os(), *client_os, &collect_identity(), None)
.computer()
.into()
}
pub fn default_os_version(client_os: &ClientOs) -> String {
if *client_os == runtime_client_os() {
RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60)))
.unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions())
.0
} else {
defaults::os_version(*client_os)
}
}
pub fn default_software_version(client_os: &ClientOs) -> String {
if *client_os == runtime_client_os() {
RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60)))
.unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions())
.1
} else {
defaults::software_version(*client_os)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,180 @@
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = collect_identity_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = collect_identity();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = identity_from_parts(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = identity_from_parts(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = identity_from_parts(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = identity_from_parts(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
#[test]
fn builder_delegates_default_identity_to_host_identity() {
let expected = collect_identity();
let profile = collect_profile(
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
None,
);
assert_eq!(profile.host_identity(), &expected);
}
#[test]
fn builder_host_id_override_uses_supplied_runtime_identity_seed() {
let profile = collect_profile(OsProfileBuilder::new(runtime_client_os()), Some("provided-host-id"));
assert_eq!(profile.host_identity().host_id(), "provided-host-id");
}
#[test]
fn builder_host_id_override_is_used_as_projected_identity_seed() {
let client_os = match runtime_client_os() {
ClientOs::Linux => ClientOs::Mac,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux,
};
let first = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id"));
let second = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id"));
assert_eq!(first.host_identity().host_id(), "provided-host-id");
assert_eq!(first.host_id(), second.host_id());
assert_ne!(first.host_id(), "provided-host-id");
}
#[test]
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Mac), None, &cancelled).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let expired = CollectionBudget::new(Duration::ZERO);
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
+136
View File
@@ -0,0 +1,136 @@
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
serial_number,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
resolve_linux_serial_number(
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
collect_linux_product_uuid,
)
}
fn resolve_linux_serial_number(
product_serial: Option<String>,
product_uuid: impl FnOnce() -> Option<String>,
) -> Option<String> {
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
#[test]
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
assert_eq!(
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
Some("product-serial".to_string())
);
assert_eq!(
resolve_linux_serial_number(None, || uuid),
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
);
}
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
control.check()?;
Ok(Self::fallback_versions())
}
pub(super) fn fallback_versions() -> (String, String) {
(
format!(
"Linux {}",
whoami::distro().unwrap_or_else(|_| super::DEFAULT_LINUX_DISTRO.into())
),
String::new(),
)
}
}
@@ -0,0 +1,107 @@
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
control.check()?;
Ok(Self::fallback_versions())
}
pub(super) fn fallback_versions() -> (String, String) {
{
let info = os_info::get();
let edition = info
.edition()
.map(str::to_owned)
.unwrap_or_else(|| whoami::distro().unwrap_or_else(|_| super::DEFAULT_WINDOWS_DISTRO.into()));
let version = match info.version() {
os_info::Version::Unknown => super::DEFAULT_WINDOWS_VERSION.into(),
version => format!("{}.0", version),
};
(format!("Microsoft {} , 64-bit", edition), version)
}
}
}
@@ -1,670 +0,0 @@
use std::{io, time::Duration};
use crate::process::collection::{CollectionBudget, CollectionControl};
use serde::{Deserialize, Serialize};
use specta::Type;
use super::{ClientOs, serial_number};
use platform::RuntimeNativeHostIdentity;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
pub fn collect() -> Self {
Self::collect_with_host_id(None)
}
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
Self::collect_with_host_id_and_control(None, control)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
Self::default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
Self::from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(crate) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<Self> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
#[cfg(test)]
pub(crate) fn new(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
/// Construct a host identity from an already collected or negotiated snapshot.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
Self {
computer,
host_id,
serial_number,
mac_address,
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
pub(crate) fn runtime_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
HostIdentity::from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
#[cfg(target_os = "macos")]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
use crate::process::collection::{CollectionControl, CollectorCommands};
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer,
serial_number,
mac_address: native_mac,
})
}
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
return Ok(Some(value));
}
}
Ok(None)
}
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return Ok(normalize_mac_colon(mac));
}
}
Ok(None)
}
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
}))
}
}
#[cfg(target_os = "windows")]
mod platform {
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
serial_number,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
resolve_linux_serial_number(
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
collect_linux_product_uuid,
)
}
fn resolve_linux_serial_number(
product_serial: Option<String>,
product_uuid: impl FnOnce() -> Option<String>,
) -> Option<String> {
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
#[test]
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
assert_eq!(
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
Some("product-serial".to_string())
);
assert_eq!(
resolve_linux_serial_number(None, || uuid),
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = HostIdentity::collect_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = HostIdentity::collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = HostIdentity::collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = HostIdentity::new(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = HostIdentity::new(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
}
+56
View File
@@ -0,0 +1,56 @@
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
/// Values already collected by the caller. Missing observations stay empty.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self {
computer,
host_id,
serial_number: serialno,
mac_address: mac_addr,
}
}
/// Identity supplied by an application; no hardware attributes are invented.
pub fn application(computer: String, installation_id: String) -> Self {
Self {
computer,
host_id: installation_id,
serial_number: String::new(),
mac_address: String::new(),
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
}
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
use super::*;
/// Observed host facts supplied by the platform owner.
#[derive(Debug, Clone)]
pub struct HostSnapshot {
pub runtime_os: ClientOs,
pub identity: HostIdentity,
pub os_version: String,
pub software_version: String,
}
// ─── ProfileHostIdentity ────────────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ProfileHostIdentity {
pub(super) computer: String,
pub(super) host_id: String,
pub(super) serial_number: String,
pub(super) mac_address: String,
}
impl ProfileHostIdentity {
pub(super) fn for_client_os(
runtime_os: ClientOs,
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> Self {
projection::project(runtime_os, client_os, host_identity, computer_override)
}
pub(super) fn computer(&self) -> &str {
&self.computer
}
pub(super) fn host_id(&self) -> &str {
&self.host_id
}
pub(super) fn serialno(&self) -> &str {
&self.serial_number
}
pub(super) fn mac_addr(&self) -> &str {
&self.mac_address
}
}
// ─── OsProfile ───────────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct OsProfile {
runtime_os: ClientOs,
client_os: ClientOs,
os_version: String,
software_version: String,
os_vendor: &'static str,
client_version: String,
host_identity: HostIdentity,
profile_identity: ProfileHostIdentity,
user_agent: String,
}
impl OsProfile {
pub fn builder(client_os: ClientOs) -> OsProfileBuilder {
OsProfileBuilder::new(client_os)
}
// ─── Identity accessors ──────────────────────────────────────────────────
pub fn client_os(&self) -> ClientOs {
self.client_os
}
pub fn computer(&self) -> &str {
self.profile_identity.computer()
}
pub fn os_version(&self) -> &str {
&self.os_version
}
pub fn client_version(&self) -> &str {
&self.client_version
}
pub fn host_identity(&self) -> &HostIdentity {
&self.host_identity
}
pub fn user_agent(&self) -> &str {
&self.user_agent
}
pub fn webview_user_agent(&self) -> WebviewUserAgent {
if self.is_native() {
WebviewUserAgent::Native {
prefix: self.user_agent.clone(),
transform: target::webview_user_agent_transform(self.client_os),
}
} else {
WebviewUserAgent::Projected {
prefix: self.user_agent.clone(),
default_user_agent: target::webview_user_agent_default(self.client_os).to_string(),
}
}
}
pub fn host_id(&self) -> &str {
self.profile_identity.host_id()
}
pub fn serialno(&self) -> &str {
self.profile_identity.serialno()
}
pub fn mac_addr(&self) -> &str {
self.profile_identity.mac_addr()
}
/// Returns true when the target client OS matches the runtime OS.
///
/// Used to decide whether to consult real OS-level state (e.g. the actual
/// network interface) versus simulated values for emulation.
pub fn is_native(&self) -> bool {
self.runtime_os == self.client_os
}
/// Default software version string for the target OS, matching the
/// official client values.
pub fn software_version(&self) -> &str {
&self.software_version
}
// ─── Behavioral methods ──────────────────────────────────────────────────
pub(crate) fn prelogin_param_location(&self) -> PreloginParamLocation {
target::prelogin_param_location(self.client_os)
}
pub(crate) fn portal_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str {
match browser_mode {
PreloginBrowserMode::Embedded => "-10",
PreloginBrowserMode::External => target::external_browser_os_value(self.client_os),
}
}
pub(crate) fn gateway_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str {
match browser_mode {
PreloginBrowserMode::Embedded => "0",
PreloginBrowserMode::External => target::external_browser_os_value(self.client_os),
}
}
pub(crate) fn saml_password(&self) -> &'static str {
target::saml_password(self.client_os)
}
pub(crate) fn gateway_server_uses_resolved_ipv4(&self) -> bool {
true
}
pub(crate) fn supports_macos_plist_csc(&self) -> bool {
target::supports_macos_plist_csc(self.client_os)
}
pub(crate) fn supports_linux_process_csc(&self) -> bool {
target::supports_linux_process_csc(self.client_os)
}
pub(crate) fn supports_windows_registry_csc(&self) -> bool {
target::supports_windows_registry_csc(self.client_os)
}
pub(crate) fn kerberos_support_in_query(&self) -> bool {
target::kerberos_support_in_query(self.client_os)
}
pub fn os_vendor(&self) -> &'static str {
self.os_vendor
}
}
// ─── OsProfileBuilder ────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct OsProfileBuilder {
pub(super) client_os: ClientOs,
pub(super) client_version: Option<String>,
pub(super) os_version_override: Option<String>,
pub(super) computer_name_override: Option<String>,
pub(super) host_identity: Option<HostIdentity>,
pub(super) user_agent: Option<String>,
}
impl OsProfileBuilder {
pub fn new(client_os: ClientOs) -> Self {
Self {
client_os,
client_version: None,
os_version_override: None,
computer_name_override: None,
host_identity: None,
user_agent: None,
}
}
pub fn computer_name_override(mut self, name: impl Into<String>) -> Self {
self.computer_name_override = Some(name.into());
self
}
pub fn client_version(mut self, version: impl Into<String>) -> Self {
self.client_version = Some(version.into());
self
}
/// Preserve an explicitly negotiated operating system version.
pub fn os_version(mut self, version: impl Into<String>) -> Self {
let version = version.into();
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
self
}
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
self.host_identity = Some(identity);
self
}
pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
let ua = ua.into();
self.user_agent = if ua.trim().is_empty() { None } else { Some(ua) };
self
}
/// Project supplied host facts without inspecting the machine running this code.
pub fn build(self, snapshot: HostSnapshot) -> OsProfile {
let (os_version, software_version) = if self.client_os == snapshot.runtime_os {
(snapshot.os_version, snapshot.software_version)
} else {
(
defaults::os_version(self.client_os),
defaults::software_version(self.client_os),
)
};
let identity = self.host_identity.clone().unwrap_or(snapshot.identity);
self.finish(snapshot.runtime_os, identity, os_version, software_version)
}
fn finish(
self,
runtime_os: ClientOs,
host_identity: HostIdentity,
default_os_version: String,
software_version: String,
) -> OsProfile {
let client_version = self
.client_version
.filter(|version| !version.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().into());
let profile_identity =
ProfileHostIdentity::for_client_os(runtime_os, self.client_os, &host_identity, self.computer_name_override);
let os_version = self.os_version_override.unwrap_or(default_os_version);
let user_agent = self
.user_agent
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
OsProfile {
client_os: self.client_os,
runtime_os,
os_version,
software_version,
os_vendor: target::os_vendor(self.client_os),
client_version,
host_identity,
profile_identity,
user_agent,
}
}
}
+171
View File
@@ -0,0 +1,171 @@
use super::*;
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
fn derived_profile_mac(seed: &str, client_os: ClientOs) -> String {
let uuid = derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), "mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
match client_os {
ClientOs::Linux | ClientOs::Windows => bytes.join("-"),
ClientOs::Mac | ClientOs::Ios => bytes.join(":"),
}
}
fn compact_uuid(seed: &str, client_os: ClientOs, suffix: &str) -> String {
derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), suffix])
.replace('-', "")
.to_uppercase()
}
pub(super) fn project(
runtime_os: ClientOs,
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> ProfileHostIdentity {
if client_os == runtime_os {
return native::project(client_os, host_identity, computer_override);
}
match client_os {
ClientOs::Linux => linux::project(host_identity, computer_override),
ClientOs::Windows => windows::project(host_identity, computer_override),
ClientOs::Mac => macos::project(host_identity, computer_override),
ClientOs::Ios => native::project(client_os, host_identity, computer_override),
}
}
fn computer(host_identity: &HostIdentity, computer_override: Option<String>) -> String {
computer_override
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| host_identity.computer().to_string())
}
fn profile_mac_for(client_os: ClientOs, mac_address: &str) -> String {
match client_os {
ClientOs::Linux | ClientOs::Windows => mac_address.replace(':', "-"),
ClientOs::Mac | ClientOs::Ios => mac_address.replace('-', ":"),
}
}
mod native {
use super::*;
pub(super) fn project(
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> ProfileHostIdentity {
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: match client_os {
ClientOs::Mac => host_identity.host_id().replace('-', ":"),
ClientOs::Linux | ClientOs::Windows | ClientOs::Ios => host_identity.host_id().to_string(),
},
serial_number: host_identity.serialno().to_string(),
mac_address: profile_mac_for(client_os, host_identity.mac_addr()),
}
}
}
mod linux {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
let host_id = derive_uuid_from_seed(seed, &["os-profile", ClientOs::Linux.as_str(), "host-id"]);
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
serial_number: serial_number::vmware_from_uuid(&host_id).expect("projected Linux host ID should be a UUID"),
host_id,
mac_address: derived_profile_mac(seed, ClientOs::Linux),
}
}
}
mod windows {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: derive_uuid_from_seed(seed, &["os-profile", ClientOs::Windows.as_str(), "host-id"]),
serial_number: serial_number::vmware_from_compact_hex(&compact_uuid(seed, ClientOs::Windows, "serialno"))
.expect("projected Windows serial seed should be compact hex"),
mac_address: derived_profile_mac(seed, ClientOs::Windows),
}
}
}
mod macos {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
let mac_address = derived_profile_mac(seed, ClientOs::Mac);
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: mac_address.clone(),
serial_number: compact_uuid(seed, ClientOs::Mac, "serialno").chars().take(10).collect(),
mac_address,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn host_identity() -> HostIdentity {
HostIdentity::from_parts(
"real-computer".to_string(),
"real-host-id".to_string(),
"real-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
)
}
#[test]
fn native_linux_projection_uses_real_identity_with_dash_mac() {
let profile = native::project(ClientOs::Linux, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real-host-id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff");
}
#[test]
fn native_windows_projection_uses_real_identity_with_dash_mac() {
let profile = native::project(ClientOs::Windows, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real-host-id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff");
}
#[test]
fn native_macos_projection_uses_real_identity_with_colon_mac() {
let profile = native::project(ClientOs::Mac, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real:host:id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
}
+634
View File
@@ -0,0 +1,634 @@
use super::*;
#[test]
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
let identity = HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.client_version("6.3.3")
.os_version("negotiated-system-version")
.build(test_snapshot());
assert_eq!(profile.os_version(), "negotiated-system-version");
assert!(profile.user_agent().contains("negotiated-system-version"));
}
#[test]
fn csc_support_defaults_match_official_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
assert!(ClientOs::Mac.default_csc_support());
assert!(ClientOs::Windows.default_csc_support());
}
#[test]
fn prelogin_param_location_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Body
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Body
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Query
);
}
#[test]
fn embedded_portal_default_browser_is_minus_ten_for_all() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
}
#[test]
fn embedded_gateway_default_browser_is_zero_for_all() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
}
#[test]
fn external_default_browser_values_match_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"4"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"3"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"2"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"4"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"3"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"2"
);
}
#[test]
fn saml_password_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.saml_password(),
"SAMLPASS"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.saml_password(),
""
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.saml_password(),
""
);
}
#[test]
fn gateway_server_uses_resolved_ipv4_for_all() {
assert!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
}
#[test]
fn kerberos_support_in_query_matches_official_profiles() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.kerberos_support_in_query()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.kerberos_support_in_query()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.kerberos_support_in_query()
);
}
#[test]
fn os_vendor_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.os_vendor(),
"Linux"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot()).os_vendor(),
"Apple"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.os_vendor(),
"Microsoft"
);
}
#[test]
fn supports_macos_plist_csc_only_for_mac() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_macos_plist_csc()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_macos_plist_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_macos_plist_csc()
);
}
#[test]
fn supports_linux_process_csc_only_for_linux() {
assert!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_linux_process_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_linux_process_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_linux_process_csc()
);
}
#[test]
fn supports_windows_registry_csc_only_for_windows() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_windows_registry_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_windows_registry_csc()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_windows_registry_csc()
);
}
// ─── User Agent Tests ───────────────────────────────────────────────────────
#[test]
fn user_agent_derived_format_without_override() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_explicit_override_returns_custom_value() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent("custom/1.0")
.build(test_snapshot());
assert_eq!(profile.user_agent(), "custom/1.0");
}
#[test]
fn user_agent_empty_override_falls_back_to_derived() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent("")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_whitespace_only_override_falls_back_to_derived() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent(" ")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_derived_is_non_empty_for_all_client_os_variants() {
for client_os in [ClientOs::Linux, ClientOs::Windows, ClientOs::Mac] {
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
assert!(
!profile.user_agent().is_empty(),
"user_agent() should be non-empty for {:?}",
client_os
);
}
}
#[test]
fn native_webview_user_agent_uses_native_default() {
let profile = OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Native {
prefix: profile.user_agent().to_string(),
transform: target::webview_user_agent_transform(ClientOs::Mac)
}
);
}
#[test]
fn projected_linux_webview_user_agent_uses_linux_default() {
if ClientOs::Mac == ClientOs::Linux {
return;
}
let client_os = ClientOs::Linux;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_LINUX_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn projected_macos_webview_user_agent_uses_macos_default() {
if ClientOs::Mac == ClientOs::Mac {
return;
}
let client_os = ClientOs::Mac;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_MACOS_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn projected_windows_webview_user_agent_uses_windows_default() {
if ClientOs::Mac == ClientOs::Windows {
return;
}
let client_os = ClientOs::Windows;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_WINDOWS_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn os_version_strings_match_profiles() {
assert!(defaults::os_version(ClientOs::Linux).starts_with("Linux "));
assert!(defaults::os_version(ClientOs::Mac).starts_with("Apple Mac OS X "));
assert!(defaults::os_version(ClientOs::Windows).starts_with("Microsoft "));
assert_eq!(defaults::software_version(ClientOs::Linux), "");
assert!(!defaults::software_version(ClientOs::Mac).is_empty());
assert!(!defaults::software_version(ClientOs::Windows).is_empty());
}
#[test]
fn builder_fills_defaults_when_nothing_specified() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build(test_snapshot());
assert_eq!(profile.client_os(), ClientOs::Linux);
assert!(!profile.computer().is_empty());
assert!(profile.os_version().starts_with("Linux "));
assert_eq!(profile.client_version(), GP_CLIENT_VERSION_LINUX);
assert!(!profile.host_id().is_empty());
}
#[test]
fn builder_uses_explicit_values_when_provided() {
let identity = HostIdentity::from_parts(
"identity-computer".to_string(),
"test-host-id".to_string(),
"test-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.computer_name_override("MyMac")
.client_version("6.2.0-100")
.host_identity(identity.clone())
.build(test_snapshot());
assert_eq!(profile.client_os(), ClientOs::Mac);
assert_eq!(profile.computer(), "MyMac");
assert!(profile.os_version().starts_with("Apple Mac OS X "));
assert_eq!(profile.client_version(), "6.2.0-100");
assert_eq!(profile.host_identity(), &identity);
assert!(!profile.host_id().is_empty());
assert!(!profile.serialno().is_empty());
assert!(!profile.mac_addr().is_empty());
}
#[test]
fn builder_ignores_empty_strings() {
let profile = OsProfileBuilder::new(ClientOs::Windows)
.computer_name_override("")
.client_version("")
.build(test_snapshot());
// Should fall back to defaults, not use empty strings
assert!(!profile.computer().is_empty());
assert!(profile.os_version().starts_with("Microsoft "));
assert_eq!(profile.client_version(), GP_CLIENT_VERSION_WINDOWS);
}
#[test]
fn identity_accessors_delegate_to_host_identity() {
let identity = HostIdentity::from_parts(
"test-computer".to_string(),
"host-123".to_string(),
"serial-456".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.build(test_snapshot());
assert!(!profile.host_id().is_empty());
assert_eq!(profile.serialno(), "serial-456");
assert!(!profile.mac_addr().is_empty());
}
#[test]
fn local_hostname_override_changes_only_projected_computer() {
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.computer_name_override("profile-computer")
.build(test_snapshot());
assert_eq!(profile.computer(), "profile-computer");
assert_eq!(profile.host_identity().computer(), "real-computer");
}
#[test]
fn simulated_profile_identity_is_derived_from_real_host_id() {
let client_os = non_native_client_os();
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let first = OsProfileBuilder::new(client_os)
.host_identity(identity.clone())
.build(test_snapshot());
let second = OsProfileBuilder::new(client_os)
.host_identity(identity)
.build(test_snapshot());
assert_eq!(first.host_identity().host_id(), "stable-real-host-id");
assert_ne!(first.host_id(), "stable-real-host-id");
assert_eq!(first.host_id(), second.host_id());
assert_eq!(first.serialno(), second.serialno());
assert_eq!(first.mac_addr(), second.mac_addr());
}
#[test]
fn simulated_linux_serial_uses_vmware_style_uuid_bytes() {
if ClientOs::Mac == ClientOs::Linux {
return;
}
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Linux)
.host_identity(identity)
.build(test_snapshot());
assert!(profile.serialno().starts_with("VMware-"));
assert_eq!(
profile.serialno().len(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".len()
);
}
#[test]
fn profile_os_versions_are_not_host_identity_fields() {
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.build(test_snapshot());
let value = serde_json::to_value(profile.host_identity()).unwrap();
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert!(profile.os_version().starts_with("Apple Mac OS X "));
assert!(!profile.software_version().is_empty());
}
fn non_native_client_os() -> ClientOs {
match ClientOs::Mac {
ClientOs::Linux => ClientOs::Mac,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux,
}
}
// ─── Property-Based Tests ─────────────────────────────────────────────────
mod prop_tests {
use super::*;
use proptest::prelude::*;
// **Validates: Requirements 1.1, 1.2, 1.3, 1.4, 2.3, 12.1, 12.2**
//
// Property 1: Derived user agent format
// For any valid OsProfile built without a user agent override (with arbitrary
// non-empty client_version), user_agent() returns a non-empty string matching
// the format "PAN GlobalProtect/{client_version} ({profile.os_version})".
proptest! {
#[test]
fn derived_user_agent_format(
cv in "\\S{1,50}",
) {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version(cv.clone())
.build(test_snapshot());
let expected = format!("PAN GlobalProtect/{} ({})", cv, profile.os_version());
prop_assert_eq!(profile.user_agent(), expected.as_str());
prop_assert!(!profile.user_agent().is_empty());
}
}
// **Validates: Requirements 2.2, 12.3**
//
// Property 2: Override returns verbatim
// For any non-whitespace-only string provided to OsProfileBuilder::user_agent(),
// the resulting OsProfile::user_agent() returns the exact input.
proptest! {
#[test]
fn override_returns_verbatim(ua in "[^\\s][\\s\\S]{0,49}") {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.user_agent(ua.clone())
.build(test_snapshot());
prop_assert_eq!(profile.user_agent(), ua.as_str());
}
}
// **Validates: Requirements 2.4**
//
// Property 3: Whitespace override falls back to derived
// For any string composed entirely of whitespace characters provided to
// OsProfileBuilder::user_agent(), the resulting OsProfile::user_agent()
// returns the derived format (not the whitespace string).
proptest! {
#[test]
fn whitespace_override_falls_back_to_derived(ws in "[ \\t\\n]{1,20}") {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent(ws.clone())
.build(test_snapshot());
// The result must be the derived format, not the whitespace string
let expected = format!("PAN GlobalProtect/6.0.0 ({})", profile.os_version());
prop_assert_eq!(profile.user_agent(), expected.as_str());
prop_assert_ne!(profile.user_agent(), ws.as_str());
}
}
}
+51 -7
View File
@@ -1,7 +1,7 @@
use std::net::ToSocketAddrs;
use super::{RequestParams, credential as credential_params};
use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams};
use crate::{credential::Credential, gateway::GatewayLoginContext, gp_params::GpParams, os_profile::ClientOs};
/// Inputs required to build gateway login request parameters.
pub(crate) struct GatewayLoginInput<'a> {
@@ -17,7 +17,7 @@ pub(crate) struct GatewayLoginInput<'a> {
///
/// Resolves the `server` parameter to an IPv4 address when
/// `profile.gateway_server_uses_resolved_ipv4()` is true.
/// Sets `gw` and `gateway-name` to the gateway FQDN.
/// iOS uses the portal gateway name for `gw` and `gateway-name`; desktop profiles use its FQDN.
pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
let profile = input.gp_params.os_profile();
let mut body: Vec<(String, String)> = Vec::new();
@@ -51,6 +51,10 @@ pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
// Identity fields
body.push(("host-id".into(), profile.host_id().into()));
if profile.client_os() == ClientOs::Ios {
body.push(("mobile-id".into(), profile.host_id().into()));
body.push(("vpn-type".into(), "App Level VPN".into()));
}
body.push(("serialno".into(), profile.serialno().into()));
body.push(("preferred-ip".into(), String::new()));
body.push(("preferred-ipv6".into(), String::new()));
@@ -64,8 +68,13 @@ pub(crate) fn build(input: &GatewayLoginInput) -> RequestParams {
if let Some(context) = input.context {
let gateway_host = context.host().to_string();
body.push(("host".into(), gateway_host.clone()));
body.push(("gw".into(), gateway_host.clone()));
body.push(("gateway-name".into(), gateway_host));
let gateway_name = if profile.client_os() == ClientOs::Ios {
context.name().to_owned()
} else {
gateway_host
};
body.push(("gw".into(), gateway_name.clone()));
body.push(("gateway-name".into(), gateway_name));
body.push(("internal".into(), context.kind().as_login_param().to_string()));
body.push((
"selection-type".into(),
@@ -125,7 +134,9 @@ fn resolve_server(input: &GatewayLoginInput) -> String {
/// Attempt DNS resolution of a hostname to its first IPv4 address.
fn resolve_to_ipv4(host: &str) -> Option<String> {
(host, 443)
let server = crate::utils::normalize_server(host).ok()?;
let server = reqwest::Url::parse(&server).ok()?;
(server.host_str()?, server.port_or_known_default()?)
.to_socket_addrs()
.ok()?
.find(|addr| addr.ip().is_ipv4())
@@ -141,8 +152,39 @@ mod tests {
os_profile::{ClientOs, HostIdentity, OsProfile},
};
#[test]
fn mobile_login_fields_and_gateway_names_are_ios_only() {
for os in [ClientOs::Ios, ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
let params = GpParams::builder(test_profile(os)).build();
let gateway = Gateway::new("Regional_Gateway".into(), "192.0.2.1".into());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual);
let cred = make_credential();
let result = build(&GatewayLoginInput {
gp_params: &params,
cred: &cred,
gateway_host: "192.0.2.1",
context: Some(&context),
client_ip: Some("192.0.2.2"),
extend_lifetime: false,
});
let find = |key: &str| result.body.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
assert_eq!(find("host"), Some("192.0.2.1"));
if os == ClientOs::Ios {
assert_eq!(find("mobile-id"), Some(params.os_profile().host_id()));
assert_eq!(find("vpn-type"), Some("App Level VPN"));
assert_eq!(find("gw"), Some("Regional_Gateway"));
assert_eq!(find("gateway-name"), Some("Regional_Gateway"));
} else {
assert_eq!(find("mobile-id"), None);
assert_eq!(find("vpn-type"), None);
assert_eq!(find("gw"), Some("192.0.2.1"));
assert_eq!(find("gateway-name"), Some("192.0.2.1"));
}
}
}
fn test_identity() -> HostIdentity {
HostIdentity::new(
HostIdentity::from_parts(
"test-computer".to_string(),
"host-id-123".to_string(),
"serial-456".to_string(),
@@ -151,7 +193,9 @@ mod tests {
}
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os).host_identity(test_identity()).build()
OsProfile::builder(os)
.host_identity(test_identity())
.build(crate::os_profile::test_snapshot())
}
fn make_gp_params() -> GpParams {
+7 -7
View File
@@ -40,7 +40,7 @@ mod tests {
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
@@ -49,7 +49,7 @@ mod tests {
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let profile = OsProfile::builder(ClientOs::Mac).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
@@ -59,7 +59,7 @@ mod tests {
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
@@ -69,7 +69,7 @@ mod tests {
#[test]
fn uses_embedded_gateway_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
@@ -82,7 +82,7 @@ mod tests {
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
@@ -95,7 +95,7 @@ mod tests {
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
@@ -112,7 +112,7 @@ mod tests {
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
+23 -3
View File
@@ -11,7 +11,7 @@ use crate::{credential::Credential, gp_params::GpParams, os_profile::ClientOs, p
/// and left empty on macOS/Windows, matching official client behavior.
pub(crate) fn build(cred: &Credential, gp_params: &GpParams, server: &str) -> RequestParams {
let profile = gp_params.os_profile();
let nonce = if profile.client_os() == ClientOs::Linux {
let nonce = if matches!(profile.client_os(), ClientOs::Linux | ClientOs::Ios) {
"0".to_string()
} else {
swg_nonce()
@@ -58,17 +58,37 @@ mod tests {
os_profile::{ClientOs, HostIdentity, OsProfile},
};
#[test]
fn ios_uses_zero_swg_nonce_without_changing_desktop_profiles() {
for os in [ClientOs::Ios, ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
let params = GpParams::builder(test_profile(os)).build();
let result = build(&password_cred(), &params, "vpn.example.com");
let nonce = result
.body
.iter()
.find(|(key, _)| key == "swg-nonce")
.unwrap()
.1
.as_str();
if matches!(os, ClientOs::Ios | ClientOs::Linux) {
assert_eq!(nonce, "0");
} else {
assert_ne!(nonce, "0");
}
}
}
fn test_profile(os: ClientOs) -> OsProfile {
OsProfile::builder(os)
.computer_name_override("test-computer")
.client_version("6.3.3-100")
.host_identity(HostIdentity::new(
.host_identity(HostIdentity::from_parts(
"test-computer".into(),
"test-host-id".into(),
"test-serial".into(),
"aa:bb:cc:dd:ee:ff".into(),
))
.build()
.build(crate::os_profile::test_snapshot())
}
fn password_cred() -> Credential {
+9 -9
View File
@@ -44,7 +44,7 @@ mod tests {
#[test]
fn linux_places_params_in_body() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
@@ -53,7 +53,7 @@ mod tests {
#[test]
fn mac_places_params_in_body_with_kerberos_query() {
let profile = OsProfile::builder(ClientOs::Mac).build();
let profile = OsProfile::builder(ClientOs::Mac).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(!result.body.is_empty());
@@ -63,7 +63,7 @@ mod tests {
#[test]
fn windows_places_all_params_in_query() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
assert!(result.body.is_empty());
@@ -73,7 +73,7 @@ mod tests {
#[test]
fn uses_embedded_portal_default_browser_value() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let browser_param = result
@@ -86,7 +86,7 @@ mod tests {
#[test]
fn uses_target_value_when_external_browser_is_requested() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::External);
let browser_param = result
@@ -99,7 +99,7 @@ mod tests {
#[test]
fn includes_all_required_params() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let keys: Vec<&str> = result.body.iter().map(|(k, _)| k.as_str()).collect();
@@ -116,7 +116,7 @@ mod tests {
#[test]
fn data_param_is_cas_embedded_browser_base64() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let data_param = result
@@ -129,7 +129,7 @@ mod tests {
#[test]
fn kerberos_not_in_query_for_linux() {
let profile = OsProfile::builder(ClientOs::Linux).build();
let profile = OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
@@ -138,7 +138,7 @@ mod tests {
#[test]
fn kerberos_in_query_for_windows() {
let profile = OsProfile::builder(ClientOs::Windows).build();
let profile = OsProfile::builder(ClientOs::Windows).build(crate::os_profile::test_snapshot());
let result = build(&profile, PreloginBrowserMode::Embedded);
let has_kerberos = result.query.iter().any(|(k, _)| k == "kerberos-support");
+107 -46
View File
@@ -14,7 +14,7 @@ use crate::{
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
params,
session::{InternalSessionPolicy, network::InternalHostDetection},
session::{InternalHostDetection, InternalSessionPolicy},
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
@@ -52,6 +52,37 @@ pub struct PortalConfig {
internal_session_policy: Option<InternalSessionPolicy>,
}
/// Parsed portal policy before a caller chooses network-location candidates.
pub struct PortalPolicy {
config: PortalConfig,
internal_gateways: Vec<Gateway>,
external_gateways: Vec<Gateway>,
}
impl PortalPolicy {
pub fn external_gateways(self) -> PortalConfig {
self.select_gateways(false, None)
}
pub(super) fn detection(&self) -> Option<&InternalHostDetection> {
self.config.internal_detection.as_ref()
}
pub(super) fn select_gateways(mut self, prefer_internal: bool, detected: Option<bool>) -> PortalConfig {
let mut gateways = if prefer_internal {
self.internal_gateways
} else {
self.external_gateways
};
if gateways.is_empty() {
gateways.push(Gateway::new(self.config.portal.clone(), self.config.portal.clone()));
}
self.config.gateways = gateways;
self.config.internal_host_detection = detected;
self.config
}
}
impl PortalConfig {
pub fn portal(&self) -> &str {
&self.portal
@@ -140,14 +171,13 @@ impl 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.
/// Retrieve server policy without inspecting local network location.
pub async fn retrieve_config(
portal: &str,
cred: &Credential,
gp_params: &GpParams,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
) -> anyhow::Result<PortalPolicy> {
let portal = normalize_server(portal)?;
let server_url = url::Url::parse(&portal)?;
let server = remove_url_scheme(&portal);
@@ -181,6 +211,9 @@ pub async fn retrieve_config(
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
return Err(anyhow::anyhow!(tls));
}
if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() {
return Err(anyhow::anyhow!(crate::error::AuthenticationRejected));
}
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
@@ -216,11 +249,11 @@ pub async fn retrieve_config(
};
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root, cancellation).await;
return parse_portal_policy(&server, cred, root, cancellation).await;
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root, cancellation).await
parse_portal_policy(&server, cred, root, cancellation).await
}
async fn retrieve_csc_config(
@@ -287,12 +320,12 @@ fn present(value: Option<&str>) -> &'static str {
}
}
async fn parse_portal_config(
async fn parse_portal_policy(
server: &str,
cred: &Credential,
root: Element,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
) -> anyhow::Result<PortalPolicy> {
let internal_detection = root
.descendant("internal-host-detection")
.map(parse_internal_detection)
@@ -302,22 +335,11 @@ async fn parse_portal_config(
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(|| {
info!("No gateways found in portal config");
vec![]
});
let internal_gateways = parse_gateways(&root, true).unwrap_or_default();
let external_gateways = parse_gateways(&root, false).unwrap_or_default();
let user_auth_cookie = root.descendant_text("portal-userauthcookie").unwrap_or_default();
let prelogon_user_auth_cookie = root
@@ -326,31 +348,29 @@ async fn parse_portal_config(
let config_digest = root.descendant_text("config-digest");
let connect_method = parse_connect_method(&root);
if gateways.is_empty() {
gateways.push(Gateway::new(server.to_string(), server.to_string()));
} else {
info!("Found {} gateways in portal config", gateways.len());
}
let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
let default_browser = parse_default_browser(&root);
let internal_session_policy = parse_internal_session_policy(&root).ok();
Ok(PortalConfig {
portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(),
gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
internal_detection,
version,
allow_extend_session,
default_browser,
internal_session_policy,
Ok(PortalPolicy {
internal_gateways,
external_gateways,
config: PortalConfig {
portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(),
gateways: Vec::new(),
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: None,
internal_detection,
version,
allow_extend_session,
default_browser,
internal_session_policy,
},
})
}
@@ -431,15 +451,54 @@ fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<Internal
mod tests {
use super::*;
#[tokio::test]
async fn parsed_policy_keeps_location_selection_explicit() {
let xml = "<policy><internal-host-detection><ip-address>192.0.2.1</ip-address><host>inside.example</host></internal-host-detection><gateways><internal><list><entry name='internal.example'/></list></internal><external><list><entry name='external.example'/></list></external></gateways></policy>";
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let policy = parse_portal_policy("portal.example", &credential, parse_xml(xml), &CancellationToken::new())
.await
.unwrap();
assert!(policy.detection().is_some());
let external = policy.external_gateways();
assert_eq!(external.gateways()[0].server(), "external.example");
assert_eq!(external.internal_host_detection(), None);
let policy = parse_portal_policy("portal.example", &credential, parse_xml(xml), &CancellationToken::new())
.await
.unwrap();
let internal = policy.select_gateways(true, Some(true));
assert_eq!(internal.gateways()[0].server(), "internal.example");
assert_eq!(internal.internal_host_detection(), Some(true));
}
#[tokio::test]
async fn empty_candidates_preserve_portal_gateway_fallback() {
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
for detected in [None, Some(false), Some(true)] {
let policy = parse_portal_policy(
"portal.example",
&credential,
parse_xml("<policy/>"),
&CancellationToken::new(),
)
.await
.unwrap();
let config = policy.select_gateways(detected.unwrap_or(false), detected);
assert_eq!(config.gateways().len(), 1);
assert_eq!(config.gateways()[0].server(), "portal.example");
assert_eq!(config.internal_host_detection(), detected);
}
}
#[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())
let config = parse_portal_policy("portal.example", &credential, root, &CancellationToken::new())
.await
.unwrap();
.unwrap()
.external_gateways();
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);
@@ -482,9 +541,10 @@ mod tests {
"fixture-user",
"fixture-password",
));
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
let config = parse_portal_policy("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
.unwrap()
.external_gateways();
assert_eq!(
config.internal_session_policy().unwrap().hip_interval(),
std::time::Duration::from_secs(3600)
@@ -567,9 +627,10 @@ mod tests {
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
let config = parse_portal_policy("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
.unwrap()
.external_gateways();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
+2 -2
View File
@@ -480,13 +480,13 @@ mod tests {
fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
.host_identity(HostIdentity::from_parts(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
.build(crate::os_profile::test_snapshot());
GpParams::builder(profile).build()
}
+29
View File
@@ -0,0 +1,29 @@
//! Desktop portal discovery: protocol retrieval followed by native location detection.
use super::{PortalConfig, retrieve_config};
use crate::{credential::Credential, gp_params::GpParams};
use tokio_util::sync::CancellationToken;
/// Do not drop this future on disconnect: native detection must cancel and join.
pub async fn discover(
portal: &str,
credential: &Credential,
params: &GpParams,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let policy = retrieve_config(portal, credential, params, cancellation).await?;
let detected = match policy.detection() {
Some(detection) => Some(
crate::session::desktop::network::detect(detection, cancellation)
.await
.unwrap_or_else(|error| {
log::warn!("Internal host detection failed: {error}");
false
}),
),
None => None,
};
if cancellation.is_cancelled() {
anyhow::bail!("Portal configuration cancelled");
}
Ok(policy.select_gateways(detected.unwrap_or(false), detected))
}
+3
View File
@@ -4,3 +4,6 @@ mod prelogin;
pub use config::*;
pub use prelogin::*;
#[cfg(feature = "desktop")]
pub mod discovery;
+16 -4
View File
@@ -19,6 +19,7 @@ pub struct SamlPrelogin {
region: String,
is_gateway: bool,
saml_request: String,
saml_method: String,
support_default_browser: bool,
}
@@ -27,6 +28,10 @@ impl SamlPrelogin {
&self.region
}
pub fn saml_method(&self) -> &str {
&self.saml_method
}
pub fn saml_request(&self) -> &str {
&self.saml_request
}
@@ -171,7 +176,7 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
debug!("Prelogin response XML: {}", res_xml);
let prelogin = parse_res_xml(&res_xml, is_gateway).map_err(|err| {
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
warn!("Parse response error, response: {}", res_xml);
PortalError::PreloginError(err.to_string())
})?;
@@ -187,7 +192,8 @@ fn request_param<'a>(params: &'a crate::params::RequestParams, name: &str) -> Op
.find_map(|(key, value)| (key == name).then_some(value.as_str()))
}
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
/// Parse server authentication metadata without performing a network request.
pub fn parse_prelogin_response(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let root = Element::parse(res_xml.as_bytes())?;
let status = root
@@ -211,6 +217,11 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let saml_default_browser = root.descendant_text("saml-default-browser");
// Check if the prelogin response is SAML
if saml_method.is_some() && saml_request.is_some() {
let saml_method = saml_method.unwrap();
anyhow::ensure!(
matches!(saml_method.as_str(), "REDIRECT" | "POST"),
"Unsupported SAML binding"
);
let saml_request = base64::decode_to_string(&saml_request.unwrap())?;
let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false);
@@ -218,6 +229,7 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
region,
is_gateway,
saml_request,
saml_method,
support_default_browser,
};
@@ -258,13 +270,13 @@ mod tests {
fn gp_params(client_os: ClientOs) -> GpParams {
let profile = OsProfile::builder(client_os)
.host_identity(HostIdentity::new(
.host_identity(HostIdentity::from_parts(
"test-computer".to_string(),
"host-id".to_string(),
"serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
))
.build();
.build(crate::os_profile::test_snapshot());
GpParams::builder(profile).build()
}
+10 -24
View File
@@ -33,8 +33,6 @@ pub struct SamlAuthLauncher<'a> {
certificate: Option<&'a str>,
sslkey: Option<&'a str>,
key_password: Option<&'a str>,
#[cfg(not(target_os = "macos"))]
fix_openssl: bool,
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
hidpi: bool,
@@ -67,8 +65,6 @@ impl<'a> SamlAuthLauncher<'a> {
certificate: None,
sslkey: None,
key_password: None,
#[cfg(not(target_os = "macos"))]
fix_openssl: false,
ignore_tls_errors: false,
#[cfg(feature = "webview-auth")]
hidpi: false,
@@ -115,12 +111,6 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
#[cfg(not(target_os = "macos"))]
pub fn fix_openssl(mut self, fix_openssl: bool) -> Self {
self.fix_openssl = fix_openssl;
self
}
pub fn ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
self.ignore_tls_errors = ignore_tls_errors;
self
@@ -229,11 +219,6 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--client-version").arg(client_version);
}
#[cfg(not(target_os = "macos"))]
if self.fix_openssl {
auth_cmd.arg("--fix-openssl");
}
if self.ignore_tls_errors {
auth_cmd.arg("--ignore-tls-errors");
}
@@ -419,19 +404,16 @@ mod tests {
#[test]
fn launches_with_platform_tls_options() {
let launcher = SamlAuthLauncher::new("vpn.example.com").ignore_tls_errors(true);
#[cfg(not(target_os = "macos"))]
let launcher = launcher.fix_openssl(true);
let args = child_args(launcher);
assert_eq!(
args.iter().any(|arg| arg == "--fix-openssl"),
!cfg!(target_os = "macos")
);
assert!(!args.iter().any(|arg| arg == "--fix-openssl"));
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
}
#[test]
fn os_profile_sets_os_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(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
@@ -440,7 +422,9 @@ mod tests {
#[test]
fn os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
@@ -449,7 +433,9 @@ mod tests {
#[test]
fn os_profile_sets_client_version_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(crate::os_profile::test_snapshot());
let launcher = SamlAuthLauncher::new("portal.example.com").os_profile(&profile);
+5 -38
View File
@@ -3,48 +3,15 @@ use std::{
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
time::{Duration, Instant},
};
use super::command_runner::run_controlled;
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
pub trait CollectionControl {
fn check(&self) -> io::Result<()>;
}
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
fn check(&self) -> io::Result<()> {
self()
}
}
pub struct CollectionBudget {
deadline: Instant,
}
impl CollectionBudget {
pub fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
}
impl CollectionControl for CollectionBudget {
fn check(&self) -> io::Result<()> {
if Instant::now() >= self.deadline {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Device information collection timed out",
))
} else {
Ok(())
}
}
}
#[cfg(test)]
use crate::collection::CollectionBudget;
use crate::collection::CollectionControl;
#[cfg(test)]
use std::time::{Duration, Instant};
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
const TOOL_DIRECTORIES: &[&str] = &[
"/usr/bin",
+1 -1
View File
@@ -12,7 +12,7 @@ use nix::{
unistd::Pid,
};
use super::collection::CollectionControl;
use crate::collection::CollectionControl;
/// What the child reads on stdin.
pub(crate) enum ChildInput<'a> {
+61 -22
View File
@@ -29,6 +29,18 @@ pub struct DesktopLauncher<'a> {
}
impl<'a> DesktopLauncher<'a> {
/// Bring an already-running GUI to the foreground through its service.
pub async fn activate_existing() -> anyhow::Result<()> {
let endpoint = crate::utils::endpoint::http_endpoint().await?;
crate::utils::request::client_builder()
.build()?
.post(format!("{endpoint}/active-gui"))
.send()
.await?
.error_for_status()?;
Ok(())
}
pub fn new(version: &'a str) -> Self {
Self {
version,
@@ -70,11 +82,12 @@ impl<'a> DesktopLauncher<'a> {
let mut cancelled = false;
let cancellation = CancellationToken::new();
let mut recovery = RecoveryState::default();
#[cfg(target_os = "linux")]
let switch_listener = super::gui_switch::SwitchListener::new()?;
let result = {
let operation = async {
let mut minimized = self.minimized;
let mut expecting_renewal = false;
let mut program = None;
loop {
let credential = tokio::select! {
biased;
@@ -95,37 +108,61 @@ impl<'a> DesktopLauncher<'a> {
"Service product version mismatch"
);
let mut envs: HashMap<String, String> = std::env::vars().collect();
#[cfg(target_os = "linux")]
envs.insert(
super::gui_switch::SOCKET_ENV.into(),
switch_listener.path().to_string_lossy().into_owned(),
);
if recovery.dmabuf_disabled() {
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into());
}
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential))
let launcher = GuiLauncher::new(self.version, Arc::new(credential), crate::gui::preferred()?)
.envs(envs)
.minimized(minimized);
#[cfg(not(target_os = "linux"))]
let mut unexpected = [0];
// Program resolution may launch the WebKit download helper. Keep it under
// the same cancellation, service ownership and recovery budget as gpgui.
let attempt = async {
if program.is_none() {
program = Some(launcher.resolve_program(&cancellation).await?);
}
launcher.launch_program(program.as_ref().unwrap(), &cancellation).await
};
tokio::pin!(attempt);
let outcome = tokio::select! {
biased;
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
result = &mut attempt => result,
status = service.wait() => {
cancellation.cancel(); let _ = attempt.await;
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
}
result = output.read(&mut unexpected) => {
cancellation.cancel(); let _ = attempt.await;
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
let outcome = {
let attempt = async {
let program = launcher
.resolve_program(&cancellation, crate::gui::GuiTheme::System)
.await?;
#[cfg(target_os = "linux")]
return launcher
.launch_with_switches(
&program,
&cancellation,
&switch_listener.listener,
&mut input,
&mut output,
)
.await;
#[cfg(not(target_os = "linux"))]
launcher.launch_program(&program, &cancellation).await
};
tokio::pin!(attempt);
tokio::select! {
biased;
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
result = &mut attempt => result,
status = service.wait() => {
cancellation.cancel(); let _ = attempt.await;
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
}
result = async {
#[cfg(not(target_os = "linux"))]
return output.read(&mut unexpected).await;
#[cfg(target_os = "linux")]
std::future::pending::<std::io::Result<usize>>().await
} => {
cancellation.cancel(); let _ = attempt.await;
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
}
}
};
if cancellation.is_cancelled() {
@@ -184,7 +221,9 @@ fn create_log_file(path: &Path) -> std::io::Result<File> {
OpenOptions::new().append(true).open(path)
}
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
pub(super) async fn read_credential(
reader: &mut (impl AsyncRead + Unpin),
) -> anyhow::Result<Option<SessionCredential>> {
let mut header = [0; 2];
if reader.read(&mut header[..1]).await? == 0 {
return Ok(None);
@@ -12,6 +12,8 @@ pub struct GuiHelperLauncher<'a> {
envs: Option<&'a HashMap<String, String>>,
credential: &'a SessionCredential,
gui_version: Option<&'a str>,
variant: crate::gui::GuiVariant,
theme: crate::gui::GuiTheme,
}
impl<'a> GuiHelperLauncher<'a> {
@@ -21,6 +23,8 @@ impl<'a> GuiHelperLauncher<'a> {
envs: None,
credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
}
}
@@ -34,6 +38,16 @@ impl<'a> GuiHelperLauncher<'a> {
self
}
pub fn variant(mut self, variant: crate::gui::GuiVariant) -> Self {
self.variant = variant;
self
}
pub fn theme(mut self, theme: crate::gui::GuiTheme) -> Self {
self.theme = theme;
self
}
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let mut cmd = Command::new(&self.program);
@@ -43,10 +57,16 @@ impl<'a> GuiHelperLauncher<'a> {
}
cmd.arg("--service-credential-on-stdin");
if self.variant == crate::gui::GuiVariant::Nsh {
cmd.arg("--gui-variant").arg("nsh");
}
if let Some(gui_version) = self.gui_version {
cmd.arg("--gui-version").arg(gui_version);
}
if self.theme != crate::gui::GuiTheme::System {
cmd.arg("--theme").arg(self.theme.as_str());
}
info!("Launching gpgui-helper");
anyhow::ensure!(
@@ -83,6 +103,40 @@ mod tests {
path
}
#[tokio::test]
async fn forwards_explicit_themes_and_leaves_initial_downloads_on_system() {
use crate::gui::{GuiTheme, GuiVariant};
let dir = tempfile::TempDir::new().unwrap();
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let captured = dir.path().join("arguments");
for variant in [GuiVariant::Tauri, GuiVariant::Nsh] {
for theme in [GuiTheme::System, GuiTheme::Light, GuiTheme::Dark] {
let mut launcher = GuiHelperLauncher::new(&credential)
.variant(variant)
.gui_version(Some("test"))
.theme(theme);
launcher.program = fixture(
&dir,
&credential,
&format!("printf '%s\\n' \"$@\" > '{}'", captured.display()),
);
launcher.launch(&CancellationToken::new()).await.unwrap();
let mut expected = vec!["--service-credential-on-stdin"];
if variant == GuiVariant::Nsh {
expected.extend(["--gui-variant", "nsh"]);
}
expected.extend(["--gui-version", "test"]);
if theme != GuiTheme::System {
expected.extend(["--theme", theme.as_str()]);
}
assert_eq!(
std::fs::read_to_string(&captured).unwrap().lines().collect::<Vec<_>>(),
expected
);
}
}
}
#[tokio::test]
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
let dir = tempfile::TempDir::new().unwrap();
@@ -96,6 +150,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
@@ -122,6 +178,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
let eligible =
@@ -143,6 +201,8 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
theme: crate::gui::GuiTheme::System,
};
let cancellation = CancellationToken::new();
let attempt = launcher.launch(&cancellation);
+518 -22
View File
@@ -6,7 +6,6 @@ use std::{
};
use anyhow::bail;
use common::binary_paths;
use log::info;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
@@ -15,6 +14,7 @@ use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport:
pub struct GuiLauncher<'a> {
version: &'a str,
variant: crate::gui::GuiVariant,
programs: Vec<PathBuf>,
credential: Arc<SessionCredential>,
minimized: bool,
@@ -22,9 +22,9 @@ pub struct GuiLauncher<'a> {
}
impl<'a> GuiLauncher<'a> {
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
let primary = binary_paths::gpgui();
let update_target = binary_paths::gpgui_update_target();
pub fn new(version: &'a str, credential: Arc<SessionCredential>, variant: crate::gui::GuiVariant) -> Self {
let primary = variant.primary();
let update_target = variant.update_target();
let programs = if primary == update_target {
vec![primary]
} else {
@@ -33,6 +33,7 @@ impl<'a> GuiLauncher<'a> {
Self {
version,
variant,
programs,
credential,
minimized: false,
@@ -50,20 +51,20 @@ impl<'a> GuiLauncher<'a> {
self
}
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
pub(crate) async fn resolve_program(
&self,
cancellation: &CancellationToken,
helper_theme: crate::gui::GuiTheme,
) -> anyhow::Result<PathBuf> {
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
if let Some(program) = tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.find_compatible_program() => result,
} {
if let Some(program) = self.find_compatible_program(cancellation).await? {
return Ok(program);
}
self.download_program(cancellation).await?;
let program = binary_paths::gpgui_update_target();
self.download_program(cancellation, helper_theme).await?;
let program = self.variant.update_target();
tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
@@ -72,10 +73,15 @@ impl<'a> GuiLauncher<'a> {
Ok(program)
}
async fn find_compatible_program(&self) -> Option<PathBuf> {
async fn find_compatible_program(&self, cancellation: &CancellationToken) -> anyhow::Result<Option<PathBuf>> {
for program in &self.programs {
match self.check_version(program).await {
Ok(()) => return Some(program.clone()),
let result = tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
result = self.check_version(program) => result,
};
match result {
Ok(()) => return Ok(Some(program.clone())),
Err(err) => info!(
"GUI candidate {} is unavailable or incompatible: {err}",
program.display()
@@ -83,7 +89,7 @@ impl<'a> GuiLauncher<'a> {
}
}
None
Ok(None)
}
pub(crate) async fn launch_program(
@@ -99,7 +105,7 @@ impl<'a> GuiLauncher<'a> {
if self.minimized {
cmd.arg("--minimized");
}
info!("Launching gpgui");
info!("Launching {}", program.display());
super::desktop_child::launch_desktop_child(
"gpgui",
cmd.into_std(),
@@ -137,15 +143,172 @@ impl<'a> GuiLauncher<'a> {
Ok(())
}
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
async fn download_program(
&self,
cancellation: &CancellationToken,
theme: crate::gui::GuiTheme,
) -> anyhow::Result<()> {
let gui_helper = GuiHelperLauncher::new(&self.credential);
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.variant(self.variant)
.theme(theme)
.launch(cancellation)
.await
}
#[cfg(target_os = "linux")]
pub(crate) async fn launch_with_switches(
&self,
program: &Path,
cancellation: &CancellationToken,
listener: &tokio::net::UnixListener,
service_input: &mut (impl tokio::io::AsyncWrite + Unpin),
service_output: &mut (impl tokio::io::AsyncRead + Unpin),
) -> anyhow::Result<ExitStatus> {
use super::gui_switch;
use crate::gui::GuiSwitchOutcome;
use crate::service::transport::{DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut current = Some(self.start_owned(program.to_owned(), cancellation.child_token()));
let mut retired = Vec::new();
let mut unexpected = [0];
let result = async { loop {
tokio::select! {
biased;
outcome = &mut current.as_mut().unwrap().task => {
current.take();
break outcome?;
}
accepted = listener.accept() => {
let (mut socket, _) = accepted?;
let mut pending = false;
let replacement = async {
let command = gui_switch::receive(&mut socket).await?;
let selection = command.selection;
let variant = selection.variant;
let candidate = Self::new(self.version, self.credential.clone(), variant).envs(self.envs.clone());
let program = candidate.find_compatible_program(cancellation).await?;
if program.is_none() && variant == crate::gui::GuiVariant::Nsh {
use crate::service::transport::DESKTOP_GUI_INSTALLER;
service_input.write_all(&[DESKTOP_GUI_INSTALLER]).await?;
let supplies_runtime = match service_output.read_u8().await? {
0 => false,
1 => true,
_ => anyhow::bail!("Invalid GUI installer capability response"),
};
if !supplies_runtime {
super::nsh_runtime::check()?;
}
}
if program.is_none() && !selection.allow_download {
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
return Ok(None);
}
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
pending = true;
let credential = super::desktop_launcher::read_credential(service_output).await?
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
let ready = gui_switch::SwitchListener::new()?;
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
let launcher = Self::new(self.version, Arc::new(credential), variant)
.envs(envs)
.minimized(false);
let program = match program {
Some(program) => program,
None => launcher.resolve_program(cancellation, command.theme).await?,
};
let mut child = launcher.start_owned(program, cancellation.child_token());
let start_result = tokio::select! {
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
},
outcome = &mut child.task => {
return match outcome? {
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
Err(error) => Err(error),
};
}
};
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::Switched)).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = service_input.write_all(&[DESKTOP_SWITCH_COMMIT]).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error.into());
}
pending = false;
Ok(Some(child))
}.await;
match replacement {
Ok(Some(child)) => retired.push(current.replace(child).unwrap()),
Ok(None) => {},
Err(error) => {
if pending {
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
}
let _ = gui_switch::reply(&mut socket, Err(format!("{error:#}"))).await;
}
}
}
result = service_output.read(&mut unexpected) => {
break match result {
Ok(0) => Err(anyhow::anyhow!("The privileged service closed its credential channel")),
Ok(_) => Err(anyhow::anyhow!("Unexpected service credential data while the GUI is running")),
Err(error) => Err(error.into()),
};
}
}
}}.await;
// Every GUI remains owned by this supervisor until it is reaped. The retiring
// GUI exits after the successful switch reply; cancellation also joins it.
if let Some(child) = current {
retired.push(child);
}
for child in &retired {
child.cancel.cancel();
}
for child in retired {
let _ = child.task.await;
}
result
}
#[cfg(target_os = "linux")]
fn start_owned(&self, program: PathBuf, cancel: CancellationToken) -> RunningGui {
let version = self.version.to_owned();
let variant = self.variant;
let credential = self.credential.clone();
let envs = self.envs.clone();
let minimized = self.minimized;
let task_cancel = cancel.clone();
let task = tokio::spawn(async move {
GuiLauncher::new(&version, credential, variant)
.envs(envs)
.minimized(minimized)
.launch_program(&program, &task_cancel)
.await
});
RunningGui { task, cancel }
}
}
#[cfg(target_os = "linux")]
struct RunningGui {
task: tokio::task::JoinHandle<anyhow::Result<ExitStatus>>,
cancel: CancellationToken,
}
#[cfg(test)]
@@ -174,6 +337,7 @@ mod tests {
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
GuiLauncher {
version,
variant: crate::gui::GuiVariant::Tauri,
programs,
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
minimized: false,
@@ -247,7 +411,7 @@ mod tests {
}
let launcher = launcher(VERSION, vec![first, second]);
let cancellation = CancellationToken::new();
let attempt = launcher.resolve_program(&cancellation);
let attempt = launcher.resolve_program(&cancellation, crate::gui::GuiTheme::System);
tokio::pin!(attempt);
tokio::select! {
result = &mut attempt => panic!("version probe exited early: {result:?}"),
@@ -277,7 +441,13 @@ mod tests {
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged.clone(), downloaded]);
assert_eq!(launcher.find_compatible_program().await, Some(packaged));
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(packaged)
);
}
#[tokio::test]
@@ -287,7 +457,13 @@ mod tests {
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged, downloaded.clone()]);
assert_eq!(launcher.find_compatible_program().await, Some(downloaded));
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(downloaded)
);
}
#[tokio::test]
@@ -296,6 +472,326 @@ mod tests {
let program = executable(&dir, "broken", "gpgui test-version", 1);
let launcher = launcher(VERSION, vec![program]);
assert_eq!(launcher.find_compatible_program().await, None);
assert_eq!(
launcher
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
None
);
}
#[tokio::test]
async fn nsh_version_mismatch_cannot_select_a_compatible_tauri_binary() {
let dir = TempDir::new().unwrap();
let _tauri = executable(&dir, "gpgui", "gpgui test-version", 0);
let nsh = executable(&dir, "gpgui-nsh", "gpgui-nsh old-version", 0);
let mut selected = launcher(VERSION, vec![nsh.clone()]);
selected.variant = crate::gui::GuiVariant::Nsh;
assert!(
selected
.find_compatible_program(&CancellationToken::new())
.await
.unwrap()
.is_none()
);
executable(&dir, "gpgui-nsh", "gpgui-nsh test-version", 0);
assert_eq!(
selected
.find_compatible_program(&CancellationToken::new())
.await
.unwrap(),
Some(nsh)
);
}
#[test]
#[cfg(target_os = "linux")]
fn supervisor_switch_success_and_failure_preserve_child_ownership() {
for scenario in [
"success",
"failure",
"missing",
"incompatible",
"runtime-too-old",
"runtime-too-old-confirmed",
] {
let directory = TempDir::new().unwrap();
let executable = std::env::current_exe().unwrap();
// An old host GTK must block generic downloads, but not package-managed downloads.
let gtk = super::super::nsh_runtime::tests::gtk_fixture(directory.path(), 12);
fs::rename(gtk, directory.path().join("libgtk-4.so.1")).unwrap();
for name in ["gpgui", "gpgui-nsh"] {
if (scenario == "missing" || scenario.starts_with("runtime-too-old")) && name == "gpgui-nsh" {
continue;
}
let version = if scenario == "incompatible" && name == "gpgui-nsh" {
"old-version"
} else {
VERSION
};
let path = directory.path().join(name);
fs::write(&path, format!(
"#!/bin/sh\nif [ \"$1\" = --version ]; then echo '{name} {version}'; exit 0; fi\nGP_SWITCH_GUI_VARIANT={name} exec '{}' --exact process::gui_launcher::tests::gui_process_fixture --ignored --nocapture\n",
executable.display()
)).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
let output = std::process::Command::new(&executable)
.args([
"--exact",
"process::gui_launcher::tests::supervisor_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_SCENARIO", scenario)
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", directory.path().join("gpgui"))
.env("LD_LIBRARY_PATH", directory.path())
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
output.status.success(),
"{scenario}: {} {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
}
#[test]
#[cfg(target_os = "linux")]
fn selected_nsh_upgrade_downloads_nsh_without_probing_tauri() {
let directory = TempDir::new().unwrap();
let test_executable = std::env::current_exe().unwrap();
let tauri_marker = directory.path().join("tauri-probed");
let tauri = executable(&directory, "gpgui", "gpgui test-version", 0);
fs::write(
&tauri,
format!(
"#!/bin/sh\ntouch '{}'; echo 'gpgui {VERSION}'\n",
tauri_marker.display()
),
)
.unwrap();
executable(&directory, "gpgui-nsh", "gpgui-nsh old-version", 0);
let helper = directory.path().join("gpgui-helper");
fs::write(&helper, format!(
"#!/bin/sh\n[ \"$2\" = --gui-variant ] && [ \"$3\" = nsh ] || exit 21\nexec '{}' --exact process::gui_launcher::tests::upgrade_helper_fixture --ignored --nocapture\n",
test_executable.display()
)).unwrap();
fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
let result = std::process::Command::new(test_executable)
.args([
"--exact",
"process::gui_launcher::tests::upgrade_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", &tauri)
.env("GP_GUI_HELPER_BINARY", helper)
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
result.status.success(),
"{} {}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
assert!(!tauri_marker.exists());
assert!(directory.path().join("nsh-updated").exists());
}
#[tokio::test]
#[ignore = "subprocess upgrade resolver fixture"]
#[cfg(target_os = "linux")]
async fn upgrade_fixture() {
crate::gui::save_preference(crate::gui::GuiVariant::Nsh).unwrap();
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap());
let selected = GuiLauncher::new(VERSION, credential, crate::gui::preferred().unwrap());
let program = selected
.resolve_program(&CancellationToken::new(), crate::gui::GuiTheme::System)
.await
.unwrap();
assert_eq!(program.file_name().unwrap(), "gpgui-nsh");
}
#[test]
#[ignore = "subprocess download helper fixture"]
#[cfg(target_os = "linux")]
fn upgrade_helper_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
fs::write(
directory.join("gpgui-nsh"),
format!("#!/bin/sh\necho 'gpgui-nsh {VERSION}'\n"),
)
.unwrap();
fs::write(directory.join("nsh-updated"), "").unwrap();
}
#[test]
#[ignore = "subprocess GUI fixture"]
#[cfg(target_os = "linux")]
fn gui_process_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let variant = std::env::var("GP_SWITCH_GUI_VARIANT").unwrap();
if variant == "gpgui-nsh" && std::env::var("GP_SWITCH_SCENARIO").unwrap() == "failure" {
panic!("fixture: native host failed to initialize");
}
super::super::gui_switch::notify_ready().unwrap();
fs::write(directory.join(format!("{variant}-started")), "").unwrap();
while !directory.join(format!("stop-{variant}")).exists() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
fs::write(directory.join(format!("{variant}-exited")), "").unwrap();
}
#[tokio::test]
#[ignore = "subprocess supervisor fixture with isolated GUI paths and preferences"]
#[cfg(target_os = "linux")]
async fn supervisor_fixture() {
use crate::service::transport::{
DESKTOP_GUI_INSTALLER, DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let scenario = std::env::var("GP_SWITCH_SCENARIO").unwrap();
let success = scenario == "success";
let download_required = matches!(scenario.as_str(), "missing" | "incompatible");
let runtime_too_old = scenario.starts_with("runtime-too-old");
let listener = super::super::gui_switch::SwitchListener::new().unwrap();
let (mut service_input, mut control) = tokio::io::duplex(64);
let (mut service_output, mut credentials) = tokio::io::duplex(2048);
let service_marker = directory.join("service-switch-started");
let service = tokio::spawn(async move {
loop {
let message = control.read_u8().await.unwrap();
match message {
DESKTOP_GUI_INSTALLER => {
credentials.write_all(&[u8::from(!runtime_too_old)]).await.unwrap();
}
DESKTOP_SWITCH_BEGIN => {
fs::write(&service_marker, "").unwrap();
let credential = SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap();
credentials
.write_all(&credential.encode_frame().unwrap())
.await
.unwrap();
}
DESKTOP_SWITCH_COMMIT | DESKTOP_SWITCH_CANCEL => {}
_ => panic!("unexpected fixture desktop control"),
}
}
});
let envs = std::env::vars().collect::<HashMap<_, _>>();
let launcher = launcher(VERSION, vec![]).envs(envs);
let cancel = CancellationToken::new();
let program = directory.join("gpgui");
let run = launcher.launch_with_switches(
&program,
&cancel,
&listener.listener,
&mut service_input,
&mut service_output,
);
tokio::pin!(run);
let checkpoint = async {
while !directory.join("gpgui-started").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
let result = super::super::gui_switch::request_at(
&listener.path(),
crate::gui::GuiSwitchRequest {
variant: crate::gui::GuiVariant::Nsh,
allow_download: scenario == "runtime-too-old-confirmed",
},
crate::gui::GuiTheme::System,
)
.await;
if runtime_too_old {
let error = result.unwrap_err().to_string();
anyhow::ensure!(
error.contains("4.14") && error.contains("4.12.1"),
"Unexpected runtime error: {error}"
);
} else if download_required {
anyhow::ensure!(
result? == crate::gui::GuiSwitchOutcome::DownloadRequired,
"Missing download confirmation"
);
} else {
anyhow::ensure!(result.is_ok() == success, "Unexpected switch result: {result:?}");
if success {
anyhow::ensure!(
result? == crate::gui::GuiSwitchOutcome::Switched,
"Compatible GUI did not switch directly"
);
}
}
if download_required || runtime_too_old {
anyhow::ensure!(
!directory.join("service-switch-started").exists(),
"Download check changed the service session"
);
anyhow::ensure!(
!directory.join("gpgui-nsh-started").exists(),
"Download check launched the replacement"
);
}
anyhow::ensure!(
!directory.join("gpgui-exited").exists(),
"Current GUI exited before acknowledgement"
);
if success {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Nsh,
"Successful switch did not save preference"
);
fs::write(directory.join("stop-gpgui"), "")?;
while !directory.join("gpgui-exited").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
} else {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Tauri,
"Failed switch changed preference"
);
}
Ok::<_, anyhow::Error>(())
};
let checkpoint_result = tokio::select! {
result = &mut run => panic!("supervisor exited before the owned GUI: {result:?}"),
result = tokio::time::timeout(std::time::Duration::from_secs(10), checkpoint) => result.map_err(anyhow::Error::from).and_then(|result| result),
};
if let Err(error) = checkpoint_result {
cancel.cancel();
let _ = run.await;
panic!("{error:#}");
}
let stop = if success { "stop-gpgui-nsh" } else { "stop-gpgui" };
fs::write(directory.join(stop), "").unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_secs(5), run)
.await
.unwrap()
.unwrap()
.success()
);
service.abort();
}
}
+139
View File
@@ -0,0 +1,139 @@
//! Linux GUI switching through the user-owned desktop supervisor.
use anyhow::Context;
use std::os::unix::fs::PermissionsExt;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{UnixListener, UnixStream},
};
use crate::gui::{GuiSwitchOutcome, GuiSwitchRequest, GuiTheme};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct SwitchCommand {
#[serde(flatten)]
pub selection: GuiSwitchRequest,
#[serde(default)]
pub theme: GuiTheme,
}
pub(crate) const SOCKET_ENV: &str = "GP_DESKTOP_CONTROL_SOCKET";
pub(crate) const READY_ENV: &str = "GP_DESKTOP_READY_SOCKET";
/// Called after the replacement has initialized its native host.
pub fn notify_ready() -> anyhow::Result<()> {
use std::io::Write;
let Some(path) = std::env::var_os(READY_ENV) else {
return Ok(());
};
let mut socket = std::os::unix::net::UnixStream::connect(path).context("Could not notify the desktop supervisor")?;
socket.write_all(&[1])?;
Ok(())
}
pub async fn request(selection: GuiSwitchRequest, theme: GuiTheme) -> anyhow::Result<GuiSwitchOutcome> {
let path = std::env::var_os(SOCKET_ENV).context("GUI switching requires a desktop supervisor")?;
request_at(std::path::Path::new(&path), selection, theme).await
}
pub(super) async fn request_at(
path: &std::path::Path,
selection: GuiSwitchRequest,
theme: GuiTheme,
) -> anyhow::Result<GuiSwitchOutcome> {
let mut socket = UnixStream::connect(path)
.await
.context("Could not contact the desktop supervisor")?;
socket
.write_all(&serde_json::to_vec(&SwitchCommand { selection, theme })?)
.await?;
socket.shutdown().await?;
let mut reply = Vec::new();
socket.take(4096).read_to_end(&mut reply).await?;
let result: Result<GuiSwitchOutcome, String> =
serde_json::from_slice(&reply).context("Invalid desktop supervisor response")?;
result.map_err(anyhow::Error::msg)
}
pub(crate) struct SwitchListener {
pub listener: UnixListener,
directory: tempfile::TempDir,
}
impl SwitchListener {
pub fn new() -> anyhow::Result<Self> {
let directory = tempfile::Builder::new().prefix("gp-desktop-").tempdir()?;
let path = directory.path().join("control");
let listener = UnixListener::bind(&path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
Ok(Self { listener, directory })
}
pub fn path(&self) -> std::path::PathBuf {
self.directory.path().join("control")
}
#[cfg(target_os = "linux")]
pub async fn ready(&self) -> anyhow::Result<()> {
let (mut socket, _) = self.listener.accept().await?;
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut byte = [0];
socket.read_exact(&mut byte).await?;
anyhow::ensure!(byte == [1], "Invalid GUI startup notification");
Ok(())
}
}
pub(crate) async fn receive(socket: &mut UnixStream) -> anyhow::Result<SwitchCommand> {
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut request = Vec::new();
tokio::time::timeout(
std::time::Duration::from_secs(5),
socket.take(128).read_to_end(&mut request),
)
.await??;
serde_json::from_slice(&request).context("Invalid GUI selection")
}
pub(crate) async fn reply(socket: &mut UnixStream, result: Result<GuiSwitchOutcome, String>) -> anyhow::Result<()> {
socket.write_all(&serde_json::to_vec(&result)?).await?;
socket.shutdown().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn private_switch_socket_preserves_selection_and_reports_failure() {
let selection = GuiSwitchRequest {
variant: crate::gui::GuiVariant::Nsh,
allow_download: false,
};
let control = SwitchListener::new().unwrap();
let path = control.path();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let client = tokio::spawn(async move { request_at(&path, selection, GuiTheme::Dark).await });
let (mut socket, _) = control.listener.accept().await.unwrap();
assert_eq!(
receive(&mut socket).await.unwrap(),
SwitchCommand {
selection,
theme: GuiTheme::Dark
}
);
reply(&mut socket, Err("Selected GUI could not start".into()))
.await
.unwrap();
assert_eq!(
client.await.unwrap().unwrap_err().to_string(),
"Selected GUI could not start"
);
}
}
+4
View File
@@ -9,6 +9,10 @@ pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
#[cfg(any(target_os = "linux", test))]
pub mod gui_switch;
#[cfg(any(target_os = "linux", test))]
mod nsh_runtime;
pub mod users;
pub mod collection;
+105
View File
@@ -0,0 +1,105 @@
//! Checks the generic Linux NSH runtime before offering a download.
//! Runs in the desktop supervisor, which does not load either GUI's GTK runtime.
use std::{ffi::OsStr, os::raw::c_uint};
use anyhow::{Context, ensure};
use libloading::{
Library,
os::unix::{RTLD_LOCAL, RTLD_NOW},
};
// Match nsh-platform-linux's gtk4/v4_14 feature when changing the NSH build.
const MIN_GTK_MINOR: u32 = 14;
#[cfg(target_os = "linux")]
pub(super) fn check() -> anyhow::Result<()> {
check_gtk(OsStr::new("libgtk-4.so.1"))?;
load_library(OsStr::new("libgnutls.so.30"), "GnuTLS 3")?;
load_library(OsStr::new("libdbus-1.so.3"), "D-Bus")?;
Ok(())
}
fn load_library(path: &OsStr, name: &str) -> anyhow::Result<Library> {
// Resolve symbols now as well as transitive dependencies, without initializing GTK.
let library = unsafe { libloading::os::unix::Library::open(Some(path), RTLD_LOCAL | RTLD_NOW) };
library.map(Into::into).map_err(|error| {
log::warn!("Native Shell runtime check failed for {name}: {error}");
anyhow::anyhow!("Native Shell could not load {name}. Install its runtime libraries and try again.")
})
}
fn check_gtk(path: &OsStr) -> anyhow::Result<()> {
let library = load_library(path, "GTK 4.14 or later")?;
type Version = unsafe extern "C" fn() -> c_uint;
// These public GTK getters take no arguments and do not initialize a display.
let (major, minor, micro) = unsafe {
let major = library.get::<Version>(b"gtk_get_major_version\0");
let minor = library.get::<Version>(b"gtk_get_minor_version\0");
let micro = library.get::<Version>(b"gtk_get_micro_version\0");
let message = "Native Shell requires GTK 4.14 or later. Update GTK 4 and try again.";
(
major.context(message)?(),
minor.context(message)?(),
micro.context(message)?(),
)
};
ensure!(
major == 4 && minor >= MIN_GTK_MINOR,
"Native Shell requires GTK 4.14 or later. This system has GTK {major}.{minor}.{micro}."
);
Ok(())
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
use std::{fs, process::Command};
pub(in crate::process) fn gtk_fixture(directory: &std::path::Path, minor: u32) -> std::path::PathBuf {
let source = directory.join(format!("gtk-{minor}.c"));
let library = directory.join(format!("gtk-{minor}.so"));
fs::write(
&source,
format!(
"unsigned gtk_get_major_version(void) {{ return 4; }}\n\
unsigned gtk_get_minor_version(void) {{ return {minor}; }}\n\
unsigned gtk_get_micro_version(void) {{ return 1; }}\n"
),
)
.unwrap();
assert!(
Command::new("cc")
.args(["-shared", "-fPIC"])
.arg(source)
.arg("-o")
.arg(&library)
.status()
.unwrap()
.success()
);
library
}
#[test]
fn loads_runtime_version_without_development_metadata_or_a_display() {
let directory = tempfile::tempdir().unwrap();
let old = gtk_fixture(directory.path(), 12);
let supported = gtk_fixture(directory.path(), 14);
let newer = gtk_fixture(directory.path(), 20);
let error = check_gtk(old.as_os_str()).unwrap_err().to_string();
assert!(error.contains("4.14"), "{error}");
assert!(error.contains("4.12.1"), "{error}");
check_gtk(supported.as_os_str()).unwrap();
check_gtk(newer.as_os_str()).unwrap();
}
#[test]
fn missing_runtime_reports_an_actionable_error() {
let directory = tempfile::tempdir().unwrap();
let error = check_gtk(directory.path().join("missing.so").as_os_str())
.unwrap_err()
.to_string();
assert!(error.contains("GTK 4.14 or later"), "{error}");
assert!(error.contains("Install"), "{error}");
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
use crate::session::tunnel::NegotiatedNetwork;
use crate::session::desktop::tunnel::NegotiatedNetwork;
use serde::{Deserialize, Serialize};
use std::{io, path::PathBuf};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
@@ -8,7 +8,7 @@ const MAX_MESSAGE: usize = 60 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
pub struct Identity {
pub service_instance: Uuid,
#[serde(with = "crate::session::tunnel::decimal")]
#[serde(with = "crate::session::desktop::tunnel::decimal")]
#[specta(type = String)]
pub attempt: u64,
pub launch_id: Uuid,
+1 -1
View File
@@ -5,7 +5,7 @@ use crate::service::{vpn_env::VpnEnv, vpn_state::VpnState};
/// Events that can be emitted by the service
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum WsEvent {
TunnelState(Option<crate::session::tunnel::TunnelState>),
TunnelState(Option<crate::session::desktop::tunnel::TunnelState>),
VpnEnv(VpnEnv),
VpnState(VpnState),
ActiveGui,
+9 -5
View File
@@ -7,7 +7,7 @@ use zeroize::Zeroize;
use crate::{
hip::HipSource,
os_profile::{ClientOs, HostIdentity, OsProfile},
session::ConnectionPlan,
session::desktop::ConnectionPlan,
};
use super::vpn_state::ConnectInfo;
@@ -442,6 +442,8 @@ pub enum WsRequest {
pub struct UpdateGuiRequest {
pub path: String,
pub checksum: String,
#[serde(default)]
pub variant: crate::gui::GuiVariant,
}
#[cfg(test)]
@@ -452,14 +454,14 @@ mod tests {
use crate::os_profile::OsProfileBuilder;
use crate::{
gateway::Gateway,
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
session::{GatewayAuthentication, InternalSessionPolicy, desktop::AuthenticatedGateway},
};
fn test_request(info: ConnectInfo) -> ConnectRequest {
let plan = ConnectionPlan::new(
vec![AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
binding: Some(crate::session::desktop::network::test_binding()),
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
.unwrap(),
}],
@@ -527,7 +529,9 @@ mod tests {
#[test]
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(crate::os_profile::test_snapshot());
let req = test_request(test_connect_info()).with_os_profile(&profile);
@@ -536,7 +540,7 @@ mod tests {
#[test]
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(crate::os_profile::test_snapshot());
let req = test_request(test_connect_info()).with_os_profile(&profile);
@@ -18,7 +18,7 @@ pub enum ClientMessage {
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServerMessage {
TunnelStatistics {
snapshot: crate::session::tunnel::TunnelStatisticsSnapshot,
snapshot: crate::session::desktop::tunnel::TunnelStatisticsSnapshot,
},
Attached {
connection_id: Uuid,
@@ -42,7 +42,7 @@ pub enum ServerMessage {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServiceResult {
TunnelStatisticsSnapshot(crate::session::tunnel::TunnelStatisticsSnapshot),
TunnelStatisticsSnapshot(crate::session::desktop::tunnel::TunnelStatisticsSnapshot),
Accepted,
StoredHipReport {
report_id: String,
@@ -171,10 +171,10 @@ mod tests {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
let plan = crate::session::ConnectionPlan::new(
vec![crate::session::AuthenticatedGateway {
let plan = crate::session::desktop::ConnectionPlan::new(
vec![crate::session::desktop::AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
binding: Some(crate::session::desktop::network::test_binding()),
authentication: crate::session::GatewayAuthentication::new(
"authcookie=token&user=user".into(),
"tunnel".into(),
@@ -200,12 +200,13 @@ mod tests {
#[test]
fn full_configuration_and_large_metadata_fit_complete_snapshot_envelopes_at_the_budget() {
use crate::{
os_profile::HostIdentity,
service::{
vpn_env::HostInfo,
vpn_state::{ConnectedInfo, VpnState},
},
session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport},
session::desktop::tunnel::{
MAX_CONFIGURATION_BYTES, TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport,
},
};
let mut configuration = TunnelConfiguration::default();
configuration.included_routes.items = vec!["r".repeat(1024); 15];
@@ -234,7 +235,7 @@ mod tests {
vpnc_script: Some("s".repeat(1024)),
auth_executable: "a".repeat(1024),
host_info: HostInfo {
host_identity: HostIdentity::collect(),
host_identity: crate::os_profile::desktop::collect_identity(),
},
};
for mut message in [
@@ -21,3 +21,8 @@ pub const MAX_SERVICE_MESSAGE: usize = 256;
/// Private desktop control messages; never carry credentials.
pub const DESKTOP_GUI_EXITED: u8 = 0;
pub const DESKTOP_RENDERING_RETRY: u8 = 1;
pub const DESKTOP_SWITCH_BEGIN: u8 = 2;
pub const DESKTOP_SWITCH_COMMIT: u8 = 3;
pub const DESKTOP_SWITCH_CANCEL: u8 = 4;
/// Query whether the service package can install GUI runtime dependencies; replies with 0 or 1.
pub const DESKTOP_GUI_INSTALLER: u8 = 5;
+1 -1
View File
@@ -18,7 +18,7 @@ pub struct HostInfo {
/// to the client so that it can configure itself accordingly.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VpnEnv {
pub tunnel_state: Option<crate::session::tunnel::TunnelState>,
pub tunnel_state: Option<crate::session::desktop::tunnel::TunnelState>,
/// The VPN connection state
pub vpn_state: VpnState,
+5 -1
View File
@@ -5,7 +5,7 @@ use specta::Type;
use crate::{
gateway::Gateway,
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
session::{GatewaySessionSummary, SessionInfo, desktop::GatewayFailureSummary},
};
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
@@ -105,6 +105,10 @@ impl ConnectInfo {
pub fn gateway(&self) -> &Gateway {
&self.gateway
}
pub fn gateways(&self) -> &[Gateway] {
&self.gateways
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
+4 -5
View File
@@ -5,13 +5,12 @@ use serde::{Deserialize, Serialize};
use specta::Type;
mod connection;
mod gateway_sessions;
pub mod network;
pub mod non_tunnel;
mod detection;
pub use detection::InternalHostDetection;
#[cfg(feature = "desktop")]
pub mod desktop;
pub mod transport;
pub mod tunnel;
pub use connection::*;
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
-158
View File
@@ -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));
}
}
@@ -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"));
}
+12
View File
@@ -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};
@@ -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"
@@ -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)
}
@@ -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,
@@ -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);
@@ -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},
};
@@ -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()));
+5 -2
View File
@@ -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)
}
@@ -0,0 +1,46 @@
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <limits.h>
#include <stddef.h>
/* Only decrypted PKCS#8 leaves this interface. The Rust owner releases it with
* gp_key_free, so GnuTLS allocation and wiping stay with the native allocator. */
int gp_key_import(const unsigned char *input, size_t length, int pem,
const char *password, unsigned char **output, size_t *output_length) {
gnutls_x509_privkey_t key = NULL;
gnutls_datum_t exported = {NULL, 0};
int result;
*output = NULL;
*output_length = 0;
if (length > UINT_MAX) return 3;
result = gnutls_global_init();
if (result < 0) return 3;
result = gnutls_x509_privkey_init(&key);
if (result >= 0) {
gnutls_datum_t data = {(unsigned char *)input, (unsigned int)length};
result = gnutls_x509_privkey_import2(key, &data,
pem ? GNUTLS_X509_FMT_PEM : GNUTLS_X509_FMT_DER, password, 0);
}
if (result >= 0) {
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER,
NULL, GNUTLS_PKCS_PLAIN, &exported);
}
if (key != NULL) gnutls_x509_privkey_deinit(key);
gnutls_global_deinit();
if (result >= 0) {
*output = exported.data;
*output_length = exported.size;
return 0;
}
if (result == GNUTLS_E_DECRYPTION_FAILED) return 1;
if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE)
return 2;
return 3;
}
void gp_key_free(unsigned char *data, size_t length) {
if (data != NULL) {
gnutls_memset(data, 0, length);
gnutls_free(data);
}
}
@@ -0,0 +1,66 @@
use std::ffi::{c_char, c_int};
use pkcs8::SecretDocument;
use zeroize::Zeroizing;
use crate::utils::request::RequestIdentityError;
unsafe extern "C" {
fn gp_key_import(
input: *const u8,
length: usize,
pem: c_int,
password: *const c_char,
output: *mut *mut u8,
output_length: *mut usize,
) -> c_int;
fn gp_key_free(data: *mut u8, length: usize);
}
struct ExportedKey {
data: *mut u8,
length: usize,
}
impl Drop for ExportedKey {
fn drop(&mut self) {
// The shim owns the allocation and wipes it before releasing it.
unsafe { gp_key_free(self.data, self.length) };
}
}
pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
anyhow::ensure!(
!passphrase.as_bytes().contains(&0),
"Private key passphrases containing NUL are not supported"
);
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
password.push(0);
let mut exported = ExportedKey {
data: std::ptr::null_mut(),
length: 0,
};
// All input slices remain live for the call; the output is owned by the guard.
let result = unsafe {
gp_key_import(
bytes.as_ptr(),
bytes.len(),
i32::from(pem),
password.as_ptr().cast(),
&mut exported.data,
&mut exported.length,
)
};
match result {
0 => {
anyhow::ensure!(!exported.data.is_null() && exported.length > 0, "Invalid private key");
// A successful shim call returns an initialized allocation of this length.
let bytes = unsafe { std::slice::from_raw_parts(exported.data, exported.length) };
SecretDocument::try_from(bytes).map_err(|_| RequestIdentityError::InvalidKey.into())
}
1 => Err(RequestIdentityError::DecryptError("PEM").into()),
2 => Err(RequestIdentityError::UnsupportedEncryption.into()),
_ => Err(RequestIdentityError::InvalidKey.into()),
}
}
+20
View File
@@ -0,0 +1,20 @@
pub(super) mod pkcs12;
#[cfg(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
))]
#[path = "gnutls.rs"]
mod legacy_key;
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
#[path = "unsupported.rs"]
mod legacy_key;
pub(super) use legacy_key::decrypt as decrypt_key;
@@ -0,0 +1,72 @@
use p12_keystore::Pkcs12Archive;
use rustls::{
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
sign::CertifiedKey,
};
use crate::utils::request::{RequestIdentityError, pem_request_identity};
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
anyhow::ensure!(
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
"PKCS#12 passphrases containing NUL are not supported"
);
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
if passphrase.is_none() {
RequestIdentityError::NoPassphrase("PKCS#12")
} else {
RequestIdentityError::InvalidPkcs12(error)
}
})?;
if archive.keys.is_empty() || archive.certs.is_empty() {
return Err(RequestIdentityError::IncompletePkcs12.into());
}
if archive.keys.len() != 1 {
return Err(RequestIdentityError::AmbiguousPkcs12.into());
}
let key = &archive.keys[0].key;
let provider = rustls::crypto::ring::default_provider();
let mut certs = Vec::new();
for bag in &archive.certs {
if !certs
.iter()
.any(|cert: &&p12_keystore::Certificate| cert.as_der() == bag.cert.as_der())
{
certs.push(&bag.cert);
}
}
let matches: Vec<_> = certs
.iter()
.enumerate()
.filter_map(|(index, cert)| {
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
CertifiedKey::from_der(
vec![CertificateDer::from(cert.as_der().to_vec())],
private_key,
&provider,
)
.is_ok()
.then_some(index)
})
.collect();
let leaf = match matches.as_slice() {
[leaf] => *leaf,
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
};
let mut current = certs.remove(leaf);
let mut chain = Vec::new();
loop {
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
if current.subject() == current.issuer() {
break;
}
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
break;
};
current = certs.remove(parent);
}
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
pem_request_identity(&chain, key.as_bytes())
}
@@ -0,0 +1,7 @@
pub(in crate::utils) fn decrypt(
_bytes: &[u8],
_pem: bool,
_passphrase: Option<&str>,
) -> anyhow::Result<pkcs8::SecretDocument> {
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
}
+18 -18
View File
@@ -1,4 +1,4 @@
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
//! PEM/DER normalization before rustls validates usable keys and identities.
use pkcs8::{
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
der::{
@@ -8,13 +8,7 @@ use pkcs8::{
};
use zeroize::Zeroizing;
use super::{request::RequestIdentityError, traditional_key};
pub(super) enum TraditionalKeyFormat {
Sec1Der,
PlainPem,
EncryptedPem,
}
use super::{certificate, request::RequestIdentityError};
struct PemBlock {
tag: String,
@@ -26,7 +20,9 @@ impl PemBlock {
fn encoded(&self) -> Zeroizing<Vec<u8>> {
let mut block = pem::Pem::new(&self.tag, self.contents.as_slice());
*block.headers_mut() = self.headers.clone();
let encoded = Zeroizing::new(pem::encode(&block).into_bytes());
let encoded = Zeroizing::new(
pem::encode_config(&block, pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF)).into_bytes(),
);
// The PEM crate owns a copy of the decoded private key as well.
drop(Zeroizing::new(block.into_contents()));
encoded
@@ -77,13 +73,13 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
if !matches!(block.tag.as_str(), "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
return Err(RequestIdentityError::InvalidKey.into());
}
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::EncryptedPem, passphrase)?
certificate::decrypt_key(&block.encoded(), true, passphrase)?
} else {
match block.tag.as_str() {
"PRIVATE KEY" => SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?,
"RSA PRIVATE KEY" => {
// PKCS#8 stores the original PKCS#1 bytes inside an RSA algorithm envelope.
// Native TLS validates the RSA key, as it does for existing PKCS#8 input.
// Rustls validates the RSA key along with the certificate.
let algorithm = AlgorithmIdentifierRef {
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
parameters: Some(AnyRef::NULL),
@@ -94,11 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
}
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
"EC PRIVATE KEY" => {
if pem_input {
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::PlainPem, passphrase)?
} else {
traditional_key::normalize(der, TraditionalKeyFormat::Sec1Der, passphrase)?
}
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
return Ok(block.encoded());
}
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
}
@@ -172,9 +165,16 @@ fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocumen
.map_err(|_| RequestIdentityError::InvalidKey)?;
if algorithm != pkcs8::pkcs5::pbes2::PBES2_OID {
// PKCS#12 PBE-SHA1-3DES inside standalone PKCS#8 is not implemented by
// RustCrypto. Only this known legacy scheme uses the optional executable.
// RustCrypto. Only this known legacy scheme uses the native importer.
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
return super::legacy_pkcs8::decrypt(der, passphrase);
// Older supported GnuTLS releases allow 256 UTF-16 bytes including the terminator.
if let Some(passphrase) = passphrase {
anyhow::ensure!(
passphrase.encode_utf16().count() <= 127,
"Password is too long for this legacy key format. Re-export the key with modern encryption"
);
}
return certificate::decrypt_key(der, false, passphrase);
}
return Err(RequestIdentityError::UnsupportedEncryption.into());
}
-165
View File
@@ -1,165 +0,0 @@
//! Optional compatibility conversion for standalone PKCS#12 PBE-SHA1-3DES keys.
//! The executable is a runtime option, not a linked or bundled dependency.
use std::{
io::{ErrorKind, Read, Write},
os::{fd::AsFd, unix::process::CommandExt},
process::{Child, Command, Stdio},
thread,
time::{Duration, Instant},
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
use pkcs8::SecretDocument;
use zeroize::Zeroizing;
use super::request::RequestIdentityError::{self, LegacyKeyConversion};
const TIMEOUT: Duration = Duration::from_secs(10);
const MAX_OUTPUT: u64 = 1024 * 1024;
const MAX_PASSWORD_BYTES: usize = 1023;
// The converter owns a separate process group, including wrapper descendants.
// Clean up that group and reap the direct child on every return path.
struct Converter(Child);
impl Drop for Converter {
fn drop(&mut self) {
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
fn nonblocking(pipe: &impl AsFd) -> anyhow::Result<()> {
fcntl(pipe, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))
.map_err(|_| LegacyKeyConversion("could not configure converter pipes"))?;
Ok(())
}
// Read at most one chunk per iteration so a busy pipe cannot starve the deadline.
// Returns true only after EOF; inherited pipes remain subject to the deadline.
fn read_output(pipe: &mut impl Read, output: &mut Zeroizing<Vec<u8>>, limit: u64) -> anyhow::Result<bool> {
let mut buffer = Zeroizing::new([0u8; 8192]);
match pipe.read(buffer.as_mut_slice()) {
Ok(0) => Ok(true),
Ok(count) => {
if output.len() as u64 + count as u64 > limit {
return Err(LegacyKeyConversion("converter output exceeds the size limit").into());
}
output.extend_from_slice(&buffer[..count]);
Ok(false)
}
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => Ok(false),
Err(_) => Err(LegacyKeyConversion("could not read converter output").into()),
}
}
pub(super) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
// The command's line reader reserves one byte for a terminator. The linked
// OpenSSL API accepted 1024 bytes, but the CLI would truncate that password.
if passphrase.len() > MAX_PASSWORD_BYTES {
return Err(LegacyKeyConversion("the password exceeds OpenSSL's 1023-byte input limit").into());
}
// OpenSSL's pipe password source reads one line. Never silently truncate it.
if passphrase.contains(['\r', '\n', '\0']) {
return Err(LegacyKeyConversion("the password cannot be passed through OpenSSL's line-based input").into());
}
// Only encrypted input touches disk, in a private temporary file. The
// original file is never changed and decrypted output stays in memory.
let mut input = tempfile::NamedTempFile::new()?;
input.write_all(pem::encode(&pem::Pem::new("ENCRYPTED PRIVATE KEY", der)).as_bytes())?;
let child = Command::new("openssl")
.args([
"pkcs8", "-topk8", "-nocrypt", "-inform", "PEM", "-outform", "DER", "-in",
])
.arg(input.path())
.args(["-passin", "stdin"])
.env("LC_ALL", "C")
.process_group(0)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|_| LegacyKeyConversion("the openssl executable is unavailable"))?;
let mut converter = Converter(child);
let mut stdin = converter.0.stdin.take();
let mut stdout = converter.0.stdout.take().unwrap();
let mut stderr = converter.0.stderr.take().unwrap();
nonblocking(stdin.as_ref().unwrap())?;
nonblocking(&stdout)?;
nonblocking(&stderr)?;
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
password.push(b'\n');
let mut written = 0;
let mut input_failed = false;
let mut output = Zeroizing::new(Vec::new());
let mut diagnostic = Zeroizing::new(Vec::new());
let mut output_done = false;
let mut diagnostic_done = false;
let mut status = None;
let started = Instant::now();
let status = loop {
if started.elapsed() >= TIMEOUT {
return Err(LegacyKeyConversion("conversion timed out").into());
}
if let Some(pipe) = stdin.as_mut() {
match pipe.write(&password[written..]) {
Ok(0) => {
input_failed = true;
stdin = None;
}
Ok(count) => {
written += count;
if written == password.len() {
stdin = None;
}
}
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
Err(_) => {
input_failed = true;
stdin = None;
}
}
}
if !output_done {
output_done = read_output(&mut stdout, &mut output, MAX_OUTPUT)?;
}
if !diagnostic_done {
diagnostic_done = read_output(&mut stderr, &mut diagnostic, 16 * 1024)?;
}
if status.is_none() {
status = converter
.0
.try_wait()
.map_err(|_| LegacyKeyConversion("could not wait for the converter"))?;
}
if let Some(status) = status {
if output_done && diagnostic_done && stdin.is_none() {
break status;
}
}
thread::sleep(Duration::from_millis(20));
};
if status.success() && input_failed {
return Err(LegacyKeyConversion("could not send the password").into());
}
if !status.success() {
// Never include the command's output in user-facing errors: it can contain
// key material. Preserve the old Linux password retry contract only for
// an explicit decryption failure, not missing cipher/provider support.
if [b"bad decrypt".as_slice(), b"pkcs12 cipherfinal error".as_slice()]
.iter()
.any(|message| diagnostic.windows(message.len()).any(|window| window == *message))
{
return Err(RequestIdentityError::DecryptError("PEM").into());
}
return Err(LegacyKeyConversion("this OpenSSL installation cannot decrypt the key").into());
}
SecretDocument::try_from(output.as_slice()).map_err(|_| LegacyKeyConversion("invalid converted key").into())
}
+4 -1
View File
@@ -45,7 +45,10 @@ impl LockFile {
Ok(content) => {
let url = format!("http://127.0.0.1:{}/health", content.trim());
match reqwest::get(&url).await {
let Ok(client) = crate::utils::request::client_builder().build() else {
return false;
};
match client.get(&url).send().await {
Ok(resp) => resp.status().is_success(),
Err(_) => false,
}
+10 -15
View File
@@ -1,35 +1,26 @@
pub mod xml;
pub mod base64;
mod certificate;
pub mod checksum;
pub mod crypto;
#[cfg(feature = "desktop")]
pub mod endpoint;
#[cfg(feature = "desktop")]
pub mod env_utils;
mod identity_encoding;
mod legacy_pkcs8;
#[cfg(feature = "desktop")]
pub mod lock_file;
#[cfg(not(target_os = "macos"))]
pub mod openssl;
#[cfg(target_os = "macos")]
#[path = "pkcs12_identity/macos.rs"]
mod pkcs12_identity;
#[cfg(not(target_os = "macos"))]
#[path = "pkcs12_identity/openssl.rs"]
mod pkcs12_identity;
pub mod redact;
pub mod request;
#[cfg(target_os = "macos")]
#[path = "traditional_key/macos.rs"]
mod traditional_key;
#[cfg(not(target_os = "macos"))]
#[path = "traditional_key/openssl.rs"]
mod traditional_key;
#[cfg(feature = "tauri")]
pub mod window;
#[cfg(feature = "desktop")]
mod shutdown_signal;
use log::warn;
#[cfg(feature = "desktop")]
pub use shutdown_signal::shutdown_signal;
use reqwest::{Response, StatusCode, Url};
@@ -74,6 +65,10 @@ impl GpError {
pub fn is_status_error(&self) -> bool {
self.status.is_client_error() || self.status.is_server_error()
}
pub fn is_authentication_rejection(&self) -> bool {
matches!(self.status.as_u16(), 401 | 403)
}
}
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
-107
View File
@@ -1,107 +0,0 @@
use std::path::Path;
use log::{info, warn};
use regex::Regex;
use tempfile::NamedTempFile;
use version_compare::{Cmp, compare_to};
pub fn openssl_conf() -> String {
let option = get_openssl_option();
format!(
"openssl_conf = openssl_init
[openssl_init]
ssl_conf = ssl_sect
providers = provider_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
Options = {}
[provider_sect]
default = default_sect
legacy = legacy_sect
[default_sect]
activate = 1
[legacy_sect]
activate = 1
",
option
)
}
pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
let content = openssl_conf();
std::fs::write(path, content)?;
Ok(())
}
pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
let openssl_conf = NamedTempFile::new()?;
let openssl_conf_path = openssl_conf.path();
fix_openssl(openssl_conf_path)?;
unsafe { std::env::set_var("OPENSSL_CONF", openssl_conf_path) };
Ok(openssl_conf)
}
// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled
fn get_openssl_option() -> &'static str {
let version_str = openssl::version::version();
let default_option = "UnsafeLegacyServerConnect";
let Some(version) = extract_openssl_version(version_str) else {
warn!("Failed to extract OpenSSL version from '{}'", version_str);
return default_option;
};
let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) {
Ok(result) => result,
Err(_) => {
warn!("Failed to compare OpenSSL version: {}", version);
return default_option;
}
};
if older_than_3_0_4 {
info!("Using 'UnsafeLegacyRenegotiation' option");
"UnsafeLegacyRenegotiation"
} else {
info!("Using 'UnsafeLegacyServerConnect' option");
default_option
}
}
fn extract_openssl_version(version: &str) -> Option<&str> {
let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap();
re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_version() {
let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)";
assert_eq!(extract_openssl_version(input), Some("3.4.0"));
}
#[test]
fn test_different_format() {
let input = "OpenSSL 1.1.1t 7 Feb 2023";
assert_eq!(extract_openssl_version(input), Some("1.1.1t"));
}
#[test]
fn test_invalid_input() {
let input = "Invalid string without version";
assert_eq!(extract_openssl_version(input), None);
}
}
@@ -1,24 +0,0 @@
use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions};
use super::request::RequestIdentityError;
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
// native-tls assumes a successful import has a last item with an identity.
// Incomplete archives violate that assumption and panic. Inspect them first
// in a private temporary keychain, never the user's default keychain.
let directory = tempfile::tempdir()?;
let keychain = CreateOptions::new()
.password(&uuid::Uuid::new_v4().to_string())
.create(directory.path().join("identity.keychain"))?;
if let Ok(imports) = Pkcs12ImportOptions::new()
.keychain(keychain)
.passphrase(password)
.import(bytes)
&& !imports.last().is_some_and(|item| item.identity.is_some())
{
return Err(RequestIdentityError::IncompletePkcs12.into());
}
// Leave failed imports to reqwest so password errors retain their existing
// classification and native error chain.
Ok(())
}
@@ -1,14 +0,0 @@
use openssl::pkcs12::Pkcs12;
use super::request::RequestIdentityError;
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
// Parse errors belong to the existing native TLS importer. A successful parse
// lets us report incomplete archives without suggesting a password change.
if let Ok(archive) = Pkcs12::from_der(bytes).and_then(|archive| archive.parse2(password))
&& (archive.pkey.is_none() || archive.cert.is_none())
{
return Err(RequestIdentityError::IncompletePkcs12.into());
}
Ok(())
}
+30 -27
View File
@@ -4,7 +4,7 @@ use anyhow::{Context, ensure};
use reqwest::Identity;
use zeroize::Zeroizing;
use super::{identity_encoding, pkcs12_identity};
use super::{certificate::pkcs12, identity_encoding};
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
@@ -18,10 +18,6 @@ pub enum RequestIdentityError {
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
UnsupportedEncryption,
#[error(
"Could not convert the legacy private key with OpenSSL: {0}. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
LegacyKeyConversion(&'static str),
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
UnsupportedKeyFormat,
#[error("Invalid private key")]
@@ -31,7 +27,9 @@ pub enum RequestIdentityError {
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
IncompletePkcs12,
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
InvalidPkcs12(#[source] reqwest::Error),
InvalidPkcs12(#[source] p12_keystore::error::Error),
#[error("The PKCS#12 file must contain one matching client identity")]
AmbiguousPkcs12,
}
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
@@ -91,16 +89,7 @@ impl ClientIdentity {
let (identity, passphrase) = match &key {
Some(key) => (pem_request_identity(&certificate, key)?, None),
None => {
pkcs12_identity::ensure_complete(&certificate, passphrase.unwrap_or_default())?;
// A blank settings field is stored as None. Try the empty password so
// passwordless archives work, but keep prompting for protected ones.
let identity = Identity::from_pkcs12_der(&certificate, passphrase.unwrap_or_default()).map_err(|error| {
if passphrase.is_none() {
RequestIdentityError::NoPassphrase("PKCS#12")
} else {
RequestIdentityError::InvalidPkcs12(error)
}
})?;
let identity = pkcs12::identity(&certificate, passphrase)?;
(
identity,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
@@ -160,13 +149,22 @@ impl ClientIdentityFiles {
}
}
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
let error_context =
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
let identity = Identity::from_pkcs8_pem(certificate, key).context(error_context)?;
// Native TLS may defer the certificate/key match check until connector creation.
// Build the same client used for requests without making a network connection.
reqwest::Client::builder()
let mut combined = Zeroizing::new(certificate.to_vec());
combined.push(b'\n');
combined.extend_from_slice(key);
let identity = Identity::from_pem(&combined).context(error_context)?;
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
.collect::<Result<Vec<_>, _>>()
.context(error_context)?;
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
.context(error_context)?
.context(error_context)?;
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
.context(error_context)?;
client_builder()
.no_proxy()
.identity(identity.clone())
.build()
@@ -202,6 +200,14 @@ fn write_identity_file(
Ok(file)
}
/// Ordinary Reqwest construction with the shared rustls provider initialized.
pub fn client_builder() -> reqwest::ClientBuilder {
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
reqwest::Client::builder().tls_backend_rustls()
}
/// General request clients may load an identity directly. Session owners call
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
@@ -241,7 +247,7 @@ mod tests {
}
#[test]
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(CERTIFICATE).unwrap();
source.write_all(ENCRYPTED_KEY).unwrap();
@@ -255,7 +261,7 @@ mod tests {
}
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source);
reqwest::Client::builder().identity(identity).build().unwrap();
client_builder().identity(identity).build().unwrap();
}
#[test]
@@ -277,10 +283,7 @@ mod tests {
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&path).exists());
reqwest::Client::builder()
.identity(identity.request_identity())
.build()
.unwrap();
client_builder().identity(identity.request_identity()).build().unwrap();
}
}
@@ -1,17 +0,0 @@
use pkcs8::SecretDocument;
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
pub(super) fn normalize(
_bytes: &[u8],
format: TraditionalKeyFormat,
_passphrase: Option<&str>,
) -> anyhow::Result<SecretDocument> {
Err(
match format {
TraditionalKeyFormat::EncryptedPem => RequestIdentityError::UnsupportedEncryption,
TraditionalKeyFormat::PlainPem | TraditionalKeyFormat::Sec1Der => RequestIdentityError::UnsupportedKeyFormat,
}
.into(),
)
}
@@ -1,49 +0,0 @@
use openssl::{
error::ErrorStack,
pkey::{Id, PKey},
};
use pkcs8::SecretDocument;
use zeroize::Zeroizing;
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
pub(super) fn normalize(
bytes: &[u8],
format: TraditionalKeyFormat,
passphrase: Option<&str>,
) -> anyhow::Result<SecretDocument> {
let key = match format {
TraditionalKeyFormat::Sec1Der => PKey::private_key_from_der(bytes),
TraditionalKeyFormat::PlainPem => PKey::private_key_from_pem_passphrase(bytes, b""),
TraditionalKeyFormat::EncryptedPem => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
anyhow::ensure!(
!passphrase.as_bytes().contains(&0),
"Private key passphrases containing NUL are not supported"
);
PKey::private_key_from_pem_passphrase(bytes, passphrase.as_bytes())
}
}
.map_err(import_error)?;
if !matches!(key.id(), Id::RSA | Id::EC) {
return Err(RequestIdentityError::UnsupportedKeyFormat.into());
}
let der = Zeroizing::new(
key
.private_key_to_pkcs8()
.map_err(|_| RequestIdentityError::InvalidKey)?,
);
Ok(SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?)
}
fn import_error(error: ErrorStack) -> RequestIdentityError {
// Inspect only known backend reasons. Never expose the native error stack or
// turn an unclassified decoder failure into a password retry loop.
if error.errors().iter().any(|error| error.reason() == Some("bad decrypt")) {
RequestIdentityError::DecryptError("PEM")
} else if error.errors().iter().any(|error| error.reason() == Some("unsupported")) {
RequestIdentityError::UnsupportedEncryption
} else {
RequestIdentityError::InvalidKey
}
}