mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: add connection dashboard and improve desktop authentication
Add tunnel configuration reporting, an optional CLI dashboard, manual browser authentication, native authentication controls, and broader client identity support. Improve TLS recovery, certificate validation, desktop notifications, and platform integration.
This commit is contained in:
158 files changed
+13735
-1038
No files matched your search
@@ -26,9 +26,11 @@ tauri = { workspace = true, optional = true }
|
||||
regex = { workspace = true, optional = true }
|
||||
tokio-util = { workspace = true, optional = true }
|
||||
html-escape = { version = "0.3", optional = true }
|
||||
url = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))'.dependencies]
|
||||
webkit2gtk = { version = "2", optional = true }
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = { version = "0.6", optional = true }
|
||||
@@ -36,6 +38,7 @@ objc2 = { version = "0.6", optional = true }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "block2"], optional = true }
|
||||
objc2-foundation = { version = "0.3", optional = true }
|
||||
objc2-web-kit = { version = "0.3", optional = true }
|
||||
objc2-security = { version = "0.3", default-features = false, features = ["std", "SecBase", "SecTrust", "SecCertificate"], optional = true }
|
||||
|
||||
[features]
|
||||
browser-auth = [
|
||||
@@ -54,11 +57,36 @@ webview-auth = [
|
||||
"dep:regex",
|
||||
"dep:tokio-util",
|
||||
"dep:html-escape",
|
||||
"dep:url",
|
||||
"dep:gtk",
|
||||
"dep:webkit2gtk",
|
||||
"dep:block2",
|
||||
"dep:objc2",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-web-kit",
|
||||
"dep:objc2-security",
|
||||
"objc2-app-kit/NSAlert",
|
||||
"dep:objc2-app-kit",
|
||||
"objc2-app-kit/NSView",
|
||||
"objc2-app-kit/NSText",
|
||||
"objc2-app-kit/NSTextView",
|
||||
"objc2-app-kit/NSTextContainer",
|
||||
"objc2-app-kit/NSParagraphStyle",
|
||||
"objc2-app-kit/NSFont",
|
||||
"objc2-app-kit/NSBox",
|
||||
"objc2-app-kit/NSButton",
|
||||
"objc2-app-kit/NSButtonCell",
|
||||
"objc2-app-kit/NSEvent",
|
||||
"objc2-app-kit/NSTextField",
|
||||
"objc2-app-kit/NSProgressIndicator",
|
||||
"objc2-app-kit/NSColor",
|
||||
"objc2-app-kit/NSResponder",
|
||||
"objc2-app-kit/NSAccessibilityProtocols",
|
||||
"objc2-app-kit/NSWindow",
|
||||
"objc2-app-kit/NSToolbar",
|
||||
"objc2-app-kit/NSToolbarItem",
|
||||
"objc2-app-kit/NSLayoutAnchor",
|
||||
"objc2-app-kit/NSLayoutConstraint",
|
||||
]
|
||||
release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ impl<'a> BrowserAuthenticator<'a> {
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
|
||||
let callback_receiver = if is_remote_browser(self.browser) {
|
||||
let callback_receiver = if is_manual_browser(self.browser) {
|
||||
None
|
||||
} else {
|
||||
ensure_auth_callback_handler()?;
|
||||
@@ -41,7 +41,7 @@ impl<'a> BrowserAuthenticator<'a> {
|
||||
auth_server.serve_request(&auth_request);
|
||||
});
|
||||
|
||||
if is_remote_browser(self.browser) {
|
||||
if is_manual_browser(self.browser) {
|
||||
info!(
|
||||
r#"
|
||||
|
||||
@@ -69,7 +69,7 @@ Note that the URL is only valid for a single use.
|
||||
}
|
||||
|
||||
async fn determine_addr(&self) -> anyhow::Result<SocketAddr> {
|
||||
if is_remote_browser(self.browser) {
|
||||
if is_manual_browser(self.browser) {
|
||||
let local_ip = match self.browser_listen {
|
||||
Some(ip) => ip,
|
||||
None => detect_local_ip().await?,
|
||||
@@ -81,8 +81,8 @@ Note that the URL is only valid for a single use.
|
||||
}
|
||||
}
|
||||
|
||||
fn is_remote_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("remote")
|
||||
fn is_manual_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote")
|
||||
}
|
||||
|
||||
/// Detect the local IP address by creating a UDP socket and connecting to an external address
|
||||
@@ -120,20 +120,24 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_remote_remains_auth_specific() {
|
||||
assert!(is_remote_browser("remote"));
|
||||
assert!(is_remote_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default);
|
||||
fn browser_manual_remains_auth_specific() {
|
||||
assert!(is_manual_browser("manual"));
|
||||
assert!(is_manual_browser("MANUAL"));
|
||||
assert!(is_manual_browser("remote"));
|
||||
assert!(is_manual_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("manual"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_browser_uses_explicit_listen_address() {
|
||||
async fn manual_browser_uses_explicit_listen_address() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip));
|
||||
for browser in ["manual", "MANUAL", "remote", "REMOTE"] {
|
||||
let authenticator = BrowserAuthenticator::new("request", browser, Some(listen_ip));
|
||||
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
mod address_bar;
|
||||
mod auth_messenger;
|
||||
mod recovery;
|
||||
mod tls;
|
||||
mod webview_auth;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
pub const TOOLBAR_HEIGHT: f64 = 40.0;
|
||||
pub const LOADING_ADDRESS: &str = "Loading sign-in page…";
|
||||
|
||||
/// Display web addresses with query strings and fragments, but without credentials.
|
||||
pub fn display_address(uri: Option<&str>) -> String {
|
||||
let Some(mut url) = uri.and_then(|uri| url::Url::parse(uri).ok()) else {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
}
|
||||
|
||||
let _ = url.set_username("");
|
||||
let _ = url.set_password(None);
|
||||
url.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hides_credentials_but_preserves_query_and_fragment() {
|
||||
assert_eq!(
|
||||
display_address(Some(
|
||||
"https://user:[email protected]:8443/saml?SAMLRequest=secret#token"
|
||||
)),
|
||||
"https://login.example:8443/saml?SAMLRequest=secret#token"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_scheme_host_and_encoded_path() {
|
||||
assert_eq!(
|
||||
display_address(Some("http://example.com/a%20b")),
|
||||
"http://example.com/a%20b"
|
||||
);
|
||||
assert_eq!(display_address(Some("https://[::1]:8443/")), "https://[::1]:8443/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_placeholder_for_local_pages_and_callbacks() {
|
||||
for uri in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("invalid"),
|
||||
Some("about:blank"),
|
||||
Some("data:text/html,secret"),
|
||||
Some("globalprotectcallback:secret"),
|
||||
] {
|
||||
assert_eq!(display_address(uri), LOADING_ADDRESS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::tls::TlsFailure;
|
||||
use anyhow::bail;
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use tokio::sync::{RwLock, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -14,36 +16,30 @@ pub(crate) enum AuthDataLocation {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AuthError {
|
||||
/// Failed to load page due to TLS error
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
TlsError,
|
||||
/// 1. Found auth data in headers/body but it's invalid
|
||||
/// 2. Loaded an empty page, failed to load page. etc.
|
||||
/// A certificate or TLS handshake failure in the native webview.
|
||||
Tls(TlsFailure),
|
||||
/// The authentication service returned a temporary failure.
|
||||
TemporarilyUnavailable,
|
||||
/// A sign-in request could not be loaded.
|
||||
LoadFailed(anyhow::Error),
|
||||
/// Found auth data in headers/body but it's invalid.
|
||||
Invalid(anyhow::Error, AuthDataLocation),
|
||||
/// No auth data found in headers/body
|
||||
NotFound(AuthDataLocation),
|
||||
}
|
||||
|
||||
impl AuthError {
|
||||
pub fn invalid_from_body(err: anyhow::Error) -> Self {
|
||||
Self::Invalid(err, AuthDataLocation::Body)
|
||||
}
|
||||
|
||||
pub fn not_found_in_body() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Body)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
impl AuthError {
|
||||
pub fn not_found_in_headers() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Headers)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum AuthEvent {
|
||||
Data(SamlAuthData, AuthDataLocation),
|
||||
Error(AuthError),
|
||||
Data(u64, SamlAuthData, AuthDataLocation),
|
||||
Error(u64, AuthError),
|
||||
NoAuthData(u64, AuthDataLocation),
|
||||
PageLoaded(u64),
|
||||
Retry,
|
||||
RequestTlsException,
|
||||
TlsAccepted(u64),
|
||||
RaiseWindow,
|
||||
Close,
|
||||
}
|
||||
@@ -52,6 +48,7 @@ pub struct AuthMessenger {
|
||||
tx: mpsc::UnboundedSender<AuthEvent>,
|
||||
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
|
||||
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
|
||||
impl AuthMessenger {
|
||||
@@ -62,6 +59,7 @@ impl AuthMessenger {
|
||||
tx,
|
||||
rx: RwLock::new(rx),
|
||||
raise_window_cancel_token: Default::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +77,12 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_auth_error(&self, err: AuthError) {
|
||||
self.send_auth_event(AuthEvent::Error(err));
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) {
|
||||
self.send_auth_event(AuthEvent::Data(data, location));
|
||||
pub fn begin_attempt(&self) {
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn schedule_raise_window(&self, delay: u64) {
|
||||
@@ -132,9 +130,9 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_from_html(&self, html: &str) {
|
||||
pub fn read_from_html(&self, html: &str, generation: u64) {
|
||||
if html.contains("Temporarily Unavailable") {
|
||||
return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable")));
|
||||
return self.send_auth_event(AuthEvent::Error(generation, AuthError::TemporarilyUnavailable));
|
||||
}
|
||||
|
||||
let auth_result = SamlAuthData::from_html(html).or_else(|err| {
|
||||
@@ -149,18 +147,20 @@ impl AuthMessenger {
|
||||
});
|
||||
|
||||
match auth_result {
|
||||
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
|
||||
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
|
||||
Err(err) => self.send_auth_error(AuthError::invalid_from_body(err.into())),
|
||||
Ok(data) => self.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
|
||||
Err(AuthDataParseError::NotFound) => {
|
||||
self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Body))
|
||||
}
|
||||
Err(err) => self.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(err.into()))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||
use log::warn;
|
||||
|
||||
let Some(status) = auth_response.get_header("saml-auth-status") else {
|
||||
return self.send_auth_error(AuthError::not_found_in_headers());
|
||||
return self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Headers));
|
||||
};
|
||||
|
||||
// Do not send auth error when reading from headers, as the html body may contain the auth data
|
||||
@@ -174,7 +174,7 @@ impl AuthMessenger {
|
||||
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
|
||||
|
||||
match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) {
|
||||
Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers),
|
||||
Ok(auth_data) => self.send_auth_event(AuthEvent::Data(generation, auth_data, AuthDataLocation::Headers)),
|
||||
Err(err) => {
|
||||
warn!("Failed to read auth data from headers: {}", err);
|
||||
}
|
||||
@@ -193,6 +193,43 @@ fn extract_gpcallback(html: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_sign_in_page_is_an_observation_with_its_original_generation() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html><h1>Sign in</h1></html>", 7);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::NoAuthData(7, AuthDataLocation::Body)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_temporary_failure_from_rejected_authentication() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::TemporarilyUnavailable)
|
||||
));
|
||||
messenger.read_from_html("<saml-auth-status>0</saml-auth-status>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::Invalid(..))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn html_callbacks_keep_the_generation_that_started_the_read() {
|
||||
let messenger = AuthMessenger::new();
|
||||
let generation = messenger.generation();
|
||||
messenger.begin_attempt();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", generation);
|
||||
match messenger.subscribe().await.unwrap() {
|
||||
AuthEvent::Error(generation, _) => assert_ne!(generation, messenger.generation()),
|
||||
_ => panic!("Expected an authentication error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_some() {
|
||||
let html = r#"
|
||||
|
||||
+244
-55
@@ -1,8 +1,9 @@
|
||||
use std::sync::Arc;
|
||||
use std::{cell::Cell, rc::Rc, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::warn;
|
||||
use gtk::prelude::*;
|
||||
use log::{info, warn};
|
||||
use tauri::webview::PlatformWebview;
|
||||
use webkit2gtk::{
|
||||
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
|
||||
@@ -10,10 +11,26 @@ use webkit2gtk::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_messenger::AuthError,
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::{GetHeader, PlatformWebviewExt},
|
||||
};
|
||||
|
||||
#[path = "gtk_recovery.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "gtk_tls.rs"]
|
||||
mod tls;
|
||||
|
||||
fn action_button(label: &str) -> anyhow::Result<gtk::Button> {
|
||||
let button = gtk::Button::with_label(label);
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b"button { padding: 4px 12px; }")?;
|
||||
button
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
Ok(button)
|
||||
}
|
||||
|
||||
impl GetHeader for WebResource {
|
||||
fn get_header(&self, key: &str) -> Option<String> {
|
||||
self
|
||||
@@ -25,6 +42,62 @@ impl GetHeader for WebResource {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
use super::address_bar::display_address;
|
||||
|
||||
let entry = gtk::Entry::new();
|
||||
entry.set_editable(false);
|
||||
entry.set_can_focus(true);
|
||||
entry.set_direction(gtk::TextDirection::Ltr);
|
||||
entry.set_text(&display_address(self.inner().uri().as_deref()));
|
||||
let header = gtk::Box::new(gtk::Orientation::Vertical, 4);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_TOOLBAR);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_PRIMARY_TOOLBAR);
|
||||
header.style_context().add_class("gpauth-header");
|
||||
// One native header owns the outer padding and the gap between its rows.
|
||||
// Keep theme colors, borders, focus styling, and natural button sizes.
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b".gpauth-header { padding: 6px; } entry { min-height: 22px; padding: 2px 6px; }")?;
|
||||
entry
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header.pack_start(&entry, false, false, 0);
|
||||
header.show_all();
|
||||
recovery_row::install(&self.inner(), &header, Arc::clone(&messenger))?;
|
||||
let container = window.default_vbox()?;
|
||||
container.pack_start(&header, false, false, 0);
|
||||
container.reorder_child(&header, 0);
|
||||
let separator = gtk::Separator::new(gtk::Orientation::Horizontal);
|
||||
container.pack_start(&separator, false, false, 0);
|
||||
container.reorder_child(&separator, 1);
|
||||
separator.show();
|
||||
|
||||
// Observe the top-level URI, including redirects and history API changes.
|
||||
let address = entry.clone();
|
||||
self.inner().connect_uri_notify(move |webview| {
|
||||
address.set_text(&display_address(webview.uri().as_deref()));
|
||||
address.set_position(0);
|
||||
});
|
||||
tls::install(&self.inner(), Arc::clone(&messenger));
|
||||
install_navigation_observers(&self.inner(), messenger, entry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
recovery_row::update(&self.inner(), status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
self.inner().stop_loading();
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(&self.inner())
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
if let Some(manager) = self.inner().website_data_manager() {
|
||||
manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
|
||||
@@ -34,7 +107,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -45,7 +118,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -54,72 +127,188 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn load_url(&self, url: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_uri(url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_html(html, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
let script = "document.documentElement.outerHTML";
|
||||
self
|
||||
.inner()
|
||||
.evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result {
|
||||
Ok(value) => callback(Ok(value.to_string())),
|
||||
Err(err) => callback(Err(anyhow::anyhow!(err))),
|
||||
});
|
||||
const NAVIGATION_KEY: &str = "gpauth-navigation";
|
||||
|
||||
#[derive(Default)]
|
||||
struct NavigationAttempts {
|
||||
pending: Cell<Option<u64>>,
|
||||
current: Cell<Option<u64>>,
|
||||
}
|
||||
|
||||
impl NavigationAttempts {
|
||||
fn started(&self, generation: u64) {
|
||||
self.current.set(Some(self.pending.take().unwrap_or(generation)));
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PlatformWebviewOnResponse {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>);
|
||||
struct NavigationObserver {
|
||||
attempts: NavigationAttempts,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
impl PlatformWebviewOnResponse for PlatformWebview {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>) {
|
||||
let wv = self.inner();
|
||||
let callback = Arc::new(callback);
|
||||
let callback_clone = Arc::clone(&callback);
|
||||
fn prepare_navigation(webview: &webkit2gtk::WebView) -> anyhow::Result<()> {
|
||||
let observer =
|
||||
unsafe { webview.data::<Rc<NavigationObserver>>(NAVIGATION_KEY) }.context("Navigation observer is unavailable")?;
|
||||
let observer = unsafe { observer.as_ref() };
|
||||
observer.attempts.pending.set(Some(observer.messenger.generation()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
wv.connect_load_changed(move |wv, event| {
|
||||
if event != LoadEvent::Finished {
|
||||
return;
|
||||
fn install_navigation_observers(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, address: gtk::Entry) {
|
||||
let observer = Rc::new(NavigationObserver {
|
||||
attempts: NavigationAttempts::default(),
|
||||
messenger,
|
||||
});
|
||||
unsafe {
|
||||
webview.set_data(NAVIGATION_KEY, Rc::clone(&observer));
|
||||
}
|
||||
let loading = Rc::clone(&observer);
|
||||
webview.connect_load_changed(move |webview, event| {
|
||||
match event {
|
||||
LoadEvent::Started => {
|
||||
loading.attempts.started(loading.messenger.generation());
|
||||
loading.messenger.cancel_raise_window();
|
||||
}
|
||||
|
||||
let Some(web_resource) = wv.main_resource() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let uri = web_resource.uri().unwrap_or("".into());
|
||||
if uri.is_empty() {
|
||||
callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI"))));
|
||||
} else {
|
||||
callback_clone(Ok(web_resource));
|
||||
LoadEvent::Committed => {
|
||||
if let Some(generation) = loading.attempts.current.get() {
|
||||
info!(
|
||||
"Started loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redacted_uri, err, cert
|
||||
);
|
||||
|
||||
callback(Err(AuthError::TlsError));
|
||||
true
|
||||
});
|
||||
|
||||
wv.connect_load_failed(move |_wv, _event, uri, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
if !uri.starts_with("globalprotectcallback:") {
|
||||
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
|
||||
LoadEvent::Finished => {
|
||||
// WebKitGTK finishes a cancelled load before starting its replacement.
|
||||
// Retain that load's generation instead of relabeling it at callback time.
|
||||
let Some(generation) = loading.attempts.current.take() else {
|
||||
return;
|
||||
};
|
||||
info!(
|
||||
"Finished loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
if let Some(resource) = webview.main_resource() {
|
||||
let uri = resource.uri().unwrap_or_default();
|
||||
if uri.is_empty() {
|
||||
loading.messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::invalid_from_body(anyhow::anyhow!("Empty URI")),
|
||||
));
|
||||
} else {
|
||||
loading.messenger.read_from_response(&resource, generation);
|
||||
}
|
||||
}
|
||||
loading.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
// NOTE: Don't send error here, since load_changed event will be triggered after this
|
||||
// true to stop other handlers from being invoked for the event. false to propagate the event further.
|
||||
true
|
||||
});
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
|
||||
let tls = Rc::clone(&observer);
|
||||
let tls_address = address.clone();
|
||||
webview.connect_load_failed_with_tls_errors(move |webview, uri, cert, err| {
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redact_uri(uri),
|
||||
err,
|
||||
cert
|
||||
);
|
||||
if let Some(generation) = tls.attempts.current.take() {
|
||||
if generation != tls.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
show_failed_address(&tls_address, uri);
|
||||
let failure = tls::record_failure(webview, uri, cert, err, generation);
|
||||
tls
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure)));
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
webview.connect_load_failed(move |_webview, _event, uri, err| {
|
||||
if let Some(generation) = observer.attempts.current.take() {
|
||||
if generation != observer.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
if !uri.starts_with("globalprotectcallback:") && !err.matches(webkit2gtk::NetworkError::Cancelled) {
|
||||
warn!("Failed to load uri: {} with error: {}", redact_uri(uri), err);
|
||||
show_failed_address(&address, uri);
|
||||
let error = if err.kind::<webkit2gtk::gio::TlsError>().is_some() {
|
||||
AuthError::Tls(super::tls::TlsFailure {
|
||||
host: url::Url::parse(uri)
|
||||
.ok()
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned))
|
||||
.unwrap_or_default(),
|
||||
reason: super::tls::TlsFailureReason::Handshake,
|
||||
can_continue: false,
|
||||
})
|
||||
} else {
|
||||
AuthError::LoadFailed(anyhow::anyhow!("{}", err))
|
||||
};
|
||||
observer.messenger.send_auth_event(AuthEvent::Error(generation, error));
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
// A failed provisional load may leave WebView.uri unset.
|
||||
fn show_failed_address(entry: >k::Entry, uri: &str) {
|
||||
entry.set_text(&super::address_bar::display_address(Some(uri)));
|
||||
entry.set_position(0);
|
||||
}
|
||||
|
||||
fn read_navigation_html(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
webview.evaluate_javascript(
|
||||
"document.documentElement.outerHTML",
|
||||
None,
|
||||
None,
|
||||
Cancellable::NONE,
|
||||
move |result| match result {
|
||||
Ok(value) => messenger.read_from_html(&value.to_string(), generation),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NavigationAttempts;
|
||||
|
||||
#[test]
|
||||
fn cancelled_load_keeps_its_generation_until_replacement_starts() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.started(0);
|
||||
attempts.pending.set(Some(2));
|
||||
// The previous load's cancellation/finish arrives after retry generation advances.
|
||||
assert_eq!(attempts.current.take(), Some(0));
|
||||
attempts.started(2);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_generation_survives_attempt_changes_before_native_start() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.pending.set(Some(2));
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
// User navigation after that load starts in the current attempt.
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::WebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
const CONTROLS_KEY: &str = "gpauth-recovery-controls";
|
||||
|
||||
struct RecoveryRow {
|
||||
row: gtk::Box,
|
||||
spinner: gtk::Spinner,
|
||||
label: gtk::Label,
|
||||
retry: gtk::Button,
|
||||
proceed: gtk::Button,
|
||||
cancel: gtk::Button,
|
||||
detail: gtk::Label,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, header: >k::Box, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);
|
||||
// Align status text with the address text's 6px inset and native 1px border.
|
||||
row.set_margin_start(7);
|
||||
let spinner = gtk::Spinner::new();
|
||||
spinner.set_valign(gtk::Align::Center);
|
||||
let label = gtk::Label::new(None);
|
||||
label.set_xalign(0.0);
|
||||
label.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
let detail = gtk::Label::new(None);
|
||||
detail.set_xalign(0.0);
|
||||
detail.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
detail.style_context().add_class("dim-label");
|
||||
detail.set_no_show_all(true);
|
||||
let copy = gtk::Box::new(gtk::Orientation::Vertical, 2);
|
||||
copy.set_valign(gtk::Align::Center);
|
||||
copy.pack_start(&label, false, false, 0);
|
||||
copy.pack_start(&detail, false, false, 0);
|
||||
copy.show();
|
||||
let retry = super::action_button("Try Again")?;
|
||||
retry.set_valign(gtk::Align::Center);
|
||||
let proceed = super::action_button("Continue Anyway…")?;
|
||||
proceed.set_valign(gtk::Align::Center);
|
||||
proceed.set_no_show_all(true);
|
||||
let cancel = super::action_button("Cancel")?;
|
||||
cancel.set_valign(gtk::Align::Center);
|
||||
// Showing or raising the window must not override recovery-state visibility.
|
||||
row.set_no_show_all(true);
|
||||
spinner.set_no_show_all(true);
|
||||
retry.set_no_show_all(true);
|
||||
label.show();
|
||||
cancel.set_no_show_all(true);
|
||||
let retry_messenger = Arc::clone(&messenger);
|
||||
retry.connect_clicked(move |_| retry_messenger.send_auth_event(AuthEvent::Retry));
|
||||
let proceed_messenger = Arc::clone(&messenger);
|
||||
proceed.connect_clicked(move |_| proceed_messenger.send_auth_event(AuthEvent::RequestTlsException));
|
||||
cancel.connect_clicked(move |_| messenger.send_auth_event(AuthEvent::Close));
|
||||
row.pack_start(&spinner, false, false, 0);
|
||||
row.pack_start(©, true, true, 0);
|
||||
row.pack_start(&retry, false, false, 0);
|
||||
row.pack_start(&proceed, false, false, 0);
|
||||
row.pack_start(&cancel, false, false, 0);
|
||||
header.pack_start(&row, false, false, 0);
|
||||
// The WebView owns the controls for exactly its native lifetime, on the GTK thread.
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
CONTROLS_KEY,
|
||||
RecoveryRow {
|
||||
row,
|
||||
spinner,
|
||||
label,
|
||||
retry,
|
||||
proceed,
|
||||
cancel,
|
||||
detail,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controls = unsafe { webview.data::<RecoveryRow>(CONTROLS_KEY) }.context("Recovery controls are unavailable")?;
|
||||
let controls = unsafe { controls.as_ref() };
|
||||
controls.label.set_text(status.message());
|
||||
controls.detail.set_text(status.detail());
|
||||
controls.detail.set_visible(!status.detail().is_empty());
|
||||
controls.retry.set_visible(status.can_retry());
|
||||
controls.proceed.set_visible(status.can_continue());
|
||||
controls.cancel.set_visible(status.blocks_page());
|
||||
controls.spinner.set_visible(status.is_busy());
|
||||
if status.is_busy() {
|
||||
controls.spinner.start();
|
||||
} else {
|
||||
controls.spinner.stop();
|
||||
}
|
||||
controls.row.set_visible(status != RecoveryStatus::Hidden);
|
||||
webview.set_sensitive(!status.blocks_page());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::{
|
||||
WebContextExt, WebView, WebViewExt,
|
||||
gio::{TlsCertificate, TlsCertificateFlags},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
const TLS_KEY: &str = "gpauth-tls";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
certificate: TlsCertificate,
|
||||
failure: TlsFailure,
|
||||
}
|
||||
|
||||
struct TlsState {
|
||||
pending: RefCell<Option<PendingCertificate>>,
|
||||
confirmation_open: Cell<bool>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, messenger: Arc<AuthMessenger>) {
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
TLS_KEY,
|
||||
Rc::new(TlsState {
|
||||
pending: RefCell::new(None),
|
||||
confirmation_open: Cell::new(false),
|
||||
messenger,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn state(webview: &WebView) -> anyhow::Result<Rc<TlsState>> {
|
||||
let data = unsafe { webview.data::<Rc<TlsState>>(TLS_KEY) }.context("TLS controls are unavailable")?;
|
||||
Ok(unsafe { data.as_ref() }.clone())
|
||||
}
|
||||
|
||||
pub(super) fn record_failure(
|
||||
webview: &WebView,
|
||||
uri: &str,
|
||||
certificate: &TlsCertificate,
|
||||
flags: TlsCertificateFlags,
|
||||
generation: u64,
|
||||
) -> TlsFailure {
|
||||
let reason = if flags.contains(TlsCertificateFlags::EXPIRED) {
|
||||
TlsFailureReason::Expired
|
||||
} else if flags.contains(TlsCertificateFlags::NOT_ACTIVATED) {
|
||||
TlsFailureReason::NotYetValid
|
||||
} else if flags.contains(TlsCertificateFlags::BAD_IDENTITY) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else if flags.contains(TlsCertificateFlags::UNKNOWN_CA) {
|
||||
TlsFailureReason::Untrusted
|
||||
} else {
|
||||
TlsFailureReason::InvalidCertificate
|
||||
};
|
||||
let host = url::Url::parse(uri)
|
||||
.ok()
|
||||
.filter(|uri| uri.scheme() == "https")
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned));
|
||||
let failure = TlsFailure {
|
||||
host: host.clone().unwrap_or_default(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && host.is_some(),
|
||||
};
|
||||
if let Ok(state) = state(webview) {
|
||||
*state.pending.borrow_mut() = host.map(|_| PendingCertificate {
|
||||
generation,
|
||||
certificate: certificate.clone(),
|
||||
failure: failure.clone(),
|
||||
});
|
||||
}
|
||||
failure
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WebView) -> anyhow::Result<()> {
|
||||
let state = state(webview)?;
|
||||
let pending = state
|
||||
.pending
|
||||
.borrow()
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != state.messenger.generation() || state.confirmation_open.get() {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = webview
|
||||
.toplevel()
|
||||
.and_then(|widget| widget.downcast::<gtk::Window>().ok())
|
||||
.context("Auth window is unavailable")?;
|
||||
let dialog = gtk::Dialog::builder()
|
||||
.transient_for(&parent)
|
||||
.modal(true)
|
||||
.destroy_with_parent(true)
|
||||
.title("Certificate Warning")
|
||||
.use_header_bar(0)
|
||||
.resizable(false)
|
||||
.build();
|
||||
let content = dialog.content_area();
|
||||
content.set_spacing(12);
|
||||
content.set_margin_top(18);
|
||||
content.set_margin_bottom(18);
|
||||
content.set_margin_start(18);
|
||||
content.set_margin_end(18);
|
||||
let title = gtk::Label::new(None);
|
||||
title.set_markup(&format!(
|
||||
"<b>{}</b>",
|
||||
gtk::glib::markup_escape_text(&pending.failure.confirmation_title())
|
||||
));
|
||||
let message = gtk::Label::new(Some(&pending.failure.confirmation_message()));
|
||||
for label in [&title, &message] {
|
||||
label.set_xalign(0.0);
|
||||
label.set_line_wrap(true);
|
||||
label.set_line_wrap_mode(gtk::pango::WrapMode::WordChar);
|
||||
label.set_max_width_chars(48);
|
||||
content.pack_start(label, false, false, 0);
|
||||
}
|
||||
let actions = gtk::ButtonBox::new(gtk::Orientation::Horizontal);
|
||||
actions.set_layout(gtk::ButtonBoxStyle::End);
|
||||
actions.set_spacing(8);
|
||||
actions.set_margin_top(6);
|
||||
content.pack_start(&actions, false, false, 0);
|
||||
for (label, response) in [
|
||||
("Cancel", gtk::ResponseType::Cancel),
|
||||
("Continue Anyway", gtk::ResponseType::Accept),
|
||||
] {
|
||||
let button = super::action_button(label)?;
|
||||
button.set_can_default(true);
|
||||
let weak_dialog = dialog.downgrade();
|
||||
button.connect_clicked(move |_| {
|
||||
if let Some(dialog) = weak_dialog.upgrade() {
|
||||
dialog.response(response);
|
||||
}
|
||||
});
|
||||
actions.pack_start(&button, false, false, 0);
|
||||
actions.set_child_non_homogeneous(&button, true);
|
||||
if response == gtk::ResponseType::Cancel {
|
||||
dialog.set_default(Some(&button));
|
||||
}
|
||||
}
|
||||
state.confirmation_open.set(true);
|
||||
let weak = webview.downgrade();
|
||||
dialog.connect_response(move |dialog, response| {
|
||||
state.confirmation_open.set(false);
|
||||
if response == gtk::ResponseType::Accept && pending.generation == state.messenger.generation() {
|
||||
if let Some(webview) = weak.upgrade() {
|
||||
let current = state.pending.borrow().as_ref().is_some_and(|current| {
|
||||
current.generation == pending.generation
|
||||
&& current.certificate == pending.certificate
|
||||
&& current.failure.host == pending.failure.host
|
||||
});
|
||||
if current {
|
||||
if let Some(context) = webview.context() {
|
||||
// This single-window auth process discards its WebContext on exit.
|
||||
context.allow_tls_certificate_for_host(&pending.certificate, &pending.failure.host);
|
||||
state.pending.borrow_mut().take();
|
||||
state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dialog.close();
|
||||
});
|
||||
dialog.show_all();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,58 +1,149 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use block2::{DynBlock, RcBlock};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::{info, warn};
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject, Sel},
|
||||
sel,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLErrorCancelled,
|
||||
NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorUnsupportedURL, NSURLRequest,
|
||||
NSURLSessionAuthChallengeDisposition,
|
||||
};
|
||||
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
|
||||
use objc2_web_kit::{WKNavigation, WKNavigationDelegate, WKWebView};
|
||||
use tauri::webview::PlatformWebview;
|
||||
|
||||
use super::webview_auth::PlatformWebviewExt;
|
||||
use super::{
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::PlatformWebviewExt,
|
||||
};
|
||||
|
||||
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
#[path = "macos/address_bar.rs"]
|
||||
mod address_bar;
|
||||
#[path = "macos/recovery_row.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "macos/tls.rs"]
|
||||
mod tls;
|
||||
|
||||
struct TlsNavigationDelegateIvars {
|
||||
static AUTH_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
|
||||
struct AuthNavigationDelegateIvars {
|
||||
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
ignore_tls_errors: Cell<bool>,
|
||||
navigations: RefCell<HashMap<usize, (Retained<WKNavigation>, u64)>>,
|
||||
tls: RefCell<tls::TlsState>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = TlsNavigationDelegateIvars]
|
||||
struct TlsNavigationDelegate;
|
||||
#[ivars = AuthNavigationDelegateIvars]
|
||||
struct AuthNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
|
||||
unsafe impl NSObjectProtocol for AuthNavigationDelegate {}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
|
||||
unsafe impl WKNavigationDelegate for AuthNavigationDelegate {
|
||||
#[unsafe(method(webView:didStartProvisionalNavigation:))]
|
||||
unsafe fn webView_didStartProvisionalNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
self.track_navigation(navigation);
|
||||
self.ivars().messenger.cancel_raise_window();
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didStartProvisionalNavigation:)) {
|
||||
unsafe { original.webView_didStartProvisionalNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didCommitNavigation:))]
|
||||
unsafe fn webView_didCommitNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.navigation_generation(navigation) {
|
||||
info!("Started loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didCommitNavigation:)) {
|
||||
unsafe { original.webView_didCommitNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFinishNavigation:))]
|
||||
unsafe fn webView_didFinishNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.finish_navigation(navigation) {
|
||||
info!("Finished loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFinishNavigation:)) {
|
||||
unsafe { original.webView_didFinishNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailProvisionalNavigation:withError:))]
|
||||
unsafe fn webView_didFailProvisionalNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailProvisionalNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailProvisionalNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailNavigation:withError:))]
|
||||
unsafe fn webView_didFailNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
|
||||
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
|
||||
&self,
|
||||
_webview: &WKWebView,
|
||||
webview: &WKWebView,
|
||||
challenge: &NSURLAuthenticationChallenge,
|
||||
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
|
||||
) {
|
||||
// Preserve Wry's normal authentication challenge handling unless the caller
|
||||
// approved this certificate or requested the ignore-TLS-errors behavior.
|
||||
let protection_space = challenge.protectionSpace();
|
||||
let is_server_trust = protection_space
|
||||
.authenticationMethod()
|
||||
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
|
||||
let is_server_trust = protection_space.authenticationMethod().isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
let server_trust: *mut AnyObject = if is_server_trust {
|
||||
msg_send![&*protection_space, serverTrust]
|
||||
} else { ptr::null_mut() };
|
||||
let approved = std::ptr::NonNull::new(server_trust.cast::<objc2_security::SecTrust>()).is_some_and(|trust| {
|
||||
self.ivars().tls.borrow().allows(&protection_space.host().to_string(), unsafe { trust.as_ref() })
|
||||
});
|
||||
if !self.ivars().ignore_tls_errors.get() && !approved {
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didReceiveAuthenticationChallenge:completionHandler:)) {
|
||||
unsafe { original.webView_didReceiveAuthenticationChallenge_completionHandler(webview, challenge, completion_handler); }
|
||||
} else {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !is_server_trust {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust];
|
||||
if server_trust.is_null() {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
@@ -64,7 +155,7 @@ define_class!(
|
||||
}
|
||||
}
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
impl AuthNavigationDelegate {
|
||||
#[unsafe(method(respondsToSelector:))]
|
||||
fn responds_to_selector(&self, selector: Sel) -> bool {
|
||||
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
|
||||
@@ -82,10 +173,92 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
fn new(original: Retained<ProtocolObject<dyn WKNavigationDelegate>>, mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
impl AuthNavigationDelegate {
|
||||
fn track_navigation(&self, navigation: Option<&WKNavigation>) {
|
||||
if let Some(navigation) = navigation {
|
||||
let key = navigation as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.entry(key)
|
||||
.or_insert_with(|| (navigation.retain(), self.ivars().messenger.generation()));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_generation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow()
|
||||
.get(&key)
|
||||
.map(|(_, generation)| *generation)
|
||||
}
|
||||
|
||||
fn finish_navigation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.remove(&key)
|
||||
.map(|(_, generation)| generation)
|
||||
}
|
||||
|
||||
fn report_load_failure(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
let Some(generation) = self.finish_navigation(navigation) else {
|
||||
return;
|
||||
};
|
||||
if generation != self.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let is_url_error = error.domain().isEqualToString(unsafe { NSURLErrorDomain });
|
||||
if is_url_error && error.code() == NSURLErrorCancelled {
|
||||
return;
|
||||
}
|
||||
if is_url_error && error.code() == NSURLErrorUnsupportedURL {
|
||||
let callback = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })
|
||||
.and_then(|value| value.downcast::<NSURL>().ok())
|
||||
.and_then(|url| url.scheme());
|
||||
if callback.is_some_and(|scheme| scheme.to_string() == "globalprotectcallback") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let messenger = &self.ivars().messenger;
|
||||
if let Some(failure) = self.ivars().tls.borrow_mut().record_failure(webview, error, generation) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, failure));
|
||||
return;
|
||||
}
|
||||
// Log codes rather than NSError descriptions, which may contain callback URLs.
|
||||
messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::LoadFailed(anyhow::anyhow!(
|
||||
"Navigation failed: {} ({})",
|
||||
error.domain(),
|
||||
error.code()
|
||||
)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_delegate(webview: &WKWebView) -> Option<Retained<AuthNavigationDelegate>> {
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AuthNavigationDelegate>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
fn track_requested_navigation(webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
let delegate = navigation_delegate(webview);
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.track_navigation(navigation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,15 +270,22 @@ fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisp
|
||||
}
|
||||
}
|
||||
|
||||
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
fn install_navigation_delegate(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?;
|
||||
let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?;
|
||||
let delegate = TlsNavigationDelegate::new(original, mtm);
|
||||
let delegate = AuthNavigationDelegate::alloc(mtm).set_ivars(AuthNavigationDelegateIvars {
|
||||
original,
|
||||
messenger,
|
||||
ignore_tls_errors: Cell::new(false),
|
||||
tls: RefCell::new(tls::TlsState::default()),
|
||||
navigations: RefCell::new(HashMap::new()),
|
||||
});
|
||||
let delegate: Retained<AuthNavigationDelegate> = unsafe { msg_send![super(delegate), init] };
|
||||
|
||||
unsafe {
|
||||
objc_setAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
@@ -139,9 +319,47 @@ mod tests {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
address_bar::install(webview)?;
|
||||
install_navigation_delegate(webview, Arc::clone(&messenger))?;
|
||||
recovery_row::install(webview, messenger)?;
|
||||
let window_handle = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }
|
||||
) {
|
||||
let _ = window_handle.with_webview(|webview| {
|
||||
let webview: &WKWebView = unsafe { &*webview.inner().cast() };
|
||||
address_bar::resize(webview);
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
recovery_row::update(webview, status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
unsafe {
|
||||
webview.stopLoading();
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(unsafe { &*self.inner().cast::<WKWebView>() })
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
install_tls_navigation_delegate(webview)
|
||||
let delegate = navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
delegate.ivars().ignore_tls_errors.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
@@ -173,7 +391,8 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
|
||||
let request = NSURLRequest::requestWithURL(&url);
|
||||
|
||||
wv.loadRequest(&request);
|
||||
let navigation = wv.loadRequest(&request);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -182,31 +401,31 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
let navigation = wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
fn navigation_address(webview: &WKWebView) -> String {
|
||||
let url = unsafe { webview.URL() }.and_then(|url| url.absoluteString());
|
||||
redact_uri(&url.map(|url| url.to_string()).unwrap_or_default())
|
||||
}
|
||||
|
||||
let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| {
|
||||
if let Some(err) = err.as_ref() {
|
||||
let code = err.code();
|
||||
let message = err.localizedDescription();
|
||||
callback(Err(anyhow::anyhow!("Error {}: {}", code, message)));
|
||||
} else {
|
||||
let body: &NSString = &*body.cast();
|
||||
callback(Ok(body.to_string()));
|
||||
}
|
||||
});
|
||||
|
||||
wv.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&js_callback),
|
||||
);
|
||||
fn read_navigation_html(webview: &WKWebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
let callback = RcBlock::new(move |body: *mut AnyObject, error: *mut NSError| {
|
||||
if let Some(error) = unsafe { error.as_ref() } {
|
||||
warn!("Failed to get html: {} ({})", error.domain(), error.code());
|
||||
} else if let Some(body) = unsafe { body.as_ref() }.and_then(|body| body.downcast_ref::<NSString>()) {
|
||||
messenger.read_from_html(&body.to_string(), generation);
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
webview.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&callback),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use anyhow::Context;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAccessibility, NSAutoresizingMaskOptions, NSBox, NSBoxType, NSColor, NSFont, NSLayoutConstraint,
|
||||
NSLayoutConstraintOrientation, NSLineBreakMode, NSTextView, NSToolbar, NSToolbarDelegate, NSToolbarDisplayMode,
|
||||
NSToolbarItem, NSToolbarItemIdentifier, NSWindowTitleVisibility, NSWindowToolbarStyle,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSArray, NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions, NSObject,
|
||||
NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString,
|
||||
};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::address_bar::{LOADING_ADDRESS, display_address};
|
||||
|
||||
static ADDRESS_TOOLBAR_KEY: u8 = 0;
|
||||
const ADDRESS_ITEM_ID: &str = "com.yuezk.gpauth.address";
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSTextView)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
struct AddressView;
|
||||
|
||||
impl AddressView {
|
||||
#[unsafe(method(intrinsicContentSize))]
|
||||
fn intrinsic_content_size(&self) -> NSSize {
|
||||
// URL length must not determine the toolbar item's width.
|
||||
NSSize::new(-1.0, 22.0)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
struct AddressToolbarIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
address_view: Retained<NSTextView>,
|
||||
separator: Retained<NSBox>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// The content view retains the delegate because NSToolbar's delegate is weak.
|
||||
// Drop unregisters URL observation before releasing the retained webview.
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = AddressToolbarIvars]
|
||||
struct AddressToolbar;
|
||||
|
||||
unsafe impl NSObjectProtocol for AddressToolbar {}
|
||||
|
||||
unsafe impl NSToolbarDelegate for AddressToolbar {
|
||||
#[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
|
||||
fn toolbar_item(
|
||||
&self,
|
||||
_toolbar: &NSToolbar,
|
||||
identifier: &NSToolbarItemIdentifier,
|
||||
inserting: bool,
|
||||
) -> Option<Retained<NSToolbarItem>> {
|
||||
if !inserting || !identifier.isEqualToString(&NSString::from_str(ADDRESS_ITEM_ID)) {
|
||||
None
|
||||
} else {
|
||||
let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(self.mtm()), identifier);
|
||||
item.setLabel(&NSString::from_str("Sign-in page address"));
|
||||
item.setBordered(true);
|
||||
item.setView(Some(&self.ivars().address_view));
|
||||
Some(item)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
|
||||
fn default_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
|
||||
fn allowed_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressToolbar {
|
||||
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
|
||||
fn observe_url(
|
||||
&self,
|
||||
_key_path: Option<&NSString>,
|
||||
_object: Option<&AnyObject>,
|
||||
_change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
|
||||
_context: *mut c_void,
|
||||
) {
|
||||
let uri = unsafe { self.ivars().webview.URL() }.and_then(|url| url.absoluteString());
|
||||
let address = display_address(uri.as_ref().map(|uri| uri.to_string()).as_deref());
|
||||
self.ivars().address_view.setString(&NSString::from_str(&address));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for AddressToolbar {
|
||||
fn drop(&mut self) {
|
||||
// This private observer registers only URL and remains on the main thread.
|
||||
unsafe {
|
||||
self
|
||||
.ivars()
|
||||
.webview
|
||||
.removeObserver_forKeyPath(self, &NSString::from_str("URL"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Toolbar must be installed on the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let window = webview.window().context("Webview has no window")?;
|
||||
parent.setWantsLayer(true);
|
||||
let address_view: Retained<AddressView> =
|
||||
unsafe { msg_send![AddressView::alloc(mtm), initWithFrame: NSRect::default()] };
|
||||
// Use one native text layout for display and selection.
|
||||
address_view.setString(&NSString::from_str(LOADING_ADDRESS));
|
||||
address_view.setDrawsBackground(false);
|
||||
// Keep NSTextView's visible-rect cursor tracking inside the address bar.
|
||||
address_view.setClipsToBounds(true);
|
||||
address_view.setRichText(false);
|
||||
address_view.setHorizontallyResizable(false);
|
||||
address_view.setVerticallyResizable(false);
|
||||
address_view.setTextContainerInset(NSSize::new(6.0, 3.0));
|
||||
address_view.setEditable(false);
|
||||
address_view.setSelectable(true);
|
||||
address_view.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
address_view.setContentHuggingPriority_forOrientation(1.0, NSLayoutConstraintOrientation::Horizontal);
|
||||
address_view.setAccessibilityLabel(Some(&NSString::from_str("Sign-in page address")));
|
||||
if let Some(container) = unsafe { address_view.textContainer() } {
|
||||
container.setWidthTracksTextView(true);
|
||||
container.setLineFragmentPadding(0.0);
|
||||
container.setMaximumNumberOfLines(1);
|
||||
container.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
}
|
||||
// AppKit measures the toolbar item's minimum and maximum width from its view.
|
||||
NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
|
||||
address_view.widthAnchor().constraintGreaterThanOrEqualToConstant(200.0),
|
||||
address_view.widthAnchor().constraintLessThanOrEqualToConstant(10000.0),
|
||||
address_view.heightAnchor().constraintEqualToConstant(22.0),
|
||||
]));
|
||||
let separator = NSBox::new(mtm);
|
||||
separator
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
separator.setBoxType(NSBoxType::Custom);
|
||||
separator.setBorderWidth(0.0);
|
||||
separator.setCornerRadius(0.0);
|
||||
separator.setFillColor(&NSColor::separatorColor());
|
||||
parent.addSubview(&separator);
|
||||
let delegate = AddressToolbar::alloc(mtm).set_ivars(AddressToolbarIvars {
|
||||
webview: webview.retain(),
|
||||
address_view: Retained::into_super(address_view),
|
||||
separator,
|
||||
});
|
||||
let delegate: Retained<AddressToolbar> = unsafe { msg_send![super(delegate), init] };
|
||||
// Observe the current URL independently of navigation callbacks.
|
||||
unsafe {
|
||||
webview.addObserver_forKeyPath_options_context(
|
||||
&delegate,
|
||||
&NSString::from_str("URL"),
|
||||
NSKeyValueObservingOptions::Initial,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
let toolbar = NSToolbar::initWithIdentifier(NSToolbar::alloc(mtm), &NSString::from_str("com.yuezk.gpauth.toolbar"));
|
||||
toolbar.setAllowsUserCustomization(false);
|
||||
toolbar.setDisplayMode(NSToolbarDisplayMode::IconOnly);
|
||||
toolbar.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
window.setTitleVisibility(NSWindowTitleVisibility::Visible);
|
||||
if objc2::available!(macos = 11.0) {
|
||||
window.setToolbarStyle(NSWindowToolbarStyle::Expanded);
|
||||
}
|
||||
window.setToolbar(Some(&toolbar));
|
||||
window.setInitialFirstResponder(Some(webview));
|
||||
resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn address_view(webview: &WKWebView) -> Option<Retained<NSTextView>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
}?;
|
||||
Some(delegate.ivars().address_view.clone())
|
||||
}
|
||||
|
||||
pub(super) fn show_address(webview: &WKWebView, uri: &str) {
|
||||
if let Some(view) = address_view(webview) {
|
||||
view.setString(&NSString::from_str(&display_address(Some(uri))));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resize(webview: &WKWebView) {
|
||||
let Some(parent) = (unsafe { webview.superview() }) else {
|
||||
return;
|
||||
};
|
||||
let Some(window) = webview.window() else {
|
||||
return;
|
||||
};
|
||||
// Keep the native separator outside WebKit so page backgrounds cannot cover it.
|
||||
let content = parent.convertRect_fromView(window.contentLayoutRect(), None);
|
||||
let separator_height = 1.0 / window.backingScaleFactor();
|
||||
let recovery_height = super::recovery_row::layout(webview, content);
|
||||
let page_height = (content.size.height - recovery_height - separator_height).max(0.0);
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
};
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.ivars().separator.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + page_height),
|
||||
NSSize::new(content.size.width, separator_height),
|
||||
));
|
||||
}
|
||||
webview.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(content.size.width, page_height),
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::{Retained, Weak},
|
||||
runtime::AnyObject,
|
||||
sel,
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAutoresizingMaskOptions, NSBezelStyle, NSBox, NSBoxType, NSButton, NSColor, NSControlSize, NSEvent, NSEventMask,
|
||||
NSEventModifierFlags, NSFont, NSLineBreakMode, NSProgressIndicator, NSProgressIndicatorStyle, NSTextField,
|
||||
NSTitlePosition, NSView,
|
||||
};
|
||||
use objc2_foundation::{MainThreadMarker, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
static RECOVERY_ROW_KEY: u8 = 0;
|
||||
|
||||
struct RecoveryRowIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
row: Retained<NSBox>,
|
||||
blocker: Retained<NSView>,
|
||||
label: Retained<NSTextField>,
|
||||
detail: Retained<NSTextField>,
|
||||
proceed: Retained<NSButton>,
|
||||
status: Cell<RecoveryStatus>,
|
||||
spinner: Retained<NSProgressIndicator>,
|
||||
retry: Retained<NSButton>,
|
||||
cancel: Retained<NSButton>,
|
||||
keyboard_monitor: RefCell<Option<Retained<AnyObject>>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = RecoveryRowIvars]
|
||||
struct RecoveryRow;
|
||||
|
||||
unsafe impl NSObjectProtocol for RecoveryRow {}
|
||||
|
||||
impl RecoveryRow {
|
||||
#[unsafe(method(retry:))]
|
||||
fn retry(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Retry);
|
||||
}
|
||||
|
||||
#[unsafe(method(continueTls:))]
|
||||
fn continue_tls(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::RequestTlsException);
|
||||
}
|
||||
|
||||
#[unsafe(method(cancel:))]
|
||||
fn cancel(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Close);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for RecoveryRow {
|
||||
fn drop(&mut self) {
|
||||
if let Some(monitor) = self.ivars().keyboard_monitor.borrow_mut().take() {
|
||||
unsafe {
|
||||
NSEvent::removeMonitor(&monitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecoveryRow {
|
||||
fn handle_key(&self, event: &NSEvent) -> bool {
|
||||
let controls = self.ivars();
|
||||
if !controls.status.get().blocks_page() {
|
||||
return false;
|
||||
}
|
||||
let Some(window) = controls.webview.window() else {
|
||||
return false;
|
||||
};
|
||||
if window.attachedSheet().is_some() || event.window(self.mtm()).as_deref() != Some(&*window) {
|
||||
return false;
|
||||
}
|
||||
let responder = window.firstResponder();
|
||||
let modifiers = event.modifierFlags();
|
||||
if event.keyCode() == 48 && !modifiers.intersects(NSEventModifierFlags::Command | NSEventModifierFlags::Control) {
|
||||
// Explicit traversal also works when the system skips buttons in its default key loop.
|
||||
let Some(address) = super::address_bar::address_view(&controls.webview) else {
|
||||
return false;
|
||||
};
|
||||
let mut views: Vec<&NSView> = vec![&address];
|
||||
if !controls.retry.isHidden() {
|
||||
views.push(&controls.retry);
|
||||
}
|
||||
if !controls.proceed.isHidden() {
|
||||
views.push(&controls.proceed);
|
||||
}
|
||||
views.push(&controls.cancel);
|
||||
let current = responder.as_ref().and_then(|responder| {
|
||||
views.iter().position(|view| {
|
||||
ptr::eq(
|
||||
(*view) as *const NSView as *const c_void,
|
||||
Retained::as_ptr(responder).cast(),
|
||||
)
|
||||
})
|
||||
});
|
||||
let next = match current {
|
||||
Some(index) if modifiers.contains(NSEventModifierFlags::Shift) => (index + views.len() - 1) % views.len(),
|
||||
Some(index) => (index + 1) % views.len(),
|
||||
None => views.len() - 1,
|
||||
};
|
||||
window.makeFirstResponder(Some(views[next]));
|
||||
return true;
|
||||
}
|
||||
// If WebKit regains focus programmatically, do not deliver keys to the covered page.
|
||||
if responder
|
||||
.as_deref()
|
||||
.and_then(|responder| responder.downcast_ref::<NSView>())
|
||||
.is_some_and(|view| view.isDescendantOf(&controls.webview))
|
||||
{
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Recovery controls require the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let row = NSBox::new(mtm);
|
||||
// AppKit may resize the parent after the application's window resize callback.
|
||||
row.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
row.setBoxType(NSBoxType::Custom);
|
||||
row.setTitlePosition(NSTitlePosition::NoTitle);
|
||||
row.setContentViewMargins(NSSize::new(0.0, 0.0));
|
||||
row.setBorderWidth(0.0);
|
||||
row.setCornerRadius(0.0);
|
||||
row.setFillColor(&NSColor::windowBackgroundColor());
|
||||
let label = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
label.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
label.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let detail = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
detail.setFont(Some(&NSFont::systemFontOfSize(11.0)));
|
||||
detail.setTextColor(Some(&NSColor::secondaryLabelColor()));
|
||||
detail.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
detail.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let spinner = NSProgressIndicator::new(mtm);
|
||||
spinner.setStyle(NSProgressIndicatorStyle::Spinning);
|
||||
spinner.setControlSize(NSControlSize::Small);
|
||||
spinner.setIndeterminate(true);
|
||||
let retry = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Try Again"), None, None, mtm) };
|
||||
let cancel = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Cancel"), None, None, mtm) };
|
||||
let proceed =
|
||||
unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Continue Anyway…"), None, None, mtm) };
|
||||
for button in [&retry, &proceed, &cancel] {
|
||||
button.setAutoresizingMask(NSAutoresizingMaskOptions::ViewMinXMargin);
|
||||
button.setBezelStyle(NSBezelStyle::Push);
|
||||
button.setControlSize(NSControlSize::Small);
|
||||
button.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
row.addSubview(button);
|
||||
}
|
||||
row.addSubview(&label);
|
||||
row.addSubview(&detail);
|
||||
row.addSubview(&spinner);
|
||||
let blocker = NSView::new(mtm);
|
||||
blocker
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable);
|
||||
parent.addSubview(&blocker);
|
||||
parent.addSubview(&row);
|
||||
row.setHidden(true);
|
||||
blocker.setHidden(true);
|
||||
let controller = RecoveryRow::alloc(mtm).set_ivars(RecoveryRowIvars {
|
||||
webview: webview.retain(),
|
||||
messenger,
|
||||
row,
|
||||
blocker,
|
||||
label,
|
||||
detail,
|
||||
proceed,
|
||||
status: Cell::new(RecoveryStatus::Hidden),
|
||||
spinner,
|
||||
retry,
|
||||
cancel,
|
||||
keyboard_monitor: RefCell::new(None),
|
||||
});
|
||||
let controller: Retained<RecoveryRow> = unsafe { msg_send![super(controller), init] };
|
||||
let weak_controller = Weak::from_retained(&controller);
|
||||
let handler = RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
|
||||
let blocked = weak_controller
|
||||
.load()
|
||||
.is_some_and(|controller| controller.handle_key(unsafe { event.as_ref() }));
|
||||
if blocked { ptr::null_mut() } else { event.as_ptr() }
|
||||
});
|
||||
let monitor = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(NSEventMask::KeyDown, &handler) }
|
||||
.context("Failed to guard keyboard input during sign-in recovery")?;
|
||||
*controller.ivars().keyboard_monitor.borrow_mut() = Some(monitor);
|
||||
unsafe {
|
||||
controller.ivars().retry.setTarget(Some(&controller));
|
||||
controller.ivars().retry.setAction(Some(sel!(retry:)));
|
||||
controller.ivars().proceed.setTarget(Some(&controller));
|
||||
controller.ivars().proceed.setAction(Some(sel!(continueTls:)));
|
||||
controller.ivars().cancel.setTarget(Some(&controller));
|
||||
controller.ivars().cancel.setAction(Some(sel!(cancel:)));
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&controller).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn controller(webview: &WKWebView) -> Option<Retained<RecoveryRow>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<RecoveryRow>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WKWebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controller = controller(webview).context("Recovery controls are unavailable")?;
|
||||
let controls = controller.ivars();
|
||||
let was_blocking = controls.status.replace(status).blocks_page();
|
||||
let hidden = status == RecoveryStatus::Hidden;
|
||||
controls.label.setStringValue(&NSString::from_str(status.message()));
|
||||
controls.detail.setStringValue(&NSString::from_str(status.detail()));
|
||||
controls.detail.setHidden(status.detail().is_empty());
|
||||
controls.retry.setHidden(!status.can_retry());
|
||||
controls.proceed.setHidden(!status.can_continue());
|
||||
controls.cancel.setHidden(!status.blocks_page());
|
||||
controls.spinner.setHidden(!status.is_busy());
|
||||
unsafe {
|
||||
if status.is_busy() {
|
||||
controls.spinner.startAnimation(None);
|
||||
} else {
|
||||
controls.spinner.stopAnimation(None);
|
||||
}
|
||||
}
|
||||
controls.row.setHidden(hidden);
|
||||
controls.blocker.setHidden(!status.blocks_page());
|
||||
if was_blocking != status.blocks_page() {
|
||||
if let Some(window) = webview.window() {
|
||||
if !status.blocks_page() {
|
||||
window.makeFirstResponder(Some(webview));
|
||||
} else {
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
}
|
||||
}
|
||||
}
|
||||
super::address_bar::resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position the row above the page and return the height reserved for it.
|
||||
pub(super) fn layout(webview: &WKWebView, content: NSRect) -> f64 {
|
||||
let Some(controller) = controller(webview) else {
|
||||
return 0.0;
|
||||
};
|
||||
let controls = controller.ivars();
|
||||
if controls.row.isHidden() {
|
||||
return 0.0;
|
||||
}
|
||||
let height = if controls.status.get().detail().is_empty() {
|
||||
36.0
|
||||
} else {
|
||||
52.0
|
||||
};
|
||||
let width = content.size.width;
|
||||
controls.row.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + content.size.height - height),
|
||||
NSSize::new(width, height),
|
||||
));
|
||||
controls.blocker.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(width, (content.size.height - height).max(0.0)),
|
||||
));
|
||||
controls.cancel.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 80.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(72.0, 26.0),
|
||||
));
|
||||
controls.retry.setFrame(NSRect::new(
|
||||
NSPoint::new(
|
||||
width - 162.0 - if controls.proceed.isHidden() { 0.0 } else { 132.0 },
|
||||
(height - 26.0) / 2.0,
|
||||
),
|
||||
NSSize::new(78.0, 26.0),
|
||||
));
|
||||
controls.proceed.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 212.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(128.0, 26.0),
|
||||
));
|
||||
controls
|
||||
.spinner
|
||||
.setFrame(NSRect::new(NSPoint::new(12.0, 10.0), NSSize::new(16.0, 16.0)));
|
||||
let left = if controls.spinner.isHidden() { 12.0 } else { 36.0 };
|
||||
let right = if !controls.proceed.isHidden() {
|
||||
width - 220.0
|
||||
} else if !controls.retry.isHidden() {
|
||||
width - 170.0
|
||||
} else {
|
||||
width - 88.0
|
||||
};
|
||||
controls.label.setFrame(NSRect::new(
|
||||
NSPoint::new(left, height - 26.0),
|
||||
NSSize::new((right - left).max(0.0), 17.0),
|
||||
));
|
||||
controls.detail.setFrame(NSRect::new(
|
||||
NSPoint::new(left, 7.0),
|
||||
NSSize::new((right - left).max(0.0), 15.0),
|
||||
));
|
||||
height
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{DefinedClass, MainThreadOnly, rc::Weak};
|
||||
use objc2_app_kit::{NSAlert, NSAlertSecondButtonReturn, NSAlertStyle};
|
||||
use objc2_foundation::{
|
||||
NSError, NSString, NSURL, NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorFailingURLPeerTrustErrorKey,
|
||||
NSUnderlyingErrorKey,
|
||||
};
|
||||
use objc2_security::{SecTrust, errSecHostNameMismatch};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthError, AuthEvent},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CertificateException {
|
||||
host: String,
|
||||
certificate: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
failure: TlsFailure,
|
||||
exception: CertificateException,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct TlsState {
|
||||
pending: Option<PendingCertificate>,
|
||||
exceptions: Vec<CertificateException>,
|
||||
}
|
||||
|
||||
impl TlsState {
|
||||
fn approve(&mut self, pending: &PendingCertificate, generation: u64) -> bool {
|
||||
if pending.generation != generation
|
||||
|| self.pending.as_ref().is_none_or(|current| {
|
||||
current.generation != pending.generation
|
||||
|| current.exception.certificate != pending.exception.certificate
|
||||
|| current.exception.host != pending.exception.host
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.exceptions.push(pending.exception.clone());
|
||||
self.pending = None;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn record_failure(&mut self, webview: &WKWebView, error: &NSError, generation: u64) -> Option<AuthError> {
|
||||
if !error.domain().isEqualToString(unsafe { NSURLErrorDomain }) {
|
||||
return None;
|
||||
}
|
||||
let reason = match error.code() {
|
||||
-1200 => TlsFailureReason::Handshake,
|
||||
-1201 => TlsFailureReason::Expired,
|
||||
-1202 => TlsFailureReason::InvalidCertificate,
|
||||
-1203 => TlsFailureReason::Untrusted,
|
||||
-1204 => TlsFailureReason::NotYetValid,
|
||||
_ => return None,
|
||||
};
|
||||
let reason = if has_hostname_mismatch(error, 0) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else {
|
||||
reason
|
||||
};
|
||||
let url = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })?
|
||||
.downcast::<NSURL>()
|
||||
.ok()?;
|
||||
let host = url.host()?.to_string().to_ascii_lowercase();
|
||||
if let Some(uri) = url.absoluteString() {
|
||||
super::address_bar::show_address(webview, &uri.to_string());
|
||||
}
|
||||
let trust = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLPeerTrustErrorKey });
|
||||
let certificate = trust.and_then(|trust| {
|
||||
// Foundation documents this entry as a SecTrustRef.
|
||||
let trust = unsafe { &*(objc2::rc::Retained::as_ptr(&trust).cast::<SecTrust>()) };
|
||||
certificate_data(trust)
|
||||
});
|
||||
let failure = TlsFailure {
|
||||
host: host.clone(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && certificate.is_some(),
|
||||
};
|
||||
self.pending = certificate
|
||||
.filter(|_| failure.can_continue)
|
||||
.map(|certificate| PendingCertificate {
|
||||
generation,
|
||||
failure: failure.clone(),
|
||||
exception: CertificateException { host, certificate },
|
||||
});
|
||||
Some(AuthError::Tls(failure))
|
||||
}
|
||||
|
||||
pub fn allows(&self, host: &str, trust: &SecTrust) -> bool {
|
||||
if self.exceptions.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(certificate) = certificate_data(trust) else {
|
||||
return false;
|
||||
};
|
||||
self
|
||||
.exceptions
|
||||
.iter()
|
||||
.any(|exception| exception.host.eq_ignore_ascii_case(host) && exception.certificate == certificate)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_hostname_mismatch(error: &NSError, depth: usize) -> bool {
|
||||
if depth > 4 {
|
||||
return false;
|
||||
}
|
||||
if error.code() == errSecHostNameMismatch as isize {
|
||||
return true;
|
||||
}
|
||||
error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSUnderlyingErrorKey })
|
||||
.and_then(|value| value.downcast::<NSError>().ok())
|
||||
.is_some_and(|error| has_hostname_mismatch(&error, depth + 1))
|
||||
}
|
||||
|
||||
fn certificate_data(trust: &SecTrust) -> Option<Vec<u8>> {
|
||||
// Retain the leaf immediately. No trust evaluation or mutation runs here.
|
||||
#[allow(deprecated)]
|
||||
let certificate = unsafe { trust.certificate_at_index(0) }?;
|
||||
Some(unsafe { certificate.data() }.to_vec())
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let delegate = super::navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
let pending = delegate
|
||||
.ivars()
|
||||
.tls
|
||||
.borrow()
|
||||
.pending
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != delegate.ivars().messenger.generation() {
|
||||
return Ok(());
|
||||
}
|
||||
let window = webview.window().context("Auth window is unavailable")?;
|
||||
if window.attachedSheet().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let alert = NSAlert::new(delegate.mtm());
|
||||
alert.setAlertStyle(NSAlertStyle::Warning);
|
||||
alert.setMessageText(&NSString::from_str(&pending.failure.confirmation_title()));
|
||||
alert.setInformativeText(&NSString::from_str(&pending.failure.confirmation_message()));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Cancel"));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Continue Anyway"));
|
||||
let weak = Weak::from_retained(&delegate);
|
||||
let handler = RcBlock::new(move |response: isize| {
|
||||
let Some(delegate) = weak.load() else {
|
||||
return;
|
||||
};
|
||||
if response != NSAlertSecondButtonReturn || pending.generation != delegate.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let mut state = delegate.ivars().tls.borrow_mut();
|
||||
if !state.approve(&pending, delegate.ivars().messenger.generation()) {
|
||||
return;
|
||||
}
|
||||
drop(state);
|
||||
delegate
|
||||
.ivars()
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
});
|
||||
alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pending() -> PendingCertificate {
|
||||
PendingCertificate {
|
||||
generation: 1,
|
||||
failure: TlsFailure {
|
||||
host: "login.example".into(),
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
exception: CertificateException {
|
||||
host: "login.example".into(),
|
||||
certificate: vec![1, 2, 3],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_rejects_stale_attempts_and_replacement_certificates() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
assert!(!state.approve(&original, 2));
|
||||
let mut replacement = original.clone();
|
||||
replacement.exception.certificate = vec![4, 5, 6];
|
||||
state.pending = Some(replacement);
|
||||
assert!(!state.approve(&original, 1));
|
||||
assert!(state.exceptions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_is_specific_to_the_host_and_consumed_once() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
let mut other_host = original.clone();
|
||||
other_host.exception.host = "other.example".into();
|
||||
assert!(!state.approve(&other_host, 1));
|
||||
assert!(state.approve(&original, 1));
|
||||
assert_eq!(state.exceptions.len(), 1);
|
||||
assert!(!state.approve(&original, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
use super::tls::TlsFailureReason;
|
||||
|
||||
/// Native UI state for recovering an embedded sign-in session.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) enum RecoveryStatus {
|
||||
#[default]
|
||||
Hidden,
|
||||
Restarting,
|
||||
Loading,
|
||||
Failed,
|
||||
Rejected,
|
||||
Tls {
|
||||
reason: TlsFailureReason,
|
||||
can_continue: bool,
|
||||
},
|
||||
CertificateBypassed,
|
||||
}
|
||||
|
||||
impl RecoveryStatus {
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Hidden => "",
|
||||
Self::Restarting => "Restarting sign-in…",
|
||||
Self::Loading => "Loading sign-in…",
|
||||
Self::Failed => "Couldn’t restart sign-in.",
|
||||
Self::Rejected => "Sign-in wasn’t completed.",
|
||||
Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
} => "Secure connection failed.",
|
||||
Self::Tls { .. } => "Cannot verify this server’s identity.",
|
||||
Self::CertificateBypassed => "Certificate verification bypassed in this window.",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Self::Tls { reason, .. } => reason.message(),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_continue(self) -> bool {
|
||||
match self {
|
||||
Self::Tls { reason, can_continue } => can_continue && reason.is_certificate_error(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn blocks_page(self) -> bool {
|
||||
!matches!(self, Self::Hidden | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn accepts_auth_data(self) -> bool {
|
||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn is_busy(self) -> bool {
|
||||
matches!(self, Self::Restarting | Self::Loading)
|
||||
}
|
||||
|
||||
pub fn can_retry(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Failed
|
||||
| Self::Rejected
|
||||
| Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recovery {
|
||||
status: RecoveryStatus,
|
||||
automatic_retry_used: bool,
|
||||
certificate_bypassed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetrySource {
|
||||
FreshPrelogin,
|
||||
SuppliedRequest,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetryTiming {
|
||||
Immediate,
|
||||
AutomaticDelay,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct RetryPlan {
|
||||
pub source: RetrySource,
|
||||
pub timing: RetryTiming,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
pub fn status(&self) -> RecoveryStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn loading(&mut self) {
|
||||
self.status = RecoveryStatus::Loading;
|
||||
}
|
||||
|
||||
pub fn load_failed(&mut self) {
|
||||
self.status = RecoveryStatus::Failed;
|
||||
}
|
||||
|
||||
pub fn tls_failed(&mut self, reason: TlsFailureReason, can_continue: bool) {
|
||||
self.status = RecoveryStatus::Tls { reason, can_continue };
|
||||
}
|
||||
|
||||
pub fn certificate_accepted(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_continue() {
|
||||
return None;
|
||||
}
|
||||
self.certificate_bypassed = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
/// Temporary service failures get one automatic restart per dialog.
|
||||
/// Duplicate failures while restarting or awaiting user action are ignored.
|
||||
pub fn failure(&mut self, temporary: bool) -> Option<RetryPlan> {
|
||||
if !matches!(
|
||||
self.status,
|
||||
RecoveryStatus::Hidden | RecoveryStatus::Loading | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if temporary && !self.automatic_retry_used {
|
||||
self.automatic_retry_used = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
return Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
});
|
||||
}
|
||||
self.status = if temporary {
|
||||
RecoveryStatus::Failed
|
||||
} else {
|
||||
RecoveryStatus::Rejected
|
||||
};
|
||||
None
|
||||
}
|
||||
|
||||
pub fn retry(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_retry() {
|
||||
return None;
|
||||
}
|
||||
let source = if matches!(self.status, RecoveryStatus::Tls { .. }) {
|
||||
RetrySource::SuppliedRequest
|
||||
} else {
|
||||
RetrySource::FreshPrelogin
|
||||
};
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn page_loaded(&mut self) {
|
||||
if self.status == RecoveryStatus::Loading {
|
||||
self.status = if self.certificate_bypassed {
|
||||
RecoveryStatus::CertificateBypassed
|
||||
} else {
|
||||
RecoveryStatus::Hidden
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retry_plans_preserve_request_source_and_timing() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert_eq!(
|
||||
recovery.failure(true),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
})
|
||||
);
|
||||
recovery.load_failed();
|
||||
assert_eq!(
|
||||
recovery.retry(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
recovery.tls_failed(TlsFailureReason::Expired, true);
|
||||
assert_eq!(
|
||||
recovery.certificate_accepted(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
assert!(recovery.certificate_accepted().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_failure_blocks_credentials_and_is_not_cleared_by_page_completion() {
|
||||
let mut recovery = Recovery {
|
||||
status: RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
..Recovery::default()
|
||||
};
|
||||
assert!(recovery.status.blocks_page());
|
||||
assert!(!recovery.status.accepts_auth_data());
|
||||
assert!(recovery.status.can_continue());
|
||||
recovery.page_loaded();
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.retry().is_none());
|
||||
assert!(recovery.status.can_continue());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failures_never_offer_a_certificate_exception() {
|
||||
let status = RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
can_continue: true,
|
||||
};
|
||||
assert!(!status.can_continue());
|
||||
assert!(status.can_retry());
|
||||
assert!(status.blocks_page());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_notice_keeps_successful_page_interactive() {
|
||||
let mut recovery = Recovery {
|
||||
certificate_bypassed: true,
|
||||
status: RecoveryStatus::Loading,
|
||||
..Recovery::default()
|
||||
};
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::CertificateBypassed);
|
||||
assert!(!recovery.status.blocks_page());
|
||||
assert!(recovery.status.accepts_auth_data());
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_failure_retries_once_even_after_manual_restarts() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(true).is_some());
|
||||
assert!(recovery.failure(true).is_none());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
assert!(recovery.retry().is_some());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_auth_requires_user_action_and_deduplicates_errors() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(recovery.retry().is_some());
|
||||
assert!(recovery.retry().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_completion_does_not_clear_errors_or_pending_prelogin() {
|
||||
let mut recovery = Recovery::default();
|
||||
recovery.failure(false);
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
recovery.retry();
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Restarting);
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Hidden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/// A TLS failure that can be presented without exposing request parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TlsFailureReason {
|
||||
Expired,
|
||||
NotYetValid,
|
||||
Untrusted,
|
||||
HostnameMismatch,
|
||||
InvalidCertificate,
|
||||
Handshake,
|
||||
}
|
||||
|
||||
impl TlsFailureReason {
|
||||
pub fn is_certificate_error(self) -> bool {
|
||||
self != Self::Handshake
|
||||
}
|
||||
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "The certificate has expired.",
|
||||
Self::NotYetValid => "The certificate is not valid yet.",
|
||||
Self::Untrusted => "The certificate was issued by an untrusted authority.",
|
||||
Self::HostnameMismatch => "The certificate does not match this server’s hostname.",
|
||||
Self::InvalidCertificate => "The server’s certificate could not be verified.",
|
||||
Self::Handshake => "The server could not establish a compatible TLS connection.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct TlsFailure {
|
||||
pub host: String,
|
||||
pub reason: TlsFailureReason,
|
||||
pub can_continue: bool,
|
||||
}
|
||||
|
||||
impl TlsFailure {
|
||||
pub fn confirmation_title(&self) -> String {
|
||||
format!("Continue to {}?", self.host)
|
||||
}
|
||||
|
||||
pub fn confirmation_message(&self) -> String {
|
||||
format!(
|
||||
"{} Your sign-in information could be intercepted.\n\nThis exception applies only to this host until this sign-in window closes.",
|
||||
self.reason.message()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
@@ -12,17 +13,26 @@ use gpapi::{
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
use tauri::{
|
||||
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
|
||||
webview::{PageLoadEvent, PageLoadPayload},
|
||||
};
|
||||
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||
use tokio::{sync::oneshot, time};
|
||||
|
||||
use crate::auth_prelogin;
|
||||
|
||||
use super::address_bar::TOOLBAR_HEIGHT;
|
||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
||||
|
||||
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
|
||||
|
||||
fn stop_loading(&self);
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String>;
|
||||
@@ -33,8 +43,6 @@ pub trait PlatformWebviewExt {
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()>;
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>);
|
||||
|
||||
fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> {
|
||||
if auth_request.starts_with("http") {
|
||||
info!("Loading auth request as URL: {}", redact_uri(auth_request));
|
||||
@@ -59,8 +67,6 @@ pub struct WebviewAuthenticator<'a> {
|
||||
clean: bool,
|
||||
window_title: &'a str,
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
is_retrying: tokio::sync::RwLock<bool>,
|
||||
}
|
||||
|
||||
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
|
||||
@@ -89,7 +95,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
clean: false,
|
||||
window_title: "GlobalProtect Login",
|
||||
window_theme: AuthWindowTheme::System,
|
||||
is_retrying: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,39 +125,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
|
||||
let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| {
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger_clone);
|
||||
let redacted_url = redact_uri(event.url().as_str());
|
||||
|
||||
match event.event() {
|
||||
PageLoadEvent::Started => {
|
||||
info!("Started loading page: {}", redacted_url);
|
||||
auth_messenger_clone.cancel_raise_window();
|
||||
}
|
||||
PageLoadEvent::Finished => {
|
||||
info!("Finished loading page: {}", redacted_url);
|
||||
}
|
||||
}
|
||||
|
||||
// Read auth data from the page no matter whether it's finished loading or not
|
||||
// Because we found that the finished event may not be triggered in some cases (e.g., on macOS)
|
||||
let _ = auth_window.with_webview(move |wv| {
|
||||
wv.get_html(Box::new(move |html| match html {
|
||||
Ok(html) => auth_messenger_clone.read_from_html(&html),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.on_page_load(on_page_load)
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height())
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
@@ -161,38 +140,169 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
let messenger = Arc::clone(&auth_messenger);
|
||||
let raise_task = tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
messenger.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
let result = async {
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
}
|
||||
self.wait_for_auth(&auth_window, Arc::clone(&auth_messenger)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
raise_task.abort();
|
||||
auth_messenger.begin_attempt();
|
||||
auth_messenger.cancel_raise_window();
|
||||
// Preserve the authentication outcome even if native teardown fails.
|
||||
if let Err(error) = auth_window.close() {
|
||||
warn!("Failed to close authentication window: {error}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn wait_for_auth(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<SamlAuthData> {
|
||||
let mut recovery = Recovery::default();
|
||||
let mut restart: Option<Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send + '_>>> = None;
|
||||
let mut loading_deadline = None;
|
||||
|
||||
loop {
|
||||
match auth_messenger.subscribe().await? {
|
||||
AuthEvent::Close => bail!(AuthenticationCancelled),
|
||||
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
|
||||
AuthEvent::Error(AuthError::NotFound(location)) => {
|
||||
let event = tokio::select! {
|
||||
event = auth_messenger.subscribe() => event?,
|
||||
result = async {
|
||||
match restart.as_mut() {
|
||||
Some(restart) => restart.await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
restart = None;
|
||||
match result {
|
||||
Ok(auth_request) => {
|
||||
// Fence off reads and cancellation notifications from the old page.
|
||||
auth_messenger.begin_attempt();
|
||||
recovery.loading();
|
||||
loading_deadline = Some(time::Instant::now() + RESTART_TIMEOUT);
|
||||
self.load_restarted_sign_in(auth_window, &auth_messenger, auth_request)?;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to restart sign-in: {}", err);
|
||||
if err.downcast_ref::<ServerTlsError>().is_some() {
|
||||
return Err(err);
|
||||
}
|
||||
recovery.load_failed();
|
||||
}
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
_ = async {
|
||||
match loading_deadline {
|
||||
Some(deadline) => time::sleep_until(deadline).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
loading_deadline = None;
|
||||
recovery.load_failed();
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut retry_plan = None;
|
||||
match event {
|
||||
AuthEvent::Close => {
|
||||
bail!(AuthenticationCancelled);
|
||||
}
|
||||
AuthEvent::RaiseWindow => self.raise_window(auth_window),
|
||||
AuthEvent::Data(generation, ..)
|
||||
| AuthEvent::Error(generation, _)
|
||||
| AuthEvent::NoAuthData(generation, _)
|
||||
| AuthEvent::PageLoaded(generation)
|
||||
| AuthEvent::TlsAccepted(generation)
|
||||
if generation != auth_messenger.generation() =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::Tls(failure)) => {
|
||||
warn!("TLS failure for {}: {}", failure.host, failure.reason.message());
|
||||
restart = None;
|
||||
loading_deadline = None;
|
||||
recovery.tls_failed(failure.reason, failure.can_continue);
|
||||
}
|
||||
AuthEvent::RequestTlsException => {
|
||||
if recovery.status().can_continue() {
|
||||
auth_window.with_webview(|wv| {
|
||||
if let Err(err) = wv.confirm_tls_exception() {
|
||||
warn!("Failed to confirm certificate exception: {}", err);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
AuthEvent::TlsAccepted(_) => {
|
||||
retry_plan = recovery.certificate_accepted();
|
||||
}
|
||||
AuthEvent::NoAuthData(_, location) => {
|
||||
info!(
|
||||
"No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint",
|
||||
location
|
||||
);
|
||||
self.handle_not_found(&auth_window, &auth_messenger);
|
||||
self.handle_not_found(auth_window, &auth_messenger);
|
||||
}
|
||||
AuthEvent::Error(AuthError::Invalid(err, location)) => {
|
||||
AuthEvent::Error(_, AuthError::Invalid(err, location)) => {
|
||||
warn!("Got invalid auth data in {:?}: {}", location, err);
|
||||
self.retry_auth(&auth_window).await;
|
||||
recovery.failure(false);
|
||||
}
|
||||
AuthEvent::Data(auth_data, location) => {
|
||||
AuthEvent::Error(_, AuthError::TemporarilyUnavailable) => {
|
||||
retry_plan = recovery.failure(true);
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::LoadFailed(err)) => {
|
||||
if matches!(
|
||||
recovery.status(),
|
||||
RecoveryStatus::Loading | RecoveryStatus::Hidden | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
warn!("Failed to load sign-in: {}", err);
|
||||
recovery.load_failed();
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Retry => {
|
||||
retry_plan = recovery.retry();
|
||||
}
|
||||
AuthEvent::PageLoaded(_) => {
|
||||
recovery.page_loaded();
|
||||
if !recovery.status().blocks_page() {
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Data(_, auth_data, location) => {
|
||||
if !recovery.status().accepts_auth_data() {
|
||||
continue;
|
||||
}
|
||||
info!("Got auth data from {:?}", location);
|
||||
|
||||
auth_window.close()?;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
}
|
||||
if let Some(plan) = retry_plan {
|
||||
loading_deadline = None;
|
||||
auth_messenger.begin_attempt();
|
||||
auth_window.with_webview(|wv| wv.stop_loading())?;
|
||||
restart = Some(Box::pin(async move {
|
||||
time::timeout(RESTART_TIMEOUT, self.request_sign_in(plan)).await?
|
||||
}));
|
||||
}
|
||||
if recovery.status() != RecoveryStatus::Loading {
|
||||
loading_deadline = None;
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,13 +326,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
}
|
||||
});
|
||||
|
||||
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
|
||||
let auth_request = match self.auth_request {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
None => auth_prelogin(&self.server, &self.gp_params, false, false).await?,
|
||||
@@ -231,19 +334,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let window = auth_window.clone();
|
||||
|
||||
// Set up webview
|
||||
auth_window.with_webview(move |wv| {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
use super::platform_impl::PlatformWebviewOnResponse;
|
||||
wv.on_response(Box::new(move |response| match response {
|
||||
Ok(response) => auth_messenger.read_from_response(&response),
|
||||
Err(err) => auth_messenger.send_auth_error(err),
|
||||
}));
|
||||
}
|
||||
|
||||
let controls_messenger = Arc::clone(&auth_messenger);
|
||||
let result = || -> anyhow::Result<()> {
|
||||
wv.install_auth_controls(&window, controls_messenger)?;
|
||||
if ignore_tls_errors {
|
||||
wv.ignore_tls_errors()?;
|
||||
}
|
||||
@@ -271,49 +368,48 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_messenger.schedule_raise_window(2);
|
||||
}
|
||||
|
||||
async fn retry_auth(&self, auth_window: &WebviewWindow) {
|
||||
let mut is_retrying = self.is_retrying.write().await;
|
||||
if *is_retrying {
|
||||
info!("Already retrying authentication, skipping...");
|
||||
return;
|
||||
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
if status != RecoveryStatus::Hidden {
|
||||
self.raise_window(auth_window);
|
||||
}
|
||||
|
||||
*is_retrying = true;
|
||||
drop(is_retrying);
|
||||
|
||||
if let Err(err) = self.retry_auth_impl(auth_window).await {
|
||||
warn!("Failed to retry authentication: {}", err);
|
||||
}
|
||||
|
||||
*self.is_retrying.write().await = false;
|
||||
}
|
||||
|
||||
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
|
||||
info!("Retrying authentication...");
|
||||
|
||||
auth_window.eval( r#"
|
||||
var loading = document.createElement("div");
|
||||
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
|
||||
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
|
||||
document.body.appendChild(loading);
|
||||
"#)?;
|
||||
|
||||
let auth_request = auth_prelogin(&self.server, &self.gp_params, false, false).await?;
|
||||
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
auth_window.with_webview(move |wv| {
|
||||
let result = || -> anyhow::Result<()> {
|
||||
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
|
||||
}();
|
||||
|
||||
if let Err(result) = tx.send(result) {
|
||||
warn!("Failed to send retry auth result: {:?}", result);
|
||||
if let Err(err) = wv.set_recovery_status(status) {
|
||||
warn!("Failed to update sign-in status: {}", err);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
rx.await??;
|
||||
async fn request_sign_in(&self, plan: RetryPlan) -> anyhow::Result<String> {
|
||||
info!("Restarting sign-in...");
|
||||
if plan.timing == RetryTiming::AutomaticDelay {
|
||||
time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
if plan.source == RetrySource::SuppliedRequest {
|
||||
if let Some(request) = self.auth_request {
|
||||
return Ok(request.to_owned());
|
||||
}
|
||||
}
|
||||
auth_prelogin(self.server, self.gp_params, false, false).await
|
||||
}
|
||||
|
||||
fn load_restarted_sign_in(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
messenger: &Arc<AuthMessenger>,
|
||||
auth_request: String,
|
||||
) -> anyhow::Result<()> {
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let generation = messenger.generation();
|
||||
let messenger = Arc::clone(messenger);
|
||||
auth_window.with_webview(move |wv| {
|
||||
if generation != messenger.generation() {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, AuthError::LoadFailed(err)));
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -108,17 +108,6 @@ fn sibling_binary_for_executable(executable: &Path, binary_name: &str) -> Option
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn bundled_vpnc_script() -> Option<PathBuf> {
|
||||
bundled_vpnc_script_for_executable(&env::current_exe().ok()?)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn bundled_vpnc_script_for_executable(executable: &Path) -> Option<PathBuf> {
|
||||
let executable = executable.canonicalize().ok()?;
|
||||
macos::vpnc_script_path(&executable)
|
||||
}
|
||||
|
||||
fn is_file(path: &Path) -> bool {
|
||||
path.is_file()
|
||||
}
|
||||
@@ -174,18 +163,6 @@ mod tests {
|
||||
sibling_binary_for_executable(&bin.join("gpclient"), "gpauth"),
|
||||
Some(helpers.canonicalize().unwrap().join("gpauth"))
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
assert_eq!(
|
||||
bundled_vpnc_script_for_executable(&bin.join("gpclient")),
|
||||
Some(
|
||||
helpers
|
||||
.canonicalize()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("Resources/Scripts/vpnc-script")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,29 +17,3 @@ fn contents_dir(executable: &Path) -> Option<&Path> {
|
||||
pub(super) fn helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Helpers").join(binary_name))
|
||||
}
|
||||
|
||||
pub(super) fn vpnc_script_path(executable: &Path) -> Option<PathBuf> {
|
||||
Some(contents_dir(executable)?.join("Resources/Scripts/vpnc-script"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bundle_entry_points_use_their_own_vpnc_script() {
|
||||
for executable in [
|
||||
"/Applications/GP Connect.app/Contents/Helpers/gpclient",
|
||||
"/Applications/GP Connect.app/Contents/MacOS/gpgui",
|
||||
] {
|
||||
assert_eq!(
|
||||
vpnc_script_path(Path::new(executable)),
|
||||
Some(PathBuf::from(
|
||||
"/Applications/GP Connect.app/Contents/Resources/Scripts/vpnc-script"
|
||||
))
|
||||
);
|
||||
}
|
||||
assert!(vpnc_script_path(Path::new("/opt/homebrew/bin/gpclient")).is_none());
|
||||
assert!(vpnc_script_path(Path::new("/tmp/Contents/Helpers/gpclient")).is_none());
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -13,9 +13,10 @@ base64.workspace = true
|
||||
dns-lookup.workspace = true
|
||||
log.workspace = true
|
||||
reqwest.workspace = true
|
||||
openssl.workspace = true
|
||||
version-compare = "0.2"
|
||||
native-tls = "0.2"
|
||||
pem.workspace = true
|
||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
xmltree.workspace = true
|
||||
serde.workspace = true
|
||||
specta = { workspace = true, features = ["derive", "uuid"] }
|
||||
@@ -27,14 +28,12 @@ whoami.workspace = true
|
||||
tempfile.workspace = true
|
||||
thiserror.workspace = true
|
||||
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
|
||||
redact-engine.workspace = true
|
||||
url.workspace = true
|
||||
regex.workspace = true
|
||||
uzers.workspace = true
|
||||
serde_urlencoded.workspace = true
|
||||
md5.workspace = true
|
||||
sha256.workspace = true
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
sha2.workspace = true
|
||||
uuid = { workspace = true, features = ["v4", "v5", "serde"] }
|
||||
chrono.workspace = true
|
||||
humantime.workspace = true
|
||||
@@ -54,13 +53,19 @@ env_logger = { workspace = true, optional = true }
|
||||
log-reload = { version = "0.1", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
security-framework = "3"
|
||||
oslog = { version = "0.2", default-features = false, optional = true }
|
||||
|
||||
# Dependencies for Linux and other OSes only
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(not(target_os = "macos"))'.dependencies]
|
||||
openssl.workspace = true
|
||||
version-compare = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
proptest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ pub enum SamlAuthResult {
|
||||
Success(SamlAuthData),
|
||||
Cancelled,
|
||||
Failure(String),
|
||||
ServerTlsError(crate::error::ServerTlsError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -68,6 +69,7 @@ impl SamlAuthResult {
|
||||
SamlAuthResult::Success(_) => true,
|
||||
SamlAuthResult::Cancelled => false,
|
||||
SamlAuthResult::Failure(_) => false,
|
||||
SamlAuthResult::ServerTlsError(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +78,7 @@ impl SamlAuthResult {
|
||||
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
|
||||
SamlAuthResult::Cancelled => None,
|
||||
SamlAuthResult::Failure(_) => None,
|
||||
SamlAuthResult::ServerTlsError(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,14 @@ use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
|
||||
use log::Level;
|
||||
|
||||
use crate::{
|
||||
error::PortalError,
|
||||
error::ServerTlsErrorKind,
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
@@ -26,7 +27,7 @@ pub trait Args {
|
||||
/// workaround. Empty when there is nothing useful to say — including when the
|
||||
/// relevant option is already in use.
|
||||
fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
let Some(err) = err.downcast_ref::<PortalError>() else {
|
||||
let Some(kind) = ServerTlsErrorKind::from_error(err) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -42,14 +43,15 @@ fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
if err.is_legacy_openssl_error() && !args.fix_openssl() {
|
||||
#[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 err.is_tls_error() && !args.ignore_tls_errors() {
|
||||
if kind == ServerTlsErrorKind::Certificate && !args.ignore_tls_errors() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n\n{program} --ignore-tls-errors {rest}"
|
||||
@@ -191,15 +193,25 @@ mod tests {
|
||||
use anyhow::anyhow;
|
||||
|
||||
use super::*;
|
||||
use crate::error::ServerTlsError;
|
||||
|
||||
fn certificate_error() -> ServerTlsError {
|
||||
ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::Certificate,
|
||||
}
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
@@ -224,7 +236,7 @@ mod tests {
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
|
||||
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &args).expect("writing to a Vec cannot fail");
|
||||
handle_error_to(&mut out, anyhow!(certificate_error()), &args).expect("writing to a Vec cannot fail");
|
||||
|
||||
let out = String::from_utf8(out).expect("output should be UTF-8");
|
||||
for line in out.lines() {
|
||||
@@ -235,7 +247,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_tls_failure_suggests_ignoring_tls_errors() {
|
||||
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
|
||||
let hints = retry_hints(&anyhow!(certificate_error()), &TestArgs::default());
|
||||
|
||||
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
|
||||
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
|
||||
@@ -247,6 +259,34 @@ 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 {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::Other,
|
||||
};
|
||||
assert!(retry_hints(&anyhow!(other), &TestArgs::default()).is_empty());
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
/// would be an extra record on every failed run.
|
||||
#[test]
|
||||
@@ -256,7 +296,7 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
|
||||
assert!(retry_hints(&anyhow!(certificate_error()), &args).is_empty());
|
||||
}
|
||||
|
||||
/// Most failures have no known workaround; inventing advice for them would
|
||||
@@ -272,7 +312,7 @@ mod tests {
|
||||
let hints = vec!["Re-run it with the `--ignore-tls-errors` option".to_string()];
|
||||
let mut out = Vec::new();
|
||||
|
||||
write_failure(&mut out, format, &anyhow!(PortalError::TlsError), &hints).expect("writing to a Vec cannot fail");
|
||||
write_failure(&mut out, format, &anyhow!(certificate_error()), &hints).expect("writing to a Vec cannot fail");
|
||||
|
||||
String::from_utf8(out).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
@@ -252,6 +252,7 @@ impl TryFrom<SamlAuthResult> for Credential {
|
||||
SamlAuthResult::Success(auth_data) => Ok(Self::from(auth_data)),
|
||||
SamlAuthResult::Cancelled => bail!(AuthenticationCancelled),
|
||||
SamlAuthResult::Failure(err) => bail!(err),
|
||||
SamlAuthResult::ServerTlsError(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use thiserror::Error;
|
||||
|
||||
mod server_tls;
|
||||
pub use server_tls::{ServerTlsError, ServerTlsErrorKind};
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum PortalError {
|
||||
#[error("Prelogin error: {0}")]
|
||||
@@ -10,18 +13,14 @@ pub enum PortalError {
|
||||
|
||||
#[error(transparent)]
|
||||
NetworkError(#[from] reqwest::Error),
|
||||
|
||||
#[error("TLS error")]
|
||||
TlsError,
|
||||
}
|
||||
|
||||
impl PortalError {
|
||||
pub fn is_legacy_openssl_error(&self) -> bool {
|
||||
format!("{:?}", self).contains("unsafe legacy renegotiation")
|
||||
}
|
||||
|
||||
pub fn is_tls_error(&self) -> bool {
|
||||
matches!(self, PortalError::TlsError) || format!("{:?}", self).contains("certificate verify failed")
|
||||
fn tls_error_kind(&self) -> Option<ServerTlsErrorKind> {
|
||||
match self {
|
||||
Self::NetworkError(error) => server_tls::classify(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
use std::{error::Error, fmt};
|
||||
|
||||
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)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServerTlsError {
|
||||
pub server: String,
|
||||
pub kind: ServerTlsErrorKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ServerTlsErrorKind {
|
||||
Certificate,
|
||||
ClientCertificateRequired,
|
||||
LegacyRenegotiation,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ServerTlsError {
|
||||
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
|
||||
Some(Self {
|
||||
server: server.origin().ascii_serialization(),
|
||||
kind: classify(error)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ServerTlsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ServerTlsError {}
|
||||
|
||||
impl ServerTlsErrorKind {
|
||||
/// One classification interface for CLI hints and desktop error mapping.
|
||||
pub fn from_error(error: &anyhow::Error) -> Option<Self> {
|
||||
error.chain().find_map(|source| {
|
||||
source
|
||||
.downcast_ref::<ServerTlsError>()
|
||||
.map(|error| error.kind)
|
||||
.or_else(|| {
|
||||
source
|
||||
.downcast_ref::<PortalError>()
|
||||
.and_then(PortalError::tls_error_kind)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Rsa,
|
||||
ssl::{SslAcceptor, SslMethod, SslVerifyMode},
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpListener,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[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\" }}");
|
||||
assert_eq!(
|
||||
classify_native_detail(&detail),
|
||||
ServerTlsErrorKind::Certificate,
|
||||
"{code}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
}
|
||||
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
server_with_client_auth(tls, SslVerifyMode::NONE)
|
||||
}
|
||||
|
||||
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "localhost").unwrap();
|
||||
let name = name.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert.set_subject_name(&name).unwrap();
|
||||
cert.set_issuer_name(&name).unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
cert.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
|
||||
acceptor.set_private_key(&key).unwrap();
|
||||
acceptor.set_certificate(&cert.build()).unwrap();
|
||||
acceptor.set_verify(verify);
|
||||
acceptor
|
||||
.set_ca_file(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/files/client-identity/root.pem"
|
||||
))
|
||||
.unwrap();
|
||||
let acceptor = acceptor.build();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = format!("https://{}", listener.local_addr().unwrap());
|
||||
let worker = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let body = "<prelogin-response><status>Success</status><saml-auth-method>REDIRECT</saml-auth-method><saml-request>aHR0cHM6Ly9pZHAuZXhhbXBsZS5jb20v</saml-request></prelogin-response>";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
let mut request = [0; 8192];
|
||||
if tls {
|
||||
if let Ok(mut stream) = acceptor.accept(stream) {
|
||||
let _ = stream.read(&mut request);
|
||||
let _ = stream.write_all(response.as_bytes());
|
||||
}
|
||||
} else {
|
||||
let _ = stream.read(&mut request);
|
||||
let _ = stream.write_all(response.as_bytes());
|
||||
}
|
||||
});
|
||||
(address, worker)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
let (address, worker) = server(true);
|
||||
let profile = OsProfile::builder(ClientOs::Linux).build();
|
||||
let params = GpParams::builder(profile).build();
|
||||
let error = prelogin(&address, ¶ms, PreloginOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
let tls = error
|
||||
.downcast_ref::<ServerTlsError>()
|
||||
.unwrap_or_else(|| panic!("unclassified: {error:?}"));
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::Certificate);
|
||||
assert_eq!(tls.server, address);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn certificate_bypass_allows_prelogin() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
let (address, worker) = server(true);
|
||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let result = prelogin(&address, ¶ms, PreloginOptions::default()).await;
|
||||
worker.join().unwrap();
|
||||
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||
let (address, worker) = server(false);
|
||||
let error = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&address)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
worker.join().unwrap();
|
||||
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap();
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::Other);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_refused_is_not_tls() {
|
||||
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()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(address)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let mut recovery = RecoveryState::default();
|
||||
assert!(
|
||||
recovery.recover(
|
||||
&RenderingCrash {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8)
|
||||
}
|
||||
.into()
|
||||
)
|
||||
);
|
||||
let error = recovery.terminal(
|
||||
ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::ClientCertificateRequired,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
assert_eq!(
|
||||
ServerTlsErrorKind::from_error(&error),
|
||||
Some(ServerTlsErrorKind::ClientCertificateRequired)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
|
||||
.ignore_tls_errors(true)
|
||||
.build();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let cancellation = tokio_util::sync::CancellationToken::new();
|
||||
for operation in ["prelogin", "config", "gateway"] {
|
||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let error = match operation {
|
||||
"prelogin" => prelogin(&address, ¶ms, PreloginOptions::default())
|
||||
.await
|
||||
.err()
|
||||
.unwrap(),
|
||||
"config" => crate::portal::retrieve_config(&address, &credential, ¶ms, &cancellation)
|
||||
.await
|
||||
.err()
|
||||
.unwrap(),
|
||||
_ => crate::gateway::GatewayLoginClient::new(&address, params.clone())
|
||||
.unwrap()
|
||||
.login(&credential, None, &cancellation)
|
||||
.await
|
||||
.err()
|
||||
.unwrap(),
|
||||
};
|
||||
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:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
for required in [false, true] {
|
||||
let verify = if required {
|
||||
SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT
|
||||
} else {
|
||||
SslVerifyMode::PEER
|
||||
};
|
||||
let (address, worker) = server_with_client_auth(true, verify);
|
||||
let mut builder = GpParams::builder(OsProfile::builder(ClientOs::Linux).build());
|
||||
builder.ignore_tls_errors(true);
|
||||
if required {
|
||||
builder
|
||||
.certificate(Some(
|
||||
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/files/client-identity/rsa-cert.pem").to_owned(),
|
||||
))
|
||||
.sslkey(Some(
|
||||
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/files/client-identity/rsa-pkcs8.pem").to_owned(),
|
||||
));
|
||||
}
|
||||
let result = prelogin(&address, &builder.build(), PreloginOptions::default()).await;
|
||||
worker.join().unwrap();
|
||||
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_response_reads_preserve_the_transport_cause() {
|
||||
for status in [200, 403] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = format!("http://{}", listener.local_addr().unwrap());
|
||||
let worker = thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut request = [0; 8192];
|
||||
stream.read(&mut request).unwrap();
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status} Test\r\nContent-Length: 100\r\nConnection: close\r\n\r\ntruncated"
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let response = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(address)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let error = crate::utils::parse_gp_response(response).await.unwrap_err();
|
||||
assert_eq!(error.status.as_u16(), status);
|
||||
assert!(error.source().unwrap().is::<reqwest::Error>());
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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()))
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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)
|
||||
}
|
||||
@@ -254,12 +254,18 @@ async fn receive_gateway_login(
|
||||
.await
|
||||
.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
match crate::error::ServerTlsError::from_request(origin, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
|
||||
return anyhow::anyhow!(tls);
|
||||
}
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
@@ -10,7 +10,7 @@ use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
credential::{AuthCookieCredential, Credential},
|
||||
error::PortalError,
|
||||
error::{PortalError, ServerTlsError},
|
||||
gateway::{Gateway, parse_gateways},
|
||||
gp_params::GpParams,
|
||||
params,
|
||||
@@ -149,6 +149,7 @@ pub async fn retrieve_config(
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let portal = normalize_server(portal)?;
|
||||
let server_url = url::Url::parse(&portal)?;
|
||||
let server = remove_url_scheme(&portal);
|
||||
|
||||
let url = format!("{}/global-protect/getconfig.esp", portal);
|
||||
@@ -170,10 +171,16 @@ pub async fn retrieve_config(
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
@@ -227,16 +234,23 @@ async fn retrieve_csc_config(
|
||||
let swg_nonce = csc::swg_nonce();
|
||||
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
|
||||
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
|
||||
let server_url = url::Url::parse(portal)?;
|
||||
|
||||
info!("Portal CSC config request summary: {}", csc_req.summary());
|
||||
info!("Portal CSC config request params: {}", redact_params(¶ms));
|
||||
|
||||
let res = client.post(&url).form(¶ms).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
match ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(tls) => anyhow::anyhow!(tls),
|
||||
None => anyhow::anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow::anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
);
|
||||
|
||||
let client = Client::try_from(gp_params)?;
|
||||
let server_url = url::Url::parse(&portal)?;
|
||||
|
||||
let mut request = client.post(&prelogin_url);
|
||||
if !request_params.query.is_empty() {
|
||||
@@ -146,10 +147,16 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
|
||||
|
||||
let res = request.send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
match crate::error::ServerTlsError::from_request(&server_url, &e) {
|
||||
Some(error) => anyhow!(error),
|
||||
None => anyhow!(PortalError::NetworkError(e)),
|
||||
}
|
||||
})?;
|
||||
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) {
|
||||
return Err(anyhow!(tls));
|
||||
}
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ 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")]
|
||||
@@ -66,6 +67,7 @@ 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")]
|
||||
@@ -113,6 +115,7 @@ 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
|
||||
@@ -226,6 +229,7 @@ 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");
|
||||
}
|
||||
@@ -343,10 +347,12 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `gpauth --browser remote` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||
match browser {
|
||||
Some(browser) if browser.eq_ignore_ascii_case("remote") => ChildInput::Terminal,
|
||||
Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote") => {
|
||||
ChildInput::Terminal
|
||||
}
|
||||
_ => ChildInput::Null,
|
||||
}
|
||||
}
|
||||
@@ -376,6 +382,53 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
||||
|
||||
#[test]
|
||||
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
||||
stderr: Vec::new(),
|
||||
};
|
||||
let error = decode_auth_output(output, false).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<ServerTlsError>(),
|
||||
Some(&ServerTlsError {
|
||||
server: "https://vpn.example.com:8443".into(),
|
||||
kind: ServerTlsErrorKind::Certificate,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_required_result_survives_process_decoding() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
|
||||
stderr: Vec::new(),
|
||||
};
|
||||
let error = decode_auth_output(output, false).unwrap_err();
|
||||
let tls = error.downcast_ref::<ServerTlsError>().unwrap();
|
||||
assert_eq!(tls.kind, ServerTlsErrorKind::ClientCertificateRequired);
|
||||
assert_eq!(tls.server, "https://vpn.example.com");
|
||||
}
|
||||
|
||||
#[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 == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_profile_sets_os_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
|
||||
@@ -463,7 +516,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_remote_browser_reads_the_terminal() {
|
||||
fn only_a_manual_browser_reads_the_terminal() {
|
||||
assert!(matches!(auth_stdin(Some("manual")), ChildInput::Terminal));
|
||||
assert!(matches!(auth_stdin(Some("MANUAL")), ChildInput::Terminal));
|
||||
assert!(matches!(auth_stdin(Some("remote")), ChildInput::Terminal));
|
||||
assert!(matches!(auth_stdin(Some("REMOTE")), ChildInput::Terminal));
|
||||
assert!(matches!(auth_stdin(Some("firefox")), ChildInput::Null));
|
||||
|
||||
@@ -5,6 +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>),
|
||||
VpnEnv(VpnEnv),
|
||||
VpnState(VpnState),
|
||||
ActiveGui,
|
||||
|
||||
@@ -380,6 +380,7 @@ pub struct UpdateLogLevelRequest(pub String);
|
||||
/// Requests that can be sent to the service
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub enum WsRequest {
|
||||
SetTunnelStatisticsEnabled { enabled: bool },
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||
|
||||
@@ -17,6 +17,9 @@ pub enum ClientMessage {
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerMessage {
|
||||
TunnelStatistics {
|
||||
snapshot: crate::session::tunnel::TunnelStatisticsSnapshot,
|
||||
},
|
||||
Attached {
|
||||
connection_id: Uuid,
|
||||
current_revision: u64,
|
||||
@@ -39,6 +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),
|
||||
Accepted,
|
||||
StoredHipReport {
|
||||
report_id: String,
|
||||
@@ -192,4 +196,73 @@ mod tests {
|
||||
let encoded = encode(&message).unwrap();
|
||||
assert!(encoded.len() <= MAX_PLAINTEXT);
|
||||
}
|
||||
|
||||
#[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},
|
||||
};
|
||||
let mut configuration = TunnelConfiguration::default();
|
||||
configuration.included_routes.items = vec!["r".repeat(1024); 15];
|
||||
configuration.included_routes.items.push(String::new());
|
||||
configuration.included_routes.total_count = 16;
|
||||
let padding = MAX_CONFIGURATION_BYTES - serde_json::to_vec(&configuration).unwrap().len();
|
||||
assert!(padding <= 1024);
|
||||
*configuration.included_routes.items.last_mut().unwrap() = "r".repeat(padding);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(&configuration).unwrap().len(),
|
||||
MAX_CONFIGURATION_BYTES
|
||||
);
|
||||
let gateway = Gateway::new("Gateway".repeat(20), "vpn.example.com".into());
|
||||
let info = ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway; 32]);
|
||||
let snapshot = VpnEnv {
|
||||
tunnel_state: Some(TunnelState {
|
||||
tunnel_id: Uuid::new_v4(),
|
||||
sequence: u64::MAX,
|
||||
phase: TunnelPhase::Connected,
|
||||
configuration_revision: u64::MAX,
|
||||
configuration: Some(configuration),
|
||||
transport: TunnelTransport::IpsecEsp,
|
||||
elapsed_ms: u64::MAX,
|
||||
}),
|
||||
vpn_state: VpnState::Connected(Box::new(ConnectedInfo::new(info, None))),
|
||||
vpnc_script: Some("s".repeat(1024)),
|
||||
auth_executable: "a".repeat(1024),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
},
|
||||
};
|
||||
for mut message in [
|
||||
ServerMessage::Attached {
|
||||
connection_id: Uuid::new_v4(),
|
||||
current_revision: u64::MAX,
|
||||
snapshot: snapshot.clone(),
|
||||
},
|
||||
ServerMessage::Snapshot {
|
||||
current_revision: u64::MAX,
|
||||
snapshot,
|
||||
},
|
||||
] {
|
||||
let remaining = MAX_PLAINTEXT - encode(&message).unwrap().len();
|
||||
let snapshot = match &mut message {
|
||||
ServerMessage::Attached { snapshot, .. } | ServerMessage::Snapshot { snapshot, .. } => snapshot,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
// Existing host/connection metadata has no declared maximum. Fill the
|
||||
// remaining envelope budget, then assert its actual boundary explicitly.
|
||||
snapshot.auth_executable.push_str(&"a".repeat(remaining));
|
||||
assert_eq!(encode(&message).unwrap().len(), MAX_PLAINTEXT);
|
||||
let snapshot = match &mut message {
|
||||
ServerMessage::Attached { snapshot, .. } | ServerMessage::Snapshot { snapshot, .. } => snapshot,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
snapshot.auth_executable.push('a');
|
||||
assert!(matches!(encode(&message), Err(TransportError::MessageTooLarge)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +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>,
|
||||
/// The VPN connection state
|
||||
pub vpn_state: VpnState,
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ mod gateway_sessions;
|
||||
pub mod network;
|
||||
pub mod non_tunnel;
|
||||
pub mod transport;
|
||||
pub mod tunnel;
|
||||
pub use connection::*;
|
||||
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ impl PhysicalNetwork {
|
||||
}
|
||||
|
||||
fn fingerprint(&self) -> anyhow::Result<String> {
|
||||
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
|
||||
Ok(crate::utils::checksum::sha256_hex(serde_json::to_vec(&self.snapshot)?))
|
||||
}
|
||||
|
||||
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
|
||||
|
||||
@@ -320,8 +320,8 @@ fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
|
||||
.map_err(|_| GatewayRequestError::MalformedResponse)?,
|
||||
None => 0,
|
||||
};
|
||||
// Limit this client's supported response delay to one hour. The official
|
||||
// registry scheduling cap is not evidence of a wire-protocol maximum.
|
||||
// Accept response delays up to one hour as a client policy, not a
|
||||
// wire-protocol maximum.
|
||||
if delay > 3600 {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Observed tunnel data, shared by standalone clients and service consumers.
|
||||
//! These values describe negotiated settings, not verified operating-system state.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const MAX_CONFIGURATION_BYTES: usize = 16 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TunnelPhase {
|
||||
Establishing,
|
||||
Connected,
|
||||
Reconnecting,
|
||||
Ended,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TunnelTransport {
|
||||
Negotiating,
|
||||
IpsecEsp,
|
||||
SslTls,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl TunnelTransport {
|
||||
pub fn is_active(self) -> bool {
|
||||
matches!(self, Self::IpsecEsp | Self::SslTls)
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Negotiating => "Negotiating",
|
||||
Self::IpsecEsp => "IPsec (ESP)",
|
||||
Self::SslTls => "SSL/TLS",
|
||||
Self::Unavailable => "Unavailable",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelList {
|
||||
pub items: Vec<String>,
|
||||
pub total_count: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelAddress {
|
||||
pub address: String,
|
||||
pub netmask: Option<String>,
|
||||
pub prefix_length: Option<u8>,
|
||||
}
|
||||
|
||||
impl TunnelAddress {
|
||||
pub fn display(&self) -> String {
|
||||
match self.prefix_length {
|
||||
Some(prefix) => format!("{}/{prefix}", self.address),
|
||||
None => match &self.netmask {
|
||||
Some(netmask) => format!("{} (mask {netmask})", self.address),
|
||||
None => self.address.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelConfiguration {
|
||||
pub interface: Option<String>,
|
||||
pub ipv4: Option<TunnelAddress>,
|
||||
pub ipv6: Option<TunnelAddress>,
|
||||
pub server_ip: Option<String>,
|
||||
pub dns: TunnelList,
|
||||
pub search_domains: TunnelList,
|
||||
pub split_dns: TunnelList,
|
||||
pub included_routes: TunnelList,
|
||||
pub excluded_routes: TunnelList,
|
||||
pub mtu: Option<u32>,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl TunnelConfiguration {
|
||||
/// Bound observation payloads without modifying native network configuration.
|
||||
/// Whole list entries are omitted before shortening scalar text. Counts and
|
||||
/// truncation flags preserve the distinction between absent and omitted data.
|
||||
/// Returns false if even the fixed JSON shape cannot fit the supplied budget.
|
||||
pub fn limit_encoded_size(&mut self, limit: usize) -> bool {
|
||||
while serde_json::to_vec(self).expect("configuration is serializable").len() > limit {
|
||||
self.truncated = true;
|
||||
let lists = [
|
||||
&mut self.excluded_routes,
|
||||
&mut self.included_routes,
|
||||
&mut self.split_dns,
|
||||
&mut self.search_domains,
|
||||
&mut self.dns,
|
||||
];
|
||||
if let Some(list) = lists.into_iter().find(|list| !list.items.is_empty()) {
|
||||
list.items.pop();
|
||||
list.truncated = true;
|
||||
continue;
|
||||
}
|
||||
let mut scalars = vec![&mut self.interface, &mut self.server_ip];
|
||||
if let Some(address) = &mut self.ipv4 {
|
||||
scalars.push(&mut address.netmask);
|
||||
if address.address.len() > 128 {
|
||||
address.address.truncate(address.address.floor_char_boundary(128));
|
||||
address.prefix_length = None;
|
||||
}
|
||||
}
|
||||
if let Some(address) = &mut self.ipv6 {
|
||||
scalars.push(&mut address.netmask);
|
||||
if address.address.len() > 128 {
|
||||
address.address.truncate(address.address.floor_char_boundary(128));
|
||||
address.prefix_length = None;
|
||||
}
|
||||
}
|
||||
match scalars
|
||||
.into_iter()
|
||||
.max_by_key(|value| value.as_ref().map_or(0, String::len))
|
||||
{
|
||||
Some(Some(text)) if !text.is_empty() => {
|
||||
text.truncate(text.floor_char_boundary(text.len() / 2));
|
||||
}
|
||||
_ => return serde_json::to_vec(self).expect("configuration is serializable").len() <= limit,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelState {
|
||||
pub tunnel_id: Uuid,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub sequence: u64,
|
||||
pub phase: TunnelPhase,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub configuration_revision: u64,
|
||||
pub configuration: Option<TunnelConfiguration>,
|
||||
pub transport: TunnelTransport,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelStatistics {
|
||||
pub tunnel_id: Uuid,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub sequence: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub state_sequence: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub configuration_revision: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub elapsed_ms: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub received_bytes: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub sent_bytes: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub received_packets: u64,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub sent_packets: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TunnelStatisticsState {
|
||||
Disabled,
|
||||
Waiting,
|
||||
Fresh,
|
||||
Stale,
|
||||
Ended,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TunnelStatisticsView {
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub sequence: u64,
|
||||
pub tunnel_id: Uuid,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub state_sequence: u64,
|
||||
pub phase: TunnelPhase,
|
||||
pub transport: TunnelTransport,
|
||||
pub state: TunnelStatisticsState,
|
||||
#[serde(with = "decimal")]
|
||||
#[specta(type = String)]
|
||||
pub elapsed_ms: u64,
|
||||
#[serde(with = "optional_decimal")]
|
||||
#[specta(type = Option<String>)]
|
||||
pub sample_age_ms: Option<u64>,
|
||||
pub sample: Option<TunnelStatistics>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TunnelUnavailableReason {
|
||||
NoTunnel,
|
||||
NonTunnel,
|
||||
ObservationFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum TunnelStatisticsSnapshot {
|
||||
Available(TunnelStatisticsView),
|
||||
Unavailable { reason: TunnelUnavailableReason },
|
||||
}
|
||||
|
||||
impl TunnelStatisticsSnapshot {
|
||||
pub fn unavailable(reason: TunnelUnavailableReason) -> Self {
|
||||
Self::Unavailable { reason }
|
||||
}
|
||||
|
||||
pub fn view(&self) -> Option<&TunnelStatisticsView> {
|
||||
match self {
|
||||
Self::Available(view) => Some(view),
|
||||
Self::Unavailable { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tunnel_id(&self) -> Option<Uuid> {
|
||||
self.view().map(|view| view.tunnel_id)
|
||||
}
|
||||
|
||||
pub fn sequence(&self) -> Option<u64> {
|
||||
self.view().map(|view| view.sequence)
|
||||
}
|
||||
|
||||
pub fn state_sequence(&self) -> Option<u64> {
|
||||
self.view().map(|view| view.state_sequence)
|
||||
}
|
||||
|
||||
pub fn disabled(&self) -> Self {
|
||||
let mut snapshot = self.clone();
|
||||
if let Self::Available(view) = &mut snapshot {
|
||||
if view.state != TunnelStatisticsState::Ended {
|
||||
view.state = TunnelStatisticsState::Disabled;
|
||||
}
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
pub fn stale(&self) -> Self {
|
||||
let mut snapshot = self.clone();
|
||||
if let Self::Available(view) = &mut snapshot {
|
||||
if matches!(
|
||||
view.state,
|
||||
TunnelStatisticsState::Fresh | TunnelStatisticsState::Waiting
|
||||
) {
|
||||
view.state = TunnelStatisticsState::Stale;
|
||||
}
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
|
||||
mod decimal {
|
||||
use serde::{Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_str(value)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
||||
let value = String::deserialize(deserializer)?;
|
||||
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(serde::de::Error::custom("expected an unsigned decimal string"));
|
||||
}
|
||||
value.parse().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
mod optional_decimal {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &Option<u64>, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
value.map(|value| value.to_string()).serialize(serializer)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u64>, D::Error> {
|
||||
Option::<String>::deserialize(deserializer)?
|
||||
.map(|value| {
|
||||
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(serde::de::Error::custom("expected an unsigned decimal string"));
|
||||
}
|
||||
value.parse().map_err(serde::de::Error::custom)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn counters_above_javascript_precision_round_trip_as_decimal_strings() {
|
||||
let sample = TunnelStatistics {
|
||||
tunnel_id: Uuid::nil(),
|
||||
sequence: 1,
|
||||
state_sequence: 1,
|
||||
configuration_revision: 1,
|
||||
elapsed_ms: 1000,
|
||||
received_bytes: (1_u64 << 53) + 1,
|
||||
sent_bytes: u64::MAX,
|
||||
received_packets: 3,
|
||||
sent_packets: 4,
|
||||
};
|
||||
let value = serde_json::to_value(&sample).unwrap();
|
||||
assert_eq!(value["receivedBytes"], "9007199254740993");
|
||||
assert_eq!(value["sentBytes"], "18446744073709551615");
|
||||
assert_eq!(
|
||||
serde_json::from_value::<TunnelStatistics>(value.clone()).unwrap(),
|
||||
sample
|
||||
);
|
||||
let mut numeric = value;
|
||||
numeric["receivedBytes"] = serde_json::json!(9007199254740993_u64);
|
||||
assert!(serde_json::from_value::<TunnelStatistics>(numeric).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_has_no_synthetic_counters() {
|
||||
let snapshot = TunnelStatisticsSnapshot::unavailable(TunnelUnavailableReason::NonTunnel);
|
||||
let value = serde_json::to_value(&snapshot).unwrap();
|
||||
assert_eq!(value, serde_json::json!({"kind": "unavailable", "reason": "nonTunnel"}));
|
||||
assert_eq!(
|
||||
serde_json::from_value::<TunnelStatisticsSnapshot>(value).unwrap(),
|
||||
snapshot
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,43 @@
|
||||
use std::path::Path;
|
||||
use std::{
|
||||
fmt::Write as _,
|
||||
fs::File,
|
||||
io::{self, Read},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub fn sha256_hex(data: impl AsRef<[u8]>) -> String {
|
||||
digest_hex(&Sha256::digest(data.as_ref()))
|
||||
}
|
||||
|
||||
pub fn file_sha256(path: impl AsRef<Path>) -> io::Result<String> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0; 8192];
|
||||
loop {
|
||||
let count = match file.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(count) => count,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
hasher.update(&buffer[..count]);
|
||||
}
|
||||
Ok(digest_hex(&hasher.finalize()))
|
||||
}
|
||||
|
||||
fn digest_hex(digest: &[u8]) -> String {
|
||||
let mut hex = String::with_capacity(digest.len() * 2);
|
||||
for byte in digest {
|
||||
write!(&mut hex, "{byte:02x}").expect("writing to a String cannot fail");
|
||||
}
|
||||
hex
|
||||
}
|
||||
|
||||
pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
|
||||
let file = Path::new(&path);
|
||||
let checksum = sha256::try_digest(&file)?;
|
||||
let checksum = file_sha256(path)?;
|
||||
|
||||
if checksum != expected {
|
||||
bail!("Checksum mismatch, expected: {}, actual: {}", expected, checksum);
|
||||
@@ -12,3 +45,43 @@ pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_sha256_vectors_use_lowercase_hex() {
|
||||
assert_eq!(
|
||||
sha256_hex(b""),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(b"abc"),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_files_across_buffer_boundaries_and_checks_expected_digest() {
|
||||
let mut file = tempfile::NamedTempFile::new().unwrap();
|
||||
file.write_all(&vec![b'a'; 1_000_000]).unwrap();
|
||||
let expected = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
|
||||
|
||||
assert_eq!(file_sha256(file.path()).unwrap(), expected);
|
||||
verify_checksum(file.path().to_str().unwrap(), expected).unwrap();
|
||||
assert!(verify_checksum(file.path().to_str().unwrap(), "wrong").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_empty_files_and_propagates_file_errors() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
assert_eq!(file_sha256(file.path()).unwrap(), sha256_hex(b""));
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let error = file_sha256(directory.path().join("missing")).unwrap_err();
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
|
||||
assert!(file_sha256(directory.path()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
|
||||
use pkcs8::{
|
||||
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
|
||||
der::{
|
||||
Decode, Reader, SliceReader, Tag, Tagged,
|
||||
asn1::{AnyRef, OctetStringRef, SequenceRef},
|
||||
},
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{request::RequestIdentityError, traditional_key};
|
||||
|
||||
pub(super) enum TraditionalKeyFormat {
|
||||
Sec1Der,
|
||||
PlainPem,
|
||||
EncryptedPem,
|
||||
}
|
||||
|
||||
struct PemBlock {
|
||||
tag: String,
|
||||
headers: pem::HeaderMap,
|
||||
contents: Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
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());
|
||||
// The PEM crate owns a copy of the decoded private key as well.
|
||||
drop(Zeroizing::new(block.into_contents()));
|
||||
encoded
|
||||
}
|
||||
}
|
||||
|
||||
fn is_pem(bytes: &[u8]) -> bool {
|
||||
bytes.windows(b"-----BEGIN".len()).any(|part| part == b"-----BEGIN")
|
||||
}
|
||||
|
||||
// Adopt decoded blocks immediately, including ignored keys in combined files.
|
||||
fn blocks(bytes: &[u8]) -> Result<Vec<PemBlock>, pem::PemError> {
|
||||
Ok(
|
||||
pem::parse_many(bytes)?
|
||||
.into_iter()
|
||||
.map(|block| PemBlock {
|
||||
tag: block.tag().to_owned(),
|
||||
headers: block.headers().clone(),
|
||||
contents: Zeroizing::new(block.into_contents()),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
let pem_input = is_pem(bytes);
|
||||
let block = if pem_input {
|
||||
blocks(bytes)
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?
|
||||
.into_iter()
|
||||
.find(|block| block.tag.ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?
|
||||
} else {
|
||||
// Unlike combined PEM, a standalone DER certificate cannot include a key.
|
||||
if x509_cert::Certificate::from_der(bytes).is_ok() {
|
||||
return Err(RequestIdentityError::NoKey.into());
|
||||
}
|
||||
PemBlock {
|
||||
tag: der_key_tag(bytes)
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?
|
||||
.to_owned(),
|
||||
headers: pem::HeaderMap::default(),
|
||||
contents: Zeroizing::new(bytes.to_vec()),
|
||||
}
|
||||
};
|
||||
let der = &block.contents;
|
||||
let document = if traditional_encryption(&block)? {
|
||||
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)?
|
||||
} 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.
|
||||
let algorithm = AlgorithmIdentifierRef {
|
||||
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
|
||||
parameters: Some(AnyRef::NULL),
|
||||
};
|
||||
let private_key = OctetStringRef::new(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let info = PrivateKeyInfoRef::new(algorithm, private_key);
|
||||
SecretDocument::encode_msg(&info).map_err(|_| RequestIdentityError::InvalidKey)?
|
||||
}
|
||||
"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)?
|
||||
}
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
};
|
||||
PrivateKeyInfoRef::from_der(document.as_bytes()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let pem = document.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
Ok(Zeroizing::new(pem.as_bytes().to_vec()))
|
||||
}
|
||||
|
||||
// Only choose a container here. The selected decoder/native importer validates
|
||||
// the key. Decoding the complete outer sequence rejects concatenated DER input.
|
||||
fn der_key_tag(bytes: &[u8]) -> Result<&'static str, pkcs8::der::Error> {
|
||||
let sequence = <&SequenceRef>::from_der(bytes)?;
|
||||
let mut reader = SliceReader::new(sequence.as_bytes())?;
|
||||
let first: AnyRef = reader.decode()?;
|
||||
Ok(match (first.tag(), Tag::peek(&reader)?) {
|
||||
(Tag::Integer, Tag::Sequence) => "PRIVATE KEY",
|
||||
(Tag::Integer, Tag::Integer) => "RSA PRIVATE KEY",
|
||||
(Tag::Integer, Tag::OctetString) => "EC PRIVATE KEY",
|
||||
(Tag::Sequence, Tag::OctetString) => "ENCRYPTED PRIVATE KEY",
|
||||
_ => return Err(pkcs8::der::ErrorKind::Failed.into()),
|
||||
})
|
||||
}
|
||||
|
||||
fn traditional_encryption(block: &PemBlock) -> Result<bool, RequestIdentityError> {
|
||||
let mut proc_type = None;
|
||||
let mut dek_info = None;
|
||||
for (name, value) in block.headers.iter() {
|
||||
let slot = match name {
|
||||
"Proc-Type" => &mut proc_type,
|
||||
"DEK-Info" => &mut dek_info,
|
||||
_ => continue,
|
||||
};
|
||||
if slot.replace(value).is_some() {
|
||||
return Err(RequestIdentityError::InvalidKey);
|
||||
}
|
||||
}
|
||||
if proc_type.is_none() && dek_info.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let (Some("4,ENCRYPTED"), Some(dek_info)) = (proc_type, dek_info) else {
|
||||
return Err(RequestIdentityError::InvalidKey);
|
||||
};
|
||||
let (cipher, iv) = dek_info.split_once(',').ok_or(RequestIdentityError::InvalidKey)?;
|
||||
let block_size = match cipher {
|
||||
"AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC" => 16,
|
||||
"DES-EDE3-CBC" => 8,
|
||||
_ => return Err(RequestIdentityError::UnsupportedEncryption),
|
||||
};
|
||||
if iv.len() != block_size * 2
|
||||
|| !iv.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
|| block.contents.is_empty()
|
||||
|| block.contents.len() % block_size != 0
|
||||
{
|
||||
return Err(RequestIdentityError::InvalidKey);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
// pkcs5 collapses unknown outer PBE OIDs into a generic DER value error.
|
||||
// Inspect the typed envelope first so legacy PBE is not called malformed.
|
||||
let algorithm = pkcs8::der::asn1::AnyRef::from_der(der)
|
||||
.and_then(|value| {
|
||||
value.sequence(|reader| {
|
||||
let algorithm = pkcs8::AlgorithmIdentifierRef::decode(reader)?;
|
||||
let _: &pkcs8::der::asn1::OctetStringRef = reader.decode()?;
|
||||
Ok(algorithm.oid)
|
||||
})
|
||||
})
|
||||
.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.
|
||||
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
|
||||
return super::legacy_pkcs8::decrypt(der, passphrase);
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
// Decode the full encryption scheme, including its KDF/PRF/cipher, before
|
||||
// asking for a password. Unsupported algorithms must not cause prompt loops.
|
||||
let encrypted = EncryptedPrivateKeyInfoRef::from_der(der).map_err(|error| match error.kind() {
|
||||
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
|
||||
_ => RequestIdentityError::InvalidKey,
|
||||
})?;
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
let mut plaintext = Zeroizing::new(encrypted.encrypted_data.as_bytes().to_vec());
|
||||
let decrypted = encrypted
|
||||
.encryption_algorithm
|
||||
.decrypt_in_place(passphrase, &mut plaintext)
|
||||
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
|
||||
SecretDocument::try_from(decrypted).map_err(|_| RequestIdentityError::DecryptError("PEM").into())
|
||||
}
|
||||
|
||||
pub(super) fn certificate_chain(bytes: &[u8]) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
if !is_pem(bytes) {
|
||||
return certificate_pem(bytes).map(|pem| Zeroizing::new(pem.into_bytes()));
|
||||
}
|
||||
let mut chain = Zeroizing::new(Vec::new());
|
||||
for block in blocks(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)? {
|
||||
if block.tag == "CERTIFICATE" {
|
||||
let encoded = certificate_pem(&block.contents)?;
|
||||
chain.extend_from_slice(encoded.as_bytes());
|
||||
}
|
||||
}
|
||||
if chain.is_empty() {
|
||||
return Err(RequestIdentityError::InvalidCertificate.into());
|
||||
}
|
||||
Ok(chain)
|
||||
}
|
||||
|
||||
fn certificate_pem(der: &[u8]) -> anyhow::Result<String> {
|
||||
x509_cert::Certificate::from_der(der).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
Ok(pem::encode_config(
|
||||
&pem::Pem::new("CERTIFICATE", der),
|
||||
pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! 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())
|
||||
}
|
||||
@@ -5,10 +5,25 @@ pub mod checksum;
|
||||
pub mod crypto;
|
||||
pub mod endpoint;
|
||||
pub mod env_utils;
|
||||
mod identity_encoding;
|
||||
mod legacy_pkcs8;
|
||||
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;
|
||||
|
||||
@@ -51,6 +66,8 @@ pub struct GpError {
|
||||
pub status: StatusCode,
|
||||
pub reason: String,
|
||||
body: String,
|
||||
#[source]
|
||||
source: Option<reqwest::Error>,
|
||||
}
|
||||
|
||||
impl GpError {
|
||||
@@ -63,9 +80,7 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
|
||||
let status = res.status();
|
||||
|
||||
if status.is_client_error() || status.is_server_error() {
|
||||
let (reason, body) = parse_gp_error(res).await;
|
||||
|
||||
return Err(GpError { status, reason, body });
|
||||
return Err(parse_gp_error(res).await);
|
||||
}
|
||||
|
||||
res.text().await.map_err(|err| {
|
||||
@@ -75,21 +90,28 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
|
||||
status,
|
||||
reason: "failed to read response".to_string(),
|
||||
body: "<failed to read response>".to_string(),
|
||||
source: Some(err),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn parse_gp_error(res: Response) -> (String, String) {
|
||||
async fn parse_gp_error(res: Response) -> GpError {
|
||||
let status = res.status();
|
||||
let reason = res
|
||||
.headers()
|
||||
.get("x-private-pan-globalprotect")
|
||||
.map_or_else(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
|
||||
.to_string();
|
||||
|
||||
let res = res.text().await.map_or_else(
|
||||
|_| "<failed to read response>".to_string(),
|
||||
|v| if v.is_empty() { "<empty>".to_string() } else { v },
|
||||
);
|
||||
let (body, source) = match res.text().await {
|
||||
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
|
||||
Err(error) => ("<failed to read response>".to_string(), Some(error)),
|
||||
};
|
||||
|
||||
(reason, res)
|
||||
GpError {
|
||||
status,
|
||||
reason,
|
||||
body,
|
||||
source,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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(())
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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(())
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
use std::sync::RwLock;
|
||||
|
||||
use redact_engine::{Pattern, Redaction as RedactEngine};
|
||||
use regex::Regex;
|
||||
use url::{Url, form_urlencoded};
|
||||
|
||||
pub struct Redaction {
|
||||
redact_engine: RwLock<Option<RedactEngine>>,
|
||||
patterns: RwLock<Vec<Regex>>,
|
||||
}
|
||||
|
||||
impl Default for Redaction {
|
||||
@@ -16,56 +15,45 @@ impl Default for Redaction {
|
||||
|
||||
impl Redaction {
|
||||
pub fn new() -> Self {
|
||||
let redact_engine = RedactEngine::custom("[**********]").add_pattern(Pattern {
|
||||
test: Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
|
||||
group: 1,
|
||||
});
|
||||
|
||||
Self {
|
||||
redact_engine: RwLock::new(Some(redact_engine)),
|
||||
patterns: RwLock::new(vec![
|
||||
Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_value(&self, text: &str) -> anyhow::Result<()> {
|
||||
let mut redact_engine = self
|
||||
.redact_engine
|
||||
.write()
|
||||
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
|
||||
|
||||
*redact_engine = Some(
|
||||
redact_engine
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
|
||||
.add_value(text)?,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
self.add_values(&[text])
|
||||
}
|
||||
|
||||
pub fn add_values(&self, texts: &[&str]) -> anyhow::Result<()> {
|
||||
let mut redact_engine = self
|
||||
.redact_engine
|
||||
let patterns = texts
|
||||
.iter()
|
||||
.map(|text| Regex::new(®ex::escape(text)))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
self
|
||||
.patterns
|
||||
.write()
|
||||
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
|
||||
|
||||
*redact_engine = Some(
|
||||
redact_engine
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
|
||||
.add_values(texts.to_vec())?,
|
||||
);
|
||||
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redaction patterns"))?
|
||||
.extend(patterns);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn redact_str(&self, text: &str) -> String {
|
||||
self
|
||||
.redact_engine
|
||||
let patterns = self
|
||||
.patterns
|
||||
.read()
|
||||
.expect("Failed to acquire read lock on redact engine")
|
||||
.as_ref()
|
||||
.expect("Failed to get redact engine")
|
||||
.redact_str(text)
|
||||
.expect("Failed to acquire read lock on redaction patterns");
|
||||
let mut redacted = text.to_owned();
|
||||
// Match the original text, then replace in registration order. Matching the
|
||||
// replacements would change how overlapping values are redacted.
|
||||
for pattern in patterns.iter() {
|
||||
for matched in pattern.find_iter(text) {
|
||||
redacted = redacted.replacen(matched.as_str(), "[**********]", 1);
|
||||
}
|
||||
}
|
||||
redacted
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +168,38 @@ fn redact_query(query: Option<&str>) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn redacts_repeated_ipv4_addresses() {
|
||||
assert_eq!(
|
||||
Redaction::new().redact_str("from 192.0.2.1 to 198.51.100.9, then 192.0.2.1"),
|
||||
"from [**********] to [**********], then [**********]"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_values_are_literal_and_support_unicode() {
|
||||
let redaction = Redaction::new();
|
||||
redaction.add_values(&["a.b+$[x]", "秘密🔑"]).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
redaction.redact_str("a.b+$[x] 秘密🔑 a.b+$[x] aXb"),
|
||||
"[**********] [**********] [**********] aXb"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_values_keep_registration_order() {
|
||||
let redaction = Redaction::new();
|
||||
redaction.add_values(&["foobar", "foo"]).unwrap();
|
||||
|
||||
assert_eq!(redaction.redact_str("foobar foo"), "[**********] [**********]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_word_characters_preserve_ipv4_boundaries() {
|
||||
assert_eq!(Redaction::new().redact_str("192.0.2.1é"), "192.0.2.1é");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_should_not_redact_value() {
|
||||
let text = "fo";
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use openssl::{pkey::PKey, x509::X509};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{identity_encoding, pkcs12_identity};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
#[error("Failed to find the private key")]
|
||||
@@ -13,6 +14,24 @@ pub enum RequestIdentityError {
|
||||
NoPassphrase(&'static str),
|
||||
#[error("Failed to decrypt private key")]
|
||||
DecryptError(&'static str),
|
||||
#[error(
|
||||
"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")]
|
||||
InvalidKey,
|
||||
#[error("Invalid certificate or certificate chain")]
|
||||
InvalidCertificate,
|
||||
#[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),
|
||||
}
|
||||
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
@@ -41,37 +60,17 @@ impl fmt::Debug for ClientIdentity {
|
||||
impl ClientIdentity {
|
||||
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
|
||||
let certificate_bytes = read_identity_file(certificate)?;
|
||||
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
return Self::from_data(certificate_bytes, None, Some(passphrase));
|
||||
let extension = Path::new(certificate).extension().and_then(|value| value.to_str());
|
||||
if extension.is_some_and(|value| value.eq_ignore_ascii_case("p12") || value.eq_ignore_ascii_case("pfx")) {
|
||||
return Self::from_data(certificate_bytes, None, passphrase);
|
||||
}
|
||||
let key_bytes = match key {
|
||||
Some(path) => read_identity_file(path)?,
|
||||
None => certificate_bytes.clone(),
|
||||
};
|
||||
// Keep the previous first-private-key rule: unrelated later blocks must not
|
||||
// change which key is selected or whether the caller is prompted.
|
||||
let key = pem::parse_many(&*key_bytes)?
|
||||
.into_iter()
|
||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
let key_pem = Zeroizing::new(pem::encode(&key));
|
||||
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
|
||||
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
|
||||
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
|
||||
} else {
|
||||
Zeroizing::new(key_pem.as_bytes().to_vec())
|
||||
};
|
||||
// Strip private-key blocks before importing the certificate chain: macOS
|
||||
// otherwise imports the same key twice for combined PEM files.
|
||||
let mut certificate = Zeroizing::new(Vec::new());
|
||||
for cert in X509::stack_from_pem(&certificate_bytes)? {
|
||||
certificate.extend(cert.to_pem()?);
|
||||
}
|
||||
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
|
||||
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
|
||||
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
|
||||
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
|
||||
let identity = pem_request_identity(&certificate, &key)?;
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
@@ -90,12 +89,21 @@ impl ClientIdentity {
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
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)
|
||||
}
|
||||
})?;
|
||||
(
|
||||
Identity::from_pkcs12_der(&certificate, passphrase)?,
|
||||
Some(Zeroizing::new(passphrase.to_owned())),
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -152,6 +160,20 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
.context(error_context)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
Ok(Zeroizing::new(
|
||||
fs::read(path).context("Failed to read client identity")?,
|
||||
@@ -189,50 +211,15 @@ pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>)
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
|
||||
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "identity-fixture").unwrap();
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&name).unwrap();
|
||||
certificate.set_issuer_name(&name).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(
|
||||
certificate.build().to_pem().unwrap(),
|
||||
key.private_key_to_pem_pkcs8().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
|
||||
.unwrap();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(&encrypted).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
const CERTIFICATE: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-cert.pem");
|
||||
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
|
||||
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
|
||||
|
||||
#[test]
|
||||
fn pem_without_key_reports_missing_key_even_with_passphrase() {
|
||||
let (certificate, _) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
for passphrase in [None, Some("unused")] {
|
||||
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
|
||||
assert!(matches!(
|
||||
@@ -244,249 +231,57 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn local_identity_loading_is_not_limited_by_service_message_size() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(KEY).unwrap();
|
||||
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
assert_eq!(identity.certificate_data(), CERTIFICATE);
|
||||
assert_eq!(identity.key_data().unwrap(), KEY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
|
||||
cert_file.write_all(&certificate).unwrap();
|
||||
let mut key_file = tempfile::NamedTempFile::new().unwrap();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
|
||||
.unwrap();
|
||||
key_file.write_all(&encrypted).unwrap();
|
||||
let cert = cert_file.path().to_str().unwrap();
|
||||
let key_path = Some(key_file.path().to_str().unwrap());
|
||||
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>().unwrap() {
|
||||
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
|
||||
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other}"),
|
||||
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
for (password, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other:?}"),
|
||||
}
|
||||
}
|
||||
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
|
||||
assert_eq!(loaded.key_data().unwrap(), key);
|
||||
fs::write(key_file.path(), &key).unwrap();
|
||||
for passphrase in [None, Some("ignored for unencrypted key")] {
|
||||
assert_eq!(
|
||||
ClientIdentity::load(cert, key_path, passphrase)
|
||||
.unwrap()
|
||||
.key_data()
|
||||
.unwrap(),
|
||||
key
|
||||
);
|
||||
}
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
reqwest::Client::builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
|
||||
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (certificate, key) = generated_identity();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
let mut combined = certificate.clone();
|
||||
combined.extend(&key);
|
||||
fs::write(&source, &combined).unwrap();
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
fs::write(&source, "changed after authentication").unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
|
||||
let files = identity.write_files(Some(directory.path())).unwrap();
|
||||
let certificate_path = files.certificate().to_owned();
|
||||
let key_path = files.key().unwrap().to_owned();
|
||||
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
|
||||
assert_eq!(fs::read(&key_path).unwrap(), key);
|
||||
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let identity = ClientIdentity::from_data(
|
||||
Zeroizing::new(CERTIFICATE.to_vec()),
|
||||
Some(Zeroizing::new(KEY.to_vec())),
|
||||
Some("unused password"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(identity.key_password().is_none());
|
||||
let archive = include_bytes!("../../tests/files/client-identity/modern.p12").to_vec();
|
||||
let identity = ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
|
||||
let files = identity.write_files(None).unwrap();
|
||||
let path = files.certificate().to_owned();
|
||||
assert!(path.ends_with(".p12"));
|
||||
assert!(files.key().is_none());
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&certificate_path).exists());
|
||||
assert!(!Path::new(&key_path).exists());
|
||||
// The request identity remains valid after its original files disappear.
|
||||
fs::remove_file(&source).unwrap();
|
||||
assert!(!Path::new(&path).exists());
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let certificate = X509::from_pem(&certificate).unwrap();
|
||||
let key = PKey::private_key_from_pem(&key).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("identity-fixture").pkey(&key).cert(&certificate);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
for suffix in [".p12", ".pfx"] {
|
||||
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let path = source.path().to_str().unwrap();
|
||||
assert!(ClientIdentity::load(path, None, None).is_err());
|
||||
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
|
||||
// PKCS#12 has always ignored a separately configured key path.
|
||||
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
|
||||
fs::write(source.path(), b"replaced after login").unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
assert_eq!(identity.key_password(), Some("fixture-password"));
|
||||
assert!(!format!("{identity:?}").contains("fixture-password"));
|
||||
let files = identity.write_files(None).unwrap();
|
||||
assert!(files.certificate().ends_with(".p12"));
|
||||
assert!(files.key().is_none());
|
||||
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
|
||||
let owned_path = files.certificate().to_owned();
|
||||
drop(files);
|
||||
assert!(!Path::new(&owned_path).exists());
|
||||
}
|
||||
let empty_password = builder.build2("").unwrap().to_der().unwrap();
|
||||
// Empty-password support varies by native backend and PKCS#12 algorithms.
|
||||
// Match the previous native import instead of introducing another parser.
|
||||
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
|
||||
previously_accepted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
rsa::Rsa,
|
||||
stack::Stack,
|
||||
x509::{X509NameBuilder, extension::BasicConstraints},
|
||||
};
|
||||
fn certificate(
|
||||
name: &str,
|
||||
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
|
||||
ca: bool,
|
||||
) -> (X509, PKey<openssl::pkey::Private>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut subject = X509NameBuilder::new().unwrap();
|
||||
subject.append_entry_by_text("CN", name).unwrap();
|
||||
let subject = subject.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
|
||||
.unwrap()
|
||||
.to_asn1_integer()
|
||||
.unwrap();
|
||||
cert.set_serial_number(&serial).unwrap();
|
||||
cert.set_subject_name(&subject).unwrap();
|
||||
cert
|
||||
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
|
||||
.unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
if ca {
|
||||
cert
|
||||
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
cert
|
||||
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
|
||||
.unwrap();
|
||||
(cert.build(), key)
|
||||
}
|
||||
let (root, root_key) = certificate("root", None, true);
|
||||
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
|
||||
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
|
||||
// This is the reverse CA stack consumed by the previous native-tls path.
|
||||
let mut ca = Stack::new().unwrap();
|
||||
ca.push(root.clone()).unwrap();
|
||||
ca.push(intermediate.clone()).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
ClientIdentity::from_data(
|
||||
Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
None,
|
||||
identity.key_password(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_from_pem_requires_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let identity = create_identity(cert, None, None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_with_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity(cert, None, Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_unencrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
let identity = create_identity(cert, None, None);
|
||||
println!("{:?}", identity);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_cert_and_encrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity(cert, Some(key), Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_from_pem_cert_and_encrypted_key_no_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_cert_and_unencrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
//! Public identity compatibility and native import behavior.
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
|
||||
|
||||
const PASSWORD: &str = "fixture-password";
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn load(certificate: &str, key: &str, password: Option<&str>) -> anyhow::Result<ClientIdentity> {
|
||||
ClientIdentity::load(
|
||||
fixture(certificate).to_str().unwrap(),
|
||||
Some(fixture(key).to_str().unwrap()),
|
||||
password,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsa_pkcs8_loads_without_a_password() {
|
||||
let identity = load("rsa-cert.pem", "rsa-pkcs8.pem", None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), fs::read(fixture("rsa-cert.pem")).unwrap());
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_pkcs8_records_native_import_compatibility() {
|
||||
let result = load("ec-cert.pem", "ec-pkcs8.pem", None);
|
||||
if cfg!(target_os = "macos") {
|
||||
// Apple native-tls import currently rejects this P-256 PKCS#8 fixture.
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.unwrap().key_data().unwrap(),
|
||||
fs::read(fixture("ec-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_pkcs8_keys_normalize_to_the_same_private_key() {
|
||||
for (key, expected, certificate) in [
|
||||
("rsa-pbes2-sha1.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-sha256.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-aes-128-cbc-sha1.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-aes-128-cbc-sha256.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-aes-192-cbc-sha1.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-aes-192-cbc-sha256.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("rsa-pbes2-scrypt.pem", "rsa-pkcs8.pem", "rsa-cert.pem"),
|
||||
("ec-pbes2.pem", "ec-pkcs8.pem", "ec-cert.pem"),
|
||||
] {
|
||||
let result = load(certificate, key, Some(PASSWORD));
|
||||
if cfg!(target_os = "macos") && certificate == "ec-cert.pem" {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture(expected)).unwrap(),
|
||||
"{key}"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
}
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load(certificate, key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("{key}: unexpected error {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_pem_preserves_the_certificate_chain_and_removes_key_blocks() {
|
||||
let mut chain = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
chain.extend(fs::read(fixture("root.pem")).unwrap());
|
||||
let mut combined = chain.clone();
|
||||
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
combined.extend(&key);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
fs::write(&source, combined).unwrap();
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rsa_pkcs1_normalizes_to_pkcs8_in_separate_and_combined_files() {
|
||||
let certificate = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
let expected = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
for password in [None, Some("unused")] {
|
||||
let identity = load("rsa-cert.pem", "rsa-pkcs1.pem", password).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), expected);
|
||||
assert!(identity.key_password().is_none());
|
||||
}
|
||||
|
||||
let mut combined = certificate.clone();
|
||||
combined.extend(fs::read(fixture("rsa-pkcs1.pem")).unwrap());
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
fs::write(&source, combined).unwrap();
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_rsa_pkcs1_is_rejected_by_native_import() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("invalid-key.pem");
|
||||
fs::write(&source, pem::encode(&pem::Pem::new("RSA PRIVATE KEY", vec![0x30, 0]))).unwrap();
|
||||
let error = ClientIdentity::load(
|
||||
fixture("rsa-cert.pem").to_str().unwrap(),
|
||||
Some(source.to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<reqwest::Error>().is_some());
|
||||
}
|
||||
|
||||
fn check_archive(name: &str, password: &str) {
|
||||
let source = fixture(name);
|
||||
let path = source.to_str().unwrap();
|
||||
let identity = ClientIdentity::load(path, None, Some(password)).unwrap();
|
||||
assert_eq!(identity.certificate_data(), fs::read(&source).unwrap());
|
||||
assert!(identity.key_data().is_none());
|
||||
assert_eq!(identity.key_password(), Some(password));
|
||||
let files = identity.write_files(None).unwrap();
|
||||
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
|
||||
assert!(ClientIdentity::load(path, None, Some("incorrect")).is_err());
|
||||
let error = ClientIdentity::load(path, None, None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PKCS#12"))
|
||||
));
|
||||
// The MAC is at the end of these fixtures. Change authenticated archive data
|
||||
// (a byte in the friendly name), leaving valid ASN.1 and ciphertext intact.
|
||||
let mut corrupted = fs::read(&source).unwrap();
|
||||
let label = [0, b'f', 0, b'i', 0, b'x', 0, b't', 0, b'u', 0, b'r', 0, b'e'];
|
||||
let offset = corrupted
|
||||
.windows(label.len())
|
||||
.position(|window| window == label)
|
||||
.unwrap();
|
||||
corrupted[offset + 1] = b'F';
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let damaged = directory.path().join("damaged.p12");
|
||||
fs::write(&damaged, corrupted).unwrap();
|
||||
assert!(ClientIdentity::load(damaged.to_str().unwrap(), None, Some(password)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_pkcs12_reports_that_both_certificate_and_key_are_required() {
|
||||
for name in ["certificate-only.pfx", "key-only.pfx"] {
|
||||
let bytes = fs::read(fixture(name)).unwrap();
|
||||
for result in [
|
||||
ClientIdentity::load(fixture(name).to_str().unwrap(), None, Some(PASSWORD)),
|
||||
ClientIdentity::from_data(zeroize::Zeroizing::new(bytes.clone()), None, Some(PASSWORD)),
|
||||
] {
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"The PKCS#12 file must contain both a client certificate and its private key",
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modern_pkcs12_checks_password_and_archive_integrity() {
|
||||
check_archive("modern.p12", PASSWORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_password_errors_explain_how_to_recover() {
|
||||
let archive = fs::read(fixture("modern.p12")).unwrap();
|
||||
for password in ["incorrect", ""] {
|
||||
let errors = [
|
||||
ClientIdentity::load(fixture("modern.p12").to_str().unwrap(), None, Some(password)).unwrap_err(),
|
||||
ClientIdentity::from_data(zeroize::Zeroizing::new(archive.clone()), None, Some(password)).unwrap_err(),
|
||||
];
|
||||
for error in errors {
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::InvalidPkcs12(_))
|
||||
));
|
||||
let message = error.to_string();
|
||||
assert!(message.contains("PKCS#12"), "{message}");
|
||||
assert!(message.contains("password") && message.contains("file"), "{message}");
|
||||
assert!(!format!("{error:?}").contains("incorrect"));
|
||||
assert!(error.chain().any(|cause| cause.is::<reqwest::Error>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// Apple's native importer rejects this empty-password fixture; its native
|
||||
// compatibility decision is covered by archive_snapshot_and_pfx_preserve_native_import_contract.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn empty_pkcs12_password_survives_loading_and_transport() {
|
||||
let archive = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
for password in [None, Some("")] {
|
||||
let loaded = ClientIdentity::load(fixture("empty-password.p12").to_str().unwrap(), None, password).unwrap();
|
||||
assert_eq!(loaded.key_password(), Some(""));
|
||||
let restored = ClientIdentity::from_data(zeroize::Zeroizing::new(archive.clone()), None, password).unwrap();
|
||||
assert_eq!(restored.key_password(), Some(""));
|
||||
let files = restored.write_files(None).unwrap();
|
||||
ClientIdentity::load(files.certificate(), files.key(), restored.key_password()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_accepts_non_ascii_passwords() {
|
||||
check_archive("unicode-password.p12", "pässword-密码");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_rc2_pkcs12_checks_password_and_archive_integrity() {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if std::env::var_os("GP_IDENTITY_LEGACY_TEST_CHILD").is_none() {
|
||||
// OpenSSL providers are process-global. Exercise the existing legacy-mode
|
||||
// configuration in an isolated process, without affecting parallel tests.
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let config = directory.path().join("openssl.cnf");
|
||||
fs::write(&config, gpapi::utils::openssl::openssl_conf()).unwrap();
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_rc2_pkcs12_checks_password_and_archive_integrity",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("OPENSSL_CONF", config)
|
||||
.env("GP_IDENTITY_LEGACY_TEST_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
check_archive("legacy-rc2.p12", PASSWORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_certificate_and_private_key_data_are_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let invalid = directory.path().join("invalid.pem");
|
||||
fs::write(&invalid, b"not a certificate or private key").unwrap();
|
||||
assert!(
|
||||
ClientIdentity::load(
|
||||
invalid.to_str().unwrap(),
|
||||
Some(fixture("rsa-pkcs8.pem").to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let error = ClientIdentity::load(
|
||||
fixture("rsa-cert.pem").to_str().unwrap(),
|
||||
Some(invalid.to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::InvalidKey)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbes2_legacy_ciphers_remain_supported() {
|
||||
for key in ["rsa-pbes2-des3-sha1.pem", "rsa-pbes2-des3-sha256.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load("rsa-cert.pem", key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("{key}: unexpected error {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() {
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("unexpected legacy password error: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn legacy_pkcs8_matches_previous_linux_openssl_processing() {
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
let previous = openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, PASSWORD.as_bytes())
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8()
|
||||
.unwrap();
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), previous);
|
||||
assert!(openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, b"incorrect").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
const CHILD: &str = "GP_LEGACY_CONVERTER_TEST";
|
||||
if let Ok(case) = std::env::var(CHILD) {
|
||||
let started = std::time::Instant::now();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap_err();
|
||||
assert!(
|
||||
started.elapsed() < std::time::Duration::from_secs(12),
|
||||
"conversion exceeded its deadline"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
let message = format!("{error:?}");
|
||||
assert!(message.contains("Convert the key to modern PKCS#8"));
|
||||
assert!(!message.contains(PASSWORD));
|
||||
assert!(!message.contains("PRIVATE KEY"));
|
||||
if case == "missing" {
|
||||
assert!(message.contains("unavailable"));
|
||||
} else if case.starts_with("timeout") {
|
||||
assert!(message.contains("timed out"));
|
||||
}
|
||||
for key in ["rsa-pkcs8.pem", "rsa-pbes2-sha256.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// PATH is process-global; isolate executable discovery from parallel tests.
|
||||
for (case, script) in [
|
||||
("missing", None),
|
||||
(
|
||||
"unsupported",
|
||||
Some("#!/bin/sh\nprintf 'unsupported: fixture-password PRIVATE KEY' >&2\nexit 1\n"),
|
||||
),
|
||||
("invalid-output", Some("#!/bin/sh\nprintf 'invalid converted key'\n")),
|
||||
("timeout-wrapper", Some("#!/bin/sh\n/bin/sleep 14\n")),
|
||||
("timeout-exited-wrapper", Some("#!/bin/sh\n/bin/sleep 14 &\nexit 0\n")),
|
||||
] {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
if let Some(script) = script {
|
||||
let executable = directory.path().join("openssl");
|
||||
fs::write(&executable, script).unwrap();
|
||||
fs::set_permissions(executable, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("PATH", directory.path())
|
||||
.env(CHILD, case)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "converter case: {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_converter_reports_its_password_length_limit_without_requesting_a_retry() {
|
||||
let password = "x".repeat(1024);
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des-password-1024.pem")).unwrap();
|
||||
// The previous linked API accepted this boundary. The CLI cannot carry it;
|
||||
// report that limitation rather than calling the correct password wrong.
|
||||
openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, password.as_bytes()).unwrap();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des-password-1024.pem", Some(&password)).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
assert!(error.to_string().contains("1023-byte"));
|
||||
let accepted = load(
|
||||
"rsa-cert.pem",
|
||||
"rsa-pbes1-3des-password-1023.pem",
|
||||
Some(&"x".repeat(1023)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
accepted.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords() {
|
||||
let original = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
for password in [
|
||||
PASSWORD,
|
||||
"incorrect",
|
||||
"password\nsecond line",
|
||||
"password\r",
|
||||
"password\0",
|
||||
] {
|
||||
let result = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(password));
|
||||
if password == PASSWORD {
|
||||
result.unwrap();
|
||||
} else if password != "incorrect" {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
));
|
||||
} else {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::DecryptError("PEM"))
|
||||
));
|
||||
}
|
||||
assert_eq!(fs::read(fixture("rsa-pbes1-3des.pem")).unwrap(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_key_selection_controls_password_prompt_and_ignores_later_keys() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
let certificate = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
let plain = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
let encrypted = fs::read(fixture("rsa-pbes2-sha256.pem")).unwrap();
|
||||
for (first, second, needs_password) in [(&plain, &encrypted, false), (&encrypted, &plain, true)] {
|
||||
let mut combined = certificate.clone();
|
||||
combined.extend(first);
|
||||
combined.extend(second);
|
||||
fs::write(&source, combined).unwrap();
|
||||
if needs_password {
|
||||
let error = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
}
|
||||
let identity = ClientIdentity::load(
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
if needs_password { Some(PASSWORD) } else { None },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), plain);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_pem_round_trip_retains_snapshot_and_private_file_lifecycle() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use zeroize::Zeroizing;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("identity.pem");
|
||||
let mut combined = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
combined.extend(fs::read(fixture("rsa-pkcs8.pem")).unwrap());
|
||||
fs::write(&source, combined).unwrap();
|
||||
let loaded = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
let snapshot = ClientIdentity::from_data(
|
||||
Zeroizing::new(loaded.certificate_data().to_vec()),
|
||||
Some(Zeroizing::new(loaded.key_data().unwrap().to_vec())),
|
||||
Some("unused-pem-password"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&source, b"replaced after authentication").unwrap();
|
||||
drop(loaded);
|
||||
let clone = snapshot.clone();
|
||||
drop(snapshot);
|
||||
assert!(clone.key_password().is_none());
|
||||
let debug = format!("{clone:?}");
|
||||
assert!(debug.contains("<redacted>"));
|
||||
assert!(!debug.contains("PRIVATE KEY"));
|
||||
assert!(!debug.contains("unused-pem-password"));
|
||||
let files = clone.write_files(Some(directory.path())).unwrap();
|
||||
let certificate = PathBuf::from(files.certificate());
|
||||
let key = PathBuf::from(files.key().unwrap());
|
||||
for path in [&certificate, &key] {
|
||||
assert_eq!(fs::metadata(path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
assert_eq!(fs::read(&certificate).unwrap(), clone.certificate_data());
|
||||
assert_eq!(fs::read(&key).unwrap(), clone.key_data().unwrap());
|
||||
ClientIdentity::load(files.certificate(), files.key(), None).unwrap();
|
||||
drop(files);
|
||||
assert!(!certificate.exists() && !key.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_snapshot_and_pfx_preserve_native_import_contract() {
|
||||
use zeroize::Zeroizing;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("identity.pfx");
|
||||
let data = fs::read(fixture("modern.p12")).unwrap();
|
||||
fs::write(&path, &data).unwrap();
|
||||
let identity = ClientIdentity::load(path.to_str().unwrap(), Some("nonexistent-key"), Some(PASSWORD)).unwrap();
|
||||
fs::remove_file(path).unwrap();
|
||||
let restored = ClientIdentity::from_data(
|
||||
Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
None,
|
||||
identity.key_password(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(restored.certificate_data(), data);
|
||||
assert_eq!(restored.key_password(), Some(PASSWORD));
|
||||
assert!(restored.key_data().is_none());
|
||||
assert!(!format!("{restored:?}").contains(PASSWORD));
|
||||
let empty = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
// Preserve the native backend's existing empty-password decision.
|
||||
let expected = reqwest::Identity::from_pkcs12_der(&empty, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty), None, Some("")).is_ok(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_certificate_der_and_private_key_der_are_rejected_without_secret_output() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let invalid = directory.path().join("invalid.pem");
|
||||
for (tag, invalid_certificate) in [("CERTIFICATE", true), ("PRIVATE KEY", false)] {
|
||||
let invalid_der = b"secret-invalid-der-material";
|
||||
fs::write(&invalid, pem::encode(&pem::Pem::new(tag, invalid_der))).unwrap();
|
||||
let result = if invalid_certificate {
|
||||
ClientIdentity::load(
|
||||
invalid.to_str().unwrap(),
|
||||
Some(fixture("rsa-pkcs8.pem").to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
} else {
|
||||
ClientIdentity::load(
|
||||
fixture("rsa-cert.pem").to_str().unwrap(),
|
||||
Some(invalid.to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
for message in [error.to_string(), format!("{error:?}")] {
|
||||
assert!(!message.contains("secret-invalid-der-material"));
|
||||
assert!(!message.contains("c2VjcmV0LWludmFsaWQtZGVyLW1hdGVyaWFs"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbes2_des_remains_supported_without_native_legacy_provider() {
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes2-des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load("rsa-cert.pem", "rsa-pbes2-des.pem", password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("unexpected error {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_unsupported_pbes2_algorithm(oid_der: &[u8]) {
|
||||
let mut encrypted = pem::parse(fs::read(fixture("rsa-pbes2-sha256.pem")).unwrap()).unwrap();
|
||||
let mut der = encrypted.contents().to_vec();
|
||||
let matches: Vec<_> = der
|
||||
.windows(oid_der.len())
|
||||
.enumerate()
|
||||
.filter_map(|(offset, window)| (window == oid_der).then_some(offset))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
matches.len(),
|
||||
1,
|
||||
"the fixture must contain exactly the intended algorithm OID"
|
||||
);
|
||||
// An unknown OID in the same arc preserves ASN.1 structure and algorithm
|
||||
// parameters, isolating algorithm recognition from malformed DER handling.
|
||||
der[matches[0] + oid_der.len() - 1] = 0x7f;
|
||||
encrypted = pem::Pem::new(encrypted.tag(), der);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("unsupported.pem");
|
||||
fs::write(&source, pem::encode(&encrypted)).unwrap();
|
||||
for password in [None, Some(PASSWORD), Some("incorrect")] {
|
||||
let error = ClientIdentity::load(
|
||||
fixture("rsa-cert.pem").to_str().unwrap(),
|
||||
Some(source.to_str().unwrap()),
|
||||
password,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
let message = error.to_string().to_lowercase();
|
||||
assert!(
|
||||
message.contains("unsupported") && message.contains("encryption"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_pbes2_kdf_is_identified_before_password_prompt() {
|
||||
// PBKDF2, 1.2.840.113549.1.5.12.
|
||||
assert_unsupported_pbes2_algorithm(&[0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_pbes2_cipher_is_identified_before_password_prompt() {
|
||||
// AES256-CBC, 2.16.840.1.101.3.4.1.42.
|
||||
assert_unsupported_pbes2_algorithm(&[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_pbes2_prf_is_identified_before_password_prompt() {
|
||||
// HMAC-SHA256, 1.2.840.113549.2.9.
|
||||
assert_unsupported_pbes2_algorithm(&[0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x09]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_encrypted_pkcs8_does_not_request_a_password_or_expose_material() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("malformed.pem");
|
||||
fs::write(
|
||||
&source,
|
||||
pem::encode(&pem::Pem::new(
|
||||
"ENCRYPTED PRIVATE KEY",
|
||||
b"secret-malformed-encrypted-key",
|
||||
)),
|
||||
)
|
||||
.unwrap();
|
||||
for password in [None, Some(PASSWORD), Some("incorrect")] {
|
||||
let error = ClientIdentity::load(
|
||||
fixture("rsa-cert.pem").to_str().unwrap(),
|
||||
Some(source.to_str().unwrap()),
|
||||
password,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(!matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase(_) | RequestIdentityError::DecryptError(_))
|
||||
));
|
||||
for message in [error.to_string(), format!("{error:?}")] {
|
||||
assert!(!message.contains("secret-malformed-encrypted-key"));
|
||||
assert!(!message.contains("c2VjcmV0LW1hbGZvcm1lZC1lbmNyeXB0ZWQta2V5"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_certificate_key_is_rejected_before_request_client_creation() {
|
||||
let certificate = fs::read(fixture("root.pem")).unwrap();
|
||||
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
let error = load("root.pem", "rsa-pkcs8.pem", None).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
let error = ClientIdentity::from_data(certificate.into(), Some(key.into()), None).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
# Public client identity fixtures
|
||||
|
||||
These generated keys and certificates are **public test data**, never production
|
||||
credentials. Passwords are `fixture-password`, except `unicode-password.p12`,
|
||||
which uses `pässword-密码`, and the `rsa-pbes1-3des-password-{1023,1024}.pem`
|
||||
fixtures, which use `x` repeated the indicated number of bytes.
|
||||
|
||||
Regenerate intentionally with OpenSSL 3:
|
||||
|
||||
```sh
|
||||
OPENSSL_BIN=/path/to/openssl bash generate.sh
|
||||
```
|
||||
|
||||
Generation is random; it replaces the keys, certificates, and archives together.
|
||||
The test runner reads checked-in files. Legacy standalone conversion tests
|
||||
require an `openssl` executable on PATH (OpenSSL or compatible LibreSSL).
|
||||
No fixture generation is needed to run the tests.
|
||||
|
||||
| Files | Contents |
|
||||
| --- | --- |
|
||||
| `root.pem`, `rsa-cert.pem`, `ec-cert.pem` | Test root and issued RSA-2048 / P-256 client certificates, SHA256 signatures |
|
||||
| `rsa-pkcs8.pem`, `ec-pkcs8.pem` | Plain PKCS#8 keys; expected normalized output |
|
||||
| `rsa-pkcs1.pem`, `ec-sec1.pem` | Same keys in traditional containers |
|
||||
| `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` |
|
||||
| `rsa-pbes2-sha1.pem`, `rsa-pbes2-sha256.pem` | Encrypted PKCS#8, AES256-CBC/PBKDF2 with SHA1 or SHA256 PRF |
|
||||
| `rsa-pbes2-aes-{128,192}-cbc-{sha1,sha256}.pem` | AES128/192-CBC with PBKDF2 SHA1/SHA256 |
|
||||
| `rsa-pbes2-des3-{sha1,sha256}.pem` | PBES2 3DES-CBC with PBKDF2 SHA1/SHA256; distinct from the legacy PBE scheme handled by optional conversion |
|
||||
| `rsa-pbes2-des.pem` | PBES2 DES-CBC/PBKDF2-SHA256; Rust processing requires no native legacy provider |
|
||||
| `rsa-pbes2-scrypt.pem` | PBES2 AES256-CBC with scrypt |
|
||||
| `rsa-pbes1-3des-password-{1023,1024}.pem` | Same legacy encryption with passwords at the CLI input boundary; the linked importer accepts 1024 bytes, while the converter reports its 1023-byte limit explicitly |
|
||||
| `rsa-pbes1-3des.pem` | Legacy PKCS#12 SHA1/3DES scheme inside standalone encrypted PKCS#8; optional OpenSSL executable conversion case |
|
||||
| `empty-password.p12` | RSA leaf/key/root with an empty password, preserving native backend acceptance |
|
||||
| `ec-pbes2.pem` | Encrypted EC PKCS#8, AES256-CBC/PBKDF2-SHA256 |
|
||||
| `modern.p12`, `unicode-password.p12` | Leaf/key/root, AES256-CBC/PBKDF2-SHA256, SHA256 MAC; RSA and EC respectively |
|
||||
| `certificate-only.pfx`, `key-only.pfx` | Incomplete PKCS#12 archives: certificate without key, and key without certificate; password `fixture-password` |
|
||||
| `legacy-rc2.p12` | Issue #437 case: RC2-40 certificate bags, SHA1/3DES key bag, SHA1 MAC |
|
||||
|
||||
`tests/client_identity.rs` records native import compatibility and the owned
|
||||
identity lifecycle. `tests/identity_encoding.rs` covers container normalization:
|
||||
DER certificates and keys, RSA PKCS#1, Linux/BSD EC SEC1 and traditional encrypted
|
||||
PEM, first-key selection, malformed encryption headers, and archive extension
|
||||
capitalization. macOS rejects SEC1 and traditional encrypted PEM before password
|
||||
handling. Its native importer also rejects the P-256 PKCS#8 PEM fixture, although
|
||||
its native PKCS#12 import accepts the EC archive. Legacy-provider setup is isolated
|
||||
in a child process on Linux/BSD.
|
||||
|
||||
Standalone PKCS#8 PBE-SHA1-3DES uses optional OpenSSL executable conversion,
|
||||
with missing/wrong passwords preserving the old Linux prompt/retry contract.
|
||||
Other unsupported schemes retain explicit conversion guidance. PBES2 DES/3DES
|
||||
use Rust processing and need no executable. Child-process tests isolate PATH
|
||||
for absent/unsupported/stalled converters, invalid output, and secret-free errors.
|
||||
Timeout coverage includes wrappers whose descendants retain pipes after the
|
||||
wrapper exits or is killed; all pipe I/O shares the process deadline.
|
||||
Linux/BSD additionally compare the result with the former linked OpenSSL importer.
|
||||
|
||||
The tests check archive integrity by changing the UTF-16 friendly name without
|
||||
changing the MAC, and compare normalized PEM output against the independent
|
||||
checked-in plaintext key. Public integration tests cover first-key selection,
|
||||
retained snapshots, private-file permissions and cleanup, `.pfx`, empty-password
|
||||
backend behavior, and chain retention. Unit tests in `utils/request.rs` cover
|
||||
missing keys, large local files, and native request-client construction.
|
||||
Binary file not shown.
@@ -0,0 +1,14 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICMDCCARigAwIBAgIBCjANBgkqhkiG9w0BAQsFADAgMR4wHAYDVQQDDBVHUCBJ
|
||||
ZGVudGl0eSBUZXN0IFJvb3QwHhcNMjYxMDE3MTQxNzM0WhcNMzYxMDE0MTQxNzM0
|
||||
WjAeMRwwGgYDVQQDDBNHUCBJZGVudGl0eSBUZXN0IGVjMFkwEwYHKoZIzj0CAQYI
|
||||
KoZIzj0DAQcDQgAEQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRWqTI/q
|
||||
BIwba6G3zcnZaArnCw+XsMsBvTtphuiDHouPW6NCMEAwHQYDVR0OBBYEFGySvrUf
|
||||
Wg99yhlvRHe5VcdQV+6sMB8GA1UdIwQYMBaAFNxaJz5kx8+buL1L+wnHUfOmNKDR
|
||||
MA0GCSqGSIb3DQEBCwUAA4IBAQCT4yKBspPRj66lz7y1KjMh0Ju/rVtBlE4pVtbb
|
||||
BYGi29kKVwJyv1GnzKGsbiW7YFEvcBiQFiPV1veab4UR90ESm/SUFXCzwhCkCkQr
|
||||
sYO/tDSyh4vO9zstpN6524lhnEhNqhxrDjwlbHov9Ycsk7nchR2ZXYe7NPF2SZQ3
|
||||
j+NWgOAGHk+xveyfev1sQV8oYn4WL550D0DfCDIVc2n7UdQ2MPw/fvNd1hI6uBUl
|
||||
BrYV+BKeeghn7p7NsesfXqVIuXYbgJ7GFwNh3s3Kdx3p1DQZ37f4P3reSBc7i03+
|
||||
9GmRlPj62a8GnxXFoCcfH4HHp6LkUptZTtHkgyVbsS1Uayj1
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIH0MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBBP0Qie1d771HAwIaHr
|
||||
16KPAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQJKzM5wh1ay4NLYmy
|
||||
CL43wQSBkLXODq5G55naOF0acp52yJseQ/gpFxKweaqh+dbErhComdC1WW6X1m3x
|
||||
yQZTSGkn9BXXovKbpNPgPbPb7Oks1TEQU33RMi6t89tbZHj757yEY0b+WPpH5Y1g
|
||||
JUE/r2kqpdki7oz5d38R0j7eD1sG/cOvpnkq1jVzp32wRp3cKugLOWx/dC45AhzP
|
||||
X1ZAbDubOg==
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,5 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgwiAZclkH//xmntM5
|
||||
q9LIH7sus8oUbh5BnwXHHfRtPNShRANCAARCb8yN/N6VTBYHE1F66qyust8GzXKA
|
||||
d6pfo1cEItbJFapMj+oEjBtrobfNydloCucLD5ewywG9O2mG6IMei49b
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,5 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIMIgGXJZB//8Zp7TOavSyB+7LrPKFG4eQZ8Fxx30bTzUoAoGCCqGSM49
|
||||
AwEHoUQDQgAEQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRWqTI/qBIwb
|
||||
a6G3zcnZaArnCw+XsMsBvTtphuiDHouPWw==
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-128-CBC,EDBB75FE8E4A9290FC3447531722071E
|
||||
|
||||
sg0ogRPLzqBeQztwc20ZPqnuQp/2Lv9a1oqY0SLcWm+z0WXVehUSvOVj6vxBCvuX
|
||||
TVzLYA4q6eEIyaCMEzIFLN/A39gmjBhWZK7+amp0orDuFBHoEbAcUJnGpAglj75f
|
||||
lsKGNAfn5p1WEbB2MFFI6WwKgMFDGvKqK1Dw3crQk8s=
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-192-CBC,DBD38A287B2D983EF72D8314BE8AA5C3
|
||||
|
||||
m/fzWalU1WmEf76dMsUktNG1Jo/Fvd2hKlaGB0/ITNd/tZuVf6pvz4c8+MhJ7dZ5
|
||||
FPVCe/P8crwM9D4beq8TvUq51U2jfy1iejGU9z9lMsXiutpKIOAsG4iSv0FeZALq
|
||||
cCuZ7tpw1LkIZTfRBoFkQmqYN7oZHtwP7+oGbEDNr5E=
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-256-CBC,5105F89A3448CA69E8C9784A9876D6F8
|
||||
|
||||
FkTcZ+6JtBHQHimcNXHOYiRI8s3n7lMXuss97oBQvqA/duUT2oItEQbQ548uJol2
|
||||
Xqs0uMKY5H0tvZPUoD9zOWCMIlip7Yj0n5eF5sXU+Nx3aGQHWLmroDA84iCagXRy
|
||||
4YGFRiZsgC2GAOGapTcR62jCyIMYgqyJgUyq3JJWtPA=
|
||||
-----END EC PRIVATE KEY-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: DES-EDE3-CBC,C4ABB907B69450C1
|
||||
|
||||
4KvcHjy6UN2l0uf5dPwSrEn8eG4aqvUP0wTUazeqmZ0wFYm3BxNX+Ml44SYXk7rC
|
||||
BKWAFGGjE19I+Y8FiwiIUTx3Jq3sV0/zLROPcw2fv3IxtOjWbnJEppOBrgPfg2Zq
|
||||
FxSQq/C6TyARgxb7muzGFiCD5uuuZthlr3yobSu2jJw=
|
||||
-----END EC PRIVATE KEY-----
|
||||
Binary file not shown.
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env bash
|
||||
# Public test identities only. Run with OpenSSL 3; no production credentials.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
openssl_bin=${OPENSSL_BIN:-openssl}
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
|
||||
"$openssl_bin" req -x509 -newkey rsa:2048 -noenc -sha256 -days 3650 \
|
||||
-subj '/CN=GP Identity Test Root' -addext 'basicConstraints=critical,CA:TRUE' \
|
||||
-keyout "$scratch/root.key" -out root.pem
|
||||
"$openssl_bin" genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out rsa-pkcs8.pem
|
||||
"$openssl_bin" genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec-pkcs8.pem
|
||||
for algorithm in rsa ec; do
|
||||
"$openssl_bin" req -new -key "$algorithm-pkcs8.pem" -subj "/CN=GP Identity Test $algorithm" \
|
||||
-out "$scratch/$algorithm.csr"
|
||||
"$openssl_bin" x509 -req -in "$scratch/$algorithm.csr" -CA root.pem -CAkey "$scratch/root.key" \
|
||||
-set_serial 10 -days 3650 -sha256 -out "$algorithm-cert.pem"
|
||||
done
|
||||
"$openssl_bin" rsa -in rsa-pkcs8.pem -traditional -out rsa-pkcs1.pem
|
||||
"$openssl_bin" ec -in ec-pkcs8.pem -out ec-sec1.pem
|
||||
for cipher in aes128 aes192 aes256 des3; do
|
||||
"$openssl_bin" rsa -in rsa-pkcs8.pem -traditional -"$cipher" \
|
||||
-passout pass:fixture-password -out "rsa-traditional-$cipher.pem"
|
||||
"$openssl_bin" ec -in ec-pkcs8.pem -"$cipher" \
|
||||
-passout pass:fixture-password -out "ec-traditional-$cipher.pem"
|
||||
done
|
||||
for prf in sha1 sha256; do
|
||||
if [[ "$prf" == sha1 ]]; then
|
||||
prf_name=hmacWithSHA1
|
||||
else
|
||||
prf_name=hmacWithSHA256
|
||||
fi
|
||||
"$openssl_bin" pkcs8 -topk8 -in rsa-pkcs8.pem -v2 aes-256-cbc -v2prf "$prf_name" \
|
||||
-passout pass:fixture-password -out "rsa-pbes2-$prf.pem"
|
||||
done
|
||||
for cipher in aes-128-cbc aes-192-cbc des3; do
|
||||
for prf in sha1 sha256; do
|
||||
if [[ "$prf" == sha1 ]]; then
|
||||
prf_name=hmacWithSHA1
|
||||
else
|
||||
prf_name=hmacWithSHA256
|
||||
fi
|
||||
"$openssl_bin" pkcs8 -topk8 -in rsa-pkcs8.pem -v2 "$cipher" -v2prf "$prf_name" \
|
||||
-passout pass:fixture-password -out "rsa-pbes2-$cipher-$prf.pem"
|
||||
done
|
||||
done
|
||||
"$openssl_bin" pkcs8 -topk8 -in rsa-pkcs8.pem -scrypt -v2 aes-256-cbc \
|
||||
-passout pass:fixture-password -out rsa-pbes2-scrypt.pem
|
||||
"$openssl_bin" pkcs8 -topk8 -in rsa-pkcs8.pem -v1 PBE-SHA1-3DES \
|
||||
-passout pass:fixture-password -out rsa-pbes1-3des.pem
|
||||
for length in 1023 1024; do
|
||||
printf -v password '%*s' "$length" ''
|
||||
password=${password// /x}
|
||||
"$openssl_bin" pkcs8 -topk8 -in rsa-pkcs8.pem -v1 PBE-SHA1-3DES \
|
||||
-passout "pass:$password" -out "rsa-pbes1-3des-password-$length.pem"
|
||||
done
|
||||
"$openssl_bin" pkcs8 -topk8 -in ec-pkcs8.pem -v2 aes-256-cbc \
|
||||
-passout pass:fixture-password -out ec-pbes2.pem
|
||||
"$openssl_bin" pkcs12 -export -inkey rsa-pkcs8.pem -in rsa-cert.pem -certfile root.pem \
|
||||
-name fixture -passout pass:fixture-password -out modern.p12
|
||||
"$openssl_bin" pkcs12 -export -legacy -inkey rsa-pkcs8.pem -in rsa-cert.pem -certfile root.pem \
|
||||
-keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-RC2-40 -macalg SHA1 \
|
||||
-name fixture -passout pass:fixture-password -out legacy-rc2.p12
|
||||
"$openssl_bin" pkcs12 -export -inkey ec-pkcs8.pem -in ec-cert.pem -certfile root.pem \
|
||||
-name fixture -passout 'pass:pässword-密码' -out unicode-password.p12
|
||||
"$openssl_bin" pkcs12 -export -inkey rsa-pkcs8.pem -in rsa-cert.pem -certfile root.pem \
|
||||
-name fixture -passout pass: -out empty-password.p12
|
||||
# DES requires the legacy provider in OpenSSL 3, unlike PBES2 3DES.
|
||||
"$openssl_bin" pkcs8 -provider default -provider legacy -topk8 -in rsa-pkcs8.pem \
|
||||
-v2 des-cbc -v2prf hmacWithSHA256 -passout pass:fixture-password -out rsa-pbes2-des.pem
|
||||
|
||||
# Incomplete identity archives exercise validation before native TLS import.
|
||||
"$openssl_bin" pkcs12 -export -nokeys -in rsa-cert.pem \
|
||||
-name fixture -passout pass:fixture-password -out certificate-only.pfx
|
||||
"$openssl_bin" pkcs12 -export -nocerts -inkey rsa-pkcs8.pem \
|
||||
-name fixture -passout pass:fixture-password -out key-only.pfx
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDADCCAeigAwIBAgIUch4EHQx2jG1SVy93ALCnjWiZz1cwDQYJKoZIhvcNAQEL
|
||||
BQAwIDEeMBwGA1UEAwwVR1AgSWRlbnRpdHkgVGVzdCBSb290MB4XDTI2MTAxNzE0
|
||||
MTczNFoXDTM2MTAxNDE0MTczNFowIDEeMBwGA1UEAwwVR1AgSWRlbnRpdHkgVGVz
|
||||
dCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAorjY7yd+KUlM
|
||||
afkNbdRn8JyJnD/C/blSOcT4qghiGiFrEF3hUvui1bkZSF4CwkyO/d/DVlf5RE57
|
||||
+mSlK/0omDptJifR10NExqNq5pFPYZ+Do7Y75w4NyyPj759ruUTonpm7EFYqQOc8
|
||||
N/QiFfanisQ5D1CO2PwVBe7aKodAgihq6C8SmBKCBRR9m8HDmtckmKnQWNczxOBh
|
||||
7BbAx4WxiQSHxIrt3woSps1QfEHcYTZhPKD7EDRGEMryBvYdI2dtIjVQwRJ4t/r+
|
||||
9sQeK5fJVNYxVjpdtqMJCLT4INBzIKaPKy2R1geWy5a1Zn6EJ1uIx3f6H0NU02Cr
|
||||
Rj5sN3Yw7wIDAQABozIwMDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTcWic+
|
||||
ZMfPm7i9S/sJx1HzpjSg0TANBgkqhkiG9w0BAQsFAAOCAQEAoHAmAMuG4joVReqb
|
||||
81rOQScHfai6lwBVKXsC5lJj/ptfk8n252TObO9s2beOl6mYPs4nMRmq8NIc2ezA
|
||||
CvlndpQhgHhesTIvZGVG43/4Zy3YrzbMSfrYOdlKe6rlIvVbZcMkRIyUbUFVkDO3
|
||||
QjNfOHXMNGCV+2K+/1moru0OkU8fvla1m2b2N6FZIS5q62SVm9HSppqTj/nWS4kD
|
||||
q987vf177vX0qTLWM7YchI+N7IzQyNLElfajJ7SiCBNCz5AggYuwEPmVXdnrdlCe
|
||||
XP7P4t/tZqch0ZpkOvCK2glTNIc+4PHvZ7aNANvaR08QXmSKiwbWX8X9EMdFia7c
|
||||
VvQVDQ==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,18 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIC/DCCAeSgAwIBAgIBCjANBgkqhkiG9w0BAQsFADAgMR4wHAYDVQQDDBVHUCBJ
|
||||
ZGVudGl0eSBUZXN0IFJvb3QwHhcNMjYxMDE3MTQxNzM0WhcNMzYxMDE0MTQxNzM0
|
||||
WjAfMR0wGwYDVQQDDBRHUCBJZGVudGl0eSBUZXN0IHJzYTCCASIwDQYJKoZIhvcN
|
||||
AQEBBQADggEPADCCAQoCggEBAN3VB3+IqFO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pE1YK+UGtzPFWf9Nv
|
||||
DkyZTb6qG3jAMNNP9kWe+i03e1YGW7HB0I9ac4CPFG/FxDfDk3o6tt8fT3y/Aa6z
|
||||
HHOP5C+GtaNcG8BWTkzwEwYlyu496Tw+C2K+PWQ4zdw/kBLjkP3/8yKnFDQMoeRL
|
||||
eHX+Aho9OHioXe3gX7Ya+Bgp/8koarW0XsPIRyMCQ5x4oRtYp+sIPf6BJ1a3WvM2
|
||||
owhTo2/DC7kWnAbJBGpodKeydwM7lYFsrTv+JsjbtyqDP7z++G8dhCDTXvgzFZKg
|
||||
N7d5HqwCYkmmneNFMNntgvivdWjQvrb6H4jexWF5FIpoLUCW5EO6dVyRsC4d3A6j
|
||||
PC5GKCh4fZB+LhfIYGkrzLDx0iaAKWv16as+fHSY8vDBFhUFed6INsMlHNEuOEpX
|
||||
GtM1QzGta4GbVNVue7XIRjiY/XPzQ1RmZPwOCzBi03PFwbt7zti13v0oQs49W7Yh
|
||||
5E+yu7PQPKxr1WbmmU8e0U5NF0bkPsFVauUKFCOC164nEn0zGZRSyFL54O7+lF+b
|
||||
zAPRM0zYEVbCkkQsF87ToGwPRY9LoNikP14MV1npujkWIK1wZ/eysBACDCdW8mxR
|
||||
X2ONO70h8TsO1R6KS5Y=
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,29 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIE6jAcBgoqhkiG9w0BDAEDMA4ECOIH1TuPOHfxAgIIAASCBMgcv+kci9FRoLjr
|
||||
zYevFdoYS66/aUAy0V/173CuRMb1hzwsxfXeoRzTgXaWXUOExJX2PSCIai2cwCcj
|
||||
SvZUXPSQz+9aWrZjO/R+tWfKW0ttmT6Et2Kfps6MkJpRK/jbmaYOISpNa/8ROCty
|
||||
A7P6f4KNFeRhU89TgLqegm+so4un7d/n9vwYQBC1oCaRuCvxuNIugbnVKJkJ2RMx
|
||||
e7JLk16HVox8UGb66knS5kvaFV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BPWS6XRx+YvAKz96cGtzb81Aa3aoa3Qu+D6/wWXC7s=
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFJzBRBgkqhkiG9w0BBQ0wRDAjBgkqhkiG9w0BBQwwFgQQZ/Awu/UgqU7guQ0o
|
||||
iUbVJQICCAAwHQYJYIZIAWUDBAEWBBCZv8MLB6vhKR9lbtkDUru5BIIE0L0CIxIL
|
||||
G7qAmJ1dK2yUlZ5uH9k58ApCYz/xxFcyB4H6xRgumORe38WOKH76UqO4az8B0X+N
|
||||
tkftkOjG4sXtizKIqT2krJtEBH0SZKleylz8TzdZuVD13/dloEoouhR4vIxjPQcT
|
||||
UeAso21Nobc5o8gTevZutpu8JBmK0mkVc8aKHQVLgR0LXMFsBbcTa8QKgWKhc21w
|
||||
OtxM1XPfvYxHJ6EwPSJBJrt2Ri3bBAUprO4vysmfuCvHgyIhjJKC8AY2ugfOBVmI
|
||||
YotJgbqrxXVEsfEdTHHTdYSN21zpELWlGi1dWBbJiYA5o7pCc7vF4OYOgOO3ci58
|
||||
zLdnMUUYE77qrwM+SfYbKFDxFElbiCxeG2nlmRzqSCmZmEWIZmGiNItqbt5cxrZs
|
||||
Ef4omAPI0uUy2wfey/9moflVS28GY/7NjKFeMuGZ1od+ixml4qGXssYyt8UfvzDb
|
||||
+p6dGvFPBUyAVtmwpPjUU5g9mYrupMUB/BAWhazSL/DDTH/9Zynl0co+/AszTUvN
|
||||
ufHHvcndUA7el42OylMbycZlVla2ZdCVsuNexIfr/9TlFpINqxKmKyWlaYvHXju/
|
||||
T6DCItC/ADvmaa0j6Aw8FPf/ArPPFp9a7N6y93WcCp07Ydm5U07cm82biLF6qida
|
||||
sj7YEj0qUxLXtDSgYzFvywmiB86MpryxnvQXoaZN53gWWeSzZhpRWghBsnWxgIco
|
||||
zenjxiS45nnwRXby4mXpPpNpWVnC0YaTvN1tPvHaM+dAUkxa6BA9xU/uXatofr28
|
||||
zM6YldvNOR99fsuk3zRvPQm0Pj3jszUG48kWXsAgZ/w8AVDiIq0GFm46QDNxm6QL
|
||||
RuTl04MajnskNpj0i6nqs3s8ooBbhYfd+dKUyVAzpLByshewuMniCdVvPGdn8HXP
|
||||
bYbFvMHlD+7sQoFJ4990TwsdCBPjwqbFo1mGbieCL/okncqU7QCOrGWhwFYIy7Wt
|
||||
4VIAwVqkh7tVG56te0C1hJj4V7rWzVNw12Y4/NlkQBWvZlrGCVLelBLF3vX6/R1c
|
||||
OlG+wTuUNswBbnBZzcprjvU4XaeufU0ntsiAgXt4sFTRWwmHZTMf9lHT4GVkVH+3
|
||||
ugMtiL+ePdcWcGYmhPFg1m4atveSoMB0m3vkUJDF/KMDiQaC52FwhXr/G/2wU+GE
|
||||
G6HmnK60AsucXqolZgWjizID/t5DRhIicFfqx8a9Ik6g+qrZoPMzrfIqjsUKIeXN
|
||||
uCvMICHJ+mFy0riFZCOrZMggBregYXdV+mrCpcV18lxCmri+vYXaiY2NaVhcUJOL
|
||||
R/OJiQeWuK4kCQvWnj3YiN9kbUHGfFHH56oeMKbcv+oOha2/ATe7/XlhH3LOYXp9
|
||||
+DOqP+wVlSPQZ7rGCubI+Msc1Zpx/PoyN/VnXDs8A2H5bMUv8+RdAUkzSe3KoMWi
|
||||
KKrB7MbombXrhc7l9dK5vCU5YWAES3c20XzzqZ+SNBUBeFubmfVwdpQXge7sUHAP
|
||||
kh9Yyyc78ruwZrPE4x0d0mQmdYbWK6fqAO0VWuF6YrRfGaPBUFbHEXCVk5YBc4+O
|
||||
biLmxV/POGF6L0VLlaXnkpMk6qIUpILmoS5FQaz8KLetlAPd5pQuhkOmnaBYGeTE
|
||||
d78fn68IHzmRw/wdyd7/f3I/74vO0HcFFy01
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFNTBfBgkq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A1txnCa20twESLaNHqLqfe26t9vErNxssx
|
||||
UDIw/El+3rBJlDjrjnbDQ+jwbAtcXQFhwNLMvnB+eLF7ALylrfU1H8+TvptbghfV
|
||||
1GQgidw9rJ7UvQGkcPOsa0vDMnnzSev0xJf1d0t3YlRMGP7N2RRO3SqjeYET4pzh
|
||||
TsOrVjYMA7se8vmyf64nNk/4w6pOsmW3SEO+fro3dH4J0MwP8d/+swdLpZlESVME
|
||||
fLLMRwOxR5Pzr30v8sSl77tVm99g3gdXiZHmo24E2vK9MjSvHBs6LEwX7NezAD15
|
||||
ZzeKRe8FeaigJTu68UNbIFMGXds0A4pP5DOYTkY1T0/LdUT/kC0hS/h4rfi6ebjZ
|
||||
fQEH4Z7Fax5khP089fUs8HLpAuNBlcDEl1gY/QUcQ+ZPQ2ybnv0xiH3AO1Gfe7iA
|
||||
W1x+Btu2Y/KBIewtt6WfC7tfU6Ymau2xhb+YeWOchHGdx9+TJvmlfSeGbfazaFUT
|
||||
v6WJBmeMRPYLglFiPtOBtv+a1sa/CRtI5aeQu/Vt7/NpgUt+bmdFhSb1BaLVDMnd
|
||||
XV+e47lpg/rrmGwEIpNKutxo2LTeRGyO5p68362S3t9XpJVEbo6pUT1H/e9I4tqq
|
||||
bMnI+Y158sbEOXHrjAtPR/qyHt84g2HPWd9kBzofYfsH23crbCP88a61EuSSSDeW
|
||||
WZiV+4CyLZiFAdPtHjGotcNCy2SKSQVbtTleOssDz7k2LVLingCg1zy/smzv6vQ3
|
||||
WwsDQwfvlNelsrs/5C9t8V3/TAKKuZOQqQk6QHJQ6MJpnPicNlZpKjc=
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFITBTBgkqhkiG9w0BBQ0wRjAxBgkqhkiG9w0BBQwwJAQQL3LfHM5IdiCRo6Jd
|
||||
on16lgICCAAwDAYIKoZIhvcNAgkFADARBgUrDgMCBwQIjWT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aQTyIvrePJK25P28
|
||||
xbpSb+widMmFYSDrxjzxl2iUcdTdR7pUX/qldO2oOngXA8FfDxhNuOJtidoPMGBF
|
||||
ygypYHxIMrhmEV42tXODE5uBi1KWtJ8xEGhcJqvsOrWWf7cv//aPTmdSv/kcazCk
|
||||
ReNlVLk3vUAjA18OiW83unQjWt0J0jJ0F5jQTm7WfW9VB7L55qe9ExexNFl5CPJc
|
||||
JYNWSBvg6MlEzvk+rD/hDOszFdrLS5A3HtJIY9+3qO+OlqFtlp9JIaXmfke2dMy1
|
||||
PHHLD1PgYZ5vyBIJbf00QKclsVG5vrLYvDTv9kNKZJhVxbagzax1b6WGY6GIrR9N
|
||||
8dRQpkCCYqUYgzanpkLQfofxb+TTv6JSQIRZSHKpxR7wQBuS7lT+6fTRE1tPB4OU
|
||||
JPXn3W1jx05K/OxeyCFtpN/xLnnQKvnj4ZU6DXB9vO3UydUtCSpq9KvDvm55lll4
|
||||
ZkuGey11V+pn23s3ygVFuV4oPvg9zk5wHUQAlWkUL818T9pIwFLN+H10rNSVitB+
|
||||
YxlgGQfLhKsjyuUyTpKUwhqp6idosFkioWB5lmLoP5Brdsm7eOYe/sLEbUKxbEFD
|
||||
xKKA7XVaqJQEPb8+069Q9iTlxv00Zng4plMNtKh2r9j9h1VOEQzLaV33yS6Wmuw6
|
||||
XJXa4mML2vuEWv8kpnetqCG/8aFu
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFFjBIBgkqhkiG9w0BBQ0wOzAjBgkqhkiG9w0BBQwwFgQQr23WBmE1lkxsGA1t
|
||||
yZ+WjAICCAAwFAYIKoZIhvcNAwcECDNnS5hARTEYBIIEyI/XTneU4bZPrEbXBVuY
|
||||
eunGKPNfmUJAfTftRO8w7K5j0zXo01Q9POdPbuNvVPsQQhv10Lq3hAjOeoMbWIGR
|
||||
NW2a8/Ru+0ycr4hUwzbV/t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ingsT3TW6E15gCqSEKbHsV
|
||||
qGtlCoj3zFzmVW7y4UFXrOz93BBmaR1nI3nwLokSoxPMD+hoXjlsexpCrOKdWHQ+
|
||||
RaRmpiLRwGwH+ukrRwIfPCwS7+an4lUxOmFM327zvcJiVaLMLk0oHVFgl8wRUKWN
|
||||
7Cn9KIKtt/1M2v1k94EV+sr2zO2SRO4659rKJ2WHT5HeBhbaAe08Oz9EW9aealKL
|
||||
kMEE5S9bqHVu9amz2RuJ92V8Fjs3bTBYSV/spl85VAH0Q7pMUKRHALuUe/sBI2A2
|
||||
miyum1F6WSslnxEC88PGFzbF87qZEkntF+nJheP2GnqUV4XDCvvvNfGkt40NGcv8
|
||||
v/rnVBJFGpgOLd4S2BxBaaKM9HhM9qtiHrTeo536FAENDfkNO1IDeytLqMZlK0os
|
||||
eHRLfG0NMKpMMMndyJ1BuvJHOIu5Ph3LcP2ghuVVnbvDO0thqblGCXWsjOEfuhFF
|
||||
cIUFlGyWVyh9RsFmqZgGJ/ACJ2yr/ENgATWPNEMhHWUp07hUphNFGk+0p+SWrCsW
|
||||
+caljkPly+7J0A==
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFJDBWBgkqhkiG9w0BBQ0wSTAxBgkqhkiG9w0BBQwwJAQQPrSU6A8HS2rfL2Aw
|
||||
tj4NAgICCAAwDAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQIlos2bamhisgEggTI
|
||||
DrQM/Syozmo0P0VjQYYB1LHUw/LRP/m+/7vJSDtg9gsxmFlhe7fOFc9nBV2Lk1aT
|
||||
QcvADQm3vzmQxWllXIcqHUAbnt9YmMCxOX5rgfxNC2OIRwsxKENcIxASUrurDNd2
|
||||
YfSyEYKdqNGbgpCOFQZN279Fak1IaGaWWfnhvVV1tfrtmNKd4DuW/JB5BVLKeZXC
|
||||
xZJ9KyocmciAROXYglEiucsWz0wYo8D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BI8P9WBHeKlo3+soTxhW08Fztk5Ypp
|
||||
80zlgAEQLsqCCkZLnUys0B3vSu2ipcp1RWI7fFdNzr7qXdfpraF6kpPkI6vsGuS4
|
||||
8DnB13vjfGm22DM0gyahrgWbEYbh0qjdPU9YNFkAdw22QZZM7DRxgexABo2cBJ4b
|
||||
DsZyR6X9mAUF+GoM9uk6LlNHOBjJhf1hQghUFafzXAnv2uRWTKElX8495BQIMkJf
|
||||
7wWvD0xFouyOaBs2WG2sVvqLEsuaDWma5hl8OHfIBy/bGtM7kTTPpyW7GJhl7UpS
|
||||
ECr2FeCU+AxE4d1fLLSk0NJ3p6D15BUD4J3jZsCXUKWV
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFJzBRBgkqhkiG9w0BBQ0wRDAjBgkqhkiG9w0BBQwwFgQQaWRBwIFvqszAZR3q
|
||||
Ela+lwICCAAwHQYJYIZIAWUDBAEqBBAhUTeex/AihIZOOCw+Di7xBIIE0O2QU8kp
|
||||
fBGNyBtIJNFfeWw14v3nTRYO2YUjOCTYc86xPNJK4yV69+lxuQ1ibGQim6QSaGU0
|
||||
xoooQh1UoTHNpp9hEF+7dcvGJkOzTg5UqshrNL9d+x5CbIyfiMO23pa69VnBWeRo
|
||||
4TwICc7MMT95FUkbONjbIg0jqtaCsmIEIvIIfj/jk87yAGfAqfY/5IbenXP3526M
|
||||
xzMGDn5ysPYsIVNN672uRoRLL8XlR6oFVqA2Gljg38+jq5vfj7dQeRuWk0Np27Uu
|
||||
dbv01SJctGIr+oLcD6gN+WQLhxgudJxy7jkmYBB6Gt669Wqnevv0konv6fk6w9hJ
|
||||
Y7/220hSbLxuD0Qki34zJQ9Illi0OmsAuw575/2aEHozaJkvUPsXfbiCDiO6ykQm
|
||||
HPjAMKmOIC07Uz/4VYF4EiBW94VE46kjfsXeSratSNcrZjl3qcEyQvdbNgfxhwjg
|
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BwF+zR34DyoF47t9oNqZ+D+ZZZ+85KFN5qpWxQ+78aON
|
||||
kmLJS2aDLFbbixAinSWtC7T2WlrunRKtqhHbD16OlSwaqSbCTK/BXvAcyjQOCRWU
|
||||
V6gskJ6Dup1pFscy63jW4H0nreH4hLignVAafxpo7HGJU3/UI+HsWrgNxL5yusoe
|
||||
+MTlZRDeoBLKnH9aXKW887SVzPcZIJw82QOo
|
||||
-----END ENCRYPTED PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN ENCRYPTED PRIVATE KEY-----
|
||||
MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQKNgPQnRyv9a3bJxh
|
||||
F/mvLwICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEHm8bkHGT8F6igjH
|
||||
EjG0tWoEggTQSV1Rw99vpqwXzU9twY9QPlk/OX9znHaHJhjURg6MocfiRPRVY73l
|
||||
pALAqX88fwD0opmYPcVn1FgN5I/xg7hHu7nXXeddAGnEvO4z3uP2pJXeankjwPwB
|
||||
upJRXIpRScenybVA9t+OQj9RQW+Wm0l7/yArgiiV5h8lprQWIQEYOVqnFsQ+wrQB
|
||||
jHaoH5sJmrOuRKDqQRJqvmANzbNrWDCTcAoTf9tB4lZqJ/7/SLQBeh39AiepXcMt
|
||||
JzCOPbn02UJ0DhHT+PZS6ZAyADYDNfgSxY8oh6oK3DO1JS5uzVLHyWx89uXJk7eX
|
||||
qWX5y91Qv5simVN6Eyhtb7Zxwc6Q2ux+6J1WrTIDV9F9KyZINvcQyeYn0QAhOh8w
|
||||
D46jpKSS7WplW4hzYC4YBSldPlFlc1DEDlyPP4rRP4ngyFS10fVH8SGblWFBSq9T
|
||||
f5mA21b5Mww7T4MEuhXNl9DIIJGmm+MvzYin3OGUVXxpScPtzUjaZxFXMzNoxnuL
|
||||
sRHlAD9O+zAqmLK9DMF1iohoZ1tcxSueNE4YkeTovZNFuZ+3HjBDdInk3P/b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HiOQh0tnRtnzGaRqv4QDUm0XFCLXwdPhDp
|
||||
bXo4KuEVqRICOLJEe9GIOJO0xvzcwTv2A1YzTnu1G1pg7GaeiG4Si3cCgYEA5Lpr
|
||||
7goqHEJEUm6MTowkXzuahXRv0lOAkZkb16hjzUW4RJuKNHvyibaqBVTQ6b7iRLNK
|
||||
omyXLUMamShYB353IKMWldAT4D4TNBirblJYN/z2h2nf05ZdQGGHAuTTmz3HsYhT
|
||||
twDNLJqhb3cGQAX/lLPXQx74HdjGyvQjmhf1sXECgYEAmL3U8xtpXWopyH8jfcbW
|
||||
+yGhja4Vb/K4q7OfN59ea6/DHowk9CJyviZfetkXULYa/9RnJNHLr9pab1p51VTw
|
||||
lWGsW6rY3bzoSl31hZqtXOAudEkMvGgvEtjDwS1j4/VeRH73Pq0y/otwBZL+RCqd
|
||||
OIRJYBke28sIIacoFIqTAhUCgYEAzzAC9lQkwwZP5y+WTsxpYg6WsQ7BAA99peXA
|
||||
L8Cr7tSZzyPptBMWpyJcrome2C19vud90tV0t55SaKv/2YH4HQs+OSSL7JOuR4GV
|
||||
QFC88rJlClKgWoSZIel2J+vptnTm/+zSkDHcqOvFEjgJ5FLKqgOiGX3jGP41TMCL
|
||||
w1iyyTECgYBJCzaBLXXPDPMWNK/5aTo0GRuO714kiwehvp1K+sSRKz85qx4r8Cb/
|
||||
anDVf8ONZR5mIzKUgEO3HppTKgG+yfgQg2cTsNZXuWwOl8FV83I7Zno7HMm5Rem+
|
||||
NyHj0Yb+k3D4TyB2AVE4YD78u5jXFIWrJVroIAO7mRXwD/gkZWphcA==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,28 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDd1Qd/iKhTpVWO
|
||||
jhfwPTqlaj9Ac6CKubFr0fZsVgR8r1OSmRv16e2tjhfjjhOI0cz3S4Cqt9ZPLWIM
|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zG2ldainIfyN9xtb7IaGNrhVv8rirs583n15rr8MejCT0
|
||||
InK+Jl962RdQthr/1Gck0cuv2lpvWnnVVPCVYaxbqtjdvOhKXfWFmq1c4C50SQy8
|
||||
aC8S2MPBLWPj9V5Efvc+rTL+i3AFkv5EKp04hElgGR7bywghpygUipMCFQKBgQDP
|
||||
MAL2VCTDBk/nL5ZOzGliDpaxDsEAD32l5cAvwKvu1JnPI+m0ExanIlyuiZ7YLX2+
|
||||
533S1XS3nlJoq//ZgfgdCz45JIvsk65HgZVAULzysmUKUqBahJkh6XYn6+m2dOb/
|
||||
7NKQMdyo68USOAnkUsqqA6IZfeMY/jVMwIvDWLLJMQKBgEkLNoEtdc8M8xY0r/lp
|
||||
OjQZG47vXiSLB6G+nUr6xJErPzmrHivwJv9qcNV/w41lHmYjMpSAQ7cemlMqAb7J
|
||||
+BCDZxOw1le5bA6XwVXzcjtmejscyblF6b43IePRhv6TcPhPIHYBUThgPvy7mNcU
|
||||
haslWuggA7uZFfAP+CRlamFw
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-128-CBC,1DA771DCC527783F6EFD4C6CD926AB1D
|
||||
|
||||
jBGtgZupvnF4w3Abxswu06uk/GZt8fe6HJ8LqwqhiO4grseWfTgUFD/UoQzuAO8U
|
||||
YrtKDbf1A/Ps0oe6pUeHUwIyw5nUU3gryFTmip5cqVuEOZJNdxCTV6Vyc5j4DQzc
|
||||
cGOOBLR6bgi0l/lc2B6dHIlWYv/elnK7oYHbEOVehX8w4hQzLG00fDQmxyEQqBBA
|
||||
HwZWfTLCEYHMdKf0RelPYk5OwbUq7ePn4EqNXHddmEvZNK0LVOfD9KFO/4Yy6DIa
|
||||
5kLfOG/E3J82ldvwn1AYVKKCPjdKNl45u52wfgL/GbDxv29p/Z2HqEGhs5iA4weK
|
||||
GW4X2psQJPFRIzX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yVxQKcO7KYe7HDIaVjUsUr9Oz+UG2Qwxi
|
||||
yiB5XsjbU9dFn8X57HMqvZOW8kICnucqurFx3RruO1CrWG0OlRytP8BjtI+sCLnl
|
||||
Y7OYuRHLJClJZMgVCJfWNC7wjvX39gY1PjbYVzNwGhnOFu12jXFE7+s0KT2G575M
|
||||
XQE8OZ208P1rlDo0PHvs2tlk1bOz942m14tpABzXkEIC35OHjwj6Vi+aGrU4kv2i
|
||||
HhVTsSwPDrCf5acTlmawxKoj2jAey8xHRlrV6O7B94mEJFCEbHjw7thVd3ssoSLT
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-192-CBC,3676585752281E1F13CD59E6EB36EC8C
|
||||
|
||||
ImHFk1Pvr7eeFtS7eorBiq1eMNEJqn7ydhMOsP+4GCJ42zihMSbkwIbEt5Q7h3oO
|
||||
G0aZvr0vwnYIvWWwc9s7jdpbKU4w6ll00xDL2bmbFGoyJx9li8fiYL7SrHg1Uw6A
|
||||
0VFKuBCBjndQaRAw1+YFETscIcw2g3qdeaO2C4DKLQqCE/INucGCAljzjcevRNIo
|
||||
lxM27bQQgO2iI99LVAeXwPFgGij0QBJnI50Fydsv+b65Pn5AVl8Q842Qjb6OuKs5
|
||||
UinlPMSzvZ824FO8Q4eGHyVVII2o9RGQRm249szyxwm/a5TetGzMQaZo3vERYTtL
|
||||
fR65j0YiCuqfCb8seKywtvcUITRo2Da5bS+ZvxUxuP01JyEd+0N/h/ekUyBBg1q5
|
||||
pb91zrdI4aL2he1m6EQYqzxka6UZWrKiKaw5UEVb9cC2fftxaInRa8h/WDqCN8U4
|
||||
ukVg2SLDMT+6BWTeEVSFOY6727Dy9a9UBneHc1ejvX0lrUmsL0w42tH2AI+WZx0c
|
||||
saRp7ali+/Gj5E7otchakMAfjusZ0pNCcuRHaPY6QMswacDU7o/7l5z/P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b6NRYOAmg8icIzTbcGhnFHZbiFfaqBX8Qd3yWk10KmdJipU3Rn+t
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: AES-256-CBC,C47A164F22721903963FC768F2BFF0FD
|
||||
|
||||
Ultu7rEweaaOx6V8pce+mVsFmaDSOGyZjBk9eUOIcdIEseDmzms4TBNyYBddUrhb
|
||||
6AiIwo1kz/2D7YED7dEckyuZyX9LETDcno3MwwDrXAve0Nn7zj4qgHl+Pj2GBfWf
|
||||
PioDdmXHthbOjJp5rHgR9+gYbhPYnBW09OV6ml1WnPjqOlpsI1izKa3sWBsje0/W
|
||||
rNiHM4AZ2TJbrI9/rb9Nvd3X4t0RdsKsHpocxuBzq9YOKTt/rxD3uwI3fBkwyySZ
|
||||
PZhWxBL1iydiMwTWpXd6RwpH20pjUWyxzBdeb03py8ZE6kW8nA/GT5pu+wKnWoLk
|
||||
c/I1S0tKcI/LjRrOtorBNyHy2+sVH4vQVHCiCA6JV0+7u+uNP2SekQ/+8OsXB6bk
|
||||
KRslQeuIrEhqdUmwkrdxP5fu6034/pPFdBHo4qbIYRY+vCvzJYuRLQfyapzSacNo
|
||||
qloRG/aMxJtg1SZdQnE/Zt7bj1tow3b/Ks4fmX/xdO12Ye9GrEbEXu3yXGky7yz8
|
||||
z/n9eUYvhUP2qvVxqvHEZlEnyixTRRC5YO8PovpWAM7XdhbdVculfgqYm8JQaqcy
|
||||
DBkT5t6AExvRpTXqkIAG+RMlsUHCoFVMJJyGK7eMtg94RP+Y97bAaAlch4Cw/ulH
|
||||
9m56MluMtbThKRy4gxIojNb/Vd9poAMmNJVlB5gY5UGrbeLWxvVZzFDcv5BmadIa
|
||||
iJyJ/TrLvHhH9umewBqGYafnNJNdlp2PbZ0eRx7idCwlhOwhhuBJZTqLNoKK+CYt
|
||||
6GrG04IZQB+N2id9hXTNyomaASBXgc3Nq+CnLssIpPLfHB0O4f7boYwlPCzsIrWE
|
||||
EAeGBOZv3Njv9iuKX9HhB8GDNcQ4TSJ1ShsnqULDpbklza+fL8HEmD00BKY4AuIO
|
||||
RmH5CgmHgW0MwBuX2kJDd7Hrz9WJB6vKNOLuNsai5xX9L+Ivsk+RB+YQLoMSBk24
|
||||
DpD+LRgKTdY/vakinHpR9inznUjBQbg0KZtmqxlcznlVmo5Gx3imWmCNurmW+wwQ
|
||||
kn4mj0gI99VMWbWwJu1mUVt2j3Zy1PgeYbCtG26VfOW7a+jl7+a31LIn9taQzFH2
|
||||
20788uRl96kx3ijETCt/VGuqj+tZx8bcCz4o+22K2ycqzYlStKq17PCm2yrWYbXD
|
||||
nWEdXpASv+blugFDH/GvBSf5RGP0HYbSIIVxcruvJerlIkc9tWb5+gs/beEzV/Xu
|
||||
c3BYz5fpljecprZJq8TvBvb5T8mK1D3YdZnp7COWxY+I7wt9PP5GTqOzYFmauFZO
|
||||
/AOx0VickKMhfLLC4LkLGfYnaRpMpQ9pB3Z8AhLsY3mxXBxKYacIT6dgUXafpRKO
|
||||
13ILxvG+VC6Q9yScm6GpL8gsldxDQXzQ6STyDjw5wR42MqtqA4tTmnkxSlsPdj9i
|
||||
R4WeUjAtUXj/VBfB9X85LVjpN+thHpZwYtpvYdWk4CAqVAl8pjHkndm4oWpKxMXC
|
||||
OeQpZVsd/t5ZKGDwccKrUm10nQmeDw4NNzQDsLWCB15E60cegsGcBa27BVwYhVnf
|
||||
25iyJp525Sio9LFJDNk3UNSof2n2TrbF9EyhRIZhx2guIxKomntoAuT1NcxiDEUz
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,30 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
Proc-Type: 4,ENCRYPTED
|
||||
DEK-Info: DES-EDE3-CBC,083D46DC0D0EFB2C
|
||||
|
||||
iJLYLqu75j6reCA0CvZLBN7SpZzJufa3emjV+vlCzcZAbIa0WDdRz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x7c+c8aZqkbqAp9/2KPCuiGfgiq7RJgtFHlFaHIG9q6ulKv8Oo+ULA/eLTaP4
|
||||
rwUNzF6fFKXwnfwbPj2LxbHYQ18q0pWJpvTR+7/a8osCipwb+MZTzQ33ckghjeQG
|
||||
+zCa1rRRvha7oe641WTq9hbKUnBJa385/7xkhGfCTuhRsqOui83UAnC+GXdKsJaS
|
||||
pfstw1zVlKMHetW0WRaboQu5LHMCdYYOOUJSRSzJN0+r3m9PrfA9y7UR9usrhYUZ
|
||||
s4bY0louuzyZ6u7N67v0hVFvgVHEyuWavXHHRzlau3jrcqD57Fpp9zZP+TDEf7aW
|
||||
VKTJYsbdVhbpQnQhRcSUHC78NqVp1dXf85i6Fr/dLBuG68VcR3pvK7xxTPsrv7Bd
|
||||
a9c9ORbF+wgMJc0LwjFo5N27c1NfnWCJXf4rPUhjtnpcF3Vs5p/0rKWxdYDHC4gi
|
||||
KobPxDZgVdFpPzfXHGvNzz6pX1o3okKtD76f6apFI/uKn14MhFRAspWMoX39YPkv
|
||||
kzklzSVOziWQ+c5lO9JWofs18y3Yawdu9SPoyrQOFfQV7aCTgX54E2qNmS9gksLd
|
||||
-----END RSA PRIVATE KEY-----
|
||||
Binary file not shown.
@@ -0,0 +1,274 @@
|
||||
//! Container compatibility through the public identity loader, using public fixtures.
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
|
||||
|
||||
const PASSWORD: &str = "fixture-password";
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn bytes(name: &str) -> Vec<u8> {
|
||||
fs::read(fixture(name)).unwrap()
|
||||
}
|
||||
|
||||
fn load(certificate: &Path, key: &Path, password: Option<&str>) -> anyhow::Result<ClientIdentity> {
|
||||
ClientIdentity::load(certificate.to_str().unwrap(), Some(key.to_str().unwrap()), password)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn der_certificates_and_rsa_keys_normalize_to_the_existing_pem_identity() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let certificate = directory.path().join("client.cer");
|
||||
let key = directory.path().join("client.key");
|
||||
fs::write(&certificate, pem::parse(bytes("rsa-cert.pem")).unwrap().contents()).unwrap();
|
||||
let missing = ClientIdentity::load(certificate.to_str().unwrap(), None, None).unwrap_err();
|
||||
assert!(matches!(
|
||||
missing.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoKey)
|
||||
));
|
||||
for name in ["rsa-pkcs8.pem", "rsa-pkcs1.pem", "rsa-pbes2-sha256.pem"] {
|
||||
fs::write(&key, pem::parse(bytes(name)).unwrap().contents()).unwrap();
|
||||
let identity = load(&certificate, &key, Some(PASSWORD)).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
assert_eq!(identity.certificate_data(), bytes("rsa-cert.pem"));
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
assert!(identity.key_password().is_none());
|
||||
let snapshot = ClientIdentity::from_data(
|
||||
zeroize::Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
Some(zeroize::Zeroizing::new(identity.key_data().unwrap().to_vec())),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(snapshot.key_data(), identity.key_data());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_der_preserves_password_errors() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("key.der");
|
||||
fs::write(&key, pem::parse(bytes("rsa-pbes2-sha256.pem")).unwrap().contents()).unwrap();
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load(&fixture("rsa-cert.pem"), &key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
|
||||
other => panic!("unexpected DER password error: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_sec1_normalizes_on_linux_and_bsd_and_is_terminal_on_macos() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("ec.der");
|
||||
fs::write(&key, pem::parse(bytes("ec-sec1.pem")).unwrap().contents()).unwrap();
|
||||
for source in [fixture("ec-sec1.pem"), key] {
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = load(&fixture("ec-cert.pem"), &source, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedKeyFormat)
|
||||
));
|
||||
} else {
|
||||
assert_eq!(result.unwrap().key_data().unwrap(), bytes("ec-pkcs8.pem"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traditional_encrypted_pem_has_platform_specific_support_and_password_errors() {
|
||||
for algorithm in ["rsa", "ec"] {
|
||||
for cipher in ["aes128", "aes192", "aes256", "des3"] {
|
||||
let certificate = fixture(&format!("{algorithm}-cert.pem"));
|
||||
let key = fixture(&format!("{algorithm}-traditional-{cipher}.pem"));
|
||||
for password in [None, Some("incorrect"), Some(PASSWORD)] {
|
||||
let result = load(&certificate, &key, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password == Some(PASSWORD) {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}"));
|
||||
assert_eq!(identity.key_data().unwrap(), bytes(&format!("{algorithm}-pkcs8.pem")));
|
||||
assert!(identity.key_password().is_none());
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(password.is_none()),
|
||||
Some(RequestIdentityError::DecryptError("PEM")) => assert!(password.is_some()),
|
||||
other => panic!("{key:?}: unexpected password error {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn traditional_passphrase_with_nul_returns_a_redacted_terminal_error() {
|
||||
let error = load(
|
||||
&fixture("rsa-cert.pem"),
|
||||
&fixture("rsa-traditional-aes256.pem"),
|
||||
Some("secret-password\0do-not-log"),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(!matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase(_) | RequestIdentityError::DecryptError(_))
|
||||
));
|
||||
for diagnostic in [error.to_string(), format!("{error:?}")] {
|
||||
assert!(!diagnostic.contains("secret-password"));
|
||||
assert!(!diagnostic.contains("do-not-log"));
|
||||
assert!(!diagnostic.contains("115, 101, 99, 114, 101, 116"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_traditional_encrypted_key_controls_combined_pem_loading() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
let mut chain = bytes("rsa-cert.pem");
|
||||
chain.extend(bytes("root.pem"));
|
||||
let mut combined = chain.clone();
|
||||
combined.extend(bytes("rsa-traditional-aes256.pem"));
|
||||
combined.extend(bytes("rsa-pkcs8.pem"));
|
||||
fs::write(&source, &combined).unwrap();
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = ClientIdentity::load(source.to_str().unwrap(), None, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password.is_none() {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
} else {
|
||||
let identity = result.unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
}
|
||||
}
|
||||
assert_eq!(fs::read(source).unwrap(), combined);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_traditional_headers_are_terminal_and_do_not_expose_material() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("invalid.pem");
|
||||
for (headers, unsupported) in [
|
||||
(vec![("Proc-Type", "4,ENCRYPTED")], false),
|
||||
(
|
||||
vec![("DEK-Info", "AES-256-CBC,00000000000000000000000000000000")],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
("Proc-Type", "4,ENCRYPTED"),
|
||||
("DEK-Info", "AES-256-CBC,invalid-secret-iv"),
|
||||
],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![("Proc-Type", "4,ENCRYPTED"), ("DEK-Info", "AES-256-CBC,00")],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
("Proc-Type", "4,ENCRYPTED"),
|
||||
("Proc-Type", "4,ENCRYPTED"),
|
||||
("DEK-Info", "AES-256-CBC,00000000000000000000000000000000"),
|
||||
],
|
||||
false,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
("Proc-Type", "4,ENCRYPTED"),
|
||||
("DEK-Info", "UNKNOWN-CIPHER,00000000000000000000000000000000"),
|
||||
],
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let mut block = pem::Pem::new("RSA PRIVATE KEY", b"secret-invalid-key-material");
|
||||
for (name, value) in headers {
|
||||
block.headers_mut().add(name, value).unwrap();
|
||||
}
|
||||
fs::write(&key, pem::encode(&block)).unwrap();
|
||||
for password in [None, Some("secret-passphrase")] {
|
||||
let error = load(&fixture("rsa-cert.pem"), &key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::UnsupportedEncryption) => assert!(unsupported),
|
||||
Some(RequestIdentityError::InvalidKey) => assert!(!unsupported),
|
||||
other => panic!("unexpected traditional header error: {other:?}"),
|
||||
}
|
||||
let diagnostic = format!("{error:?}");
|
||||
for secret in ["secret-invalid-key-material", "secret-passphrase", "invalid-secret-iv"] {
|
||||
assert!(!diagnostic.contains(secret));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn der_with_trailing_data_is_rejected_for_certificates_and_keys() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("trailing.der");
|
||||
for name in [
|
||||
"rsa-cert.pem",
|
||||
"rsa-pkcs1.pem",
|
||||
"rsa-pkcs8.pem",
|
||||
"rsa-pbes2-sha256.pem",
|
||||
"ec-sec1.pem",
|
||||
] {
|
||||
let mut der = pem::parse(bytes(name)).unwrap().into_contents();
|
||||
der.push(0);
|
||||
fs::write(&source, der).unwrap();
|
||||
let result = if name == "rsa-cert.pem" {
|
||||
load(&source, &fixture("rsa-pkcs8.pem"), Some(PASSWORD))
|
||||
} else {
|
||||
load(&fixture("rsa-cert.pem"), &source, Some(PASSWORD))
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::InvalidKey | RequestIdentityError::InvalidCertificate)
|
||||
),
|
||||
"{name}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_extensions_are_ascii_case_insensitive() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let archive = bytes("modern.p12");
|
||||
for extension in ["P12", "p12", "PFX", "pFx"] {
|
||||
let path = directory.path().join(format!("identity.{extension}"));
|
||||
fs::write(&path, &archive).unwrap();
|
||||
let identity = ClientIdentity::load(path.to_str().unwrap(), None, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.certificate_data(), archive);
|
||||
assert!(identity.key_data().is_none());
|
||||
for password in [None, Some("incorrect")] {
|
||||
let error = ClientIdentity::load(path.to_str().unwrap(), None, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::NoPassphrase("PKCS#12")) => assert!(password.is_none()),
|
||||
Some(RequestIdentityError::InvalidPkcs12(_)) => assert!(password.is_some()),
|
||||
other => panic!("unexpected archive error: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "gptunnel"
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
gpapi = { path = "../gpapi" }
|
||||
openconnect = { path = "../openconnect" }
|
||||
log.workspace = true
|
||||
tokio = { workspace = true, features = ["rt", "sync", "time", "macros"] }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -0,0 +1,217 @@
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
use gpapi::session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelAddress, TunnelConfiguration, TunnelList, TunnelState};
|
||||
use log::{debug, info};
|
||||
use openconnect::tunnel::{Configuration, NativeList};
|
||||
|
||||
pub(crate) fn normalize(configuration: Configuration) -> TunnelConfiguration {
|
||||
let ipv4 = configuration.ipv4.map(|address| {
|
||||
let prefix_length = address
|
||||
.parse::<Ipv4Addr>()
|
||||
.ok()
|
||||
.and_then(|_| configuration.netmask.as_deref().and_then(ipv4_prefix));
|
||||
TunnelAddress {
|
||||
address,
|
||||
netmask: configuration.netmask,
|
||||
prefix_length,
|
||||
}
|
||||
});
|
||||
let ipv6 = configuration.ipv6.map(|address| {
|
||||
let prefix_length = configuration
|
||||
.netmask6
|
||||
.as_deref()
|
||||
.and_then(|mask| ipv6_prefix(&address, mask));
|
||||
TunnelAddress {
|
||||
address,
|
||||
netmask: configuration.netmask6,
|
||||
prefix_length,
|
||||
}
|
||||
});
|
||||
let mut configuration = TunnelConfiguration {
|
||||
interface: configuration.interface,
|
||||
ipv4,
|
||||
ipv6,
|
||||
server_ip: configuration.server_ip,
|
||||
dns: list(configuration.dns),
|
||||
search_domains: list(configuration.search_domains),
|
||||
split_dns: list(configuration.split_dns),
|
||||
included_routes: list(configuration.included_routes),
|
||||
excluded_routes: list(configuration.excluded_routes),
|
||||
mtu: configuration.mtu,
|
||||
truncated: configuration.truncated,
|
||||
};
|
||||
assert!(configuration.limit_encoded_size(MAX_CONFIGURATION_BYTES));
|
||||
configuration
|
||||
}
|
||||
|
||||
fn list(list: NativeList) -> TunnelList {
|
||||
TunnelList {
|
||||
items: list.items,
|
||||
total_count: list.total_count,
|
||||
truncated: list.truncated,
|
||||
}
|
||||
}
|
||||
|
||||
fn ipv4_prefix(mask: &str) -> Option<u8> {
|
||||
let mask = u32::from(mask.parse::<Ipv4Addr>().ok()?);
|
||||
let prefix = mask.leading_ones();
|
||||
let expected = if prefix == 0 { 0 } else { u32::MAX << (32 - prefix) };
|
||||
(mask == expected).then_some(prefix as u8)
|
||||
}
|
||||
|
||||
fn ipv6_prefix(address: &str, mask: &str) -> Option<u8> {
|
||||
let (network_address, prefix) = mask.split_once('/')?;
|
||||
if network_address.parse::<Ipv6Addr>().ok()? != address.parse::<Ipv6Addr>().ok()? {
|
||||
return None;
|
||||
}
|
||||
prefix.parse::<u8>().ok().filter(|prefix| *prefix <= 128)
|
||||
}
|
||||
|
||||
fn escaped(value: &str) -> String {
|
||||
value.chars().flat_map(char::escape_debug).collect()
|
||||
}
|
||||
|
||||
fn optional(value: Option<&str>) -> String {
|
||||
value.map(escaped).unwrap_or_else(|| "none".into())
|
||||
}
|
||||
|
||||
fn addresses(address: Option<&TunnelAddress>) -> String {
|
||||
match address {
|
||||
Some(address) => escaped(&address.display()),
|
||||
None => "none".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn values(list: &TunnelList) -> String {
|
||||
let mut value = if list.items.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
list
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| escaped(item))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
};
|
||||
if list.truncated {
|
||||
value.push_str(&format!(
|
||||
" ({} of {} shown; truncated)",
|
||||
list.items.len(),
|
||||
list.total_count
|
||||
));
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
pub(crate) fn log_configuration(state: &TunnelState) {
|
||||
debug!(
|
||||
"VPN configuration: tunnel {}, revision {}",
|
||||
state.tunnel_id, state.configuration_revision
|
||||
);
|
||||
let Some(configuration) = &state.configuration else {
|
||||
info!("VPN configuration: unavailable");
|
||||
return;
|
||||
};
|
||||
info!("VPN interface: {}", optional(configuration.interface.as_deref()));
|
||||
info!("VPN IPv4: {}", addresses(configuration.ipv4.as_ref()));
|
||||
info!("VPN IPv6: {}", addresses(configuration.ipv6.as_ref()));
|
||||
info!("VPN gateway IP: {}", optional(configuration.server_ip.as_deref()));
|
||||
info!("VPN DNS: {}", values(&configuration.dns));
|
||||
info!("VPN search domains: {}", values(&configuration.search_domains));
|
||||
info!("VPN split DNS: {}", values(&configuration.split_dns));
|
||||
info!(
|
||||
"VPN routes: {} included, {} excluded",
|
||||
configuration.included_routes.total_count, configuration.excluded_routes.total_count
|
||||
);
|
||||
for (kind, routes) in [
|
||||
("included", &configuration.included_routes),
|
||||
("excluded", &configuration.excluded_routes),
|
||||
] {
|
||||
for route in &routes.items {
|
||||
debug!("VPN {kind} route: {}", escaped(route));
|
||||
}
|
||||
if routes.truncated {
|
||||
debug!(
|
||||
"VPN {kind} routes truncated ({} of {} shown)",
|
||||
routes.items.len(),
|
||||
routes.total_count
|
||||
);
|
||||
}
|
||||
}
|
||||
let mtu = configuration
|
||||
.mtu
|
||||
.map(|mtu| mtu.to_string())
|
||||
.unwrap_or_else(|| "unavailable".into());
|
||||
info!("VPN MTU: {mtu}");
|
||||
if configuration.truncated {
|
||||
info!("VPN configuration: truncated");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn masks_preserve_missing_or_invalid_prefixes() {
|
||||
let configuration = normalize(Configuration {
|
||||
ipv4: Some("10.0.0.2".into()),
|
||||
netmask: Some("255.0.255.0".into()),
|
||||
ipv6: Some("2001:db8::2".into()),
|
||||
netmask6: Some("2001:db8::2/64".into()),
|
||||
..Default::default()
|
||||
});
|
||||
let ipv4 = configuration.ipv4.unwrap();
|
||||
assert_eq!(ipv4.prefix_length, None);
|
||||
assert_eq!(ipv4.netmask.as_deref(), Some("255.0.255.0"));
|
||||
assert_eq!(ipv4.display(), "10.0.0.2 (mask 255.0.255.0)");
|
||||
assert_eq!(configuration.ipv6.unwrap().prefix_length, Some(64));
|
||||
assert_eq!(ipv4_prefix("0.0.0.0"), Some(0));
|
||||
assert_eq!(ipv4_prefix("255.255.255.255"), Some(32));
|
||||
assert_eq!(ipv6_prefix("2001:db8::2", "2001:db8::3/64"), None);
|
||||
assert_eq!(
|
||||
normalize(Configuration {
|
||||
ipv4: Some("invalid".into()),
|
||||
netmask: Some("255.255.255.0".into()),
|
||||
..Default::default()
|
||||
})
|
||||
.ipv4
|
||||
.unwrap()
|
||||
.prefix_length,
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
normalize(Configuration {
|
||||
ipv4: Some("10.0.0.2".into()),
|
||||
..Default::default()
|
||||
})
|
||||
.ipv4
|
||||
.unwrap()
|
||||
.prefix_length,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_route_lists_fit_the_contract_budget_without_claiming_completeness() {
|
||||
let routes = NativeList {
|
||||
items: vec!["\u{1}".repeat(1024); 16],
|
||||
total_count: 20,
|
||||
truncated: true,
|
||||
};
|
||||
let configuration = normalize(Configuration {
|
||||
included_routes: routes,
|
||||
..Default::default()
|
||||
});
|
||||
assert!(serde_json::to_vec(&configuration).unwrap().len() <= MAX_CONFIGURATION_BYTES);
|
||||
assert_eq!(configuration.included_routes.total_count, 20);
|
||||
assert!(configuration.included_routes.truncated);
|
||||
assert!(configuration.truncated);
|
||||
assert!(configuration.included_routes.items.len() < 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_characters_cannot_create_log_lines_or_terminal_sequences() {
|
||||
assert_eq!(escaped("corp\n\u{1b}[2J"), "corp\\n\\u{1b}[2J");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! Shared observation of native tunnels, independent of terminal and service transport.
|
||||
|
||||
mod configuration;
|
||||
mod monitor;
|
||||
|
||||
pub use monitor::{TunnelMonitor, TunnelUpdate};
|
||||
@@ -0,0 +1,637 @@
|
||||
use std::{
|
||||
sync::{Arc, Mutex, Weak},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use gpapi::session::tunnel::{
|
||||
TunnelPhase, TunnelState, TunnelStatistics, TunnelStatisticsSnapshot, TunnelStatisticsState, TunnelStatisticsView,
|
||||
TunnelTransport,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use openconnect::{
|
||||
Vpn,
|
||||
tunnel::{Event, Statistics, Transport},
|
||||
};
|
||||
use tokio::{
|
||||
sync::{Notify, watch},
|
||||
task::JoinHandle,
|
||||
time::Instant,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::configuration::{log_configuration, normalize};
|
||||
|
||||
const SAMPLE_INTERVAL: Duration = Duration::from_secs(2);
|
||||
const SAMPLE_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TunnelUpdate {
|
||||
pub state: TunnelState,
|
||||
pub statistics: TunnelStatisticsSnapshot,
|
||||
}
|
||||
|
||||
struct RequestStamp {
|
||||
generation: u64,
|
||||
state_sequence: u64,
|
||||
issued: Instant,
|
||||
}
|
||||
|
||||
struct RetainedSample {
|
||||
value: TunnelStatistics,
|
||||
acquired: Instant,
|
||||
}
|
||||
|
||||
struct Observation {
|
||||
state: TunnelState,
|
||||
sequence: u64,
|
||||
statistics_sequence: u64,
|
||||
started: Option<Instant>,
|
||||
ended_elapsed: Option<u64>,
|
||||
configuration_observed: bool,
|
||||
enabled: bool,
|
||||
generation: u64,
|
||||
pending: Option<RequestStamp>,
|
||||
sample: Option<RetainedSample>,
|
||||
statistics_state: TunnelStatisticsState,
|
||||
finished: bool,
|
||||
request_failed: bool,
|
||||
}
|
||||
|
||||
impl Observation {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
state: TunnelState {
|
||||
tunnel_id: Uuid::new_v4(),
|
||||
sequence: 1,
|
||||
phase: TunnelPhase::Establishing,
|
||||
configuration_revision: 0,
|
||||
configuration: None,
|
||||
transport: TunnelTransport::Negotiating,
|
||||
elapsed_ms: 0,
|
||||
},
|
||||
sequence: 1,
|
||||
statistics_sequence: 1,
|
||||
started: None,
|
||||
ended_elapsed: None,
|
||||
configuration_observed: false,
|
||||
enabled: false,
|
||||
generation: 0,
|
||||
pending: None,
|
||||
sample: None,
|
||||
statistics_state: TunnelStatisticsState::Disabled,
|
||||
finished: false,
|
||||
request_failed: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_sequence(&mut self) -> u64 {
|
||||
// A 64-bit sequence cannot exhaust in a practical tunnel lifetime. Never
|
||||
// wrap an ordering token into an earlier generation.
|
||||
self.sequence = self
|
||||
.sequence
|
||||
.checked_add(1)
|
||||
.expect("tunnel observation sequence exhausted");
|
||||
self.sequence
|
||||
}
|
||||
|
||||
fn elapsed_ms(&self, now: Instant) -> u64 {
|
||||
if let Some(elapsed) = self.ended_elapsed {
|
||||
return elapsed;
|
||||
}
|
||||
self
|
||||
.started
|
||||
.map_or(0, |started| millis(now.saturating_duration_since(started)))
|
||||
}
|
||||
|
||||
fn active(&self) -> bool {
|
||||
!self.finished && self.state.phase == TunnelPhase::Connected && self.state.transport.is_active()
|
||||
}
|
||||
|
||||
fn project(&self, now: Instant) -> TunnelUpdate {
|
||||
let mut state = self.state.clone();
|
||||
state.elapsed_ms = self.elapsed_ms(now);
|
||||
let statistics = TunnelStatisticsSnapshot::Available(TunnelStatisticsView {
|
||||
sequence: self.statistics_sequence,
|
||||
tunnel_id: state.tunnel_id,
|
||||
state_sequence: state.sequence,
|
||||
phase: state.phase,
|
||||
transport: state.transport,
|
||||
state: self.statistics_state,
|
||||
elapsed_ms: state.elapsed_ms,
|
||||
sample_age_ms: self
|
||||
.sample
|
||||
.as_ref()
|
||||
.map(|sample| millis(now.saturating_duration_since(sample.acquired))),
|
||||
sample: self.sample.as_ref().map(|sample| sample.value.clone()),
|
||||
});
|
||||
TunnelUpdate { state, statistics }
|
||||
}
|
||||
|
||||
fn invalidate_statistics(&mut self) {
|
||||
self.statistics_state = if self.finished {
|
||||
TunnelStatisticsState::Ended
|
||||
} else if !self.enabled {
|
||||
TunnelStatisticsState::Disabled
|
||||
} else if self.sample.is_some() || !self.active() {
|
||||
TunnelStatisticsState::Stale
|
||||
} else {
|
||||
TunnelStatisticsState::Waiting
|
||||
};
|
||||
self.statistics_sequence = self.next_sequence();
|
||||
}
|
||||
|
||||
fn state_changed(&mut self) {
|
||||
self.state.sequence = self.next_sequence();
|
||||
self.invalidate_statistics();
|
||||
}
|
||||
|
||||
fn enable(&mut self, enabled: bool) -> bool {
|
||||
if self.finished || self.enabled == enabled {
|
||||
return false;
|
||||
}
|
||||
self.enabled = enabled;
|
||||
self.generation = self
|
||||
.generation
|
||||
.checked_add(1)
|
||||
.expect("tunnel collection generation exhausted");
|
||||
self.statistics_state = if enabled {
|
||||
TunnelStatisticsState::Waiting
|
||||
} else {
|
||||
TunnelStatisticsState::Disabled
|
||||
};
|
||||
self.statistics_sequence = self.next_sequence();
|
||||
true
|
||||
}
|
||||
|
||||
fn finish(&mut self, now: Instant) {
|
||||
if self.finished {
|
||||
return;
|
||||
}
|
||||
self.ended_elapsed = Some(self.elapsed_ms(now));
|
||||
self.finished = true;
|
||||
self.enabled = false;
|
||||
self.pending = None;
|
||||
self.state.phase = TunnelPhase::Ended;
|
||||
self.state.transport = TunnelTransport::Unavailable;
|
||||
self.state_changed();
|
||||
}
|
||||
|
||||
/// Returns whether the configuration/transport should be logged. Logging is
|
||||
/// performed outside the observation lock and never includes traffic samples.
|
||||
fn apply(&mut self, event: Event, now: Instant) -> (bool, bool) {
|
||||
if self.finished {
|
||||
return (false, false);
|
||||
}
|
||||
match event {
|
||||
Event::Configuration(configuration) => {
|
||||
let configuration = configuration.map(normalize);
|
||||
if self.configuration_observed && self.state.configuration == configuration {
|
||||
return (false, false);
|
||||
}
|
||||
self.configuration_observed = true;
|
||||
self.state.configuration = configuration;
|
||||
self.state.configuration_revision = self
|
||||
.state
|
||||
.configuration_revision
|
||||
.checked_add(1)
|
||||
.expect("configuration revision exhausted");
|
||||
self.state_changed();
|
||||
(true, false)
|
||||
}
|
||||
Event::Established => {
|
||||
self.started.get_or_insert(now);
|
||||
if self.state.phase != TunnelPhase::Connected {
|
||||
self.state.phase = TunnelPhase::Connected;
|
||||
self.state_changed();
|
||||
}
|
||||
(false, false)
|
||||
}
|
||||
Event::Reconnected => {
|
||||
if self.started.is_some() && self.state.phase != TunnelPhase::Connected {
|
||||
self.state.phase = TunnelPhase::Connected;
|
||||
self.state_changed();
|
||||
}
|
||||
(false, false)
|
||||
}
|
||||
Event::Reconnecting => {
|
||||
let phase = if self.started.is_some() {
|
||||
TunnelPhase::Reconnecting
|
||||
} else {
|
||||
TunnelPhase::Establishing
|
||||
};
|
||||
if self.state.phase != phase {
|
||||
self.state.phase = phase;
|
||||
self.state_changed();
|
||||
}
|
||||
(false, false)
|
||||
}
|
||||
Event::Transport(transport) => {
|
||||
let transport = match transport {
|
||||
Transport::Negotiating => TunnelTransport::Negotiating,
|
||||
Transport::IpsecEsp => TunnelTransport::IpsecEsp,
|
||||
Transport::SslTls => TunnelTransport::SslTls,
|
||||
Transport::Unavailable => TunnelTransport::Unavailable,
|
||||
};
|
||||
if self.state.transport == transport {
|
||||
return (false, false);
|
||||
}
|
||||
self.state.transport = transport;
|
||||
self.state_changed();
|
||||
(false, true)
|
||||
}
|
||||
Event::Statistics(statistics) => {
|
||||
self.receive_statistics(statistics, now);
|
||||
(false, false)
|
||||
}
|
||||
Event::Ended => {
|
||||
self.finish(now);
|
||||
(false, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_statistics(&mut self, statistics: Statistics, now: Instant) {
|
||||
let Some(stamp) = self.pending.take() else {
|
||||
return;
|
||||
};
|
||||
if !self.enabled
|
||||
|| !self.active()
|
||||
|| stamp.generation != self.generation
|
||||
|| stamp.state_sequence != self.state.sequence
|
||||
{
|
||||
return;
|
||||
}
|
||||
let sequence = self.next_sequence();
|
||||
self.sample = Some(RetainedSample {
|
||||
value: TunnelStatistics {
|
||||
tunnel_id: self.state.tunnel_id,
|
||||
sequence,
|
||||
state_sequence: self.state.sequence,
|
||||
configuration_revision: self.state.configuration_revision,
|
||||
elapsed_ms: self.elapsed_ms(now),
|
||||
received_bytes: statistics.received_bytes,
|
||||
sent_bytes: statistics.sent_bytes,
|
||||
received_packets: statistics.received_packets,
|
||||
sent_packets: statistics.sent_packets,
|
||||
},
|
||||
acquired: now,
|
||||
});
|
||||
self.statistics_sequence = sequence;
|
||||
self.statistics_state = TunnelStatisticsState::Fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/// One native tunnel's negotiated state and optional sampler. The connection
|
||||
/// owner must join `Vpn::connect` before calling `stop`.
|
||||
pub struct TunnelMonitor {
|
||||
vpn: Arc<Vpn>,
|
||||
observation: Mutex<Observation>,
|
||||
updates: watch::Sender<TunnelUpdate>,
|
||||
wake: Arc<Notify>,
|
||||
worker: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl TunnelMonitor {
|
||||
pub fn attach(vpn: Arc<Vpn>) -> Arc<Self> {
|
||||
let observation = Observation::new();
|
||||
let (updates, _) = watch::channel(observation.project(Instant::now()));
|
||||
let monitor = Arc::new(Self {
|
||||
vpn,
|
||||
observation: Mutex::new(observation),
|
||||
updates,
|
||||
wake: Arc::new(Notify::new()),
|
||||
worker: Mutex::new(None),
|
||||
});
|
||||
let observer = Arc::downgrade(&monitor);
|
||||
monitor.vpn.set_tunnel_observer(move |event| {
|
||||
if let Some(monitor) = observer.upgrade() {
|
||||
monitor.observe(event);
|
||||
}
|
||||
});
|
||||
let worker = tokio::spawn(sample(Arc::downgrade(&monitor), monitor.wake.clone()));
|
||||
*monitor.worker.lock().unwrap() = Some(worker);
|
||||
monitor
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> watch::Receiver<TunnelUpdate> {
|
||||
self.updates.subscribe()
|
||||
}
|
||||
|
||||
pub fn state(&self) -> TunnelState {
|
||||
self.observation.lock().unwrap().project(Instant::now()).state
|
||||
}
|
||||
|
||||
pub fn statistics(&self) -> TunnelStatisticsSnapshot {
|
||||
self.observation.lock().unwrap().project(Instant::now()).statistics
|
||||
}
|
||||
|
||||
pub fn set_statistics_enabled(&self, enabled: bool) {
|
||||
let mut observation = self.observation.lock().unwrap();
|
||||
if observation.enable(enabled) {
|
||||
self.publish(&observation);
|
||||
self.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
/// End observation after native execution has returned. This does not request
|
||||
/// VPN disconnect or take over its credential/network cleanup.
|
||||
pub fn finish(&self) {
|
||||
let mut observation = self.observation.lock().unwrap();
|
||||
observation.finish(Instant::now());
|
||||
self.publish(&observation);
|
||||
drop(observation);
|
||||
self.vpn.clear_tunnel_observer();
|
||||
self.wake.notify_one();
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.finish();
|
||||
let worker = self.worker.lock().unwrap().take();
|
||||
if let Some(worker) = worker {
|
||||
let _ = worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn publish(&self, observation: &Observation) {
|
||||
self.updates.send_replace(observation.project(Instant::now()));
|
||||
}
|
||||
|
||||
fn observe(&self, event: Event) {
|
||||
let is_statistics = matches!(event, Event::Statistics(_));
|
||||
let mut observation = self.observation.lock().unwrap();
|
||||
let (configuration_changed, transport_changed) = observation.apply(event, Instant::now());
|
||||
self.publish(&observation);
|
||||
let state = observation.project(Instant::now()).state;
|
||||
let retry = is_statistics
|
||||
&& observation.sample.as_ref().is_none_or(|sample| {
|
||||
sample.value.state_sequence != observation.state.sequence
|
||||
|| observation.statistics_state != TunnelStatisticsState::Fresh
|
||||
});
|
||||
drop(observation);
|
||||
if configuration_changed {
|
||||
log_configuration(&state);
|
||||
}
|
||||
if transport_changed {
|
||||
info!("VPN transport: {}", state.transport.label());
|
||||
}
|
||||
if !is_statistics || retry {
|
||||
self.wake.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn request_sample(&self) -> bool {
|
||||
let mut observation = self.observation.lock().unwrap();
|
||||
if observation.finished {
|
||||
return false;
|
||||
}
|
||||
if !observation.enabled || !observation.active() {
|
||||
return true;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if let Some(pending) = &observation.pending {
|
||||
if now.saturating_duration_since(pending.issued) >= SAMPLE_TIMEOUT
|
||||
&& observation.statistics_state != TunnelStatisticsState::Stale
|
||||
{
|
||||
observation.statistics_state = TunnelStatisticsState::Stale;
|
||||
observation.statistics_sequence = observation.next_sequence();
|
||||
self.publish(&observation);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
match self.vpn.request_statistics() {
|
||||
Ok(true) => {
|
||||
observation.pending = Some(RequestStamp {
|
||||
generation: observation.generation,
|
||||
state_sequence: observation.state.sequence,
|
||||
issued: now,
|
||||
});
|
||||
observation.request_failed = false;
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(error) => {
|
||||
if !observation.request_failed {
|
||||
warn!("VPN statistics request failed: {error}");
|
||||
observation.request_failed = true;
|
||||
}
|
||||
observation.statistics_state = TunnelStatisticsState::Stale;
|
||||
observation.statistics_sequence = observation.next_sequence();
|
||||
self.publish(&observation);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TunnelMonitor {
|
||||
fn drop(&mut self) {
|
||||
self.vpn.clear_tunnel_observer();
|
||||
if let Some(worker) = self.worker.get_mut().unwrap().take() {
|
||||
worker.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn sample(monitor: Weak<TunnelMonitor>, wake: Arc<Notify>) {
|
||||
loop {
|
||||
let enabled = {
|
||||
let Some(monitor) = monitor.upgrade() else {
|
||||
return;
|
||||
};
|
||||
if !monitor.request_sample() {
|
||||
return;
|
||||
}
|
||||
monitor.observation.lock().unwrap().enabled
|
||||
};
|
||||
if enabled {
|
||||
tokio::select! {
|
||||
_ = wake.notified() => {}
|
||||
_ = tokio::time::sleep(SAMPLE_INTERVAL) => {}
|
||||
}
|
||||
} else {
|
||||
wake.notified().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn millis(duration: Duration) -> u64 {
|
||||
duration.as_millis().min(u64::MAX as u128) as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn connected(now: Instant) -> Observation {
|
||||
let mut observation = Observation::new();
|
||||
observation.apply(Event::Established, now);
|
||||
observation.apply(Event::Transport(Transport::IpsecEsp), now);
|
||||
observation
|
||||
}
|
||||
|
||||
fn request(observation: &mut Observation, now: Instant) {
|
||||
observation.pending = Some(RequestStamp {
|
||||
generation: observation.generation,
|
||||
state_sequence: observation.state.sequence,
|
||||
issued: now,
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retries_before_first_tun_establishment_do_not_start_session_elapsed_time() {
|
||||
let now = Instant::now();
|
||||
let mut observation = Observation::new();
|
||||
observation.apply(Event::Reconnecting, now);
|
||||
observation.apply(Event::Reconnected, now + Duration::from_secs(10));
|
||||
let update = observation.project(now + Duration::from_secs(60));
|
||||
assert_eq!(update.state.phase, TunnelPhase::Establishing);
|
||||
assert_eq!(update.state.elapsed_ms, 0);
|
||||
assert_eq!(update.statistics.view().unwrap().elapsed_ms, 0);
|
||||
observation.apply(Event::Established, now + Duration::from_secs(61));
|
||||
assert_eq!(
|
||||
observation.project(now + Duration::from_secs(62)).state.elapsed_ms,
|
||||
1000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_sample_after_disable_reenable_cannot_become_fresh() {
|
||||
let now = Instant::now();
|
||||
let mut observation = connected(now);
|
||||
observation.enable(true);
|
||||
request(&mut observation, now);
|
||||
observation.enable(false);
|
||||
observation.enable(true);
|
||||
observation.receive_statistics(
|
||||
Statistics {
|
||||
received_bytes: 5,
|
||||
..Default::default()
|
||||
},
|
||||
now,
|
||||
);
|
||||
assert!(observation.pending.is_none());
|
||||
assert!(observation.sample.is_none());
|
||||
assert_eq!(observation.statistics_state, TunnelStatisticsState::Waiting);
|
||||
request(&mut observation, now);
|
||||
observation.receive_statistics(
|
||||
Statistics {
|
||||
received_bytes: 8,
|
||||
..Default::default()
|
||||
},
|
||||
now,
|
||||
);
|
||||
assert_eq!(observation.sample.as_ref().unwrap().value.received_bytes, 8);
|
||||
assert_eq!(observation.statistics_state, TunnelStatisticsState::Fresh);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_preserves_elapsed_and_rejects_old_transport_sample() {
|
||||
let now = Instant::now();
|
||||
let mut observation = connected(now);
|
||||
observation.enable(true);
|
||||
request(&mut observation, now);
|
||||
observation.apply(Event::Reconnecting, now + Duration::from_secs(2));
|
||||
observation.apply(Event::Transport(Transport::Unavailable), now + Duration::from_secs(2));
|
||||
observation.apply(Event::Reconnected, now + Duration::from_secs(5));
|
||||
observation.apply(Event::Transport(Transport::SslTls), now + Duration::from_secs(5));
|
||||
observation.receive_statistics(Statistics::default(), now + Duration::from_secs(5));
|
||||
assert!(observation.sample.is_none());
|
||||
request(&mut observation, now + Duration::from_secs(5));
|
||||
observation.receive_statistics(
|
||||
Statistics {
|
||||
sent_bytes: 40,
|
||||
..Default::default()
|
||||
},
|
||||
now + Duration::from_secs(6),
|
||||
);
|
||||
assert_eq!(observation.elapsed_ms(now + Duration::from_secs(6)), 6000);
|
||||
assert_eq!(observation.sample.as_ref().unwrap().value.sent_bytes, 40);
|
||||
assert_eq!(observation.statistics_state, TunnelStatisticsState::Fresh);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_projection_does_not_poll_or_rewrite_acquisition_time() {
|
||||
let now = Instant::now();
|
||||
let mut observation = connected(now);
|
||||
observation.enable(true);
|
||||
request(&mut observation, now);
|
||||
observation.receive_statistics(Statistics::default(), now + Duration::from_secs(1));
|
||||
let later = observation.project(now + Duration::from_secs(600));
|
||||
assert_eq!(later.state.elapsed_ms, 600000);
|
||||
let view = later.statistics.view().unwrap();
|
||||
assert_eq!(view.sample_age_ms, Some(599000));
|
||||
assert_eq!(view.sample.as_ref().unwrap().elapsed_ms, 1000);
|
||||
assert!(observation.pending.is_none());
|
||||
observation.finish(now + Duration::from_secs(601));
|
||||
assert_eq!(
|
||||
observation.project(now + Duration::from_secs(700)).state.elapsed_ms,
|
||||
601000
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn sampling_is_demand_driven_and_coalesces_commands_on_the_native_pipe() {
|
||||
use std::{
|
||||
io::Read,
|
||||
os::{fd::AsRawFd, unix::net::UnixStream},
|
||||
};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn vpn_attach_command_pipe(vpn: *mut std::ffi::c_void, fd: std::ffi::c_int) -> std::ffi::c_int;
|
||||
fn vpn_detach_command_pipe(vpn: *mut std::ffi::c_void);
|
||||
}
|
||||
|
||||
let vpn = Arc::new(
|
||||
Vpn::builder("vpn.example.com", "cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let (sender, mut receiver) = UnixStream::pair().unwrap();
|
||||
sender.set_nonblocking(true).unwrap();
|
||||
receiver.set_nonblocking(true).unwrap();
|
||||
let pointer = Arc::as_ptr(&vpn).cast_mut().cast();
|
||||
// SAFETY: this test owns the live Vpn and both socket endpoints, and detaches
|
||||
// the borrowed command descriptor before either endpoint or Vpn is dropped.
|
||||
assert_eq!(unsafe { vpn_attach_command_pipe(pointer, sender.as_raw_fd()) }, 0);
|
||||
let monitor = TunnelMonitor::attach(vpn.clone());
|
||||
monitor.observe(Event::Established);
|
||||
monitor.observe(Event::Transport(Transport::IpsecEsp));
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(Duration::from_secs(60)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let mut command = [0];
|
||||
assert_eq!(
|
||||
receiver.read(&mut command).unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
assert!(monitor.observation.lock().unwrap().pending.is_none());
|
||||
assert_eq!(
|
||||
monitor.statistics().view().unwrap().state,
|
||||
TunnelStatisticsState::Disabled
|
||||
);
|
||||
|
||||
monitor.set_statistics_enabled(true);
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(receiver.read(&mut command).unwrap(), 1);
|
||||
assert_eq!(command, [b's']);
|
||||
tokio::time::advance(Duration::from_secs(6)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
receiver.read(&mut command).unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
assert_eq!(monitor.statistics().view().unwrap().state, TunnelStatisticsState::Stale);
|
||||
monitor.set_statistics_enabled(false);
|
||||
tokio::time::advance(Duration::from_secs(60)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
receiver.read(&mut command).unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
|
||||
monitor.stop().await;
|
||||
// SAFETY: pointer still identifies the Vpn retained by this test.
|
||||
unsafe { vpn_detach_command_pipe(pointer) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "gpvpnc"
|
||||
rust-version.workspace = true
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
log.workspace = true
|
||||
@@ -0,0 +1,2 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod macos;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,231 @@
|
||||
use std::{
|
||||
io::{self, BufRead, BufReader, Read},
|
||||
process::{Command, Stdio},
|
||||
thread,
|
||||
};
|
||||
|
||||
const VPNC_SCRIPT: &str = include_str!("macos-vpnc-script.sh");
|
||||
|
||||
pub fn configure_network(reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
|
||||
run_script(VPNC_SCRIPT, reason, environment)
|
||||
}
|
||||
|
||||
fn run_script(script: &str, reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
|
||||
// Only compiled-in content reaches the shell. Gateway values stay in a
|
||||
// child-local environment, never interpolated into shell commands.
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.args(["-c", script, "vpnc-script"]).env_clear().current_dir("/");
|
||||
for (name, value) in environment {
|
||||
match value {
|
||||
Some(value) => {
|
||||
command.env(name, value);
|
||||
}
|
||||
None => {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
command
|
||||
.env("reason", reason)
|
||||
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
|
||||
.env("HOME", "/var/root")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = command.spawn()?;
|
||||
let stdout = child.stdout.take().expect("stdout is piped");
|
||||
let stderr = child.stderr.take().expect("stderr is piped");
|
||||
let status = thread::scope(|scope| {
|
||||
// Drain both pipes while waiting, so either stream can exceed pipe capacity.
|
||||
let stdout = scope.spawn(|| log_output(stdout, reason, log::Level::Info));
|
||||
let stderr = scope.spawn(|| log_output(stderr, reason, log::Level::Warn));
|
||||
let status = child.wait();
|
||||
let stdout = stdout
|
||||
.join()
|
||||
.unwrap_or_else(|_| Err(io::Error::other("VPN script stdout reader panicked")));
|
||||
let stderr = stderr
|
||||
.join()
|
||||
.unwrap_or_else(|_| Err(io::Error::other("VPN script stderr reader panicked")));
|
||||
stdout?;
|
||||
stderr?;
|
||||
status
|
||||
})?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(format!(
|
||||
"VPN configuration failed for {reason}: {status}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn log_output(output: impl Read, reason: &str, level: log::Level) -> io::Result<()> {
|
||||
let mut reader = BufReader::new(output);
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
// Split oversized lines into bounded chunks, including output without a newline.
|
||||
if reader.by_ref().take(8192).read_until(b'\n', &mut line)? == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if line.last() == Some(&b'\n') {
|
||||
line.pop();
|
||||
if line.last() == Some(&b'\r') {
|
||||
line.pop();
|
||||
}
|
||||
}
|
||||
log::log!(level, "vpnc-script [{reason}]: {}", String::from_utf8_lossy(&line));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct CapturedLogs(Mutex<Vec<(log::Level, String)>>);
|
||||
|
||||
static LOGS: CapturedLogs = CapturedLogs(Mutex::new(Vec::new()));
|
||||
|
||||
impl log::Log for CapturedLogs {
|
||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
let message = record.args().to_string();
|
||||
if message.starts_with("vpnc-script [capture-test]: ") {
|
||||
self.0.lock().unwrap().push((record.level(), message));
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captures_both_streams_with_levels_and_reason_even_on_failure() {
|
||||
log::set_logger(&LOGS).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Info);
|
||||
let error = run_script(
|
||||
"printf 'first\\n\\nlast'; printf 'warning\\r\\nfinal' >&2; exit 23",
|
||||
"capture-test",
|
||||
&[],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("23"));
|
||||
let mut records = std::mem::take(&mut *LOGS.0.lock().unwrap());
|
||||
records.sort();
|
||||
let mut expected = vec![
|
||||
(log::Level::Info, "vpnc-script [capture-test]: first".to_string()),
|
||||
(log::Level::Info, "vpnc-script [capture-test]: ".to_string()),
|
||||
(log::Level::Info, "vpnc-script [capture-test]: last".to_string()),
|
||||
(log::Level::Warn, "vpnc-script [capture-test]: warning".to_string()),
|
||||
(log::Level::Warn, "vpnc-script [capture-test]: final".to_string()),
|
||||
];
|
||||
expected.sort();
|
||||
assert_eq!(records, expected);
|
||||
|
||||
// Each stream exceeds pipe capacity. Both must be drained before wait returns.
|
||||
run_script(
|
||||
r#"
|
||||
i=0
|
||||
while [ "$i" -lt 3000 ]; do
|
||||
printf 'stdout-abcdefghijklmnopqrstuvwxyz0123456789\n'
|
||||
printf 'stderr-abcdefghijklmnopqrstuvwxyz0123456789\n' >&2
|
||||
i=$((i + 1))
|
||||
done
|
||||
"#,
|
||||
"capture-test",
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let records = std::mem::take(&mut *LOGS.0.lock().unwrap());
|
||||
assert_eq!(
|
||||
records.iter().filter(|(level, _)| *level == log::Level::Info).count(),
|
||||
3000
|
||||
);
|
||||
assert_eq!(
|
||||
records.iter().filter(|(level, _)| *level == log::Level::Warn).count(),
|
||||
3000
|
||||
);
|
||||
|
||||
log_output(&vec![b'x'; 20000][..], "capture-test", log::Level::Info).unwrap();
|
||||
log_output(&[0xff, b'\n'][..], "capture-test", log::Level::Warn).unwrap();
|
||||
let records = std::mem::take(&mut *LOGS.0.lock().unwrap());
|
||||
let prefix = "vpnc-script [capture-test]: ";
|
||||
assert_eq!(records.len(), 4);
|
||||
assert_eq!(records[0].1.len() - prefix.len(), 8192);
|
||||
assert_eq!(records[1].1.len() - prefix.len(), 8192);
|
||||
assert_eq!(records[2].1.len() - prefix.len(), 3616);
|
||||
assert_eq!(records[3], (log::Level::Warn, format!("{prefix}\u{fffd}")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_shell_syntax_is_valid_and_does_not_load_vpnc_hooks() {
|
||||
assert!(
|
||||
Command::new("/bin/sh")
|
||||
.args(["-n", "-c", VPNC_SCRIPT, "vpnc-script"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(!VPNC_SCRIPT.contains("/etc/vpnc"));
|
||||
assert!(!VPNC_SCRIPT.contains("run_hooks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tunnel_self_routes_are_skipped_without_skipping_other_routes() {
|
||||
// Exercise the embedded route functions with a recorder instead of changing
|
||||
// the host's routing table or running the script's initialization.
|
||||
let mut script = String::from(
|
||||
"route() { printf '%s\\n' \"$*\"; }\n\
|
||||
INTERNAL_IP4_ADDRESS=10.197.121.133\n\
|
||||
route_syntax_netmask=-netmask\n\
|
||||
route_syntax_del=delete\n",
|
||||
);
|
||||
for name in ["set_network_route", "del_network_route"] {
|
||||
let declaration = format!("\t{name}() {{");
|
||||
let start = VPNC_SCRIPT.rfind(&declaration).unwrap();
|
||||
let end = start + VPNC_SCRIPT[start..].find("\n\t}").unwrap() + 3;
|
||||
script.push_str(&VPNC_SCRIPT[start..end]);
|
||||
script.push('\n');
|
||||
}
|
||||
script.push_str(
|
||||
"set_network_route 10.197.121.133 255.255.255.255 32 utun7\n\
|
||||
del_network_route 10.197.121.133 255.255.255.255 32 utun7\n\
|
||||
set_network_route 10.15.70.11 255.255.255.255 32 utun7\n\
|
||||
set_network_route 10.0.0.0 255.0.0.0 8 utun7\n\
|
||||
del_network_route 10.15.70.11 255.255.255.255 32 utun7\n\
|
||||
set_network_route 10.197.121.133 255.255.255.255 32 utun7 10.197.121.1\n",
|
||||
);
|
||||
let output = Command::new("/bin/sh").args(["-c", &script]).output().unwrap();
|
||||
assert!(output.status.success());
|
||||
assert!(output.stderr.is_empty());
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stdout).unwrap(),
|
||||
"add -net 10.15.70.11 -netmask 255.255.255.255 10.197.121.133\n\
|
||||
add -net 10.0.0.0 -netmask 255.0.0.0 10.197.121.133\n\
|
||||
delete -net 10.15.70.11 -netmask 255.255.255.255 10.197.121.133\n\
|
||||
add -net 10.197.121.133 -netmask 255.255.255.255 10.197.121.1\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runner_passes_configuration_as_data_and_uses_a_trusted_environment() {
|
||||
let environment = vec![
|
||||
("TUNDEV".into(), Some("utun3; exit 99".into())),
|
||||
("UNSET_VARIABLE".into(), None),
|
||||
("PATH".into(), Some("/untrusted".into())),
|
||||
];
|
||||
run_script(
|
||||
r#"
|
||||
[ "$0" = vpnc-script ] && [ "$reason" = connect ] &&
|
||||
[ "$TUNDEV" = 'utun3; exit 99' ] && [ -z "${UNSET_VARIABLE+x}" ] &&
|
||||
[ "$PATH" = /usr/bin:/bin:/usr/sbin:/sbin ] && [ "$HOME" = /var/root ]
|
||||
"#,
|
||||
"connect",
|
||||
&environment,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(run_script("exit 23", "connect", &environment).is_err());
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,11 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
config.disable_static().enable_shared().without("gnutls", None);
|
||||
config
|
||||
.disable_static()
|
||||
.enable_shared()
|
||||
.with("gnutls", None)
|
||||
.without("openssl", None);
|
||||
config.ldflag("-liconv");
|
||||
config.env("LIBS", "-liconv");
|
||||
}
|
||||
@@ -139,6 +143,15 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let configuration = std::fs::read_to_string(dst.join("build/config.h"))
|
||||
.expect("Failed to read the OpenConnect TLS backend configuration");
|
||||
assert!(
|
||||
configuration.lines().any(|line| line == "#define OPENCONNECT_GNUTLS 1")
|
||||
&& !configuration
|
||||
.lines()
|
||||
.any(|line| line == "#define OPENCONNECT_OPENSSL 1"),
|
||||
"macOS OpenConnect must use GnuTLS"
|
||||
);
|
||||
// Do not embed Cargo's temporary build directory in consumers of this library.
|
||||
let library = std::fs::canonicalize(lib_dir.join("libopenconnect.dylib")).unwrap();
|
||||
let library_name = library.file_name().unwrap().to_str().unwrap();
|
||||
@@ -198,7 +211,7 @@ fn main() {
|
||||
// Using pkg-config to find system deps
|
||||
pkg_config::probe_library("zlib").unwrap();
|
||||
#[cfg(target_os = "macos")]
|
||||
pkg_config::probe_library("openssl").unwrap();
|
||||
pkg_config::probe_library("gnutls").unwrap();
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
|
||||
Submodule crates/openconnect/deps/openconnect updated: 0557ead16b...fa45f13d06.
@@ -1,10 +1,13 @@
|
||||
mod hip;
|
||||
mod network_configuration;
|
||||
mod tunnel;
|
||||
use crate::Vpn;
|
||||
use hip::HipGenerateFn;
|
||||
pub(crate) use hip::{
|
||||
HipControlRaw, HipScriptRaw, collect_hip_script, collect_hip_source, generate_hip_report, script_environment,
|
||||
};
|
||||
use log::{debug, info, trace, warn};
|
||||
pub(crate) use network_configuration::{VpnOptionRaw, configure_network};
|
||||
use std::ffi::{c_char, c_int, c_long, c_void};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
@@ -26,6 +29,7 @@ pub(crate) struct ConnectOptions {
|
||||
pub local_hostname: *const c_char,
|
||||
|
||||
pub script: *const c_char,
|
||||
pub configure_network: Option<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> c_int>,
|
||||
pub interface: *const c_char,
|
||||
pub script_tun: u32,
|
||||
|
||||
@@ -61,6 +65,7 @@ pub(crate) struct VpnSessionInfoRaw {
|
||||
#[link(name = "vpn")]
|
||||
unsafe extern "C" {
|
||||
fn vpn_write_cancel(fd: c_int) -> c_int;
|
||||
fn vpn_write_statistics(fd: c_int) -> c_int;
|
||||
#[link_name = "vpn_connect"]
|
||||
fn vpn_connect(
|
||||
options: *const ConnectOptions,
|
||||
@@ -78,6 +83,15 @@ pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> {
|
||||
let error = unsafe { vpn_write_statistics(fd) };
|
||||
if error == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::from_raw_os_error(error))
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int {
|
||||
unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into()
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
use std::{
|
||||
ffi::{CStr, c_char, c_int, c_void},
|
||||
io,
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
};
|
||||
|
||||
use crate::{NetworkConfiguration, Vpn};
|
||||
|
||||
/// Matches OpenConnect's oc_vpn_option list. Borrowed for this invocation only.
|
||||
#[repr(C)]
|
||||
pub(crate) struct VpnOptionRaw {
|
||||
pub option: *const c_char,
|
||||
pub value: *const c_char,
|
||||
pub next: *const VpnOptionRaw,
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// A non-null `value` must point to a readable, NUL-terminated string that
|
||||
/// remains valid and unchanged until this function returns.
|
||||
unsafe fn read_string(value: *const c_char) -> io::Result<String> {
|
||||
if value.is_null() {
|
||||
return Err(io::Error::from_raw_os_error(libc::EINVAL));
|
||||
}
|
||||
// SAFETY: The caller guarantees a valid C string; null was rejected above.
|
||||
unsafe { CStr::from_ptr(value) }
|
||||
.to_str()
|
||||
.map(str::to_owned)
|
||||
.map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Non-null strings must satisfy `read_string`'s contract. `options` must be
|
||||
/// null or a finite, acyclic list of aligned, readable nodes. The list and its
|
||||
/// strings must remain valid and unchanged until this function returns.
|
||||
unsafe fn snapshot(reason: *const c_char, mut options: *const VpnOptionRaw) -> io::Result<NetworkConfiguration> {
|
||||
// SAFETY: The caller guarantees the string lifetime and validity.
|
||||
let reason = unsafe { read_string(reason)? };
|
||||
let mut environment = Vec::new();
|
||||
while !options.is_null() {
|
||||
// SAFETY: This is a non-null node in the valid list supplied by the caller.
|
||||
let option = unsafe { &*options };
|
||||
// SAFETY: Node strings satisfy read_string's contract, including null handling.
|
||||
let name = unsafe { read_string(option.option)? };
|
||||
let value = if option.value.is_null() {
|
||||
None
|
||||
} else {
|
||||
// SAFETY: The caller guarantees this non-null string's validity and lifetime.
|
||||
Some(unsafe { read_string(option.value)? })
|
||||
};
|
||||
environment.push((name, value));
|
||||
options = option.next;
|
||||
}
|
||||
Ok(NetworkConfiguration { reason, environment })
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `data` must point to an aligned, live `Vpn` that may be shared immutably for
|
||||
/// this entire invocation. `reason` and `options` must satisfy `snapshot`'s
|
||||
/// contract. OpenConnect invokes this callback synchronously during `connect`,
|
||||
/// including cleanup, before the borrowed `Vpn` or configuration data is freed.
|
||||
pub(crate) unsafe extern "C" fn configure_network(
|
||||
data: *mut c_void,
|
||||
reason: *const c_char,
|
||||
options: *const VpnOptionRaw,
|
||||
) -> c_int {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
// SAFETY: The caller supplies the live Vpn pointer registered for this connection.
|
||||
let vpn = unsafe { &*(data as *const Vpn) };
|
||||
// SAFETY: The caller keeps OpenConnect's list and strings valid during this call.
|
||||
let configuration = unsafe { snapshot(reason, options)? };
|
||||
let handler = vpn
|
||||
.network_configuration_handler
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
|
||||
handler(&configuration)
|
||||
}));
|
||||
match result {
|
||||
Ok(Ok(())) => 0,
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("Network configuration failed: {error}");
|
||||
-error.raw_os_error().filter(|code| *code > 0).unwrap_or(libc::EIO)
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!("Network configuration handler panicked");
|
||||
-libc::EIO
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{
|
||||
ffi::CString,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn callback_copies_configuration_and_preserves_unset_values() {
|
||||
let observed = Arc::new(Mutex::new(None));
|
||||
let output = observed.clone();
|
||||
let vpn = Vpn::builder("server", "cookie")
|
||||
.network_configuration_handler(move |configuration| {
|
||||
*output.lock().unwrap() = Some(configuration.clone());
|
||||
Ok(())
|
||||
})
|
||||
.build()
|
||||
.unwrap();
|
||||
let name = CString::new("TUNDEV").unwrap();
|
||||
let value = CString::new("utun3").unwrap();
|
||||
let unset_name = CString::new("INTERNAL_IP6_ADDRESS").unwrap();
|
||||
let unset = VpnOptionRaw {
|
||||
option: unset_name.as_ptr(),
|
||||
value: std::ptr::null(),
|
||||
next: std::ptr::null(),
|
||||
};
|
||||
let option = VpnOptionRaw {
|
||||
option: name.as_ptr(),
|
||||
value: value.as_ptr(),
|
||||
next: &unset,
|
||||
};
|
||||
// SAFETY: vpn, both list nodes, and their C strings remain live for the call.
|
||||
let result = unsafe { configure_network((&vpn as *const Vpn).cast_mut().cast(), c"connect".as_ptr(), &option) };
|
||||
assert_eq!(result, 0);
|
||||
let configuration = observed.lock().unwrap().take().unwrap();
|
||||
assert_eq!(configuration.reason, "connect");
|
||||
assert_eq!(
|
||||
configuration.environment,
|
||||
vec![
|
||||
("TUNDEV".into(), Some("utun3".into())),
|
||||
("INTERNAL_IP6_ADDRESS".into(), None)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_and_panics_do_not_cross_ffi() {
|
||||
for panics in [false, true] {
|
||||
let vpn = Vpn::builder("server", "cookie")
|
||||
.network_configuration_handler(move |_| {
|
||||
if panics {
|
||||
panic!("test panic");
|
||||
}
|
||||
Err(io::Error::from_raw_os_error(libc::EPERM))
|
||||
})
|
||||
.build()
|
||||
.unwrap();
|
||||
// SAFETY: vpn and the static reason are live; a null list is permitted.
|
||||
let result = unsafe {
|
||||
configure_network(
|
||||
(&vpn as *const Vpn).cast_mut().cast(),
|
||||
c"connect".as_ptr(),
|
||||
std::ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_eq!(result, if panics { -libc::EIO } else { -libc::EPERM });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_rejects_script_options() {
|
||||
assert!(
|
||||
Vpn::builder("server", "cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.script_tun(true)
|
||||
.build()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
Vpn::builder("server", "cookie")
|
||||
.network_configuration_handler(|_| Ok(()))
|
||||
.script(Some("/bin/true".into()))
|
||||
.build()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
use std::{
|
||||
ffi::{CStr, c_char, c_int, c_void},
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Vpn,
|
||||
tunnel::{Configuration, Event, NativeList, Statistics, Transport},
|
||||
};
|
||||
|
||||
const TEXT_LIMIT: usize = 1024;
|
||||
const COPY_BUDGET: usize = 16 * 1024;
|
||||
const LIST_LIMIT: usize = 256;
|
||||
|
||||
#[repr(C)]
|
||||
struct SplitInclude {
|
||||
route: *const c_char,
|
||||
next: *const SplitInclude,
|
||||
}
|
||||
|
||||
/// Matches oc_ip_info in the bundled public openconnect.h.
|
||||
#[repr(C)]
|
||||
struct IpInfo {
|
||||
addr: *const c_char,
|
||||
netmask: *const c_char,
|
||||
addr6: *const c_char,
|
||||
netmask6: *const c_char,
|
||||
dns: [*const c_char; 3],
|
||||
nbns: [*const c_char; 3],
|
||||
domain: *const c_char,
|
||||
proxy_pac: *const c_char,
|
||||
mtu: c_int,
|
||||
split_dns: *const SplitInclude,
|
||||
split_includes: *const SplitInclude,
|
||||
split_excludes: *const SplitInclude,
|
||||
gateway_addr: *const c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Stats {
|
||||
tx_pkts: u64,
|
||||
tx_bytes: u64,
|
||||
rx_pkts: u64,
|
||||
rx_bytes: u64,
|
||||
}
|
||||
|
||||
struct CopyBudget {
|
||||
remaining: usize,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
impl CopyBudget {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
remaining: COPY_BUDGET,
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&mut self, bytes: &[u8]) -> String {
|
||||
let limit = self.remaining.min(TEXT_LIMIT).min(bytes.len());
|
||||
// Lossy UTF-8 is bounded before allocation, then truncated at a character
|
||||
// boundary so replacement characters cannot exceed the retained budget.
|
||||
let mut text = String::from_utf8_lossy(&bytes[..limit]).into_owned();
|
||||
let mut end = text.len().min(limit);
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
text.truncate(end);
|
||||
self.truncated |= end < bytes.len();
|
||||
self.remaining -= text.len();
|
||||
text
|
||||
}
|
||||
|
||||
unsafe fn optional(&mut self, value: *const c_char) -> Option<String> {
|
||||
if value.is_null() {
|
||||
return None;
|
||||
}
|
||||
// The native value is NUL terminated and borrowed only during the callback.
|
||||
// Bound the scan as well as the retained allocation for scalar fields.
|
||||
let length = unsafe { libc::strnlen(value, TEXT_LIMIT + 1) };
|
||||
Some(self.text(unsafe { std::slice::from_raw_parts(value.cast(), length) }))
|
||||
}
|
||||
|
||||
fn push(&mut self, list: &mut NativeList, bytes: &[u8]) {
|
||||
list.total_count = list.total_count.saturating_add(1);
|
||||
// Retain whole list entries; the native list is not a user-owned buffer.
|
||||
if list.items.len() >= LIST_LIMIT || bytes.len() > TEXT_LIMIT || bytes.len() > self.remaining {
|
||||
list.truncated = true;
|
||||
self.truncated = true;
|
||||
return;
|
||||
}
|
||||
let text = self.text(bytes);
|
||||
list.truncated |= text.len() != bytes.len();
|
||||
list.items.push(text);
|
||||
}
|
||||
|
||||
unsafe fn routes(&mut self, mut node: *const SplitInclude) -> NativeList {
|
||||
let mut list = NativeList::default();
|
||||
while !node.is_null() {
|
||||
let entry = unsafe { &*node };
|
||||
if !entry.route.is_null() {
|
||||
self.push(&mut list, unsafe { CStr::from_ptr(entry.route) }.to_bytes());
|
||||
}
|
||||
node = entry.next;
|
||||
}
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn configuration(interface: *const c_char, raw: &IpInfo) -> Configuration {
|
||||
let mut budget = CopyBudget::new();
|
||||
let mut result = Configuration {
|
||||
interface: unsafe { budget.optional(interface) },
|
||||
ipv4: unsafe { budget.optional(raw.addr) },
|
||||
netmask: unsafe { budget.optional(raw.netmask) },
|
||||
ipv6: unsafe { budget.optional(raw.addr6) },
|
||||
netmask6: unsafe { budget.optional(raw.netmask6) },
|
||||
server_ip: unsafe { budget.optional(raw.gateway_addr) },
|
||||
mtu: u32::try_from(raw.mtu).ok().filter(|mtu| *mtu > 0),
|
||||
..Configuration::default()
|
||||
};
|
||||
for server in raw.dns {
|
||||
if !server.is_null() {
|
||||
budget.push(&mut result.dns, unsafe { CStr::from_ptr(server) }.to_bytes());
|
||||
}
|
||||
}
|
||||
if !raw.domain.is_null() {
|
||||
// GlobalProtect builds its search list with spaces in gpst.c.
|
||||
for domain in unsafe { CStr::from_ptr(raw.domain) }
|
||||
.to_bytes()
|
||||
.split(u8::is_ascii_whitespace)
|
||||
{
|
||||
if !domain.is_empty() {
|
||||
budget.push(&mut result.search_domains, domain);
|
||||
}
|
||||
}
|
||||
}
|
||||
result.split_dns = unsafe { budget.routes(raw.split_dns) };
|
||||
result.included_routes = unsafe { budget.routes(raw.split_includes) };
|
||||
result.excluded_routes = unsafe { budget.routes(raw.split_excludes) };
|
||||
result.truncated = budget.truncated;
|
||||
result
|
||||
}
|
||||
|
||||
fn observe(vpn: *mut c_void, action: impl FnOnce(&Vpn)) {
|
||||
if vpn.is_null() {
|
||||
return;
|
||||
}
|
||||
// All exports are called synchronously with the live Vpn registered by connect.
|
||||
if catch_unwind(AssertUnwindSafe(|| action(unsafe { &*vpn.cast::<Vpn>() }))).is_err() {
|
||||
log::warn!("Tunnel observer panicked");
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_tunnel_configuration(vpn: *mut c_void, interface: *const c_char, info: *const IpInfo) {
|
||||
observe(vpn, |vpn| {
|
||||
let configuration = unsafe { info.as_ref().map(|info| configuration(interface, info)) };
|
||||
vpn.on_tunnel_event(Event::Configuration(configuration));
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_tunnel_event(vpn: *mut c_void, event: c_int) {
|
||||
observe(vpn, |vpn| match event {
|
||||
0 => vpn.on_tunnel_event(Event::Transport(Transport::Negotiating)),
|
||||
1 => vpn.on_tunnel_event(Event::Transport(Transport::IpsecEsp)),
|
||||
2 => vpn.on_tunnel_event(Event::Transport(Transport::SslTls)),
|
||||
3 => vpn.on_tunnel_event(Event::Transport(Transport::Unavailable)),
|
||||
4 => {
|
||||
vpn.on_tunnel_event(Event::Transport(Transport::Unavailable));
|
||||
vpn.on_tunnel_event(Event::Reconnecting);
|
||||
}
|
||||
5 => vpn.on_tunnel_event(Event::Established),
|
||||
6 => vpn.on_tunnel_event(Event::Reconnected),
|
||||
7 => {
|
||||
vpn.on_tunnel_event(Event::Transport(Transport::Unavailable));
|
||||
vpn.on_tunnel_event(Event::Ended);
|
||||
}
|
||||
_ => log::warn!("Unknown native tunnel observation: {event}"),
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_tunnel_statistics(vpn: *mut c_void, stats: *const Stats) {
|
||||
observe(vpn, |vpn| {
|
||||
vpn.statistics_received();
|
||||
if let Some(stats) = unsafe { stats.as_ref() } {
|
||||
vpn.on_tunnel_event(Event::Statistics(Statistics {
|
||||
received_bytes: stats.rx_bytes,
|
||||
sent_bytes: stats.tx_bytes,
|
||||
received_packets: stats.rx_pkts,
|
||||
sent_packets: stats.tx_pkts,
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{
|
||||
ffi::CString,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
fn empty_info() -> IpInfo {
|
||||
// Every pointer is nullable, and zero MTU denotes unavailable.
|
||||
unsafe { std::mem::zeroed() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_owns_configuration_and_preserves_native_mask_semantics() {
|
||||
let domain = CString::new("one.example two.example\tthree.example").unwrap();
|
||||
let ipv6 = CString::new("2001:db8::1").unwrap();
|
||||
let mask6 = CString::new("2001:db8::1/64").unwrap();
|
||||
let server = CString::new("2001:db8::53").unwrap();
|
||||
let route = CString::new("10.0.0.0/8").unwrap();
|
||||
let node = SplitInclude {
|
||||
route: route.as_ptr(),
|
||||
next: std::ptr::null(),
|
||||
};
|
||||
let raw = IpInfo {
|
||||
domain: domain.as_ptr(),
|
||||
addr6: ipv6.as_ptr(),
|
||||
netmask6: mask6.as_ptr(),
|
||||
dns: [server.as_ptr(), std::ptr::null(), std::ptr::null()],
|
||||
split_includes: &node,
|
||||
mtu: 1400,
|
||||
..empty_info()
|
||||
};
|
||||
let snapshot = unsafe { configuration(std::ptr::null(), &raw) };
|
||||
drop((domain, ipv6, mask6, server, route));
|
||||
assert_eq!(
|
||||
snapshot.search_domains.items,
|
||||
["one.example", "two.example", "three.example"]
|
||||
);
|
||||
assert_eq!(snapshot.dns.items, ["2001:db8::53"]);
|
||||
assert_eq!(snapshot.netmask6.as_deref(), Some("2001:db8::1/64"));
|
||||
assert_eq!(snapshot.included_routes.items, ["10.0.0.0/8"]);
|
||||
assert_eq!(snapshot.mtu, Some(1400));
|
||||
assert!(!snapshot.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observation_budget_keeps_whole_entries_and_counts_omitted_values() {
|
||||
let domain = CString::new(
|
||||
std::iter::repeat_n("example.internal", 2000)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
)
|
||||
.unwrap();
|
||||
let long_ipv6 = CString::new("界".repeat(500)).unwrap();
|
||||
let raw = IpInfo {
|
||||
domain: domain.as_ptr(),
|
||||
addr6: long_ipv6.as_ptr(),
|
||||
..empty_info()
|
||||
};
|
||||
let snapshot = unsafe { configuration(std::ptr::null(), &raw) };
|
||||
assert!(snapshot.truncated);
|
||||
assert!(snapshot.ipv6.as_ref().unwrap().len() <= TEXT_LIMIT);
|
||||
assert_eq!(snapshot.search_domains.total_count, 2000);
|
||||
assert!(snapshot.search_domains.truncated);
|
||||
assert!(snapshot.search_domains.items.len() <= LIST_LIMIT);
|
||||
assert!(
|
||||
snapshot
|
||||
.search_domains
|
||||
.items
|
||||
.iter()
|
||||
.all(|item| item == "example.internal")
|
||||
);
|
||||
let retained = snapshot.ipv6.unwrap().len() + snapshot.search_domains.items.iter().map(String::len).sum::<usize>();
|
||||
assert!(retained <= COPY_BUDGET);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observer_deduplicates_transport_and_survives_panics() {
|
||||
let vpn = Vpn::builder("vpn.example.com", "cookie")
|
||||
.script_path("/bin/sh".to_owned())
|
||||
.build()
|
||||
.unwrap();
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let collected = events.clone();
|
||||
vpn.set_tunnel_observer(move |event| collected.lock().unwrap().push(event));
|
||||
let pointer = (&vpn as *const Vpn).cast_mut().cast();
|
||||
vpn_tunnel_event(pointer, 1);
|
||||
vpn_tunnel_event(pointer, 1);
|
||||
vpn_tunnel_event(pointer, 4);
|
||||
vpn_tunnel_event(pointer, 6);
|
||||
vpn_tunnel_event(pointer, 7);
|
||||
assert_eq!(
|
||||
*events.lock().unwrap(),
|
||||
[
|
||||
Event::Transport(Transport::IpsecEsp),
|
||||
Event::Transport(Transport::Unavailable),
|
||||
Event::Reconnecting,
|
||||
Event::Reconnected,
|
||||
Event::Ended,
|
||||
]
|
||||
);
|
||||
vpn.set_tunnel_observer(|_| panic!("test observer panic"));
|
||||
vpn_tunnel_event(pointer, 5);
|
||||
vpn.clear_tunnel_observer();
|
||||
vpn_tunnel_event(pointer, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statistics_callback_clears_pending_before_notifying_observer() {
|
||||
use std::{
|
||||
io::Read,
|
||||
os::{fd::AsRawFd, unix::net::UnixStream},
|
||||
};
|
||||
let vpn = Arc::new(
|
||||
Vpn::builder("vpn.example.com", "cookie")
|
||||
.script_path("/bin/sh".to_owned())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let (mut reader, writer) = UnixStream::pair().unwrap();
|
||||
reader.set_nonblocking(true).unwrap();
|
||||
assert!(!vpn.attach_command_pipe(writer.as_raw_fd()));
|
||||
assert!(vpn.request_statistics().unwrap());
|
||||
let received = Arc::new(Mutex::new(None));
|
||||
let captured = received.clone();
|
||||
let weak = Arc::downgrade(&vpn);
|
||||
vpn.set_tunnel_observer(move |event| {
|
||||
if let Event::Statistics(statistics) = event {
|
||||
*captured.lock().unwrap() = Some(statistics);
|
||||
assert!(weak.upgrade().unwrap().request_statistics().unwrap());
|
||||
}
|
||||
});
|
||||
let raw = Stats {
|
||||
tx_pkts: u64::MAX,
|
||||
tx_bytes: 1 << 54,
|
||||
rx_pkts: 12,
|
||||
rx_bytes: 34,
|
||||
};
|
||||
vpn_tunnel_statistics(Arc::as_ptr(&vpn).cast_mut().cast(), &raw);
|
||||
assert_eq!(
|
||||
*received.lock().unwrap(),
|
||||
Some(Statistics {
|
||||
sent_packets: u64::MAX,
|
||||
sent_bytes: 1 << 54,
|
||||
received_packets: 12,
|
||||
received_bytes: 34,
|
||||
})
|
||||
);
|
||||
let mut commands = [0; 2];
|
||||
reader.read_exact(&mut commands).unwrap();
|
||||
assert_eq!(commands, [b's', b's']);
|
||||
vpn.detach_command_pipe();
|
||||
vpn.clear_tunnel_observer();
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,34 @@ struct vpn_context {
|
||||
vpn_connected_callback on_connected;
|
||||
};
|
||||
|
||||
static void observe_configuration(struct vpn_context *context)
|
||||
{
|
||||
const struct oc_ip_info *info = NULL;
|
||||
if (openconnect_get_ip_info(context->vpninfo, &info, NULL, NULL))
|
||||
info = NULL;
|
||||
vpn_tunnel_configuration(context->options->user_data,
|
||||
openconnect_get_ifname(context->vpninfo), info);
|
||||
}
|
||||
|
||||
static void observe_reconnected(void *private_data)
|
||||
{
|
||||
struct vpn_context *context = private_data;
|
||||
observe_configuration(context);
|
||||
vpn_tunnel_event(context->options->user_data, VPN_TUNNEL_RECONNECTED);
|
||||
}
|
||||
|
||||
static void observe_tunnel(void *private_data, enum openconnect_tunnel_event event)
|
||||
{
|
||||
struct vpn_context *context = private_data;
|
||||
vpn_tunnel_event(context->options->user_data, event);
|
||||
}
|
||||
|
||||
static void observe_statistics(void *private_data, const struct oc_stats *stats)
|
||||
{
|
||||
struct vpn_context *context = private_data;
|
||||
vpn_tunnel_statistics(context->options->user_data, stats);
|
||||
}
|
||||
|
||||
/* Validate the peer certificate */
|
||||
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
|
||||
const char *reason)
|
||||
@@ -54,6 +82,8 @@ static void setup_tun_handler(void *private_data)
|
||||
}
|
||||
|
||||
if (!ret) {
|
||||
observe_configuration(context);
|
||||
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ESTABLISHED);
|
||||
vpn_session_info session_info = {
|
||||
.auth_expiration = (long)openconnect_get_auth_expiration(_vpninfo),
|
||||
.lifetime_secs = openconnect_get_gp_session_lifetime(_vpninfo),
|
||||
@@ -84,7 +114,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
INFO("OS: %s", options->os);
|
||||
INFO("CLIENT_VERSION: %s", options->client_version);
|
||||
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
||||
INFO("VPNC_SCRIPT: %s", options->script);
|
||||
INFO("Network configuration: %s", options->configure_network ? "callback" : options->script);
|
||||
INFO("SCRIPT_TUN: %d", options->script_tun);
|
||||
INFO("CSD_USER: %d", options->hip_script.uid);
|
||||
INFO("CSD_WRAPPER: %s", options->hip_script.path);
|
||||
@@ -101,10 +131,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
|
||||
if (!vpninfo) {
|
||||
ERROR("openconnect_vpninfo_new failed");
|
||||
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED);
|
||||
return 1;
|
||||
}
|
||||
|
||||
context.vpninfo = vpninfo;
|
||||
openconnect_set_tunnel_handler(vpninfo, observe_tunnel);
|
||||
openconnect_set_reconnected_handler(vpninfo, observe_reconnected);
|
||||
openconnect_set_stats_handler(vpninfo, observe_statistics);
|
||||
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
|
||||
options->on_hip_report_submitted);
|
||||
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
|
||||
@@ -191,6 +225,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
openconnect_set_dpd(vpninfo, options->dpd_interval);
|
||||
}
|
||||
// Essential step
|
||||
vpn_tunnel_event(options->user_data, OC_TUNNEL_NEGOTIATING);
|
||||
if (openconnect_make_cstp_connection(vpninfo) != 0) {
|
||||
ERROR("openconnect_make_cstp_connection failed");
|
||||
goto cleanup;
|
||||
@@ -200,6 +235,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
openconnect_disable_dtls(vpninfo);
|
||||
}
|
||||
// Essential step
|
||||
openconnect_set_configure_tun_handler(vpninfo, options->user_data,
|
||||
options->configure_network);
|
||||
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
|
||||
|
||||
while (1) {
|
||||
@@ -216,7 +253,9 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
}
|
||||
cleanup:
|
||||
vpn_detach_command_pipe(options->user_data);
|
||||
openconnect_set_tunnel_handler(vpninfo, NULL);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -231,6 +270,16 @@ int vpn_write_cancel(int fd)
|
||||
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||
}
|
||||
|
||||
int vpn_write_statistics(int fd)
|
||||
{
|
||||
char command = OC_CMD_STATS;
|
||||
ssize_t written;
|
||||
do {
|
||||
written = write(fd, &command, 1);
|
||||
} while (written < 0 && errno == EINTR);
|
||||
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||
}
|
||||
|
||||
int vpn_collect_hip_report(const vpn_hip_script *script,
|
||||
const struct openconnect_gp_hip_request *request,
|
||||
const struct openconnect_gp_hip_control *control, openconnect_gp_hip_generate_fn generate, void *data,
|
||||
|
||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user