feat: prepare 3.0.0 release

This commit is contained in:
Kevin Yue committed 2026-10-09 18:21:44 +08:00
1 parent e98fd7894a
commit b7b708e9cd
252 files changed
+26210 -7457

No files matched your search

+14 -8
View File
@@ -8,20 +8,18 @@ edition.workspace = true
license.workspace = true
[dependencies]
common = { path = "../common" }
gpapi = { path = "../gpapi" }
# Shared dependencies
anyhow.workspace = true
log.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["io-util", "net", "time"] }
# Browser auth dependencies
webbrowser = { version = "1", optional = true }
open = { version = "5", optional = true }
which = { workspace = true, optional = true }
browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true }
tiny_http = { version = "0.12", optional = true }
uuid = { version = "1", optional = true, features = ["v4"] }
uzers = { workspace = true, optional = true }
# Webview auth dependencies
tauri = { workspace = true, optional = true }
@@ -35,16 +33,20 @@ webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = { version = "0.6", optional = true }
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 }
[features]
browser-auth = [
"dep:webbrowser",
"dep:open",
"dep:which",
"dep:browser-launcher",
"dep:tiny_http",
"dep:uuid",
"dep:uzers",
"dep:block2",
"dep:objc2",
"dep:objc2-app-kit",
"dep:objc2-foundation",
]
webview-auth = [
"gpapi/tauri",
@@ -58,3 +60,7 @@ webview-auth = [
"dep:objc2-foundation",
"dep:objc2-web-kit",
]
release-devtools = ["webview-auth", "tauri/devtools"]
[dev-dependencies]
tempfile.workspace = true
+2 -2
View File
@@ -1,4 +1,4 @@
use std::io::Cursor;
use std::{io::Cursor, net::SocketAddr};
use log::info;
use tiny_http::{Header, Method, Response, Server};
@@ -10,7 +10,7 @@ pub(super) struct AuthServer {
}
impl AuthServer {
pub fn new(addr: &str) -> anyhow::Result<Self> {
pub fn new(addr: SocketAddr) -> anyhow::Result<Self> {
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?;
let auth_id = Uuid::new_v4().to_string();
+61 -136
View File
@@ -1,64 +1,36 @@
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use std::net::{IpAddr, SocketAddr};
use common::constants::GP_CALLBACK_PORT_FILENAME;
use browser_launcher::Browser as LaunchBrowser;
use gpapi::auth::SamlAuthData;
use log::info;
use tokio::{
io::AsyncReadExt,
net::{TcpListener, UdpSocket},
};
use tokio::net::UdpSocket;
use crate::browser::auth_server::AuthServer;
pub enum Browser<'a> {
Auto,
Default,
Chrome,
Firefox,
Remote,
Other(&'a str),
}
impl<'a> Browser<'a> {
pub fn from_str(browser: &'a str) -> Self {
match browser.to_lowercase().as_str() {
"auto" => Browser::Auto,
"default" => Browser::Default,
"chrome" => Browser::Chrome,
"firefox" => Browser::Firefox,
"remote" => Browser::Remote,
_ => Browser::Other(browser),
}
}
fn as_str(&self) -> &str {
match self {
Browser::Auto => "auto",
Browser::Default => "default",
Browser::Chrome => "chrome",
Browser::Firefox => "firefox",
Browser::Remote => "remote",
Browser::Other(browser) => browser,
}
}
}
use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_callback_handler};
pub struct BrowserAuthenticator<'a> {
auth_request: &'a str,
browser: Browser<'a>,
browser: &'a str,
browser_listen: Option<IpAddr>,
}
impl<'a> BrowserAuthenticator<'a> {
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
pub fn new(auth_request: &'a str, browser: &'a str, browser_listen: Option<IpAddr>) -> Self {
Self {
auth_request,
browser: Browser::from_str(browser),
browser,
browser_listen,
}
}
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
let callback_receiver = if is_remote_browser(self.browser) {
None
} else {
ensure_auth_callback_handler()?;
Some(AuthCallbackReceiver::bind()?)
};
let addr = self.determine_addr().await?;
let auth_server = AuthServer::new(&addr)?;
let auth_server = AuthServer::new(addr)?;
let auth_url = auth_server.auth_url();
let auth_request = self.auth_request.to_string();
@@ -66,10 +38,9 @@ impl<'a> BrowserAuthenticator<'a> {
auth_server.serve_request(&auth_request);
});
match self.browser {
Browser::Remote => {
info!(
r#"
if is_remote_browser(self.browser) {
info!(
r#"
==== Manual Authentication Required ====
@@ -82,109 +53,45 @@ After completing the authentication, please paste the authentication data back t
Note that the URL is only valid for a single use.
"#,
auth_url
);
return read_auth_data_from_stdin();
}
Browser::Default => {
info!("Launching the default browser...");
webbrowser::open(&auth_url)?;
}
Browser::Auto => {
if let Some(app) = find_auto_browser_path() {
info!("Launching browser: {}", app);
open::with_detached(&auth_url, app)?;
} else {
info!("No preferred browser found; launching the default browser...");
webbrowser::open(&auth_url)?;
}
}
_ => {
let app = find_browser_path(&self.browser);
info!("Launching browser: {}", app);
open::with_detached(auth_url, app)?;
}
auth_url
);
return read_auth_data_from_stdin();
}
browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?;
info!("Please continue the authentication process in the default browser");
wait_auth_data().await
callback_receiver.unwrap().receive().await
}
async fn determine_addr(&self) -> anyhow::Result<String> {
if matches!(self.browser, Browser::Remote) {
let local_ip = detect_local_ip().await?;
Ok(format!("{}:0", local_ip))
async fn determine_addr(&self) -> anyhow::Result<SocketAddr> {
if is_remote_browser(self.browser) {
let local_ip = match self.browser_listen {
Some(ip) => ip,
None => detect_local_ip().await?,
};
Ok(SocketAddr::new(local_ip, 0))
} else {
Ok("127.0.0.1:0".to_string())
Ok(SocketAddr::from(([127, 0, 0, 1], 0)))
}
}
}
fn is_remote_browser(browser: &str) -> bool {
browser.eq_ignore_ascii_case("remote")
}
/// Detect the local IP address by creating a UDP socket and connecting to an external address
async fn detect_local_ip() -> anyhow::Result<String> {
async fn detect_local_ip() -> anyhow::Result<IpAddr> {
let socket = UdpSocket::bind("0.0.0.0:0").await?;
if let Err(err) = socket.connect("1.1.1.1:80").await {
anyhow::bail!("Failed to connect to external address to determine local IP: {}", err);
}
let local_addr = socket.local_addr()?;
let ip = local_addr.ip().to_string();
let ip = local_addr.ip();
info!("Determined local IP address: {}", ip);
Ok(ip.to_string())
}
fn find_browser_path(browser: &Browser) -> String {
match browser {
Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()),
_ => browser.as_str().to_string(),
}
}
fn find_auto_browser_path() -> Option<String> {
find_chrome_path().or_else(|| find_program_path("firefox"))
}
fn find_chrome_path() -> Option<String> {
["google-chrome-stable", "google-chrome", "chromium"]
.iter()
.find_map(|browser_name| find_program_path(browser_name))
}
fn find_program_path(name: &str) -> Option<String> {
which::which(name).ok().map(|path| path.to_string_lossy().to_string())
}
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
// Write the port to a file
fs::write(&port_file, port.to_string())?;
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
// Remove the previous log file
let callback_log = temp_dir().join("gpcallback.log");
let _ = fs::remove_file(&callback_log);
info!("Listening authentication data on port {}", port);
info!(
"If it hangs, please check the logs at `{}` for more information",
callback_log.display()
);
let (mut socket, _) = listener.accept().await?;
info!("Received the browser authentication data from the socket");
let mut data = String::new();
socket.read_to_string(&mut data).await?;
// Remove the port file
fs::remove_file(&port_file)?;
let auth_data = SamlAuthData::from_gpcallback(&data)?;
Ok(auth_data)
Ok(ip)
}
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
@@ -200,8 +107,26 @@ mod tests {
use super::*;
#[test]
fn browser_auto_is_distinct_from_system_default() {
assert!(matches!(Browser::from_str("auto"), Browser::Auto));
assert!(matches!(Browser::from_str("default"), Browser::Default));
fn shared_launcher_keeps_auto_distinct_from_system_default() {
assert_eq!(LaunchBrowser::from_name("auto"), LaunchBrowser::Auto);
assert_eq!(LaunchBrowser::from_name("default"), LaunchBrowser::Default);
}
#[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);
}
#[tokio::test]
async fn remote_browser_uses_explicit_listen_address() {
let listen_ip = "192.168.107.15".parse().unwrap();
let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip));
assert_eq!(
authenticator.determine_addr().await.unwrap(),
SocketAddr::new(listen_ip, 0)
);
}
}
+512
View File
@@ -0,0 +1,512 @@
use std::{
fs::{self, DirBuilder, OpenOptions, TryLockError},
io::ErrorKind,
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
path::{Path, PathBuf},
time::Duration,
};
use anyhow::{Context, bail};
use gpapi::auth::SamlAuthData;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{UnixListener, UnixStream},
time::timeout,
};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use log::warn;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
use std::ffi::OsStr;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use std::process::{Command, Output};
const CALLBACK_SCHEME: &str = "globalprotectcallback";
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
const PROTOCOL_VERSION: u8 = 1;
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
const IO_TIMEOUT: Duration = Duration::from_secs(5);
const STATUS_ACCEPTED: u8 = 0;
const STATUS_INVALID_CALLBACK: u8 = 1;
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
#[cfg(target_os = "macos")]
mod macos;
pub struct AuthCallbackReceiver {
listener: UnixListener,
socket_path: PathBuf,
_lock_file: fs::File,
}
impl AuthCallbackReceiver {
pub fn bind() -> anyhow::Result<Self> {
let socket_path = callback_socket_path();
prepare_socket_directory(&socket_path)?;
Self::bind_at(socket_path)
}
fn bind_at(socket_path: PathBuf) -> anyhow::Result<Self> {
let lock_file = acquire_lock(&socket_path)?;
match fs::symlink_metadata(&socket_path) {
Ok(_) => remove_stale_socket(&socket_path)?,
Err(err) if err.kind() == ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
finish_bind(UnixListener::bind(&socket_path)?, socket_path, lock_file)
}
pub async fn receive(&self) -> anyhow::Result<SamlAuthData> {
loop {
let (mut stream, _) = self.listener.accept().await?;
let callback = match timeout(IO_TIMEOUT, read_callback(&mut stream)).await {
Ok(callback) => callback,
Err(_) => continue,
};
match callback {
Ok(callback) => match SamlAuthData::from_gpcallback(&callback) {
Ok(auth_data) => {
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
return Ok(auth_data);
}
Err(_) => {
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
}
},
Err(CallbackReadError::UnsupportedVersion) => {
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
}
Err(CallbackReadError::Invalid) => {
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
}
Err(CallbackReadError::Io) => continue,
}
}
}
}
impl Drop for AuthCallbackReceiver {
fn drop(&mut self) {
if fs::symlink_metadata(&self.socket_path)
.is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uzers::get_current_uid())
{
let _ = fs::remove_file(&self.socket_path);
}
}
}
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
validate_callback(callback)?;
forward_auth_callback_to(callback, &callback_socket_path()).await
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
const MIME_TYPE: &str = "x-scheme-handler/globalprotectcallback";
const HANDLER: &str = "gpgui.desktop";
ensure_lxqt_mime_tool()?;
let current_handler = query_callback_handler(MIME_TYPE)?;
if !should_register_handler(&current_handler) {
return Ok(());
}
let output = Command::new("xdg-mime")
.args(["default", HANDLER, MIME_TYPE])
.output()
.context("xdg-mime is required for external-browser authentication")?;
if !output.status.success() {
log_command_failure("register callback handler", &output);
bail!("Failed to register the globalprotectcallback URL handler");
}
if query_callback_handler(MIME_TYPE)? != HANDLER {
bail!("The globalprotectcallback URL handler registration did not take effect");
}
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn query_callback_handler(mime_type: &str) -> anyhow::Result<String> {
let output = Command::new("xdg-mime")
.args(["query", "default", mime_type])
.output()
.context("xdg-mime is required for external-browser authentication")?;
if !output.status.success() {
log_command_failure("query callback handler", &output);
bail!("Failed to query the globalprotectcallback URL handler");
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn ensure_lxqt_mime_tool() -> anyhow::Result<()> {
if !is_lxqt_desktop(std::env::var_os("XDG_CURRENT_DESKTOP").as_deref()) {
return Ok(());
}
let result = Command::new("qtxdg-mat").args(["defapp", "--help"]).output();
match result {
Ok(output) if output.status.success() => Ok(()),
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
warn!(
"qtxdg-mat readiness check failed with {}: {}",
output.status,
stderr.trim()
);
bail!("Install qtxdg-tools for browser SSO.")
}
Err(err) => {
warn!("Failed to run qtxdg-mat readiness check: {err}");
bail!("Install qtxdg-tools for browser SSO.")
}
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn is_lxqt_desktop(current_desktop: Option<&OsStr>) -> bool {
current_desktop
.and_then(OsStr::to_str)
.is_some_and(|desktop| desktop.split(':').any(|name| name.eq_ignore_ascii_case("lxqt")))
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn log_command_failure(action: &str, output: &Output) {
let stderr = String::from_utf8_lossy(&output.stderr);
warn!("xdg-mime failed to {action} with {}: {}", output.status, stderr.trim());
}
#[cfg(target_os = "macos")]
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
macos::ensure_auth_callback_handler()
}
#[cfg(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd",
target_os = "macos"
)))]
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn should_register_handler(current_handler: &str) -> bool {
current_handler != "gpgui.desktop"
}
async fn forward_auth_callback_to(callback: &str, socket_path: &Path) -> anyhow::Result<()> {
validate_callback(callback)?;
let (version, status) = timeout(IO_TIMEOUT, async {
let mut stream = UnixStream::connect(socket_path)
.await
.context("No external-browser authentication is waiting for a callback")?;
stream.write_all(PROTOCOL_MAGIC).await?;
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u32(callback.len() as u32).await?;
stream.write_all(callback.as_bytes()).await?;
Ok::<_, anyhow::Error>((stream.read_u8().await?, stream.read_u8().await?))
})
.await
.context("Timed out forwarding the authentication callback")??;
if version != PROTOCOL_VERSION {
bail!("Authentication callback protocol version mismatch");
}
match status {
STATUS_ACCEPTED => Ok(()),
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
STATUS_UNSUPPORTED_VERSION => bail!("Authentication callback protocol version is unsupported"),
_ => bail!("Authentication callback handler returned an unknown status"),
}
}
fn callback_socket_path() -> PathBuf {
let uid = uzers::get_current_uid();
#[cfg(target_os = "linux")]
{
let runtime_dir = PathBuf::from(format!("/run/user/{uid}"));
if fs::symlink_metadata(&runtime_dir).is_ok_and(|metadata| {
metadata.is_dir()
&& !metadata.file_type().is_symlink()
&& metadata.uid() == uid
&& metadata.permissions().mode() & 0o077 == 0
}) {
return runtime_dir.join("gp-connect/auth-callback.sock");
}
}
PathBuf::from(format!("/tmp/gp-connect-{uid}/auth-callback.sock"))
}
fn prepare_socket_directory(socket_path: &Path) -> anyhow::Result<()> {
let directory = socket_path
.parent()
.ok_or_else(|| anyhow::anyhow!("Authentication callback socket has no parent directory"))?;
match DirBuilder::new().mode(0o700).create(directory) {
Ok(()) => {}
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
let metadata = fs::symlink_metadata(directory)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
bail!("Authentication callback runtime path is not a directory");
}
if metadata.uid() != uzers::get_current_uid() {
bail!("Authentication callback runtime directory has the wrong owner");
}
if metadata.permissions().mode() & 0o077 != 0 {
bail!("Authentication callback runtime directory permissions are too broad");
}
}
Err(err) => return Err(err.into()),
}
Ok(())
}
fn finish_bind(
listener: UnixListener,
socket_path: PathBuf,
lock_file: fs::File,
) -> anyhow::Result<AuthCallbackReceiver> {
fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600))?;
Ok(AuthCallbackReceiver {
listener,
socket_path,
_lock_file: lock_file,
})
}
fn acquire_lock(socket_path: &Path) -> anyhow::Result<fs::File> {
let lock_path = socket_path.with_file_name("auth-callback.lock");
let lock_file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.open(lock_path)?;
lock_file.set_permissions(fs::Permissions::from_mode(0o600))?;
match lock_file.try_lock() {
Ok(()) => Ok(lock_file),
Err(TryLockError::WouldBlock) => bail!("Another external-browser authentication is already in progress"),
Err(TryLockError::Error(err)) => Err(err.into()),
}
}
fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
let metadata = fs::symlink_metadata(socket_path)?;
if !metadata.file_type().is_socket() || metadata.uid() != uzers::get_current_uid() {
bail!("Authentication callback socket is not owned by the current user");
}
fs::remove_file(socket_path)?;
Ok(())
}
fn validate_callback(callback: &str) -> anyhow::Result<()> {
if callback.len() > MAX_CALLBACK_SIZE {
bail!("Authentication callback exceeds the maximum supported size");
}
let Some((scheme, data)) = callback.split_once(':') else {
bail!("Authentication callback URL is invalid");
};
if scheme != CALLBACK_SCHEME || data.is_empty() {
bail!("Authentication callback URL is invalid");
}
Ok(())
}
enum CallbackReadError {
UnsupportedVersion,
Invalid,
Io,
}
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
let mut magic = [0_u8; 4];
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
if &magic != PROTOCOL_MAGIC {
return Err(CallbackReadError::Invalid);
}
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
if version != PROTOCOL_VERSION {
return Err(CallbackReadError::UnsupportedVersion);
}
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
if length == 0 || length > MAX_CALLBACK_SIZE {
return Err(CallbackReadError::Invalid);
}
let mut payload = vec![0; length];
stream
.read_exact(&mut payload)
.await
.map_err(|_| CallbackReadError::Io)?;
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
validate_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
Ok(callback)
}
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
stream.write_u8(PROTOCOL_VERSION).await?;
stream.write_u8(status).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use tempfile::tempdir;
use super::*;
const VALID_CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";
#[test]
fn validates_supported_callback_scheme() {
assert!(validate_callback(VALID_CALLBACK).is_ok());
assert!(validate_callback("https://example.com").is_err());
assert!(validate_callback("globalprotectcallback:").is_err());
assert!(validate_callback(&format!("globalprotectcallback:{}", "x".repeat(MAX_CALLBACK_SIZE))).is_err());
}
#[test]
fn replaces_any_other_callback_handler() {
assert!(!should_register_handler("gpgui.desktop"));
assert!(should_register_handler(""));
assert!(should_register_handler("gpauth.desktop"));
assert!(should_register_handler("other-vpn.desktop"));
}
#[test]
fn detects_lxqt_desktop_session() {
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt"))));
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt:KDE"))));
assert!(is_lxqt_desktop(Some(OsStr::new("lxqt"))));
assert!(!is_lxqt_desktop(Some(OsStr::new("LXDE"))));
assert!(!is_lxqt_desktop(None));
}
#[tokio::test]
async fn forwards_callback_to_waiting_receiver() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("callback.sock");
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
assert_eq!(
fs::symlink_metadata(&socket_path).unwrap().permissions().mode() & 0o777,
0o600
);
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
let auth_data = receiver.receive().await.unwrap();
sender.await.unwrap().unwrap();
assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.token(), Some("very_long_string"));
let socket_path = receiver.socket_path.clone();
drop(receiver);
assert!(!socket_path.exists());
}
#[tokio::test]
async fn rejects_bad_requests_and_keeps_waiting() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("callback.sock");
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
let sender = tokio::spawn(async move {
assert_eq!(
send_raw_callback(&socket_path, PROTOCOL_VERSION, "https://example.com").await,
STATUS_INVALID_CALLBACK
);
assert_eq!(
send_raw_callback(&socket_path, PROTOCOL_VERSION + 1, VALID_CALLBACK).await,
STATUS_UNSUPPORTED_VERSION
);
forward_auth_callback_to(VALID_CALLBACK, &socket_path).await
});
let auth_data = receiver.receive().await.unwrap();
sender.await.unwrap().unwrap();
assert_eq!(auth_data.username(), "[email protected]");
}
#[tokio::test]
async fn ignores_sender_that_disconnects_before_sending() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("callback.sock");
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
drop(UnixStream::connect(&socket_path).await.unwrap());
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
let auth_data = receiver.receive().await.unwrap();
sender.await.unwrap().unwrap();
assert_eq!(auth_data.username(), "[email protected]");
}
#[tokio::test]
async fn replaces_owned_stale_socket() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("callback.sock");
drop(std::os::unix::net::UnixListener::bind(&socket_path).unwrap());
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
assert!(socket_path.exists());
drop(receiver);
assert!(!socket_path.exists());
}
#[tokio::test]
async fn reports_when_no_receiver_is_active() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("missing.sock");
let err = forward_auth_callback_to(VALID_CALLBACK, &socket_path)
.await
.unwrap_err();
assert!(err.to_string().contains("No external-browser authentication"));
}
#[test]
fn rejects_runtime_directory_with_broad_permissions() {
let directory = tempdir().unwrap();
let runtime_dir = directory.path().join("runtime");
fs::create_dir(&runtime_dir).unwrap();
fs::set_permissions(&runtime_dir, fs::Permissions::from_mode(0o755)).unwrap();
let err = prepare_socket_directory(&runtime_dir.join("callback.sock")).unwrap_err();
assert!(err.to_string().contains("permissions are too broad"));
}
#[tokio::test]
async fn rejects_second_active_receiver() {
let directory = tempdir().unwrap();
let socket_path = directory.path().join("callback.sock");
let _receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
let err = AuthCallbackReceiver::bind_at(socket_path).err().unwrap();
assert!(err.to_string().contains("already in progress"));
}
async fn send_raw_callback(socket_path: &Path, version: u8, callback: &str) -> u8 {
let mut stream = UnixStream::connect(socket_path).await.unwrap();
stream.write_all(PROTOCOL_MAGIC).await.unwrap();
stream.write_u8(version).await.unwrap();
stream.write_u32(callback.len() as u32).await.unwrap();
stream.write_all(callback.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), PROTOCOL_VERSION);
stream.read_u8().await.unwrap()
}
}
+119
View File
@@ -0,0 +1,119 @@
use std::{ffi::OsStr, os::raw::c_void, path::PathBuf, thread, time::Duration};
use anyhow::{Context, bail};
use objc2_app_kit::NSWorkspace;
use objc2_foundation::{NSBundle, NSString, NSURL};
const CALLBACK_SCHEME: &str = "globalprotectcallback";
const CALLBACK_URL: &str = "globalprotectcallback:";
const HANDLER_BUNDLE_ID: &str = "com.yuezk.gpauth";
const LOGIN_APP_NAME: &str = "GP Connect Login.app";
#[link(name = "CoreServices", kind = "framework")]
unsafe extern "C" {
fn LSRegisterURL(url: *const c_void, update: u8) -> i32;
}
pub(super) fn ensure_auth_callback_handler() -> anyhow::Result<()> {
let workspace = NSWorkspace::sharedWorkspace();
let app_paths = callback_app_paths();
let selected_handler = current_handler(&workspace);
match selected_handler.as_ref() {
Some((handler, path))
if handler == HANDLER_BUNDLE_ID && app_paths.iter().any(|candidate| same_path(candidate, path)) =>
{
return Ok(());
}
Some((handler, _)) if handler == HANDLER_BUNDLE_ID => {}
None => {}
Some((handler, _)) => bail!("The globalprotectcallback URL scheme is owned by {handler}"),
}
let app_path = app_paths
.first()
.context("GP Connect Login.app is required for external-browser authentication; install GP Connect")?;
let app_url = file_url(app_path);
register_app(&app_url)?;
workspace.setDefaultApplicationAtURL_toOpenURLsWithScheme_completionHandler(
&app_url,
&NSString::from_str(CALLBACK_SCHEME),
None,
);
for _ in 0..50 {
if current_handler(&workspace)
.is_some_and(|(handler, path)| handler == HANDLER_BUNDLE_ID && same_path(app_path, &path))
{
return Ok(());
}
thread::sleep(Duration::from_millis(100));
}
bail!("The globalprotectcallback URL handler registration did not take effect")
}
fn register_app(app_url: &NSURL) -> anyhow::Result<()> {
// A nested application is not necessarily known to LaunchServices until it
// has been launched. Register it explicitly before assigning its URL scheme.
let status = unsafe { LSRegisterURL(app_url as *const NSURL as *const c_void, 1) };
if status != 0 {
bail!("Failed to register GP Connect Login.app with LaunchServices (OSStatus {status})");
}
Ok(())
}
fn current_handler(workspace: &NSWorkspace) -> Option<(String, PathBuf)> {
let callback_url = NSURL::URLWithString(&NSString::from_str(CALLBACK_URL))?;
let app_url = workspace.URLForApplicationToOpenURL(&callback_url)?;
let identifier = bundle_identifier(&app_url)?;
let path = app_url.path().map(|path| PathBuf::from(path.to_string()))?;
Some((identifier, path))
}
fn callback_app_paths() -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Ok(executable) = std::env::current_exe() {
for path in executable.ancestors() {
if path.file_name() == Some(OsStr::new("Helpers")) {
candidates.push(path.join(LOGIN_APP_NAME));
}
if path.extension() == Some(OsStr::new("app")) {
candidates.push(path.to_path_buf());
}
}
}
if let Some(user_dir) = std::env::var_os("HOME").filter(|path| !path.is_empty()) {
let applications = PathBuf::from(user_dir).join("Applications");
candidates.push(
applications
.join("GP Connect.app/Contents/Helpers")
.join(LOGIN_APP_NAME),
);
}
candidates.push(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers").join(LOGIN_APP_NAME));
candidates
.into_iter()
.filter(|path| path.is_dir() && bundle_identifier(&file_url(path)).as_deref() == Some(HANDLER_BUNDLE_ID))
.collect()
}
fn same_path(left: &std::path::Path, right: &std::path::Path) -> bool {
match (left.canonicalize(), right.canonicalize()) {
(Ok(left), Ok(right)) => left == right,
_ => left == right,
}
}
fn file_url(path: &std::path::Path) -> objc2::rc::Retained<NSURL> {
NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
}
fn bundle_identifier(app_url: &NSURL) -> Option<String> {
NSBundle::bundleWithURL(app_url)?
.bundleIdentifier()
.map(|identifier| identifier.to_string())
}
+6
View File
@@ -7,9 +7,15 @@ use gpapi::{
#[cfg(feature = "browser-auth")]
mod browser;
#[cfg(feature = "browser-auth")]
mod callback;
#[cfg(feature = "browser-auth")]
pub use browser::*;
#[cfg(feature = "browser-auth")]
pub use callback::*;
#[cfg(feature = "webview-auth")]
mod webview;
#[cfg(feature = "webview-auth")]
+1 -1
View File
@@ -17,4 +17,4 @@ mod platform_impl;
)))]
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::WebviewAuthenticator;
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
+138 -8
View File
@@ -1,17 +1,147 @@
use anyhow::bail;
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest};
use objc2_web_kit::WKWebView;
use std::{ffi::c_void, ptr};
use anyhow::{Context, bail};
use block2::{DynBlock, RcBlock};
use objc2::{
DefinedClass, MainThreadOnly, define_class,
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
msg_send,
rc::Retained,
runtime::{AnyObject, ProtocolObject, Sel},
};
use objc2_foundation::{
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
NSURLSessionAuthChallengeDisposition,
};
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
use tauri::webview::PlatformWebview;
use super::webview_auth::PlatformWebviewExt;
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
struct TlsNavigationDelegateIvars {
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
}
define_class!(
#[unsafe(super = NSObject)]
#[thread_kind = MainThreadOnly]
#[ivars = TlsNavigationDelegateIvars]
struct TlsNavigationDelegate;
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
#[allow(non_snake_case)]
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
&self,
_webview: &WKWebView,
challenge: &NSURLAuthenticationChallenge,
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
) {
let protection_space = challenge.protectionSpace();
let is_server_trust = protection_space
.authenticationMethod()
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
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;
}
let credential: Retained<NSURLCredential> =
msg_send![objc2::class!(NSURLCredential), credentialForTrust: server_trust];
completion_handler.call((challenge_disposition(true), Retained::as_ptr(&credential).cast_mut()));
}
}
impl TlsNavigationDelegate {
#[unsafe(method(respondsToSelector:))]
fn responds_to_selector(&self, selector: Sel) -> bool {
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
responds || self.ivars().original.respondsToSelector(selector)
}
#[unsafe(method(forwardingTargetForSelector:))]
fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject {
if self.ivars().original.respondsToSelector(selector) {
Retained::as_ptr(&self.ivars().original).cast_mut().cast()
} else {
unsafe { msg_send![super(self), forwardingTargetForSelector: selector] }
}
}
}
);
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] }
}
}
fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisposition {
if is_server_trust {
NSURLSessionAuthChallengeDisposition::UseCredential
} else {
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
}
}
fn install_tls_navigation_delegate(webview: &WKWebView) -> 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);
unsafe {
objc_setAssociatedObject(
webview as *const WKWebView as *mut AnyObject,
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
Retained::as_ptr(&delegate).cast_mut().cast(),
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
);
webview.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use objc2_foundation::NSURLSessionAuthChallengeDisposition;
use super::challenge_disposition;
#[test]
fn accepts_server_trust_challenges() {
assert_eq!(
challenge_disposition(true),
NSURLSessionAuthChallengeDisposition::UseCredential
);
}
#[test]
fn preserves_default_handling_for_other_challenges() {
assert_eq!(
challenge_disposition(false),
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
);
}
}
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
warn!("Ignoring TLS errors is not supported on macOS");
Ok(())
let webview: &WKWebView = unsafe { &*self.inner().cast() };
install_tls_navigation_delegate(webview)
}
fn user_agent(&self) -> anyhow::Result<String> {
+72 -16
View File
@@ -1,13 +1,17 @@
use std::{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::SamlAuthData,
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
utils::{redact::redact_uri, window::get_title_bar_height},
};
use log::{info, warn};
#[cfg(target_os = "macos")]
use tauri::Manager;
use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
webview::{PageLoadEvent, PageLoadPayload},
@@ -53,10 +57,28 @@ pub struct WebviewAuthenticator<'a> {
auth_request: Option<&'a str>,
webview_user_agent: Option<WebviewUserAgent>,
clean: bool,
window_title: &'a str,
window_theme: AuthWindowTheme,
is_retrying: tokio::sync::RwLock<bool>,
}
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
match theme {
AuthWindowTheme::System => None,
AuthWindowTheme::Light => Some(tauri::Theme::Light),
AuthWindowTheme::Dark => Some(tauri::Theme::Dark),
}
}
pub fn apply_auth_theme(app_handle: &AppHandle, theme: AuthWindowTheme) {
app_handle.set_theme(native_theme(theme));
}
fn present_after_setup(clean: bool) -> bool {
clean
}
impl<'a> WebviewAuthenticator<'a> {
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
Self {
@@ -65,6 +87,8 @@ impl<'a> WebviewAuthenticator<'a> {
auth_request: None,
webview_user_agent: None,
clean: false,
window_title: "GlobalProtect Login",
window_theme: AuthWindowTheme::System,
is_retrying: Default::default(),
}
}
@@ -84,6 +108,16 @@ impl<'a> WebviewAuthenticator<'a> {
self
}
pub fn with_window_title(mut self, window_title: &'a str) -> Self {
self.window_title = window_title;
self
}
pub fn with_window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
self.window_theme = window_theme;
self
}
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);
@@ -112,25 +146,32 @@ impl<'a> WebviewAuthenticator<'a> {
});
};
let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 };
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.on_page_load(on_page_load)
.title("GlobalProtect Login")
.inner_size(900.0, 650.0 + title_bar_height)
.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())
.focused(true)
// when clean is true, the window is expected to be shown because the cookies are cleared
.visible(self.clean)
.visible(false)
.center()
.build()?;
#[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);
}
loop {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"),
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),
@@ -285,13 +326,15 @@ impl<'a> WebviewAuthenticator<'a> {
info!("Raising auth window...");
#[cfg(target_os = "macos")]
let result = auth_window.show();
if let Err(err) = auth_window
.app_handle()
.set_activation_policy(tauri::ActivationPolicy::Regular)
{
warn!("Failed to show the application in the Dock: {}", err);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let result = {
use gpapi::utils::window::WindowExt;
auth_window.raise()
};
use gpapi::utils::window::WindowExt;
let result = auth_window.raise();
if let Err(err) = result {
warn!("Failed to raise window: {}", err);
@@ -377,6 +420,19 @@ fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) ->
mod tests {
use super::*;
#[test]
fn maps_auth_window_theme_to_native_theme() {
assert_eq!(native_theme(AuthWindowTheme::System), None);
assert_eq!(native_theme(AuthWindowTheme::Light), Some(tauri::Theme::Light));
assert_eq!(native_theme(AuthWindowTheme::Dark), Some(tauri::Theme::Dark));
}
#[test]
fn presents_clean_auth_after_setup() {
assert!(present_after_setup(true));
assert!(!present_after_setup(false));
}
#[test]
fn prepends_prefix_to_default_user_agent() {
let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap();
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "browser-launcher"
rust-version.workspace = true
version.workspace = true
authors.workspace = true
homepage.workspace = true
edition.workspace = true
license = "MIT"
[dependencies]
anyhow.workspace = true
log.workspace = true
open = { version = "5", optional = true }
webbrowser = { version = "1", optional = true }
which = { workspace = true, optional = true }
[features]
default = []
launcher = ["dep:open", "dep:webbrowser", "dep:which"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Kevin Yue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+89
View File
@@ -0,0 +1,89 @@
#[cfg(all(feature = "launcher", target_os = "macos"))]
#[path = "platform/macos.rs"]
mod platform;
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
#[path = "platform/generic.rs"]
mod platform;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Browser<'a> {
Auto,
Default,
Chrome,
Edge,
Firefox,
Safari,
Other(&'a str),
}
impl<'a> Browser<'a> {
pub fn from_config(value: Option<&'a str>) -> Self {
let Some(value) = value.filter(|value| !value.trim().is_empty()) else {
return Browser::Auto;
};
Self::from_name(value)
}
pub fn from_name(value: &'a str) -> Self {
match value.trim().to_lowercase().as_str() {
"auto" => Browser::Auto,
"default" => Browser::Default,
"chrome" => Browser::Chrome,
"edge" => Browser::Edge,
"firefox" => Browser::Firefox,
"safari" => Browser::Safari,
_ => Browser::Other(value),
}
}
#[cfg(all(feature = "launcher", not(target_os = "macos")))]
pub(crate) fn as_str(&self) -> &str {
match self {
Browser::Auto => "auto",
Browser::Default => "default",
Browser::Chrome => "chrome",
Browser::Edge => "edge",
Browser::Firefox => "firefox",
Browser::Safari => "safari",
Browser::Other(browser) => browser,
}
}
}
#[cfg(feature = "launcher")]
pub fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
platform::open_url(url, browser)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_config_uses_auto() {
assert_eq!(Browser::from_config(None), Browser::Auto);
assert_eq!(Browser::from_config(Some("")), Browser::Auto);
assert_eq!(Browser::from_config(Some(" ")), Browser::Auto);
}
#[test]
fn known_browser_names_are_case_insensitive() {
assert_eq!(Browser::from_name("AUTO"), Browser::Auto);
assert_eq!(Browser::from_name("Default"), Browser::Default);
assert_eq!(Browser::from_name("Chrome"), Browser::Chrome);
assert_eq!(Browser::from_name("EDGE"), Browser::Edge);
assert_eq!(Browser::from_name("Firefox"), Browser::Firefox);
assert_eq!(Browser::from_name("Safari"), Browser::Safari);
}
#[test]
fn custom_browser_names_are_preserved() {
assert_eq!(Browser::from_name("/opt/browser"), Browser::Other("/opt/browser"));
assert_eq!(
Browser::from_config(Some(" custom-browser ")),
Browser::Other(" custom-browser ")
);
}
}
@@ -0,0 +1,467 @@
use std::{
os::unix::process::CommandExt,
process::{Command, Stdio},
};
use anyhow::Context;
use log::{debug, info, warn};
use crate::Browser;
const GOOGLE_CHROME_BROWSERS: &[&str] = &["google-chrome-stable", "google-chrome"];
const CHROMIUM_BROWSERS: &[&str] = &["chromium", "chromium-browser"];
const EDGE_BROWSERS: &[&str] = &["microsoft-edge-stable", "microsoft-edge"];
const EDGE_BETA_BROWSERS: &[&str] = &["microsoft-edge-beta"];
const EDGE_DEV_BROWSERS: &[&str] = &["microsoft-edge-dev"];
const FIREFOX_BROWSERS: &[&str] = &["firefox"];
const FIREFOX_ESR_BROWSERS: &[&str] = &["firefox-esr"];
const BRAVE_BROWSERS: &[&str] = &["brave-browser-stable"];
const VIVALDI_BROWSERS: &[&str] = &["vivaldi-stable"];
const FALKON_BROWSERS: &[&str] = &["falkon"];
const EPIPHANY_BROWSERS: &[&str] = &["epiphany"];
const OPERA_BROWSERS: &[&str] = &["opera"];
const LIBREWOLF_BROWSERS: &[&str] = &["librewolf"];
const WATERFOX_BROWSERS: &[&str] = &["waterfox"];
const QUTEBROWSER_BROWSERS: &[&str] = &["qutebrowser"];
const AUTO_BROWSER_PROGRAMS: &[&[&str]] = &[
GOOGLE_CHROME_BROWSERS,
CHROMIUM_BROWSERS,
EDGE_BROWSERS,
EDGE_BETA_BROWSERS,
EDGE_DEV_BROWSERS,
FIREFOX_BROWSERS,
FIREFOX_ESR_BROWSERS,
BRAVE_BROWSERS,
VIVALDI_BROWSERS,
FALKON_BROWSERS,
EPIPHANY_BROWSERS,
OPERA_BROWSERS,
LIBREWOLF_BROWSERS,
WATERFOX_BROWSERS,
QUTEBROWSER_BROWSERS,
];
const AUTO_BROWSER_FLATPAK_IDS: &[&str] = &[
"com.google.Chrome",
"org.chromium.Chromium",
"com.microsoft.Edge",
"org.mozilla.firefox",
"com.brave.Browser",
"com.vivaldi.Vivaldi",
"org.kde.falkon",
"org.gnome.Epiphany",
"com.opera.Opera",
"io.gitlab.librewolf-community",
"net.waterfox.waterfox",
"org.qutebrowser.qutebrowser",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LauncherSpec {
Programs(&'static [&'static str]),
Flatpak(&'static str),
ProgramsOrFlatpak {
programs: &'static [&'static str],
app_id: &'static str,
},
}
#[derive(Debug, PartialEq, Eq)]
enum BrowserLauncher {
Executable(String),
Flatpak { executable: String, app_id: &'static str },
}
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
match browser {
Browser::Auto => open_auto_browser(url),
Browser::Default => open_default_browser(url),
Browser::Chrome => open_resolved_browser(url, find_chrome_browser(), "Chrome is not available."),
Browser::Edge => open_resolved_browser(url, find_edge_browser(), "Edge is not available."),
Browser::Firefox => open_resolved_browser(url, find_firefox_browser(), "Firefox is not available."),
Browser::Safari => open_resolved_browser(url, find_program(browser.as_str()), "Safari is not available."),
Browser::Other(browser) => open_resolved_browser(
url,
find_program(browser.trim()),
"Configured browser is not available.",
),
}
}
fn open_resolved_browser(
url: &str,
executable: Option<String>,
unavailable_message: &'static str,
) -> anyhow::Result<()> {
let executable = executable.context(unavailable_message)?;
open_with_browser(url, &executable)
}
fn open_auto_browser(url: &str) -> anyhow::Result<()> {
let default_launcher = find_default_browser_launcher();
if let Some(launcher) = default_launcher.as_ref() {
if let Err(err) = open_with_launcher(url, launcher) {
warn!("Failed to launch recognized default browser: {err}");
} else {
return Ok(());
}
}
if let Some(launcher) = find_auto_browser_launcher()
&& Some(&launcher) != default_launcher.as_ref()
{
if let Err(err) = open_with_launcher(url, &launcher) {
warn!("Failed to launch an automatically detected browser: {err}");
} else {
return Ok(());
}
}
warn!("Falling back to the system URL handler");
open_default_browser(url)
}
fn open_default_browser(url: &str) -> anyhow::Result<()> {
if webbrowser::open(url).is_ok() {
return Ok(());
}
open::that_detached(url).map_err(Into::into)
}
fn open_with_browser(url: &str, browser: &str) -> anyhow::Result<()> {
info!("Launching browser: {}", browser);
open::with_detached(url, browser).map_err(Into::into)
}
fn open_with_launcher(url: &str, launcher: &BrowserLauncher) -> anyhow::Result<()> {
match launcher {
BrowserLauncher::Executable(executable) => open_with_browser(url, executable),
BrowserLauncher::Flatpak { executable, app_id } => {
info!("Launching Flatpak browser: {app_id}");
Command::new(executable)
.args(["run", app_id, url])
.process_group(0)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
Ok(())
}
}
}
fn find_default_browser_launcher() -> Option<BrowserLauncher> {
let desktop_id = default_browser_desktop_id()?;
let Some(spec) = launcher_spec_for_desktop_id(&desktop_id) else {
warn!("Default browser desktop ID is not recognized: {desktop_id}");
return None;
};
let launcher = resolve_launcher(spec);
if launcher.is_none() {
warn!("Default browser is recognized but its launcher is unavailable: {desktop_id}");
}
launcher
}
fn default_browser_desktop_id() -> Option<String> {
let output = match Command::new("xdg-settings")
.args(["get", "default-web-browser"])
.output()
{
Ok(output) => output,
Err(err) => {
debug!("Unable to query the default browser: {err}");
return None;
}
};
if !output.status.success() {
debug!("xdg-settings could not determine the default browser");
return None;
}
let desktop_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
(!desktop_id.is_empty()).then_some(desktop_id)
}
fn launcher_spec_for_desktop_id(desktop_id: &str) -> Option<LauncherSpec> {
match desktop_id {
"google-chrome.desktop" | "google-chrome-stable.desktop" => Some(LauncherSpec::Programs(GOOGLE_CHROME_BROWSERS)),
"chromium.desktop" | "chromium-browser.desktop" | "chromium_chromium.desktop" => {
Some(LauncherSpec::Programs(CHROMIUM_BROWSERS))
}
"microsoft-edge.desktop" | "microsoft-edge-stable.desktop" => Some(LauncherSpec::Programs(EDGE_BROWSERS)),
"microsoft-edge-beta.desktop" => Some(LauncherSpec::Programs(EDGE_BETA_BROWSERS)),
"microsoft-edge-dev.desktop" => Some(LauncherSpec::Programs(EDGE_DEV_BROWSERS)),
"firefox.desktop" | "firefox_firefox.desktop" => Some(LauncherSpec::Programs(FIREFOX_BROWSERS)),
"firefox-esr.desktop" => Some(LauncherSpec::Programs(FIREFOX_ESR_BROWSERS)),
"com.google.Chrome.desktop" => Some(LauncherSpec::Flatpak("com.google.Chrome")),
"org.chromium.Chromium.desktop" => Some(LauncherSpec::Flatpak("org.chromium.Chromium")),
"com.microsoft.Edge.desktop" => Some(LauncherSpec::Flatpak("com.microsoft.Edge")),
"org.mozilla.firefox.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
programs: FIREFOX_BROWSERS,
app_id: "org.mozilla.firefox",
}),
"com.brave.Browser.desktop" => Some(LauncherSpec::Flatpak("com.brave.Browser")),
"vivaldi-stable.desktop" => Some(LauncherSpec::Programs(VIVALDI_BROWSERS)),
"com.vivaldi.Vivaldi.desktop" => Some(LauncherSpec::Flatpak("com.vivaldi.Vivaldi")),
"org.kde.falkon.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
programs: FALKON_BROWSERS,
app_id: "org.kde.falkon",
}),
"org.gnome.Epiphany.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
programs: EPIPHANY_BROWSERS,
app_id: "org.gnome.Epiphany",
}),
"com.opera.Opera.desktop" => Some(LauncherSpec::Flatpak("com.opera.Opera")),
"io.gitlab.librewolf-community.desktop" => Some(LauncherSpec::Flatpak("io.gitlab.librewolf-community")),
"net.waterfox.waterfox.desktop" => Some(LauncherSpec::Flatpak("net.waterfox.waterfox")),
"org.qutebrowser.qutebrowser.desktop" => Some(LauncherSpec::ProgramsOrFlatpak {
programs: QUTEBROWSER_BROWSERS,
app_id: "org.qutebrowser.qutebrowser",
}),
_ => None,
}
}
fn resolve_launcher(spec: LauncherSpec) -> Option<BrowserLauncher> {
match spec {
LauncherSpec::Programs(programs) => find_programs(programs).map(BrowserLauncher::Executable),
LauncherSpec::Flatpak(app_id) => find_flatpak_browser(app_id),
LauncherSpec::ProgramsOrFlatpak { programs, app_id } => find_programs(programs)
.map(BrowserLauncher::Executable)
.or_else(|| find_flatpak_browser(app_id)),
}
}
fn find_flatpak_browser(app_id: &'static str) -> Option<BrowserLauncher> {
let executable = find_program("flatpak")?;
let installed = Command::new(&executable)
.args(["info", app_id])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success());
installed.then_some(BrowserLauncher::Flatpak { executable, app_id })
}
fn find_auto_browser_launcher() -> Option<BrowserLauncher> {
find_auto_browser()
.map(BrowserLauncher::Executable)
.or_else(find_auto_flatpak_browser)
}
fn find_auto_browser() -> Option<String> {
AUTO_BROWSER_PROGRAMS
.iter()
.find_map(|programs| find_programs(programs))
}
fn find_auto_flatpak_browser() -> Option<BrowserLauncher> {
let executable = find_program("flatpak")?;
let output = Command::new(&executable)
.args(["list", "--app", "--columns=application"])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let installed_apps = String::from_utf8_lossy(&output.stdout);
let app_id = find_auto_flatpak_app_id(&installed_apps)?;
Some(BrowserLauncher::Flatpak { executable, app_id })
}
fn find_auto_flatpak_app_id(installed_apps: &str) -> Option<&'static str> {
AUTO_BROWSER_FLATPAK_IDS
.iter()
.copied()
.find(|app_id| installed_apps.lines().any(|installed| installed.trim() == *app_id))
}
fn find_chrome_browser() -> Option<String> {
find_programs(GOOGLE_CHROME_BROWSERS).or_else(|| find_programs(CHROMIUM_BROWSERS))
}
fn find_edge_browser() -> Option<String> {
find_programs(EDGE_BROWSERS)
.or_else(|| find_programs(EDGE_BETA_BROWSERS))
.or_else(|| find_programs(EDGE_DEV_BROWSERS))
}
fn find_firefox_browser() -> Option<String> {
find_programs(FIREFOX_BROWSERS).or_else(|| find_programs(FIREFOX_ESR_BROWSERS))
}
fn find_programs(programs: &[&str]) -> Option<String> {
programs.iter().find_map(|program| find_program(program))
}
fn find_program(name: &str) -> Option<String> {
which::which(name).ok().map(|path| path.to_string_lossy().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auto_candidates_use_the_expected_order() {
let candidates = AUTO_BROWSER_PROGRAMS
.iter()
.flat_map(|programs| programs.iter())
.copied()
.collect::<Vec<_>>();
assert_eq!(
candidates,
vec![
"google-chrome-stable",
"google-chrome",
"chromium",
"chromium-browser",
"microsoft-edge-stable",
"microsoft-edge",
"microsoft-edge-beta",
"microsoft-edge-dev",
"firefox",
"firefox-esr",
"brave-browser-stable",
"vivaldi-stable",
"falkon",
"epiphany",
"opera",
"librewolf",
"waterfox",
"qutebrowser",
]
);
assert_eq!(
AUTO_BROWSER_FLATPAK_IDS,
[
"com.google.Chrome",
"org.chromium.Chromium",
"com.microsoft.Edge",
"org.mozilla.firefox",
"com.brave.Browser",
"com.vivaldi.Vivaldi",
"org.kde.falkon",
"org.gnome.Epiphany",
"com.opera.Opera",
"io.gitlab.librewolf-community",
"net.waterfox.waterfox",
"org.qutebrowser.qutebrowser",
]
);
}
#[test]
fn known_desktop_ids_map_to_expected_launchers() {
let cases = [
("google-chrome.desktop", LauncherSpec::Programs(GOOGLE_CHROME_BROWSERS)),
("chromium.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
("chromium-browser.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
("chromium_chromium.desktop", LauncherSpec::Programs(CHROMIUM_BROWSERS)),
("microsoft-edge.desktop", LauncherSpec::Programs(EDGE_BROWSERS)),
(
"microsoft-edge-beta.desktop",
LauncherSpec::Programs(EDGE_BETA_BROWSERS),
),
("microsoft-edge-dev.desktop", LauncherSpec::Programs(EDGE_DEV_BROWSERS)),
("firefox.desktop", LauncherSpec::Programs(FIREFOX_BROWSERS)),
("firefox-esr.desktop", LauncherSpec::Programs(FIREFOX_ESR_BROWSERS)),
("firefox_firefox.desktop", LauncherSpec::Programs(FIREFOX_BROWSERS)),
("com.google.Chrome.desktop", LauncherSpec::Flatpak("com.google.Chrome")),
(
"org.chromium.Chromium.desktop",
LauncherSpec::Flatpak("org.chromium.Chromium"),
),
(
"com.microsoft.Edge.desktop",
LauncherSpec::Flatpak("com.microsoft.Edge"),
),
(
"org.mozilla.firefox.desktop",
LauncherSpec::ProgramsOrFlatpak {
programs: FIREFOX_BROWSERS,
app_id: "org.mozilla.firefox",
},
),
("com.brave.Browser.desktop", LauncherSpec::Flatpak("com.brave.Browser")),
("vivaldi-stable.desktop", LauncherSpec::Programs(VIVALDI_BROWSERS)),
(
"com.vivaldi.Vivaldi.desktop",
LauncherSpec::Flatpak("com.vivaldi.Vivaldi"),
),
(
"org.kde.falkon.desktop",
LauncherSpec::ProgramsOrFlatpak {
programs: FALKON_BROWSERS,
app_id: "org.kde.falkon",
},
),
(
"org.gnome.Epiphany.desktop",
LauncherSpec::ProgramsOrFlatpak {
programs: EPIPHANY_BROWSERS,
app_id: "org.gnome.Epiphany",
},
),
("com.opera.Opera.desktop", LauncherSpec::Flatpak("com.opera.Opera")),
(
"io.gitlab.librewolf-community.desktop",
LauncherSpec::Flatpak("io.gitlab.librewolf-community"),
),
(
"net.waterfox.waterfox.desktop",
LauncherSpec::Flatpak("net.waterfox.waterfox"),
),
(
"org.qutebrowser.qutebrowser.desktop",
LauncherSpec::ProgramsOrFlatpak {
programs: QUTEBROWSER_BROWSERS,
app_id: "org.qutebrowser.qutebrowser",
},
),
];
for (desktop_id, expected) in cases {
assert_eq!(launcher_spec_for_desktop_id(desktop_id), Some(expected));
}
}
#[test]
fn unknown_desktop_id_is_not_used() {
assert_eq!(launcher_spec_for_desktop_id("code.desktop"), None);
}
#[test]
fn auto_flatpak_candidates_use_priority_and_exact_ids() {
assert_eq!(
find_auto_flatpak_app_id("org.kde.falkon\ncom.brave.Browser\n"),
Some("com.brave.Browser")
);
assert_eq!(find_auto_flatpak_app_id("com.brave.Browser.beta\n"), None);
}
#[test]
fn unavailable_custom_browser_returns_an_error() {
let err = open_url(
"https://example.com",
Browser::Other("gpgui-browser-that-does-not-exist"),
)
.unwrap_err();
assert_eq!(err.to_string(), "Configured browser is not available.");
}
}
@@ -0,0 +1,45 @@
use log::info;
use crate::Browser;
const SAFARI_BUNDLE_ID: &str = "com.apple.Safari";
const CHROME_BUNDLE_ID: &str = "com.google.Chrome";
const EDGE_BUNDLE_ID: &str = "com.microsoft.edgemac";
const FIREFOX_BUNDLE_ID: &str = "org.mozilla.firefox";
pub(super) fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> {
match browser {
Browser::Auto | Browser::Default => open_default_browser(url),
Browser::Safari => open_browser_bundle(url, SAFARI_BUNDLE_ID),
Browser::Chrome => open_browser_bundle(url, CHROME_BUNDLE_ID),
Browser::Edge => open_browser_bundle(url, EDGE_BUNDLE_ID),
Browser::Firefox => open_browser_bundle(url, FIREFOX_BUNDLE_ID),
Browser::Other(application) => open_browser_application(url, application),
}
}
fn open_default_browser(url: &str) -> anyhow::Result<()> {
if webbrowser::open(url).is_ok() {
return Ok(());
}
open::that_detached(url).map_err(Into::into)
}
fn open_browser_bundle(url: &str, bundle_id: &str) -> anyhow::Result<()> {
info!("Launching browser bundle: {}", bundle_id);
let status = std::process::Command::new("/usr/bin/open")
.args(["-b", bundle_id, url])
.status()?;
if !status.success() {
anyhow::bail!("Failed to launch browser bundle {bundle_id}: {status}");
}
Ok(())
}
fn open_browser_application(url: &str, application: &str) -> anyhow::Result<()> {
info!("Launching browser application: {}", application);
open::with_detached(url, application).map_err(Into::into)
}
+1 -1
View File
@@ -5,4 +5,4 @@ version.workspace = true
authors.workspace = true
homepage.workspace = true
edition.workspace = true
license.workspace = true
license = "MIT"
+21 -674
View File
@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
MIT License
Copyright (c) 2024 Kevin Yue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+79 -1
View File
@@ -3,6 +3,15 @@ use std::{
path::{Path, PathBuf},
};
#[cfg(all(
not(debug_assertions),
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
))]
use crate::constants::GP_DOWNLOADED_GUI_BINARY;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use crate::constants::GP_HIP_SCRIPT_INSTALLER_BINARY;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use crate::constants::GP_VPNC_SCRIPT_INSTALLER_BINARY;
use crate::constants::{GP_AUTH_BINARY, GP_CLIENT_BINARY, GP_GUI_BINARY, GP_GUI_HELPER_BINARY, GP_SERVICE_BINARY};
pub fn gpclient() -> PathBuf {
@@ -13,6 +22,24 @@ pub fn gpservice() -> PathBuf {
resolve("GP_SERVICE_BINARY", "gpservice", GP_SERVICE_BINARY)
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn gp_vpnc_script_installer() -> PathBuf {
resolve(
"GP_VPNC_SCRIPT_INSTALLER_BINARY",
"gp-vpnc-script-installer",
GP_VPNC_SCRIPT_INSTALLER_BINARY,
)
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn gp_hip_script_installer() -> PathBuf {
resolve(
"GP_HIP_SCRIPT_INSTALLER_BINARY",
"gp-hip-script-installer",
GP_HIP_SCRIPT_INSTALLER_BINARY,
)
}
pub fn gpauth() -> PathBuf {
resolve("GP_AUTH_BINARY", "gpauth", GP_AUTH_BINARY)
}
@@ -21,6 +48,24 @@ pub fn gpgui() -> PathBuf {
resolve("GP_GUI_BINARY", "gpgui", GP_GUI_BINARY)
}
pub fn gpgui_update_target() -> PathBuf {
#[cfg(all(
not(debug_assertions),
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
))]
{
PathBuf::from(GP_DOWNLOADED_GUI_BINARY)
}
#[cfg(any(
debug_assertions,
not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))
))]
{
gpgui()
}
}
pub fn gpgui_helper() -> PathBuf {
resolve("GP_GUI_HELPER_BINARY", "gpgui-helper", GP_GUI_HELPER_BINARY)
}
@@ -37,8 +82,27 @@ fn sibling_binary(binary_name: &str) -> Option<PathBuf> {
let current_exe = env::current_exe().ok()?;
let bin_dir = current_exe.parent()?;
let binary = bin_dir.join(binary_name);
if is_file(&binary) {
return Some(binary);
}
#[cfg(target_os = "macos")]
if let Some(binary) = bundled_helper_path(&current_exe, binary_name)
&& is_file(&binary)
{
return Some(binary);
}
None
}
is_file(&binary).then_some(binary)
#[cfg(target_os = "macos")]
fn bundled_helper_path(executable: &Path, binary_name: &str) -> Option<PathBuf> {
let bin_dir = executable.parent()?;
let contents = bin_dir.parent()?;
let bundle = contents.parent()?;
if bin_dir.file_name()? != "MacOS" || contents.file_name()? != "Contents" || bundle.extension()? != "app" {
return None;
}
Some(contents.join("Helpers").join(binary_name))
}
fn is_file(path: &Path) -> bool {
@@ -49,6 +113,20 @@ fn is_file(path: &Path) -> bool {
mod tests {
use super::*;
#[test]
#[cfg(target_os = "macos")]
fn desktop_resolves_helpers_in_the_actual_app_bundle_layout() {
assert_eq!(
bundled_helper_path(
Path::new("/Applications/GP Connect.app/Contents/MacOS/gpgui"),
"gpclient"
),
Some(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers/gpclient"))
);
assert!(bundled_helper_path(Path::new("/usr/local/bin/gpgui"), "gpclient").is_none());
assert!(bundled_helper_path(Path::new("/tmp/Contents/MacOS/gpgui"), "gpclient").is_none());
}
#[test]
fn default_path_is_used_when_no_sibling_exists() {
let path = resolve("GP_TEST_BINARY", "missing-gp-test-binary", "/usr/bin/gp-test");
+22 -1
View File
@@ -3,7 +3,24 @@ pub const GP_CLIENT_VERSION_LINUX: &str = "6.3.3-619";
pub const GP_CLIENT_VERSION_WINDOWS: &str = "6.3.3-650";
pub const GP_CLIENT_VERSION_MACOS: &str = "6.3.3-915";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
#[cfg(target_os = "linux")]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(target_os = "linux")]
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-hip-script-installer";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/local/libexec/gpclient/gp-hip-script-installer";
#[cfg(target_os = "linux")]
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/lib/gpclient/scripts/vpnc-script";
#[cfg(target_os = "linux")]
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/lib/gpclient/scripts/vpnc-script.metadata";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/local/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/db/gpclient/scripts/vpnc-script";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/db/gpclient/scripts/vpnc-script.metadata";
pub const MAX_VPNC_SCRIPT_SIZE: usize = 1024 * 1024;
pub const MAX_HIP_SCRIPT_SIZE: usize = 1024 * 1024;
// Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
@@ -36,6 +53,8 @@ pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const GP_DOWNLOADED_GUI_BINARY: &str = "/usr/local/libexec/gpclient/gpgui";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), any(target_os = "freebsd", target_os = "openbsd")))]
@@ -57,6 +76,8 @@ pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(target_os = "linux")]
pub const GP_DOWNLOADED_GUI_BINARY: &str = "/var/lib/gpclient/gpgui";
#[cfg(all(
not(debug_assertions),
not(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))
+13 -3
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license = "MIT"
[dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"] }
common = { path = "../common" }
anyhow.workspace = true
base64.workspace = true
@@ -17,9 +18,10 @@ version-compare = "0.2"
pem.workspace = true
xmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive", "uuid"] }
urlencoding.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
tokio-util.workspace = true
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
@@ -32,11 +34,15 @@ uzers.workspace = true
serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
uuid = { workspace = true, features = ["v5"] }
uuid = { workspace = true, features = ["v4", "v5", "serde"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
socket2 = { version = "0.6", features = ["all"] }
os_info = { version = "3", default-features = false }
snow.workspace = true
zeroize = { workspace = true, features = ["serde"] }
getrandom = "0.4"
# Optional dependencies for features
tauri = { workspace = true, optional = true }
@@ -46,15 +52,19 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
[target.'cfg(target_os="macos")'.dependencies]
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 }
[dev-dependencies]
proptest.workspace = true
tokio = { workspace = true, features = ["test-util"] }
[features]
tauri = ["dep:tauri", "dep:gtk"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"]
logger = ["dep:env_logger", "dep:log-reload", "dep:oslog"]
+49 -3
View File
@@ -1,4 +1,7 @@
use std::borrow::{Borrow, Cow};
use std::{
borrow::{Borrow, Cow},
fmt,
};
use anyhow::bail;
use log::{info, warn};
@@ -9,6 +12,25 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum AuthWindowTheme {
#[default]
System,
Light,
Dark,
}
impl AuthWindowTheme {
pub fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlAuthData {
@@ -25,13 +47,26 @@ pub struct SamlAuthData {
#[serde(rename_all = "camelCase")]
pub enum SamlAuthResult {
Success(SamlAuthData),
Cancelled,
Failure(String),
}
#[derive(Debug)]
pub struct AuthenticationCancelled;
impl fmt::Display for AuthenticationCancelled {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Authentication cancelled")
}
}
impl std::error::Error for AuthenticationCancelled {}
impl SamlAuthResult {
pub fn is_success(&self) -> bool {
match self {
SamlAuthResult::Success(_) => true,
SamlAuthResult::Cancelled => false,
SamlAuthResult::Failure(_) => false,
}
}
@@ -39,6 +74,7 @@ impl SamlAuthResult {
pub fn host_id(&self) -> Option<&str> {
match self {
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
SamlAuthResult::Cancelled => None,
SamlAuthResult::Failure(_) => None,
}
}
@@ -118,7 +154,6 @@ impl SamlAuthData {
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| {
warn!("Failed to parse token auth data: {}", e);
warn!("Auth data: {}", auth_data);
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
@@ -127,7 +162,7 @@ impl SamlAuthData {
}
let auth_data = decode_to_string(auth_data).map_err(|e| {
warn!("Failed to decode SAML auth data: {}, data: {}", e, data);
warn!("Failed to decode SAML auth data: {}", e);
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
let auth_data = Self::from_html(&auth_data)?;
@@ -246,4 +281,15 @@ mod tests {
let value = serde_json::to_value(result).unwrap();
assert!(value["success"].get("hostId").is_none());
}
#[test]
fn auth_result_cancelled_is_structured() {
let value = serde_json::to_value(SamlAuthResult::Cancelled).unwrap();
assert_eq!(value, "cancelled");
let result: SamlAuthResult = serde_json::from_value(value).unwrap();
assert!(!result.is_success());
assert_eq!(result.host_id(), None);
}
}
+243 -11
View File
@@ -1,33 +1,139 @@
use std::io::{self, Write};
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
use log::Level;
use crate::error::PortalError;
use crate::{
error::PortalError,
log_format::{LogFormat, write_json_record},
};
pub mod args;
pub trait Args {
fn fix_openssl(&self) -> bool;
fn ignore_tls_errors(&self) -> bool;
/// How this program renders its logs.
///
/// Required rather than defaulted: a default would let an implementor drop
/// the override and silently report failures as prose to a caller that asked
/// for JSON, with nothing — not even a warning — to catch it.
fn log_format(&self) -> LogFormat;
}
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
eprintln!("\nError: {:?}", err);
/// Suggestions for re-running the command, for failures that have a known
/// 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 {
return;
return Vec::new();
};
let command_line = || {
let argv = std::env::args().collect::<Vec<_>>();
let program = argv.first().cloned().unwrap_or_default();
let rest = argv.get(1..).map(|rest| rest.join(" ")).unwrap_or_default();
(program, rest)
};
// The blank line between the sentence and the command is part of the output
// users already see; keep it exactly.
let mut hints = Vec::new();
if err.is_legacy_openssl_error() && !args.fix_openssl() {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
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() {
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
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}"
));
}
hints
}
/// Write one message to `w` the way `format` asks for.
///
/// Text is emitted exactly as it always was, so existing output does not move.
/// JSON is written directly rather than through the `log` macros, because these
/// are reports rather than log lines: they must survive `--quiet`, which would
/// otherwise discard the only explanation of a failed run.
///
/// The record is rendered into one buffer and written once. `serde_json`'s
/// `Display` would otherwise reach the stream in dozens of fragments, and any
/// process sharing this stderr — the spawned authenticator, a connect script —
/// could land a line inside a half-written record.
fn write_message<W: Write>(w: &mut W, format: LogFormat, level: Level, message: &str) -> io::Result<()> {
match format {
LogFormat::Text => writeln!(w, "{message}"),
LogFormat::Json => {
// Callers pass the exact text line, blank-line padding included, so the
// text form does not move. A record carries its own separation.
let message = message.trim_start_matches('\n');
let mut line = Vec::new();
write_json_record(
&mut line,
&log::Record::builder()
.level(level)
.target(module_path!())
.args(format_args!("{message}"))
.build(),
)?;
w.write_all(&line)
}
}
}
/// Report a user-facing line that is not a log record — a note, a warning, or
/// advice about what to try next.
///
/// Callers used `eprintln!` directly, which in JSON mode drops prose into a
/// stream the caller is parsing a line at a time. Routing them here keeps one
/// answer to "how does this program emit a user-facing line", and leaves the
/// text form byte-for-byte unchanged.
pub fn report(format: LogFormat, level: Level, message: &str) {
let _ = write_message(&mut io::stderr().lock(), format, level, message);
}
fn write_failure<W: Write>(w: &mut W, format: LogFormat, err: &anyhow::Error, hints: &[String]) -> io::Result<()> {
match format {
LogFormat::Text => {
writeln!(w, "\nError: {err:?}")?;
for hint in hints {
writeln!(w, "\n{hint}\n")?;
}
}
LogFormat::Json => {
write_message(w, format, Level::Error, &format!("{err:?}"))?;
for hint in hints {
write_message(w, format, Level::Error, hint)?;
}
}
}
Ok(())
}
fn handle_error_to<W: Write>(w: &mut W, err: anyhow::Error, args: &impl Args) -> io::Result<()> {
let hints = retry_hints(&err, args);
write_failure(w, args.log_format(), &err, &hints)
}
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
// Nothing useful to do if stderr itself is gone.
let _ = handle_error_to(&mut io::stderr().lock(), err, args);
}
#[derive(Debug)]
@@ -79,3 +185,129 @@ impl ToVerboseArg for Level {
}
}
}
#[cfg(test)]
mod tests {
use anyhow::anyhow;
use super::*;
#[derive(Default)]
struct TestArgs {
fix_openssl: bool,
ignore_tls_errors: bool,
log_format: LogFormat,
}
impl Args for TestArgs {
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
fn log_format(&self) -> LogFormat {
self.log_format
}
}
/// The seam that matters: `handle_error` must ask the args which format to
/// use. Testing the writer alone would leave a version that always reports as
/// prose passing every test.
#[test]
fn handle_error_honours_the_requested_format() {
let args = TestArgs {
log_format: LogFormat::Json,
..Default::default()
};
let mut out = Vec::new();
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &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() {
serde_json::from_str::<serde_json::Value>(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
}
assert!(!out.is_empty(), "the failure must be reported");
}
#[test]
fn a_tls_failure_suggests_ignoring_tls_errors() {
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
// The command sits on its own line after a blank one, as it always has.
assert!(
hints[0].contains("e.g.:\n\n"),
"blank line before the command: {:?}",
hints[0]
);
}
/// Suggesting an option the user already passed is noise, and in JSON mode it
/// would be an extra record on every failed run.
#[test]
fn no_hint_when_the_option_is_already_in_use() {
let args = TestArgs {
ignore_tls_errors: true,
..Default::default()
};
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
}
/// Most failures have no known workaround; inventing advice for them would
/// mislead.
#[test]
fn no_hints_for_an_unrelated_error() {
let hints = retry_hints(&anyhow!("something else went wrong"), &TestArgs::default());
assert!(hints.is_empty(), "got {hints:?}");
}
fn failure_output(format: LogFormat) -> String {
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");
String::from_utf8(out).expect("output should be UTF-8")
}
/// The failure is the program's final report, so in JSON mode it must be one
/// more record on the same stream — and it must not be filtered away, which
/// is why it does not go through the log macros. A run that fails silently is
/// worse than one that fails noisily.
#[test]
fn the_failure_is_reported_as_records() {
let out = failure_output(LogFormat::Json);
let lines: Vec<_> = out.lines().collect();
assert_eq!(lines.len(), 2, "expected the error and its hint: {out:?}");
for line in lines {
let v: serde_json::Value = serde_json::from_str(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
assert_eq!(v["level"], "ERROR");
}
}
/// The format has to be honoured, not merely available: reporting the failure
/// as prose to a caller that asked for JSON is the defect this whole flag
/// exists to remove.
#[test]
fn the_format_decides_how_the_failure_is_written() {
assert!(
serde_json::from_str::<serde_json::Value>(failure_output(LogFormat::Json).lines().next().unwrap()).is_ok(),
"json mode must not emit prose"
);
let text = failure_output(LogFormat::Text);
assert!(text.starts_with("\nError: "), "text mode keeps its shape: {text:?}");
assert!(
serde_json::from_str::<serde_json::Value>(text.trim()).is_err(),
"text mode must not emit JSON: {text:?}"
);
}
}
+2 -1
View File
@@ -2,7 +2,7 @@ use anyhow::bail;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::auth::{SamlAuthData, SamlAuthResult};
use crate::auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult};
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
@@ -250,6 +250,7 @@ impl TryFrom<SamlAuthResult> for Credential {
fn try_from(value: SamlAuthResult) -> anyhow::Result<Self> {
match value {
SamlAuthResult::Success(auth_data) => Ok(Self::from(auth_data)),
SamlAuthResult::Cancelled => bail!(AuthenticationCancelled),
SamlAuthResult::Failure(err) => bail!(err),
}
}
+109
View File
@@ -0,0 +1,109 @@
//! Neutral device-anchor transport model and deterministic derivation.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u8", into = "u8")]
pub enum AnchorSource {
UnixMac,
UnixRandom,
MacosIokit,
}
impl From<AnchorSource> for u8 {
fn from(source: AnchorSource) -> Self {
match source {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidAnchorSource(u8);
impl fmt::Display for InvalidAnchorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "unsupported device anchor source {}", self.0)
}
}
impl std::error::Error for InvalidAnchorSource {}
impl TryFrom<u8> for AnchorSource {
type Error = InvalidAnchorSource;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
value => Err(InvalidAnchorSource(value)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceAnchor {
pub hardware_id: String,
pub source: AnchorSource,
}
impl DeviceAnchor {
pub fn validate(&self) -> bool {
URL_SAFE_NO_PAD
.decode(&self.hardware_id)
.is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == self.hardware_id)
}
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
let domain = match source {
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
};
let mut input = domain.to_vec();
input.extend_from_slice(seed.as_ref());
Self {
hardware_id: URL_SAFE_NO_PAD.encode(openssl::sha::sha256(&input)),
source,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hashes_original_seed_order_with_stable_domain_separation() {
let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
assert!(mac.validate());
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
);
assert_ne!(
mac.hardware_id,
DeviceAnchor::derive(AnchorSource::UnixRandom, [0, 17, 34, 51, 68, 85]).hardware_id
);
}
#[test]
fn source_uses_stable_numeric_json_codes() {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
}
+565 -60
View File
@@ -1,10 +1,15 @@
use std::{borrow::Cow, net::UdpSocket};
use std::{
borrow::Cow,
net::{SocketAddr, UdpSocket},
};
use anyhow::bail;
use log::{debug, info, warn};
use reqwest::Client;
use tokio_util::sync::CancellationToken;
use urlencoding::{decode, encode};
use xmltree::Element;
use zeroize::Zeroizing;
use crate::{
credential::Credential,
@@ -12,68 +17,238 @@ use crate::{
gateway::GatewayLoginContext,
gp_params::GpParams,
params::gateway_login::{self, GatewayLoginInput},
session::{
GatewayAuthentication,
network::GatewayBinding,
transport::{bound_client, gateway_origin},
},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
pub enum GatewayLogin {
Cookie(String),
Authenticated(GatewayAuthentication),
Mfa(String, String),
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, false).await
/// Protocol failures cannot be repaired by repeating login with different
/// credentials. Issued credentials, when identifiable, are cleaned up first.
#[derive(Debug, thiserror::Error)]
#[error("Gateway login returned invalid session configuration")]
pub struct GatewayLoginProtocolError;
#[derive(Clone)]
pub struct GatewayLoginClient {
origin: reqwest::Url,
client: Client,
params: GpParams,
binding: Option<GatewayBinding>,
login_endpoint: Option<SocketAddr>,
login_url: Option<reqwest::Url>,
maintenance_client: Option<Client>,
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
impl GatewayLoginClient {
pub fn register_session(
&self,
gateway: crate::gateway::Gateway,
authentication: GatewayAuthentication,
sessions: &mut crate::session::GatewaySessions,
) {
sessions.register(crate::session::GatewaySession {
gateway,
transport: self.authenticated_transport(authentication),
addresses: self
.binding
.as_ref()
.map(|binding| binding.addresses())
.unwrap_or_default(),
});
}
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
let client = Client::try_from(&params)?;
Ok(Self {
origin,
client,
params,
binding: None,
login_endpoint: None,
login_url: None,
maintenance_client: None,
})
}
/// Only called after an authenticated non-tunnel response and registration in
/// the caller's cleanup ledger. Tunnel login never inspects physical routing.
pub async fn bind_non_tunnel(
&mut self,
disable_ipv6: bool,
detection: Option<&crate::session::network::InternalHostDetection>,
cancellation: &tokio_util::sync::CancellationToken,
) -> anyhow::Result<()> {
let origin = gateway_origin(self.origin.as_str())?;
let response_url = self
.login_url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?;
anyhow::ensure!(
response_url.origin() == origin.origin(),
"Redirected non-tunnel authentication is unsupported"
);
let endpoint = self
.login_endpoint
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?;
let binding = network
.bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation)
.await?;
network
.validate_internal_binding(&binding, detection, cancellation)
.await?;
let client = bound_client(origin.as_str(), &self.params, &binding)?;
self.binding = Some(binding);
self.maintenance_client = Some(client);
Ok(())
}
pub fn update_registered_session(
&self,
gateway: &crate::gateway::Gateway,
authentication: &GatewayAuthentication,
sessions: &mut crate::session::GatewaySessions,
) {
sessions.update(crate::session::GatewaySession {
gateway: gateway.clone(),
transport: self.authenticated_transport(authentication.clone()),
addresses: self
.binding
.as_ref()
.map(|binding| binding.addresses())
.unwrap_or_default(),
});
}
pub fn authenticated_transport(
&self,
authentication: GatewayAuthentication,
) -> crate::session::transport::GatewayTransport {
crate::session::transport::GatewayTransport::from_authenticated_login(
self.maintenance_client.as_ref().unwrap_or(&self.client).clone(),
self.origin.clone(),
authentication,
self.params.os_profile().clone(),
)
}
pub fn binding(&self) -> Option<&GatewayBinding> {
self.binding.as_ref()
}
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
self.params.client_identity()
}
pub(crate) fn request_client(&self) -> &Client {
&self.client
}
pub(crate) fn origin(&self) -> &reqwest::Url {
&self.origin
}
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
self.params.set_input_str(input);
self.params.set_otp(otp);
}
pub async fn login(
&mut self,
cred: &Credential,
context: Option<&GatewayLoginContext>,
cancellation: &CancellationToken,
) -> anyhow::Result<GatewayLogin> {
if cancellation.is_cancelled() {
return Err(crate::auth::AuthenticationCancelled.into());
}
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(str::to_owned)
.or_else(|| detect_local_ipv4(context.host()))
});
let request = receive_gateway_login(
&self.origin,
&self.client,
cred,
&self.params,
context,
client_ip.as_deref(),
false,
);
let response = tokio::select! {
biased;
response = request => response?,
_ = cancellation.cancelled() => return Err(crate::auth::AuthenticationCancelled.into()),
};
// Once the full response is available, retain issued authentication or finish
// cleanup-only logout before the caller observes cancellation.
let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?;
self.login_endpoint = response.endpoint;
self.login_url = Some(response.url);
Ok(response.login)
}
pub(crate) async fn extend_lifetime(&self, cred: &Credential) -> anyhow::Result<GatewayLogin> {
let response = receive_gateway_login(&self.origin, &self.client, cred, &self.params, None, None, true).await?;
Ok(
parse_login_response(response, &self.client, &self.origin, &self.params)
.await?
.login,
)
}
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, true).await
struct LoginResponse {
login: GatewayLogin,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
}
async fn gateway_login_with_options(
gateway: &str,
struct ReceivedLogin {
body: String,
endpoint: Option<SocketAddr>,
url: reqwest::Url,
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
async fn receive_gateway_login(
origin: &reqwest::Url,
client: &Client,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
client_ip: Option<&str>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let client_ip = context.and_then(|context| {
context
.client_ip()
.map(|ip| ip.to_string())
.or_else(|| detect_local_ipv4(context.host()))
});
) -> anyhow::Result<ReceivedLogin> {
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
let request_params = gateway_login::build(&GatewayLoginInput {
gp_params,
cred,
gateway_host: &gateway,
context,
client_ip: client_ip.as_deref(),
client_ip,
extend_lifetime,
});
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
log_gateway_login_context(context, client_ip, gp_params);
let res = client
.post(&login_url)
.post(login_url)
.form(&request_params.body)
.send()
.await
@@ -82,11 +257,32 @@ async fn gateway_login_with_options(
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let endpoint = res.remote_addr();
let url = res.url().clone();
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason)
})?;
Ok(ReceivedLogin {
body: res,
endpoint,
url,
})
}
async fn parse_login_response(
response: ReceivedLogin,
client: &Client,
origin: &reqwest::Url,
gp_params: &GpParams,
) -> anyhow::Result<LoginResponse> {
let ReceivedLogin {
body: res,
endpoint,
url,
} = response;
// It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res);
@@ -96,27 +292,47 @@ async fn gateway_login_with_options(
// MFA detected
if res.contains("Challenge") {
let Some((message, input_str)) = parse_mfa(&res) else {
bail!("Failed to parse MFA challenge: {res}");
bail!("Failed to parse MFA challenge");
};
return Ok(GatewayLogin::Mfa(message, input_str));
return Ok(LoginResponse {
login: GatewayLogin::Mfa(message, input_str),
endpoint,
url,
});
}
debug!("Gateway login response: {}", res);
let root = Element::parse(res.as_bytes())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie))
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
let lower = res.to_ascii_lowercase();
if lower.contains("<!doctype") || lower.contains("<!entity") {
return Err(GatewayLoginProtocolError.into());
}
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
let (cookie, connection_type) =
parse_issued_authentication(&root, gp_params.computer()).map_err(|_| GatewayLoginProtocolError)?;
let cookie = Zeroizing::new(cookie);
let authentication = connection_type.and_then(|mode| GatewayAuthentication::new(cookie.to_string(), mode));
let authentication = match authentication {
Ok(authentication) => authentication,
Err(_) => {
match tokio::time::timeout(
std::time::Duration::from_secs(5),
crate::session::transport::logout_cookie(client, origin, &cookie, gp_params.os_profile()),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(error)) => warn!("Cleanup-only gateway logout failed: {error}"),
Err(_) => warn!("Cleanup-only gateway logout timed out"),
}
return Err(GatewayLoginProtocolError.into());
}
};
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
Ok(LoginResponse {
login: GatewayLogin::Authenticated(authentication),
endpoint,
url,
})
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
@@ -136,13 +352,33 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
);
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
anyhow::ensure!(
element.attr("status").is_none_or(|status| status == "success"),
"Gateway login response rejected authentication"
);
let application = element
.child("application-desc")
.ok_or_else(|| anyhow::anyhow!("Gateway login response has no application description"))?;
let args = application
.children("argument")
.iter()
.map(|e| e.get_text().unwrap_or_default())
.collect::<Vec<_>>();
let cookie = build_gateway_token(&args, computer)?;
let connection_type = read_arg_value(&args, 12)
.and_then(|mode| mode.ok_or_else(|| anyhow::anyhow!("Gateway login response has no connection type")));
Ok((cookie, connection_type))
}
#[cfg(test)]
fn parse_gateway_authentication(element: &Element, computer: &str) -> anyhow::Result<GatewayAuthentication> {
let (cookie, mode) = parse_issued_authentication(element, computer)?;
GatewayAuthentication::new(cookie, mode?)
}
fn build_gateway_token(args: &[Cow<'_, str>], computer: &str) -> anyhow::Result<String> {
let mut params = vec![
read_required_arg(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?,
@@ -198,11 +434,15 @@ fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
let value = decode(value)?;
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
anyhow::ensure!(
!value.chars().any(char::is_control),
"Gateway argument contains control characters"
);
Ok(Some(value.into_owned()))
}
fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -223,6 +463,268 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
mod tests {
use super::*;
fn tunnel_response() -> String {
let root = login_response(Some("tunnel"), "issued-cookie");
let mut xml = Vec::new();
root.write(&mut xml).unwrap();
crate::session::transport::tests::response(std::str::from_utf8(&xml).unwrap())
}
fn test_params() -> GpParams {
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
}
#[tokio::test]
async fn gateway_login_cancels_stalled_headers_and_body() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
for partial_response in ["", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<jnlp>"] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let (ready, received) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = [0; 4096];
assert!(socket.read(&mut buffer).await.unwrap() > 0);
socket.write_all(partial_response.as_bytes()).await.unwrap();
ready.send(()).unwrap();
released.await.unwrap();
});
let cancellation = CancellationToken::new();
let token = cancellation.clone();
let login = tokio::spawn(async move {
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
client.login(&credential, None, &token).await
});
received.await.unwrap();
cancellation.cancel();
let result = tokio::time::timeout(std::time::Duration::from_secs(1), login)
.await
.unwrap()
.unwrap();
assert!(result.err().unwrap().is::<crate::auth::AuthenticationCancelled>());
release.send(()).unwrap();
server.await.unwrap();
}
}
#[tokio::test]
async fn cancellation_during_cleanup_only_logout_awaits_cleanup() {
use crate::session::transport::tests::response;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let mut xml = Vec::new();
login_response(None, "issued-cookie").write(&mut xml).unwrap();
let login_response = response(std::str::from_utf8(&xml).unwrap());
let (ready, received) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = [0; 4096];
assert!(socket.read(&mut buffer).await.unwrap() > 0);
socket.write_all(login_response.as_bytes()).await.unwrap();
drop(socket);
let (mut socket, _) = listener.accept().await.unwrap();
let read = socket.read(&mut buffer).await.unwrap();
assert!(
std::str::from_utf8(&buffer[..read])
.unwrap()
.contains("/ssl-vpn/logout.esp")
);
ready.send(()).unwrap();
released.await.unwrap();
socket
.write_all(response("<response status='success'/>").as_bytes())
.await
.unwrap();
});
let cancellation = CancellationToken::new();
let token = cancellation.clone();
let mut login = tokio::spawn(async move {
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
client.login(&credential, None, &token).await
});
received.await.unwrap();
cancellation.cancel();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), &mut login)
.await
.is_err()
);
release.send(()).unwrap();
assert!(login.await.unwrap().err().unwrap().is::<GatewayLoginProtocolError>());
server.await.unwrap();
}
#[tokio::test]
async fn ordinary_tunnel_login_follows_redirects_without_physical_binding() {
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
tunnel_response(),
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
tunnel_response(),
]).await;
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(
matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel)
);
assert!(client.binding().is_none());
assert!(matches!(
client.extend_lifetime(&credential).await.unwrap(),
GatewayLogin::Authenticated(_)
));
let requests = server.await.unwrap();
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
assert_eq!(requests[1].0, "/redirected-login");
assert_eq!(requests[3].0, "/redirected-login");
assert!(requests[3].1.contains("extend-lifetime=true"));
}
#[tokio::test]
async fn ordinary_login_keeps_reqwest_address_fallback() {
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
let port = origin.port().unwrap();
let params = test_params();
let mut client = GatewayLoginClient::new(&format!("http://gateway.invalid:{port}"), params.clone()).unwrap();
// Supply deterministic DNS candidates; all other client behavior is the
// ordinary request path. The first address refuses, the second is reachable.
client.client = params
.client_builder()
.unwrap()
.no_proxy()
.resolve_to_addrs(
"gateway.invalid",
&[
SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
SocketAddr::from(([127, 0, 0, 1], port)),
],
)
.build()
.unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(matches!(
client
.login(&credential, None, &CancellationToken::new())
.await
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(server.await.unwrap().len(), 1);
}
#[tokio::test]
async fn ordinary_tunnel_login_can_use_a_proxy_without_local_gateway_resolution() {
let (_, proxy, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
let params = test_params();
let mut client = GatewayLoginClient::new("http://unresolvable.invalid", params.clone()).unwrap();
client.client = params
.client_builder()
.unwrap()
.proxy(reqwest::Proxy::all(proxy.as_str()).unwrap())
.build()
.unwrap();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
assert!(matches!(
client
.login(&credential, None, &CancellationToken::new())
.await
.unwrap(),
GatewayLogin::Authenticated(_)
));
assert!(client.binding().is_none());
assert_eq!(
server.await.unwrap()[0].0,
"http://unresolvable.invalid/ssl-vpn/login.esp"
);
}
#[tokio::test]
async fn invalid_mode_logs_out_issued_cookie_before_returning_protocol_error() {
use crate::session::transport::tests::{login_gateway, response};
let root = login_response(None, "issued-cookie");
let mut xml = Vec::new();
root.write(&mut xml).unwrap();
let (client, origin, server) = login_gateway(vec![
response(std::str::from_utf8(&xml).unwrap()),
response("<response status='success'/>"),
])
.await;
let params =
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let mut client = GatewayLoginClient {
client,
..GatewayLoginClient::new(origin.as_str(), params).unwrap()
};
let error = client
.login(&credential, None, &CancellationToken::new())
.await
.err()
.unwrap();
assert!(error.is::<GatewayLoginProtocolError>());
let requests = server.await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[1].1).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("issued-cookie"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
}
#[test]
fn cleanup_only_parsing_does_not_salvage_server_error_authentication() {
let mut root = login_response(None, "issued-cookie");
root.attributes.insert("status".into(), "error".into());
assert!(parse_issued_authentication(&root, "computer").is_err());
for encoded in ["%28null%29", "%2D1", "%00"] {
assert!(parse_issued_authentication(&login_response(Some("tunnel"), encoded), "computer").is_err());
}
}
fn login_response(mode: Option<&str>, cookie: &str) -> Element {
let mut args = vec![""; 19];
args[1] = cookie;
args[4] = "alice";
if let Some(mode) = mode {
args[12] = mode;
}
let arguments = args
.iter()
.map(|value| format!("<argument>{value}</argument>"))
.collect::<String>();
Element::parse(format!("<jnlp><application-desc>{arguments}</application-desc></jnlp>").as_bytes()).unwrap()
}
#[test]
fn login_mode_is_independent_of_network_location() {
for (value, mode) in [
("tunnel", crate::session::SessionMode::Tunnel),
("non-tunnel", crate::session::SessionMode::NonTunnel),
("internal", crate::session::SessionMode::NonTunnel),
] {
let authentication =
parse_gateway_authentication(&login_response(Some(value), "test-cookie"), "computer").unwrap();
assert_eq!(authentication.mode(), mode);
assert_eq!(authentication.connection_type(), value);
assert!(!format!("{authentication:?}").contains("test-cookie"));
}
}
#[test]
fn login_rejects_missing_mode_or_cookie() {
for mode in [None, Some(""), Some("(null)"), Some("-1"), Some(" ")] {
assert!(parse_gateway_authentication(&login_response(mode, "test-cookie"), "computer").is_err());
}
assert!(parse_gateway_authentication(&login_response(Some("tunnel"), ""), "computer").is_err());
let response = Element::parse(b"<response status='error'/>".as_slice()).unwrap();
assert!(parse_gateway_authentication(&response, "computer").is_err());
}
#[test]
fn mfa() {
let res = r#"var respStatus = "Challenge";
@@ -263,7 +765,9 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
let token = authentication.cookie();
assert_eq!(authentication.mode(), crate::session::SessionMode::Tunnel);
assert_eq!(
token,
@@ -300,7 +804,8 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
let token = authentication.cookie();
assert_eq!(
token,
+1 -1
View File
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
pub fn kind(&self) -> GatewayKind {
self.kind
}
+22 -29
View File
@@ -5,15 +5,13 @@ use std::{
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
gateway::login::{GatewayLogin, GatewayLoginClient},
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
utils::{parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
@@ -22,12 +20,18 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
client: GatewayLoginClient,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
Self { credential, client }
}
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
self.client.client_identity()
}
pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> {
self.client.binding()
}
}
@@ -35,7 +39,7 @@ impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.field("client", &"<redacted>")
.finish()
}
}
@@ -83,10 +87,15 @@ impl SessionContext {
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let client = auth.client.request_client();
let url = format!(
"{}/ssl-vpn/agentmessage.esp",
auth.client.origin().as_str().trim_end_matches('/')
);
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
@@ -108,33 +117,17 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
let login = auth.client.extend_lifetime(&auth.credential).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Authenticated(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = Client::builder();
if let Some(user_agent) = args.user_agent() {
builder = builder.user_agent(user_agent);
}
if let Some(cert) = args.certificate() {
info!("Using client certificate authentication...");
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
builder = builder.identity(identity);
}
Ok(builder.build()?)
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
+109 -14
View File
@@ -1,11 +1,12 @@
use log::info;
use reqwest::Client;
use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use specta::Type;
use zeroize::Zeroize;
use crate::{
os_profile::{ClientOs, HostIdentity, OsProfile},
utils::request::create_identity,
utils::request::{ClientIdentity, create_identity},
};
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
@@ -43,6 +44,7 @@ pub struct GpParams {
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
prepared_identity: Option<ClientIdentity>,
// Feature
csc_mode: CscMode,
// Per-request state
@@ -135,9 +137,49 @@ impl GpParams {
pub(crate) fn otp(&self) -> Option<&str> {
self.otp.as_deref()
}
pub fn prepare_client_identity(&mut self) -> anyhow::Result<()> {
if self.prepared_identity.is_none() {
if let Some(certificate) = self.certificate.as_deref() {
self.prepared_identity = Some(ClientIdentity::load(
certificate,
self.sslkey.as_deref(),
self.key_password.as_deref(),
)?);
}
}
self.certificate = None;
self.sslkey = None;
if let Some(mut passphrase) = self.key_password.take() {
passphrase.zeroize();
}
Ok(())
}
pub fn client_identity(&self) -> Option<&ClientIdentity> {
self.prepared_identity.as_ref()
}
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(self.ignore_tls_errors)
.user_agent(self.user_agent());
if let Some(identity) = &self.prepared_identity {
builder = builder.identity(identity.request_identity());
} else if let Some(cert) = self.certificate.as_deref() {
info!("Using client certificate authentication...");
builder = builder.identity(create_identity(
cert,
self.sslkey.as_deref(),
self.key_password.as_deref(),
)?);
}
Ok(builder)
}
}
pub struct GpParamsBuilder {
prepared_identity: Option<ClientIdentity>,
is_gateway: bool,
os_profile: OsProfile,
csc_mode: CscMode,
@@ -150,6 +192,7 @@ pub struct GpParamsBuilder {
impl GpParamsBuilder {
pub fn new(os_profile: OsProfile) -> Self {
Self {
prepared_identity: None,
is_gateway: false,
os_profile,
csc_mode: Default::default(),
@@ -176,22 +219,34 @@ impl GpParamsBuilder {
}
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
self.prepared_identity = None;
self.certificate = certificate.into();
self
}
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
self.prepared_identity = None;
self.sslkey = sslkey.into();
self
}
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut Self {
self.prepared_identity = None;
self.key_password = password.into();
self
}
pub fn client_identity(&mut self, identity: Option<ClientIdentity>) -> &mut Self {
self.prepared_identity = identity;
self.certificate = None;
self.sslkey = None;
self.key_password = None;
self
}
pub fn build(&self) -> GpParams {
GpParams {
prepared_identity: self.prepared_identity.clone(),
os_profile: self.os_profile.clone(),
ignore_tls_errors: self.ignore_tls_errors,
certificate: self.certificate.clone(),
@@ -209,24 +264,64 @@ impl TryFrom<&GpParams> for Client {
type Error = anyhow::Error;
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
let mut builder = Client::builder()
.danger_accept_invalid_certs(value.ignore_tls_errors)
.user_agent(value.user_agent());
if let Some(cert) = value.certificate.as_deref() {
info!("Using client certificate authentication...");
let identity = create_identity(cert, value.sslkey.as_deref(), value.key_password.as_deref())?;
builder = builder.identity(identity);
}
let client = builder.build()?;
Ok(client)
Ok(value.client_builder()?.build()?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_identity_settings_replace_a_prepared_snapshot() {
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
let setters: [fn(&mut GpParamsBuilder); 3] = [
|builder| {
builder.certificate(Some("missing-replacement-certificate.pem".into()));
},
|builder| {
builder.sslkey(Some("replacement-key.pem".into()));
},
|builder| {
builder.key_password(Some("replacement-password".into()));
},
];
for setter in setters {
let mut builder = GpParams::builder(profile(ClientOs::Linux));
builder.client_identity(Some(identity.clone()));
setter(&mut builder);
let params = builder.build();
assert!(
params.client_identity().is_none(),
"Path settings must not silently use the previous identity"
);
if params.certificate.is_some() {
assert!(
Client::try_from(&params).is_err(),
"The replacement certificate path must actually be loaded"
);
}
}
}
#[test]
fn prepared_identity_replaces_paths_and_can_be_explicitly_disabled() {
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
let mut builder = GpParams::builder(profile(ClientOs::Linux));
builder
.certificate(Some("missing-certificate.pem".into()))
.sslkey(Some("missing-key.pem".into()))
.key_password(Some("unused-password".into()))
.client_identity(Some(identity));
let params = builder.build();
assert!(params.client_identity().is_some());
assert!(params.certificate.is_none() && params.sslkey.is_none() && params.key_password.is_none());
assert!(Client::try_from(&params).is_ok());
builder.certificate(None);
let params = builder.build();
assert!(params.client_identity().is_none());
assert!(params.certificate.is_none());
}
use crate::os_profile::runtime_client_os;
fn profile(client_os: ClientOs) -> OsProfile {
+47
View File
@@ -0,0 +1,47 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// The GUI's choice of HIP report source. gpservice resolves execution details.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Type, PartialEq, Eq)]
#[serde(tag = "source", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum HipSource {
#[default]
Disabled,
Generated,
Edited {
report_id: String,
},
UserScript {
path: String,
},
ApprovedRootScript {
approval_id: String,
},
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Type, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum HipApprovalStatus {
Valid,
Revoked,
Corrupt,
OtherUser,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_round_trips_without_execution_uid_or_wrapper() {
let source = HipSource::ApprovedRootScript {
approval_id: "approved-1".into(),
};
let json = serde_json::to_value(&source).unwrap();
assert_eq!(
json,
serde_json::json!({ "source": "approvedRootScript", "approvalId": "approved-1" })
);
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
}
}
+3 -3
View File
@@ -1,9 +1,12 @@
pub mod auth;
pub mod cookie_store;
pub mod credential;
pub mod device_anchor;
pub mod error;
pub mod gateway;
pub mod gp_params;
pub mod hip;
pub mod log_format;
pub mod os_profile;
pub mod params;
pub mod portal;
@@ -17,6 +20,3 @@ pub mod logger;
#[cfg(feature = "clap")]
pub mod clap;
#[cfg(debug_assertions)]
pub const GP_API_KEY: &[u8; 32] = &[0; 32];
+164
View File
@@ -0,0 +1,164 @@
//! Machine-readable log output.
//!
//! The default human format is fine at a terminal, but tools that drive
//! gpclient headless have to parse it — and end up matching on prose, including
//! text that comes from dependencies rather than from this project. JSON lines
//! give those callers fields instead.
//!
//! This module deliberately depends only on `log` and `serde_json`, so every
//! binary can use it without pulling in a logging backend, and so the rendering
//! can be tested without installing a global logger.
use std::io::{self, Write};
use chrono::{SecondsFormat, Utc};
use serde_json::json;
/// How log records are rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum LogFormat {
/// The human-readable default.
#[default]
Text,
/// One JSON object per line.
Json,
}
impl LogFormat {
/// The name this format is known by on a command line.
pub fn as_str(&self) -> &'static str {
match self {
Self::Text => "text",
Self::Json => "json",
}
}
}
/// Write a [`log::Record`] to `w` as one JSON line, newline included.
///
/// This is the form a logging backend needs, and it writes into the buffer the
/// backend already handed us rather than allocating a line to be copied. It
/// takes a `Record` and a `Write` rather than any backend's own types, so `log`
/// stays the only logging dependency here — with `env_logger`, this function
/// *is* the format callback:
///
/// ```ignore
/// // Not compiled as a doctest: env_logger is an optional dependency of this
/// // crate, so it is not linked when the docs are built.
/// env_logger::builder().format(write_json_record).init();
/// ```
pub fn write_json_record<W: Write>(w: &mut W, record: &log::Record) -> io::Result<()> {
writeln!(
w,
"{}",
json!({
"timestamp": Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
"level": record.level().as_str(),
"target": record.target(),
"message": record.args().to_string(),
})
)
}
#[cfg(test)]
mod tests {
use chrono::{DateTime, SubsecRound};
use log::Level;
use super::*;
fn parse(line: &str) -> serde_json::Value {
serde_json::from_str(line).expect("each line must be valid JSON")
}
fn write_record(record: &log::Record) -> String {
let mut buf = Vec::new();
write_json_record(&mut buf, record).expect("writing to a Vec cannot fail");
String::from_utf8(buf).expect("output should be UTF-8")
}
/// The fields a consumer is promised, taken off a `Record` as a backend
/// hands it over.
#[test]
fn record_renders_the_expected_fields() {
// Built inline: `format_args!` borrows its arguments for the statement it
// appears in, so a `Record` held in a `let` would outlive them.
let v = parse(&write_record(
&log::Record::builder()
.level(Level::Error)
.target("gpclient::connect")
.args(format_args!("portal {} unreachable", "vpn.example.com"))
.build(),
));
assert_eq!(v["level"], "ERROR");
assert_eq!(v["target"], "gpclient::connect");
assert_eq!(v["message"], "portal vpn.example.com unreachable");
}
/// Without a timestamp the JSON output would be strictly less informative
/// than the text format it replaces, and a consumer could not order or
/// correlate events.
#[test]
fn records_carry_a_utc_timestamp() {
let before = Utc::now();
let v = parse(&write_record(
&log::Record::builder()
.level(Level::Info)
.target("t")
.args(format_args!("connected"))
.build(),
));
let after = Utc::now();
let ts = v["timestamp"].as_str().expect("timestamp must be a string");
let parsed = DateTime::parse_from_rfc3339(ts)
.unwrap_or_else(|e| panic!("timestamp must be RFC 3339: {ts:?} ({e})"))
.with_timezone(&Utc);
assert!(ts.ends_with('Z'), "timestamp must be UTC, got {ts:?}");
assert!(
parsed >= before.trunc_subsecs(3) && parsed <= after,
"timestamp {parsed} should be between {before} and {after}"
);
}
/// The backend appends records to one stream, so each has to terminate its
/// own line — exactly one, or the next record joins this one. A message
/// containing a newline must be escaped into the JSON string rather than
/// splitting the record in two.
#[test]
fn record_ends_with_a_single_newline() {
let out = write_record(
&log::Record::builder()
.level(Level::Info)
.target("t")
.args(format_args!("first\nsecond"))
.build(),
);
assert!(out.ends_with('\n'), "record must terminate its line: {out:?}");
assert_eq!(out.matches('\n').count(), 1, "record must be one line: {out:?}");
assert_eq!(parse(&out)["message"], "first\nsecond", "the newline must survive");
}
/// `as_str` is what gets passed to a child process on the command line, and
/// clap parses that with the names from its own `ValueEnum` derive. If the
/// two ever disagree, gpclient hands gpauth a value gpauth rejects.
#[cfg(feature = "clap")]
#[test]
fn as_str_agrees_with_the_names_clap_parses() {
use clap::ValueEnum;
for format in [LogFormat::Text, LogFormat::Json] {
let clap_name = format
.to_possible_value()
.expect("every variant is selectable")
.get_name()
.to_owned();
assert_eq!(format.as_str(), clap_name);
}
}
}
+132 -11
View File
@@ -1,21 +1,44 @@
use std::sync::OnceLock;
use anyhow::bail;
use env_logger::Logger;
use log::{Level, warn};
use log::{Level, Log, warn};
use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
use crate::log_format::{LogFormat, write_json_record};
pub fn init(level: Level) {
// Initialize the env_logger and global max level to trace, the logs will be
// filtered by the outer logger
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
init_with_logger(level, logger);
pub const LOG_BACKEND_ENV: &str = "GP_LOG_BACKEND";
pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
type BoxedLogger = Box<dyn Log + Send + Sync>;
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
#[cfg(target_os = "macos")]
if log_format == LogFormat::Text && macos_unified_log_enabled() {
init_with_logger(level, MacosLogger::new(subsystem, category));
return;
}
#[cfg(not(target_os = "macos"))]
let _ = (subsystem, category);
init_with_logger(level, build_env_logger(log_format).build());
}
pub fn init_with_logger(level: Level, logger: Logger) {
if let Some(_) = LOG_HANDLE.get() {
fn build_env_logger(log_format: LogFormat) -> env_logger::Builder {
let mut builder = env_logger::builder();
// The outer reloadable logger owns filtering.
builder.filter_level(log::LevelFilter::Trace);
if log_format == LogFormat::Json {
builder.format(write_json_record);
}
builder
}
pub fn init_with_logger(level: Level, logger: impl Log + Send + Sync + 'static) {
if LOG_HANDLE.get().is_some() {
warn!("Logger already initialized");
return;
}
@@ -23,7 +46,7 @@ pub fn init_with_logger(level: Level, logger: Logger) {
log::set_max_level(log::LevelFilter::Trace);
// Create a new logger that will filter the logs based on the max level
let level_filter_logger = log_reload::LevelFilter::new(level, logger);
let level_filter_logger = log_reload::LevelFilter::new(level, Box::new(logger) as BoxedLogger);
let reload_log = ReloadLog::new(level_filter_logger);
let handle = reload_log.handle();
@@ -42,3 +65,101 @@ pub fn set_max_level(level: Level) -> anyhow::Result<()> {
.modify(|logger| logger.set_level(level))
.map_err(|e| anyhow::anyhow!(e))
}
pub fn macos_unified_log_enabled() -> bool {
cfg!(target_os = "macos") && std::env::var(LOG_BACKEND_ENV).as_deref() == Ok(MACOS_UNIFIED_LOG_BACKEND)
}
#[cfg(target_os = "macos")]
pub struct MacosLogger {
inner: oslog::OsLog,
}
#[cfg(target_os = "macos")]
impl MacosLogger {
pub fn new(subsystem: &str, category: &str) -> Self {
Self {
inner: oslog::OsLog::new(subsystem, category),
}
}
pub fn write(&self, level: Level, target: &str, message: &str) {
self
.inner
.with_level(macos_log_level(level), &format!("[{target}] {message}"));
}
}
#[cfg(target_os = "macos")]
impl Log for MacosLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
self.inner.level_is_enabled(macos_log_level(metadata.level()))
}
fn log(&self, record: &log::Record<'_>) {
if self.enabled(record.metadata()) {
self.write(record.level(), record.target(), &record.args().to_string());
}
}
fn flush(&self) {}
}
#[cfg(target_os = "macos")]
fn macos_log_level(level: Level) -> oslog::Level {
match level {
Level::Trace | Level::Debug => oslog::Level::Debug,
Level::Info => oslog::Level::Default,
Level::Warn | Level::Error => oslog::Level::Error,
}
}
#[cfg(test)]
mod tests {
use std::{
io::Write,
sync::{Arc, Mutex},
};
use super::*;
#[derive(Clone, Default)]
struct Captured(Arc<Mutex<Vec<u8>>>);
impl Write for Captured {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn json_format_configures_the_env_logger() {
let captured = Captured::default();
let logger = build_env_logger(LogFormat::Json)
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
.build();
logger.log(
&log::Record::builder()
.level(Level::Info)
.target("gpauth")
.args(format_args!("authenticating"))
.build(),
);
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
let value: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(value["message"], "authenticating");
}
#[test]
#[cfg(target_os = "macos")]
fn info_logs_use_the_persistent_macos_level() {
assert_eq!(macos_log_level(Level::Info) as u8, oslog::Level::Default as u8);
}
}
+153 -64
View File
@@ -1,3 +1,6 @@
use std::{io, time::Duration};
use crate::process::collection::{CollectionBudget, CollectionControl};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -20,8 +23,39 @@ impl HostIdentity {
Self::collect_with_host_id(None)
}
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
Self::collect_with_host_id_and_control(None, control)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
Self::default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
Self::from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(crate) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<Self> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
#[cfg(test)]
@@ -29,7 +63,8 @@ impl HostIdentity {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
/// Construct a host identity from an already collected or negotiated snapshot.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
@@ -163,12 +198,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
#[cfg(target_os = "macos")]
mod platform {
use std::process::Command;
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
use crate::process::collection::{CollectionControl, CollectorCommands};
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
@@ -177,74 +212,80 @@ mod platform {
ClientOs::Mac
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
NativeHostIdentitySnapshot {
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
serial_number: collect_macos_serial_number(),
computer,
serial_number,
mac_address: native_mac,
}
})
}
}
fn macos_computer_name() -> Option<String> {
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
if !output.status.success() {
return None;
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
String::from_utf8(output.stdout)
.ok()
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
}
fn macos_builtin_mac() -> Option<String> {
macos_networksetup_mac("Wi-Fi")
.or_else(|| macos_networksetup_mac("AirPort"))
.or_else(macos_system_profiler_wifi_mac)
}
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
let output = Command::new("networksetup")
.arg("-listallhardwareports")
.output()
.ok()?;
if !output.status.success() {
return None;
{
return Ok(Some(value));
}
}
Ok(None)
}
let stdout = String::from_utf8(output.stdout).ok()?;
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == port_name;
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac() -> Option<String> {
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
@@ -252,29 +293,24 @@ mod platform {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return normalize_mac_colon(mac);
return Ok(normalize_mac_colon(mac));
}
}
None
Ok(None)
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}))
}
}
@@ -291,7 +327,17 @@ mod platform {
ClientOs::Windows
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
@@ -362,6 +408,7 @@ mod platform {
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
serial_number,
};
use log::debug;
@@ -372,7 +419,17 @@ mod platform {
ClientOs::Linux
}
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
@@ -429,9 +486,17 @@ mod platform {
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.iter()
.find_map(|path| read_linux_identity_file(path))
resolve_linux_serial_number(
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
collect_linux_product_uuid,
)
}
fn resolve_linux_serial_number(
product_serial: Option<String>,
product_uuid: impl FnOnce() -> Option<String>,
) -> Option<String> {
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
}
#[cfg(test)]
@@ -446,6 +511,20 @@ mod platform {
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
#[test]
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
assert_eq!(
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
Some("product-serial".to_string())
);
assert_eq!(
resolve_linux_serial_number(None, || uuid),
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
);
}
}
}
@@ -453,6 +532,15 @@ mod platform {
mod tests {
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = HostIdentity::collect_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
@@ -505,7 +593,8 @@ mod tests {
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native = RuntimeNativeHostIdentity::collect(None);
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
+114 -21
View File
@@ -3,6 +3,9 @@ mod serial_number;
pub use host_identity::HostIdentity;
use crate::process::collection::{CollectionBudget, CollectionControl};
use std::{io, time::Duration};
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -366,6 +369,7 @@ impl OsProfile {
pub struct OsProfileBuilder {
client_os: ClientOs,
client_version: Option<String>,
os_version_override: Option<String>,
computer_name_override: Option<String>,
host_id_override: Option<String>,
host_identity: Option<HostIdentity>,
@@ -377,6 +381,7 @@ impl OsProfileBuilder {
Self {
client_os,
client_version: None,
os_version_override: None,
computer_name_override: None,
host_id_override: None,
host_identity: None,
@@ -394,6 +399,13 @@ impl OsProfileBuilder {
self
}
/// Preserve an explicitly negotiated operating system version.
pub fn os_version(mut self, version: impl Into<String>) -> Self {
let version = version.into();
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
self
}
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
self.host_identity = Some(identity);
self
@@ -411,31 +423,67 @@ impl OsProfileBuilder {
self
}
/// Build a best-effort profile with a bounded native collection budget.
/// Use `build_with_control` when interruption or timeout must be reported.
pub fn build(self) -> OsProfile {
match self
.clone()
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
{
Ok(profile) => profile,
Err(error) => {
log::warn!("OS profile collection was unavailable: {error}");
let identity = self
.host_identity
.clone()
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
let (os_version, software_version) = match self.client_os {
ClientOs::Mac => (
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
DEFAULT_MACOS_VERSION.into(),
),
os => (target::os_version(os), target::software_version(os)),
};
self.finish(identity, os_version, software_version)
}
}
}
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
control.check()?;
let host_identity = match (&self.host_identity, &self.host_id_override) {
(Some(identity), _) => identity.clone(),
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
};
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
let version = macos_version_with_control(control)?;
(format!("Apple Mac OS X {version}"), version)
} else {
(
target::os_version(self.client_os),
target::software_version(self.client_os),
)
};
control.check()?;
Ok(self.finish(host_identity, os_version, software_version))
}
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
let client_version = self
.client_version
.filter(|v| !v.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
let host_identity = match (self.host_identity, self.host_id_override) {
(Some(identity), _) => identity,
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
};
.filter(|version| !version.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().into());
let profile_identity =
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
let os_version = target::os_version(self.client_os);
let software_version = target::software_version(self.client_os);
let os_vendor = target::os_vendor(self.client_os);
let os_version = self.os_version_override.unwrap_or(default_os_version);
let user_agent = self
.user_agent
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
OsProfile {
client_os: self.client_os,
os_version,
software_version,
os_vendor,
os_vendor: target::os_vendor(self.client_os),
client_version,
host_identity,
profile_identity,
@@ -500,14 +548,28 @@ fn runtime_distro_or(fallback: &str) -> String {
}
fn macos_version() -> String {
if runtime_client_os() == ClientOs::Mac {
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
v => v.to_string(),
}
} else {
DEFAULT_MACOS_VERSION.to_string()
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
log::warn!("Operating system version collection was unavailable: {error}");
DEFAULT_MACOS_VERSION.into()
})
}
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
control.check()?;
#[cfg(target_os = "macos")]
{
let commands = crate::process::collection::CollectorCommands::new(control);
let version = commands
.run("sw_vers", &["-productVersion"])?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|version| version.trim().to_string())
.filter(|version| !version.is_empty());
control.check()?;
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
}
#[cfg(not(target_os = "macos"))]
Ok(DEFAULT_MACOS_VERSION.into())
}
fn macos_os_string() -> String {
@@ -691,6 +753,37 @@ mod target_identity {
mod tests {
use super::*;
#[test]
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = OsProfileBuilder::new(ClientOs::Mac)
.build_with_control(&cancelled)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let expired = CollectionBudget::new(Duration::ZERO);
let error = OsProfileBuilder::new(ClientOs::Linux)
.build_with_control(&expired)
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
#[test]
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
let identity = HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.client_version("6.3.3")
.os_version("negotiated-system-version")
.build();
assert_eq!(profile.os_version(), "negotiated-system-version");
assert!(profile.user_agent().contains("negotiated-system-version"));
}
#[test]
fn csc_support_defaults_match_official_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
+180 -56
View File
@@ -1,11 +1,11 @@
use std::collections::HashMap;
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
use tokio_util::sync::CancellationToken;
use xmltree::Element;
use crate::{
@@ -14,6 +14,7 @@ use crate::{
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
params,
session::{InternalSessionPolicy, network::InternalHostDetection},
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
};
@@ -35,6 +36,7 @@ pub struct PortalConfig {
* - Some(true): Internal host detection is supported and the user is connected to the internal network
*/
internal_host_detection: Option<bool>,
internal_detection: Option<InternalHostDetection>,
/**
* The version returned by the portal config, if any
*/
@@ -47,6 +49,7 @@ pub struct PortalConfig {
* Whether the portal policy enables default-browser authentication.
*/
default_browser: Option<bool>,
internal_session_policy: Option<InternalSessionPolicy>,
}
impl PortalConfig {
@@ -70,6 +73,10 @@ impl PortalConfig {
self.internal_host_detection
}
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
self.internal_detection.as_ref()
}
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
@@ -86,6 +93,10 @@ impl PortalConfig {
self.default_browser
}
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
self.internal_session_policy
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -129,7 +140,14 @@ impl PortalConfig {
}
}
pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<PortalConfig> {
/// Cancellation is handled inside the request so a running native detection
/// helper is always cancelled and joined. Do not drop this future on disconnect.
pub async fn retrieve_config(
portal: &str,
cred: &Credential,
gp_params: &GpParams,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let portal = normalize_server(portal)?;
let server = remove_url_scheme(&portal);
@@ -146,29 +164,35 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_form_params(&body_pairs));
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = tokio::select! {
biased;
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = async {
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal config error: {}", err.reason);
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})?;
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
} => result?,
};
if res_xml.is_empty() {
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response: {}", res_xml);
debug!("Portal config response received: {} bytes", res_xml.len());
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
@@ -178,14 +202,18 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
"Portal returned CSC criteria but CSC support is disabled".to_string()
));
}
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let csc_xml = tokio::select! {
biased;
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
};
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
return parse_portal_config(&server, cred, root, cancellation).await;
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
parse_portal_config(&server, cred, root, cancellation).await
}
async fn retrieve_csc_config(
@@ -245,12 +273,31 @@ fn present(value: Option<&str>) -> &'static str {
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false;
let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(ihd_node)
async fn parse_portal_config(
server: &str,
cred: &Credential,
root: Element,
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let internal_detection = root
.descendant("internal-host-detection")
.map(parse_internal_detection)
.transpose()
.unwrap_or_else(|error| {
warn!("Internal host detection policy is unavailable: {error}");
None
})
.flatten();
let prefer_internal = match &internal_detection {
Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| {
warn!("Internal host detection failed: {error}");
false
}),
None => false,
};
if cancellation.is_cancelled() {
bail!("Portal configuration cancelled");
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -275,6 +322,7 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
let default_browser = parse_default_browser(&root);
let internal_session_policy = parse_internal_session_policy(&root).ok();
Ok(PortalConfig {
portal: server.to_string(),
@@ -283,13 +331,42 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
internal_detection,
version,
allow_extend_session,
default_browser,
internal_session_policy,
})
}
fn parse_internal_session_policy(root: &Element) -> anyhow::Result<InternalSessionPolicy> {
let hip = root.descendant("hip-collection");
let interval = hip
.and_then(|hip| hip.child("hip-report-interval"))
.map(|element| element.get_text().unwrap_or_default().into_owned());
let collect = hip
.and_then(|hip| hip.child("collect-hip-data"))
.map(|element| element.get_text().unwrap_or_default().into_owned());
let interval = parse_policy_number(interval, 3600, "hip-report-interval")?;
let collect = match collect.as_deref().map(str::trim) {
None | Some("yes") => true,
Some("no") => false,
Some(_) => bail!("Invalid portal collect-hip-data policy"),
};
InternalSessionPolicy::new(interval, collect)
}
fn parse_policy_number(value: Option<String>, default: u32, field: &str) -> anyhow::Result<u32> {
match value {
Some(value) => value
.trim()
.parse()
.map_err(|_| anyhow::anyhow!("Invalid portal {field} policy")),
None => Ok(default),
}
}
fn parse_default_browser(root: &Element) -> Option<bool> {
match root.descendant_text("default-browser")?.trim() {
"yes" => Some(true),
@@ -313,49 +390,94 @@ fn parse_connect_method(root: &Element) -> Option<String> {
.map(|s| s.to_string())
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool {
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
let ip_info = [
(element.child_text("ip-address"), element.child_text("host")),
(element.child_text("ipv6-address"), element.child_text("ipv6-host")),
];
info!("Found internal-host-detection, performing DNS lookup");
let mut targets = Vec::new();
for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
&& !ip_address.is_empty()
&& !host.is_empty()
{
match ip_address.parse::<std::net::IpAddr>() {
Ok(ip) => match lookup_addr(&ip) {
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
return true;
}
Ok(host_lookup) => {
info!(
"rDNS lookup for {} returned {}, expected {}",
ip_address, host_lookup, host
);
}
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
},
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}
let address = ip_address.as_deref().filter(|value| !value.is_empty());
let host = host.as_deref().filter(|value| !value.is_empty());
match (address, host) {
(None, None) => {}
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
_ => bail!("Incomplete internal host detection policy"),
}
}
false
if targets.is_empty() {
Ok(None)
} else {
Ok(Some(InternalHostDetection::new(targets)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() {
let root = parse_xml(
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
);
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new())
.await
.unwrap();
assert!(config.internal_session_policy().is_none());
assert_eq!(config.gateways()[0].server(), "vpn.example");
assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External);
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn parses_internal_maintenance_policy_with_explicit_units() {
let root = parse_xml(
"<policy><hip-collection><hip-report-interval>60</hip-report-interval><collect-hip-data>no</collect-hip-data></hip-collection><max-internal-gateway-connection-attempts>3</max-internal-gateway-connection-attempts></policy>",
);
let policy = parse_internal_session_policy(&root).unwrap();
assert_eq!(policy.hip_interval(), std::time::Duration::from_secs(60));
assert!(!policy.collect_hip_data());
assert_eq!(
parse_internal_session_policy(&parse_xml("<policy/>")).unwrap(),
InternalSessionPolicy::default()
);
}
#[test]
fn rejects_invalid_supplied_internal_policy() {
for interval in ["0", "-1", "", "4294967295", "not-a-number"] {
let root = parse_xml(&format!(
"<policy><hip-collection><hip-report-interval>{interval}</hip-report-interval></hip-collection></policy>"
));
assert!(parse_internal_session_policy(&root).is_err());
}
let root = parse_xml("<policy><hip-collection><collect-hip-data>true</collect-hip-data></hip-collection></policy>");
assert!(parse_internal_session_policy(&root).is_err());
}
#[tokio::test]
async fn accepts_existing_full_portal_fixture() {
let root = parse_xml(include_str!("../../tests/files/portal_config.xml"));
let cred = Credential::from(crate::credential::PasswordCredential::new(
"fixture-user",
"fixture-password",
));
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
assert_eq!(
config.internal_session_policy().unwrap().hip_interval(),
std::time::Duration::from_secs(3600)
);
assert!(!config.gateways().is_empty());
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
@@ -412,8 +534,8 @@ mod tests {
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
#[tokio::test]
async fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
@@ -431,7 +553,9 @@ mod tests {
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
.await
.unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
+155 -18
View File
@@ -1,14 +1,23 @@
use std::{path::PathBuf, process::Stdio};
use std::{
net::IpAddr,
path::{Path, PathBuf},
};
use anyhow::bail;
use common::binary_paths;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
#[cfg(feature = "webview-auth")]
use crate::auth::AuthWindowTheme;
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
use super::command_traits::CommandExt;
use super::{command_runner::run_controlled, command_traits::CommandExt};
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
pub struct SamlAuthLauncher<'a> {
cancellation: CancellationToken,
server: &'a str,
auth_executable: Option<&'a str>,
gateway: bool,
@@ -27,13 +36,20 @@ pub struct SamlAuthLauncher<'a> {
clean: bool,
#[cfg(feature = "webview-auth")]
default_browser: bool,
#[cfg(feature = "webview-auth")]
window_title: Option<&'a str>,
#[cfg(feature = "webview-auth")]
window_theme: Option<AuthWindowTheme>,
browser: Option<&'a str>,
browser_listen: Option<IpAddr>,
verbose: Option<&'a str>,
log_format: LogFormat,
}
impl<'a> SamlAuthLauncher<'a> {
pub fn new(server: &'a str) -> Self {
Self {
cancellation: CancellationToken::new(),
server,
auth_executable: None,
gateway: false,
@@ -52,8 +68,14 @@ impl<'a> SamlAuthLauncher<'a> {
clean: false,
#[cfg(feature = "webview-auth")]
default_browser: false,
#[cfg(feature = "webview-auth")]
window_title: None,
#[cfg(feature = "webview-auth")]
window_theme: None,
browser: None,
browser_listen: None,
verbose: None,
log_format: LogFormat::Text,
}
}
@@ -122,23 +144,54 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
#[cfg(feature = "webview-auth")]
pub fn window_title(mut self, window_title: &'a str) -> Self {
self.window_title = Some(window_title);
self
}
#[cfg(feature = "webview-auth")]
pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
self.window_theme = Some(window_theme);
self
}
pub fn browser(mut self, browser: Option<&'a str>) -> Self {
self.browser = browser;
self
}
pub fn browser_listen(mut self, browser_listen: Option<IpAddr>) -> Self {
self.browser_listen = browser_listen;
self
}
/// Render the child's logs the same way as ours.
///
/// gpauth inherits this process's stderr, so both processes must use the same
/// format to keep the stream consistent.
pub fn log_format(mut self, log_format: LogFormat) -> Self {
self.log_format = log_format;
self
}
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
self.verbose = verbose;
self
}
/// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> {
let program = self
.auth_executable
.map(PathBuf::from)
.unwrap_or_else(binary_paths::gpauth);
let mut auth_cmd = Command::new(&program);
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
self.cancellation = cancellation.clone();
self
}
/// The command line this launcher will run.
///
/// Split out from `launch` so a test can observe the argv the child actually
/// receives: asserting on the builder's own fields would not catch an
/// argument that never gets appended.
fn build_command(&self, program: &Path) -> Command {
let mut auth_cmd = Command::new(program);
auth_cmd.arg(self.server);
if self.gateway {
@@ -194,28 +247,65 @@ impl<'a> SamlAuthLauncher<'a> {
if self.default_browser {
auth_cmd.arg("--default-browser");
}
if let Some(window_title) = self.window_title {
auth_cmd.arg("--window-title").arg(window_title);
}
if let Some(window_theme) = self.window_theme {
auth_cmd.arg("--window-theme").arg(window_theme.as_str());
}
}
if let Some(browser) = self.browser {
auth_cmd.arg("--browser").arg(browser);
}
if let Some(browser_listen) = self.browser_listen {
auth_cmd.arg("--browser-listen").arg(browser_listen.to_string());
}
auth_cmd.arg("--log-format").arg(self.log_format.as_str());
if let Some(verbose) = self.verbose {
auth_cmd.arg(verbose);
}
let mut non_root_cmd = auth_cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
auth_cmd
}
let child = match child {
Ok(child) => child,
Err(err) => {
bail!("Failed to spawn {}: {}", program.display(), err);
/// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> {
let program = self
.auth_executable
.map(PathBuf::from)
.unwrap_or_else(binary_paths::gpauth);
let auth_cmd = self.build_command(&program);
let command = auth_cmd.into_non_root()?.into_std();
let cancellation = self.cancellation;
let output = tokio::task::spawn_blocking(move || {
let check = || {
if cancellation.is_cancelled() {
Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"Authentication cancelled",
))
} else {
Ok(())
}
};
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
})
.await?;
let output = match output {
Ok(output) => output,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
return Err(crate::auth::AuthenticationCancelled.into());
}
Err(error) => return Err(error.into()),
};
let output = child.wait_with_output().await?;
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data")
};
@@ -256,6 +346,45 @@ mod tests {
assert_eq!(launcher.client_version, Some("6.0.0"));
}
fn child_args(launcher: SamlAuthLauncher) -> Vec<String> {
launcher
.build_command(Path::new("gpauth"))
.as_std()
.get_args()
.map(|arg| arg.to_string_lossy().into_owned())
.collect()
}
/// gpauth writes to the same stderr as its parent, so a caller reading the
/// parent's JSON would hit gpauth's text records mid-stream unless the format
/// is passed down.
#[test]
fn json_is_forwarded_to_the_child() {
let args = child_args(SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Json));
assert!(
args.windows(2).any(|pair| pair == ["--log-format", "json"]),
"expected --log-format json in {args:?}"
);
}
/// The launcher always passes the selected format so the parent and child
/// cannot silently drift onto different output formats.
#[test]
fn text_is_forwarded_to_the_child() {
for launcher in [
SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Text),
SamlAuthLauncher::new("portal.example.com"),
] {
let args = child_args(launcher);
assert!(
args.windows(2).any(|pair| pair == ["--log-format", "text"]),
"expected --log-format text in {args:?}"
);
}
}
#[test]
fn client_certificate_options_are_stored() {
let launcher = SamlAuthLauncher::new("portal.example.com")
@@ -267,4 +396,12 @@ mod tests {
assert_eq!(launcher.sslkey, Some("/tmp/client.key"));
assert_eq!(launcher.key_password, Some("secret"));
}
#[test]
fn browser_listen_address_is_stored() {
let listen_ip = "192.168.107.15".parse().unwrap();
let launcher = SamlAuthLauncher::new("portal.example.com").browser_listen(Some(listen_ip));
assert_eq!(launcher.browser_listen, Some(listen_ip));
}
}
+315
View File
@@ -0,0 +1,315 @@
use std::{
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
time::{Duration, Instant},
};
use super::command_runner::run_controlled;
/// Invocation control borrowed by collection; interruption must never be treated
/// as an unavailable optional product.
pub trait CollectionControl {
fn check(&self) -> io::Result<()>;
}
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
fn check(&self) -> io::Result<()> {
self()
}
}
pub struct CollectionBudget {
deadline: Instant,
}
impl CollectionBudget {
pub fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
}
impl CollectionControl for CollectionBudget {
fn check(&self) -> io::Result<()> {
if Instant::now() >= self.deadline {
Err(io::Error::new(
io::ErrorKind::TimedOut,
"Device information collection timed out",
))
} else {
Ok(())
}
}
}
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
const TOOL_DIRECTORIES: &[&str] = &[
"/usr/bin",
"/usr/sbin",
"/bin",
"/sbin",
"/usr/local/bin",
"/usr/local/sbin",
#[cfg(target_os = "linux")]
"/run/current-system/sw/bin",
];
fn tool_directories() -> Vec<PathBuf> {
let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default();
let mut directories: Vec<_> = std::env::split_paths(&configured)
.filter(|path| path.is_absolute())
.collect();
directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from));
directories
}
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let Some(path) = self.resolve(name) else {
return Ok(None);
};
self.run_path(&path, args)
}
/// Run an installed helper with the same trust checks as system collectors.
/// Root only executes helpers protected from unprivileged modification.
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
return Ok(None);
};
self.run_path(&path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let home = if uzers::get_effective_uid() == 0 {
if cfg!(target_os = "macos") {
"/var/root"
} else {
"/root"
}
} else {
"/"
};
let mut command = Command::new(path);
command
.args(args)
.env_clear()
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
.env("LC_ALL", "C")
.env("HOME", home)
.current_dir("/")
.stderr(Stdio::null());
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
directories.iter().find_map(|directory| {
let directory = fs::canonicalize(directory).ok()?;
if require_root && !root_owned_path(&directory) {
return None;
}
resolve_executable(&directory.join(name), require_root)
})
}
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
let resolved = fs::canonicalize(path).ok()?;
let metadata = fs::metadata(&resolved).ok()?;
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
Some(resolved)
} else {
None
}
}
/// Known command directories, canonicalized and restricted to trusted root
/// ownership when used for privileged execution.
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
let configured = tool_directories();
let directories = configured.iter().filter_map(|directory| {
let resolved = fs::canonicalize(directory).ok()?;
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
Some(resolved)
} else {
None
}
});
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
}
fn root_owned_path(path: &Path) -> bool {
path.ancestors().all(|part| {
fs::symlink_metadata(part).is_ok_and(|metadata| {
let mode = metadata.permissions().mode();
let writable = mode & 0o022 != 0;
// A root-owned sticky directory protects each root-owned descendant
// from replacement, including entries in the Nix store.
let protected_ancestor = part != path && metadata.is_dir() && mode & 0o1000 != 0;
metadata.uid() == 0 && (!writable || protected_ancestor) && !metadata.file_type().is_symlink()
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
if uzers::get_effective_uid() != 0 {
return;
}
let directory = tempfile::tempdir().unwrap();
let tool = directory.path().join("collector");
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1775)).unwrap();
assert_eq!(resolve_executable(&tool, true), Some(fs::canonicalize(&tool).unwrap()));
// A PATH directory must itself reject unprivileged additions, even with the sticky bit.
assert!(!root_owned_path(directory.path()));
assert!(resolve_in_directories("collector", &[directory.path().to_owned()], true).is_none());
let bin = directory.path().join("bin");
fs::create_dir(&bin).unwrap();
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
fs::copy(&tool, bin.join("collector")).unwrap();
assert!(resolve_in_directories("collector", &[bin], true).is_some());
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o775)).unwrap();
assert!(resolve_executable(&tool, true).is_none());
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1777)).unwrap();
assert!(resolve_executable(&tool, true).is_some());
fs::set_permissions(&tool, fs::Permissions::from_mode(0o1775)).unwrap();
assert!(resolve_executable(&tool, true).is_none());
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
std::os::unix::fs::chown(&tool, Some(1), None).unwrap();
assert!(resolve_executable(&tool, true).is_none());
std::os::unix::fs::chown(&tool, Some(0), None).unwrap();
std::os::unix::fs::chown(directory.path(), Some(1), None).unwrap();
assert!(resolve_executable(&tool, true).is_none());
}
#[test]
fn configured_directories_resolve_tools_without_using_the_process_path() {
let dir = tempfile::tempdir().unwrap();
let tool = dir.path().join("configured-tool");
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(
resolve_in_directories("configured-tool", &[dir.path().to_owned()], false),
Some(fs::canonicalize(&tool).unwrap())
);
fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap();
assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none());
}
#[test]
fn root_command_path_contains_only_trusted_canonical_directories() {
let path = command_path(true).unwrap();
let directories: Vec<_> = std::env::split_paths(&path).collect();
assert!(!directories.is_empty());
for directory in directories {
assert!(directory.is_dir());
assert!(root_owned_path(&directory));
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
}
}
#[test]
fn executable_resolution_returns_target_not_mutable_symlink() {
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("tool");
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
let resolved = resolve_executable(&link, false).unwrap();
fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
}
#[test]
fn cancellation_stops_running_collector() {
let started = Instant::now();
let control = || {
if started.elapsed() >= Duration::from_millis(100) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
let error = CollectorCommands::new(&control)
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn collector_has_private_environment_and_cwd() {
let budget = CollectionBudget::new(Duration::from_secs(2));
let output = CollectorCommands::new(&budget)
.run_path(
Path::new("/bin/sh"),
&[
"-c",
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
],
)
.unwrap()
.unwrap();
assert!(output.status.success());
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
}
#[test]
fn deadline_stops_collector_instead_of_hanging() {
let budget = CollectionBudget::new(Duration::from_millis(100));
let started = Instant::now();
let error = CollectorCommands::new(&budget)
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn collector_output_is_bounded() {
let budget = CollectionBudget::new(Duration::from_secs(2));
let error = CollectorCommands::new(&budget)
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn cancellation_is_not_an_optional_missing_product() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
}
@@ -0,0 +1,84 @@
use std::{
io::{self, Read},
os::unix::process::CommandExt,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
use super::collection::CollectionControl;
/// Execute an already configured command. Environment, identity and executable
/// trust belong to its caller. This worker owns the process group until reaped;
/// its asynchronous caller must cancel and await it instead of dropping it.
pub(crate) fn run_controlled(
mut command: Command,
control: &dyn CollectionControl,
output_limit: usize,
) -> io::Result<Output> {
control.check()?;
let child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.process_group(0)
.spawn()?;
let mut child = ControlledChild(child);
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
fcntl(
&stdout,
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
)
.map_err(io::Error::from)?;
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
let mut eof = false;
let mut status = None;
loop {
control.check()?;
if !eof {
match stdout.read(&mut buffer) {
Ok(0) => eof = true,
Ok(length) => {
if length > output_limit.saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
continue;
}
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
Err(error) => return Err(error),
}
}
if status.is_none() {
status = child.0.try_wait()?;
}
if eof && let Some(status) = status {
return Ok(Output {
status,
stdout: output,
stderr: Vec::new(),
});
}
thread::sleep(Duration::from_millis(10));
}
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
// Reap the direct child and stop helpers retaining stdout after it exits.
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
@@ -0,0 +1,172 @@
use std::{
collections::HashMap,
fs::{File, OpenOptions},
path::Path,
process::{ExitStatus, Stdio},
sync::Arc,
};
use anyhow::{Context, ensure};
use common::binary_paths;
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
process::Command,
};
use zeroize::Zeroizing;
use super::{CommandExt, gui_launcher::GuiLauncher};
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
pub struct DesktopLauncher<'a> {
version: &'a str,
minimized: bool,
log_file: Option<String>,
}
impl<'a> DesktopLauncher<'a> {
pub fn new(version: &'a str) -> Self {
Self {
version,
minimized: false,
log_file: None,
}
}
pub fn minimized(mut self, minimized: bool) -> Self {
self.minimized = minimized;
self
}
pub fn log_file(mut self, log_file: &str) -> Self {
self.log_file = Some(log_file.to_owned());
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
ensure!(
uzers::get_effective_uid() != 0,
"The desktop launcher must not run as root"
);
let mut command = Command::new_pkexec(binary_paths::gpservice());
command
.arg("--desktop-credentials")
.stdin(Stdio::piped())
.stdout(Stdio::piped());
if let Some(path) = &self.log_file {
command.stderr(Stdio::from(create_log_file(Path::new(path))?));
}
let mut service = command.spawn().context("Failed to start the privileged service")?;
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
let mut output = service
.stdout
.take()
.context("Service credential pipe is unavailable")?;
let mut received_credential = false;
let mut cancelled = false;
let result = tokio::select! {
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
result = async {
let mut minimized = self.minimized;
loop {
let credential = read_credential(&mut output).await?;
let Some(credential) = credential else { return Ok(()); };
received_credential = true;
ensure!(credential.product_version() == self.version, "Service product version mismatch");
let mut envs: HashMap<String, String> = std::env::vars().collect();
if let Some(path) = &self.log_file {
envs.insert("GP_LOG_FILE".into(), path.clone());
}
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
let mut unexpected = [0];
tokio::select! {
result = launcher.launch() => { result?; }
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
result = output.read(&mut unexpected) => {
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
anyhow::bail!("The privileged service closed its credential channel");
}
}
input.write_all(&[0]).await?;
minimized = false;
}
} => result,
};
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
drop(input);
if cancelled && !received_credential {
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
if let Err(error) = service.start_kill()
&& error.kind() != std::io::ErrorKind::PermissionDenied
{
return Err(error.into());
}
}
let status = service.wait().await?;
result?;
ensure!(
cancelled || status.success(),
"The privileged service exited with {status}"
);
Ok(status)
}
}
fn create_log_file(path: &Path) -> std::io::Result<File> {
// Start a fresh desktop session, then let both processes append without overwriting each other.
File::create(path)?;
OpenOptions::new().append(true).open(path)
}
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
let mut header = [0; 2];
if reader.read(&mut header[..1]).await? == 0 {
return Ok(None);
}
reader.read_exact(&mut header[1..]).await?;
let length = usize::from(u16::from_be_bytes(header));
ensure!(
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
"Invalid service credential length"
);
let mut frame = Zeroizing::new(vec![0; length + 2]);
frame[..2].copy_from_slice(&header);
reader.read_exact(&mut frame[2..]).await?;
Ok(Some(SessionCredential::decode_frame(&frame)?))
}
#[cfg(test)]
mod tests {
use std::io::Write;
use super::*;
#[test]
fn desktop_log_starts_fresh_and_service_writes_preserve_gui_logs() {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("desktop.log");
std::fs::write(&path, "previous session\n").unwrap();
let mut service = create_log_file(&path).unwrap();
writeln!(service, "[gpservice] started").unwrap();
let mut gui = OpenOptions::new().append(true).open(&path).unwrap();
writeln!(gui, "[gpgui] initialized").unwrap();
writeln!(service, "[gpservice] connected").unwrap();
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"[gpservice] started\n[gpgui] initialized\n[gpservice] connected\n"
);
}
#[tokio::test]
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
assert!(read_credential(&mut &[0][..]).await.is_err());
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
let frame = credential.encode_frame().unwrap();
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
assert_eq!(decoded.session_id(), credential.session_id());
}
}
+13 -12
View File
@@ -5,21 +5,21 @@ use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::command_traits::CommandExt, utils};
use crate::service::transport::SessionCredential;
pub struct GuiHelperLauncher<'a> {
program: PathBuf,
envs: Option<&'a HashMap<String, String>>,
api_key: &'a [u8],
credential: &'a SessionCredential,
gui_version: Option<&'a str>,
}
impl<'a> GuiHelperLauncher<'a> {
pub fn new(api_key: &'a [u8]) -> Self {
pub fn new(credential: &'a SessionCredential) -> Self {
Self {
program: binary_paths::gpgui_helper(),
envs: None,
api_key,
credential,
gui_version: None,
}
}
@@ -42,15 +42,18 @@ impl<'a> GuiHelperLauncher<'a> {
cmd.envs(envs);
}
cmd.arg("--api-key-on-stdin");
cmd.arg("--service-credential-on-stdin");
if let Some(gui_version) = self.gui_version {
cmd.arg("--gui-version").arg(gui_version);
}
info!("Launching gpgui-helper");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
@@ -60,13 +63,11 @@ impl<'a> GuiHelperLauncher<'a> {
bail!("Failed to open stdin");
};
let api_key = utils::base64::encode(self.api_key);
tokio::spawn(async move {
stdin.write_all(api_key.as_bytes()).await.unwrap();
drop(stdin);
});
let frame = self.credential.encode_frame()?;
stdin.write_all(&frame).await?;
let exit_status = child.wait().await?;
drop(stdin);
info!("gpgui-helper exited with: {}", exit_status);
Ok(())
+159 -35
View File
@@ -1,32 +1,40 @@
use std::{
collections::HashMap,
path::PathBuf,
fs::OpenOptions,
path::{Path, PathBuf},
process::{ExitStatus, Stdio},
sync::Arc,
};
use anyhow::bail;
use anyhow::{Context, bail};
use common::binary_paths;
use log::info;
use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64};
use super::command_traits::CommandExt;
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
pub struct GuiLauncher<'a> {
version: &'a str,
program: PathBuf,
api_key: &'a [u8],
programs: Vec<PathBuf>,
credential: Arc<SessionCredential>,
minimized: bool,
envs: Option<HashMap<String, String>>,
}
impl<'a> GuiLauncher<'a> {
pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
let primary = binary_paths::gpgui();
let update_target = binary_paths::gpgui_update_target();
let programs = if primary == update_target {
vec![primary]
} else {
vec![primary, update_target]
};
Self {
version,
program: binary_paths::gpgui(),
api_key,
programs,
credential,
minimized: false,
envs: None,
}
@@ -43,56 +51,93 @@ impl<'a> GuiLauncher<'a> {
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
// Check if the program's version
if let Err(err) = self.check_version().await {
info!("Check version failed: {}", err);
// Download the program and replace the current one
self.download_program().await?;
anyhow::ensure!(
uzers::get_effective_uid() != 0,
"The desktop GUI must not be launched by root"
);
if let Some(program) = self.find_compatible_program().await {
return self.launch_program(&program).await;
}
self.launch_program().await
self.download_program().await?;
let program = binary_paths::gpgui_update_target();
self.check_version(&program).await?;
self.launch_program(&program).await
}
async fn launch_program(&self) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new(&self.program);
async fn find_compatible_program(&self) -> Option<PathBuf> {
for program in &self.programs {
match self.check_version(program).await {
Ok(()) => return Some(program.clone()),
Err(err) => info!(
"GUI candidate {} is unavailable or incompatible: {err}",
program.display()
),
}
}
None
}
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new(program);
if let Some(envs) = &self.envs {
cmd.env_clear();
cmd.envs(envs);
}
cmd.arg("--api-key-on-stdin");
let log_file = match &self.envs {
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
};
if let Some(path) = log_file {
let file = OpenOptions::new()
.append(true)
.open(&path)
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?;
cmd.stderr(Stdio::from(file));
}
cmd.arg("--service-credential-on-stdin");
if self.minimized {
cmd.arg("--minimized");
}
info!("Launching gpgui");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin");
};
let api_key = base64::encode(self.api_key);
tokio::spawn(async move {
stdin.write_all(api_key.as_bytes()).await.unwrap();
drop(stdin);
});
let frame = self.credential.encode_frame()?;
stdin.write_all(&frame).await?;
let exit_status = child.wait().await?;
drop(stdin);
Ok(exit_status)
}
async fn check_version(&self) -> anyhow::Result<()> {
let cmd = Command::new(&self.program).arg("--version").output().await?;
let output = String::from_utf8_lossy(&cmd.stdout);
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
let mut cmd = Command::new(program);
if let Some(envs) = &self.envs {
cmd.env_clear();
cmd.envs(envs);
}
cmd.arg("--version");
let output = cmd.output().await?;
if !output.status.success() {
bail!("Version command exited with {}", output.status);
}
let output = String::from_utf8_lossy(&output.stdout);
// Version string: "gpgui 2.0.0 (2024-02-05)"
let Some(version) = output.split_whitespace().nth(1) else {
@@ -109,17 +154,96 @@ impl<'a> GuiLauncher<'a> {
}
async fn download_program(&self) -> anyhow::Result<()> {
let gui_helper = GuiHelperLauncher::new(self.api_key);
let gui_helper = GuiHelperLauncher::new(&self.credential);
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.launch()
.await?;
.await
}
}
// Check the version again
self.check_version().await?;
#[cfg(test)]
mod tests {
use std::{fs, os::unix::fs::PermissionsExt};
Ok(())
use tempfile::TempDir;
use uuid::Uuid;
use super::*;
const VERSION: &str = "test-version";
fn executable(dir: &TempDir, name: &str, output: &str, exit_code: i32) -> PathBuf {
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
let path = dir.path().join(name);
fs::write(
&path,
format!("#!/bin/sh\nprintf '%s\\n' '{output}'\nexit {exit_code}\n"),
)
.unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
path
}
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
GuiLauncher {
version,
programs,
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
minimized: false,
envs: None,
}
}
#[tokio::test]
async fn captures_gui_logs_in_the_desktop_log_file_across_restarts() {
let dir = TempDir::new().unwrap();
let log_file = dir.path().join("desktop.log");
fs::write(&log_file, "[gpservice] started\n").unwrap();
let program = dir.path().join("gui");
fs::write(&program, "#!/bin/sh\nprintf '[gpgui] initialized\\n' >&2\n").unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
let launcher = launcher(VERSION, vec![]).envs(HashMap::from([(
"GP_LOG_FILE".to_owned(),
log_file.to_str().unwrap().to_owned(),
)]));
assert!(launcher.launch_program(&program).await.unwrap().success());
assert!(launcher.launch_program(&program).await.unwrap().success());
assert_eq!(
fs::read_to_string(log_file).unwrap(),
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
);
}
#[tokio::test]
async fn prefers_the_first_compatible_program() {
let dir = TempDir::new().unwrap();
let packaged = executable(&dir, "packaged", "gpgui test-version", 0);
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged.clone(), downloaded]);
assert_eq!(launcher.find_compatible_program().await, Some(packaged));
}
#[tokio::test]
async fn falls_back_when_the_first_program_is_incompatible() {
let dir = TempDir::new().unwrap();
let packaged = executable(&dir, "packaged", "gpgui other-version", 0);
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
let launcher = launcher(VERSION, vec![packaged, downloaded.clone()]);
assert_eq!(launcher.find_compatible_program().await, Some(downloaded));
}
#[tokio::test]
async fn rejects_an_unsuccessful_version_command() {
let dir = TempDir::new().unwrap();
let program = executable(&dir, "broken", "gpgui test-version", 1);
let launcher = launcher(VERSION, vec![program]);
assert_eq!(launcher.find_compatible_program().await, None);
}
}
-96
View File
@@ -1,96 +0,0 @@
use std::process::Stdio;
use anyhow::bail;
use tokio::process::Command;
pub struct HipLauncher<'a> {
program: &'a str,
cookie: Option<&'a str>,
client_ip: Option<&'a str>,
md5: Option<&'a str>,
client_os: Option<&'a str>,
client_version: Option<&'a str>,
}
impl<'a> HipLauncher<'a> {
pub fn new(program: &'a str) -> Self {
Self {
program,
cookie: None,
client_ip: None,
md5: None,
client_os: None,
client_version: None,
}
}
pub fn cookie(mut self, cookie: &'a str) -> Self {
self.cookie = Some(cookie);
self
}
pub fn client_ip(mut self, client_ip: &'a str) -> Self {
self.client_ip = Some(client_ip);
self
}
pub fn md5(mut self, md5: &'a str) -> Self {
self.md5 = Some(md5);
self
}
pub fn client_os(mut self, client_os: &'a str) -> Self {
self.client_os = Some(client_os);
self
}
pub fn client_version(mut self, client_version: Option<&'a str>) -> Self {
self.client_version = client_version;
self
}
pub async fn launch(&self) -> anyhow::Result<String> {
let mut cmd = Command::new(self.program);
if let Some(cookie) = self.cookie {
cmd.arg("--cookie").arg(cookie);
}
if let Some(client_ip) = self.client_ip {
cmd.arg("--client-ip").arg(client_ip);
}
if let Some(md5) = self.md5 {
cmd.arg("--md5").arg(md5);
}
if let Some(client_os) = self.client_os {
cmd.arg("--client-os").arg(client_os);
}
if let Some(client_version) = self.client_version {
cmd.env("APP_VERSION", client_version);
}
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
let child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program, err),
};
let output = child.wait_with_output().await?;
if let Some(exit_status) = output.status.code() {
if exit_status != 0 {
bail!("HIP report generation failed with exit code {}", exit_status);
}
let report = String::from_utf8(output.stdout)?;
Ok(report)
} else {
bail!("HIP report generation failed");
}
}
}
+7 -3
View File
@@ -1,9 +1,13 @@
pub(crate) mod command_traits;
mod command_runner;
mod command_traits;
mod desktop_session_env;
pub(crate) mod gui_helper_launcher;
pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
pub mod hip_launcher;
pub mod service_launcher;
pub mod users;
pub mod collection;
@@ -1,82 +0,0 @@
use std::{
fs::File,
path::PathBuf,
process::{ExitStatus, Stdio},
};
use common::binary_paths;
use tokio::process::Command;
use super::command_traits::CommandExt;
pub struct ServiceLauncher<'a> {
program: PathBuf,
minimized: bool,
env_file: Option<String>,
log_file: Option<String>,
verbose: Option<&'a str>,
}
impl Default for ServiceLauncher<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> ServiceLauncher<'a> {
pub fn new() -> Self {
Self {
program: binary_paths::gpservice(),
minimized: false,
env_file: None,
log_file: None,
verbose: None,
}
}
pub fn minimized(mut self, minimized: bool) -> Self {
self.minimized = minimized;
self
}
pub fn env_file(mut self, env_file: &str) -> Self {
self.env_file = Some(env_file.to_string());
self
}
pub fn log_file(mut self, log_file: &str) -> Self {
self.log_file = Some(log_file.to_string());
self
}
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
self.verbose = verbose;
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new_pkexec(&self.program);
if self.minimized {
cmd.arg("--minimized");
}
if let Some(env_file) = &self.env_file {
cmd.arg("--env-file").arg(env_file);
}
if let Some(verbose) = self.verbose {
cmd.arg(verbose);
}
if let Some(log_file) = &self.log_file {
let log_file = File::create(log_file)?;
let stdio = Stdio::from(log_file);
cmd.stderr(stdio);
}
let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?;
Ok(exit_status)
}
}
+2
View File
@@ -1,4 +1,6 @@
pub mod event;
pub mod request;
pub mod transport;
pub mod vpn_env;
pub mod vpn_state;
pub mod vpnc_script;
+188 -45
View File
@@ -1,15 +1,41 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt};
use serde::{Deserialize, Serialize};
use specta::Type;
use zeroize::Zeroize;
use crate::{
gateway::Gateway,
os_profile::{ClientOs, OsProfile},
hip::HipSource,
os_profile::{ClientOs, HostIdentity, OsProfile},
session::ConnectionPlan,
};
use super::vpn_state::ConnectInfo;
pub const MAX_CLIENT_IDENTITY_DATA: usize = 32 * 1024;
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreEditedHipReportChunkRequest {
pub upload_id: Option<String>,
pub offset: usize,
pub xml: String,
pub complete: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PreviewHipReportRequest {
pub source: HipSource,
pub client_os: ClientOs,
pub client_version: String,
pub host_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ReadHipPreviewChunkRequest {
pub preview_id: String,
pub offset: usize,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct LaunchGuiRequest {
user: String,
@@ -30,10 +56,11 @@ impl LaunchGuiRequest {
}
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[derive(Deserialize, Serialize, Type, Clone)]
pub struct ConnectArgs {
cookie: String,
vpnc_script: Option<String>,
host_identity: Option<HostIdentity>,
ignore_tls_errors: bool,
user_agent: Option<String>,
os: Option<ClientOs>,
@@ -43,11 +70,11 @@ pub struct ConnectArgs {
certificate: Option<String>,
sslkey: Option<String>,
certificate_data: Option<String>,
sslkey_data: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -61,10 +88,11 @@ pub struct ConnectArgs {
}
impl ConnectArgs {
pub fn new(cookie: String) -> Self {
fn new() -> Self {
Self {
cookie,
vpnc_script: None,
host_identity: None,
ignore_tls_errors: false,
user_agent: None,
os: None,
os_version: None,
@@ -72,10 +100,10 @@ impl ConnectArgs {
host_id: None,
certificate: None,
sslkey: None,
certificate_data: None,
sslkey_data: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
@@ -87,8 +115,12 @@ impl ConnectArgs {
}
}
pub fn cookie(&self) -> &str {
&self.cookie
pub fn host_identity(&self) -> Option<&HostIdentity> {
self.host_identity.as_ref()
}
pub fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
pub fn vpnc_script(&self) -> Option<String> {
@@ -127,20 +159,28 @@ impl ConnectArgs {
self.sslkey.clone()
}
pub fn certificate_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
self
.certificate_data
.as_deref()
.map(crate::utils::base64::decode_to_vec)
.transpose()
}
pub fn sslkey_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
self
.sslkey_data
.as_deref()
.map(crate::utils::base64::decode_to_vec)
.transpose()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn hip(&self) -> bool {
self.hip
}
pub fn csd_uid(&self) -> u32 {
self.csd_uid
}
pub fn csd_wrapper(&self) -> Option<String> {
self.csd_wrapper.clone()
pub fn hip_source(&self) -> &HipSource {
&self.hip_source
}
pub fn reconnect_timeout(&self) -> u32 {
@@ -176,17 +216,49 @@ impl ConnectArgs {
}
}
impl fmt::Debug for ConnectArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConnectArgs")
.field("vpnc_script", &self.vpnc_script)
.field(
"client_auth_path",
&(self.certificate.is_some() || self.sslkey.is_some()),
)
.field(
"client_auth_data",
&(self.certificate_data.is_some() || self.sslkey_data.is_some()),
)
.field("hip_source", &self.hip_source)
.field("reconnect_timeout", &self.reconnect_timeout)
.field("mtu", &self.mtu)
.field("disable_ipv6", &self.disable_ipv6)
.field("no_dtls", &self.no_dtls)
.field("allow_extend_session", &self.allow_extend_session)
.finish_non_exhaustive()
}
}
impl Drop for ConnectArgs {
fn drop(&mut self) {
self.key_password.zeroize();
self.certificate_data.zeroize();
self.sslkey_data.zeroize();
}
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectRequest {
info: ConnectInfo,
plan: ConnectionPlan,
args: ConnectArgs,
}
impl ConnectRequest {
pub fn new(info: ConnectInfo, cookie: String) -> Self {
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
Self {
info,
args: ConnectArgs::new(cookie),
plan,
args: ConnectArgs::new(),
}
}
@@ -195,22 +267,13 @@ impl ConnectRequest {
self
}
pub fn with_hip(mut self, hip: bool) -> Self {
self.args.hip = hip;
self
}
pub fn with_csd_uid(mut self, csd_uid: u32) -> Self {
self.args.csd_uid = csd_uid;
self
}
pub fn with_csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.args.csd_wrapper = csd_wrapper.into();
pub fn with_hip_source(mut self, hip_source: HipSource) -> Self {
self.args.hip_source = hip_source;
self
}
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
self.args.host_identity = Some(profile.host_identity().clone());
self.args.os = Some(profile.client_os());
self.args.os_version = Some(profile.os_version().to_string());
self.args.client_version = Some(profile.client_version().to_string());
@@ -219,6 +282,11 @@ impl ConnectRequest {
self
}
pub fn with_ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
self.args.ignore_tls_errors = ignore_tls_errors;
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.args.certificate = certificate.into();
self
@@ -229,6 +297,16 @@ impl ConnectRequest {
self
}
pub fn with_certificate_data(mut self, certificate: Option<Vec<u8>>) -> Self {
self.args.certificate_data = certificate.map(encode_secret);
self
}
pub fn with_sslkey_data(mut self, sslkey: Option<Vec<u8>>) -> Self {
self.args.sslkey_data = sslkey.map(encode_secret);
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.args.key_password = key_password.into();
self
@@ -274,8 +352,8 @@ impl ConnectRequest {
self
}
pub fn gateway(&self) -> &Gateway {
self.info.gateway()
pub fn plan(&self) -> &ConnectionPlan {
&self.plan
}
pub fn info(&self) -> &ConnectInfo {
@@ -287,6 +365,12 @@ impl ConnectRequest {
}
}
fn encode_secret(mut data: Vec<u8>) -> String {
let encoded = crate::utils::base64::encode(&data);
data.zeroize();
encoded
}
#[derive(Debug, Deserialize, Serialize, Type)]
pub struct DisconnectRequest;
@@ -298,10 +382,19 @@ pub struct UpdateLogLevelRequest(pub String);
pub enum WsRequest {
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
PreviewHipReport(PreviewHipReportRequest),
GetHipApprovalStatus { approval_id: String },
ReadHipPreviewChunk(ReadHipPreviewChunkRequest),
GetLastSubmittedHipReport,
UpdateLogLevel(UpdateLogLevelRequest),
RestartGui,
UpdateGui(UpdateGuiRequest),
GetVpncScriptMetadata,
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct UpdateGuiRequest {
pub path: String,
pub checksum: String,
@@ -313,17 +406,52 @@ mod tests {
use super::*;
use crate::os_profile::OsProfileBuilder;
use crate::{
gateway::Gateway,
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
};
fn test_request(info: ConnectInfo) -> ConnectRequest {
let plan = ConnectionPlan::new(
vec![AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
.unwrap(),
}],
vec![],
InternalSessionPolicy::default(),
)
.unwrap();
ConnectRequest::new(info, plan)
}
fn test_connect_info() -> ConnectInfo {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
}
#[test]
fn connect_request_round_trips_a_validated_plan_and_rejects_cookie_only_wire_input() {
let request = test_request(test_connect_info());
let mut value = serde_json::to_value(&request).unwrap();
assert!(value["args"].get("cookie").is_none());
let decoded: ConnectRequest = serde_json::from_value(value.clone()).unwrap();
assert_eq!(decoded.plan().members().len(), 1);
assert_eq!(decoded.plan().members()[0].authentication.connection_type(), "tunnel");
value["plan"]["members"] = json!([]);
assert!(serde_json::from_value::<ConnectRequest>(value).is_err());
let mut legacy = serde_json::to_value(&request).unwrap();
legacy.as_object_mut().unwrap().remove("plan");
legacy["args"]["cookie"] = json!("authcookie=secret-cookie&user=user");
assert!(serde_json::from_value::<ConnectRequest>(legacy).is_err());
}
#[test]
fn connect_request_serializes_allow_extend_session() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
let req = test_request(info).with_allow_extend_session(true);
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["args"]["allowExtendSession"], json!(true));
@@ -333,7 +461,7 @@ mod tests {
fn with_os_profile_sets_user_agent_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
let req = test_request(test_connect_info()).with_os_profile(&profile);
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
}
@@ -342,11 +470,26 @@ mod tests {
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
let req = test_request(test_connect_info()).with_os_profile(&profile);
assert_eq!(
req.args().host_id(),
Some(profile.host_identity().host_id().to_string())
);
}
#[test]
fn client_identity_data_round_trips_without_debug_disclosure() {
let req = test_request(test_connect_info())
.with_certificate_data(Some(b"certificate".to_vec()))
.with_sslkey_data(Some(b"private-key".to_vec()));
let encoded = serde_json::to_vec(&req).unwrap();
let decoded: ConnectRequest = serde_json::from_slice(&encoded).unwrap();
assert_eq!(decoded.args().certificate_data().unwrap().unwrap(), b"certificate");
assert_eq!(decoded.args().sslkey_data().unwrap().unwrap(), b"private-key");
let debug = format!("{decoded:?}");
assert!(!debug.contains("secret-cookie"));
assert!(!debug.contains("private-key"));
}
}
@@ -0,0 +1,223 @@
use std::fmt;
use ::base64::{Engine, engine::general_purpose};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use zeroize::Zeroizing;
use crate::device_anchor::DeviceAnchor;
use crate::utils::base64;
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
pub struct SessionCredential {
service_instance_id: Uuid,
session_id: Uuid,
secret: Zeroizing<[u8; 32]>,
product_version: String,
device_anchor: Option<DeviceAnchor>,
}
impl SessionCredential {
pub fn generate(service_instance_id: Uuid, product_version: &str) -> Result<Self, TransportError> {
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
return Err(TransportError::InvalidCredential);
}
let mut secret = Zeroizing::new([0_u8; 32]);
getrandom::fill(secret.as_mut()).map_err(|_| TransportError::InvalidState)?;
Ok(Self {
service_instance_id,
session_id: Uuid::new_v4(),
secret,
product_version: product_version.to_owned(),
device_anchor: None,
})
}
pub fn service_instance_id(&self) -> Uuid {
self.service_instance_id
}
pub fn session_id(&self) -> Uuid {
self.session_id
}
pub fn secret(&self) -> &[u8; 32] {
&self.secret
}
pub fn product_version(&self) -> &str {
&self.product_version
}
pub fn with_device_anchor(mut self, anchor: DeviceAnchor) -> Result<Self, TransportError> {
if !anchor.validate() {
return Err(TransportError::InvalidCredential);
}
self.device_anchor = Some(anchor);
Ok(self)
}
pub fn device_anchor(&self) -> Option<&DeviceAnchor> {
self.device_anchor.as_ref()
}
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
let dto = CredentialDtoRef {
service_instance_id: self.service_instance_id,
session_id: self.session_id,
secret: encoded_secret.as_str(),
product_version: &self.product_version,
device_anchor: self.device_anchor.as_ref(),
};
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
if payload.len() + 2 > MAX_CREDENTIAL_FRAME || payload.len() > u16::MAX as usize {
return Err(TransportError::MessageTooLarge);
}
let mut frame = Zeroizing::new(Vec::with_capacity(payload.len() + 2));
frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
frame.extend_from_slice(&payload);
Ok(frame)
}
pub fn decode_frame(frame: &[u8]) -> Result<Self, TransportError> {
if frame.len() < 2 || frame.len() > MAX_CREDENTIAL_FRAME {
return Err(TransportError::InvalidCredential);
}
let payload_len = u16::from_be_bytes([frame[0], frame[1]]) as usize;
if payload_len == 0 || payload_len + 2 != frame.len() {
return Err(TransportError::InvalidCredential);
}
let dto: CredentialDto = serde_json::from_slice(&frame[2..]).map_err(|_| TransportError::InvalidCredential)?;
let CredentialDto {
service_instance_id,
session_id,
secret,
product_version,
device_anchor,
} = dto;
let encoded_secret = secret;
if device_anchor.as_ref().is_some_and(|anchor| !anchor.validate()) {
return Err(TransportError::InvalidCredential);
}
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
return Err(TransportError::InvalidCredential);
}
let mut secret = Zeroizing::new([0_u8; 32]);
let decoded_len = general_purpose::STANDARD
.decode_slice(encoded_secret.as_bytes(), secret.as_mut())
.map_err(|_| TransportError::InvalidCredential)?;
if decoded_len != secret.len() {
return Err(TransportError::InvalidCredential);
}
Ok(Self {
service_instance_id,
session_id,
secret,
product_version,
device_anchor,
})
}
}
impl fmt::Debug for SessionCredential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SessionCredential")
.field("service_instance_id", &self.service_instance_id)
.field("session_id", &self.session_id)
.field("secret", &"[REDACTED]")
.field("product_version", &self.product_version)
.finish()
}
}
#[derive(Serialize)]
#[serde(deny_unknown_fields)]
struct CredentialDtoRef<'a> {
service_instance_id: Uuid,
session_id: Uuid,
secret: &'a str,
product_version: &'a str,
device_anchor: Option<&'a DeviceAnchor>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CredentialDto {
service_instance_id: Uuid,
session_id: Uuid,
secret: Zeroizing<String>,
product_version: String,
device_anchor: Option<DeviceAnchor>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credential_round_trips_without_debugging_secret() {
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.4").unwrap();
let frame = credential.encode_frame().unwrap();
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.service_instance_id(), credential.service_instance_id());
assert_eq!(decoded.session_id(), credential.session_id());
assert_eq!(decoded.secret(), credential.secret());
assert_eq!(decoded.product_version(), credential.product_version());
assert!(!format!("{credential:?}").contains(&base64::encode(credential.secret())));
}
#[test]
fn credential_rejects_malformed_lengths() {
assert!(SessionCredential::decode_frame(&[]).is_err());
assert!(SessionCredential::decode_frame(&[0, 0]).is_err());
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
}
#[test]
fn credential_round_trips_a_validated_device_anchor() {
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::UnixMac,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], 1);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
}
#[test]
fn credential_rejects_reserved_and_unknown_anchor_sources() {
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5").unwrap();
let frame = credential.encode_frame().unwrap();
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, 4] {
payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id,
"source": source
});
let bytes = serde_json::to_vec(&payload).unwrap();
let mut invalid_frame = (bytes.len() as u16).to_be_bytes().to_vec();
invalid_frame.extend_from_slice(&bytes);
assert!(SessionCredential::decode_frame(&invalid_frame).is_err());
}
}
}
+119
View File
@@ -0,0 +1,119 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Error)]
pub enum TransportError {
#[error("invalid credential frame")]
InvalidCredential,
#[error("invalid transport state")]
InvalidState,
#[error("message exceeds transport limit")]
MessageTooLarge,
#[error("malformed transport message")]
MalformedMessage,
#[error("Noise operation failed")]
Noise(#[from] snow::Error),
#[error("transport serialization failed")]
Serialization(#[from] serde_json::Error),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
pub enum HandshakeRejection {
VersionMismatch { client: String, service: String },
HipProtocolMismatch { client: u16, service: u16 },
ServiceRestarted { service_instance_id: Uuid },
ReconnectSuperseded,
Unauthorized,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ServiceErrorCode {
InvalidRequest,
Busy,
ChecksumFailed,
InstallFailed,
Internal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseReason {
VersionMismatch,
Unauthorized,
SessionReplaced,
HandshakeFailed,
MalformedMessage,
MessageTooLarge,
AuthenticationFailed,
HandshakeTimeout,
ReconnectSuperseded,
InternalError,
ServiceRestarted,
HeartbeatTimeout,
}
impl CloseReason {
pub const fn code(self) -> u16 {
match self {
Self::VersionMismatch => 4001,
Self::Unauthorized => 4002,
Self::SessionReplaced => 4003,
Self::HandshakeFailed => 4004,
Self::MalformedMessage => 4005,
Self::MessageTooLarge => 4006,
Self::AuthenticationFailed => 4007,
Self::HandshakeTimeout => 4008,
Self::ReconnectSuperseded => 4009,
Self::InternalError => 4010,
Self::ServiceRestarted => 4011,
Self::HeartbeatTimeout => 4012,
}
}
pub const fn reason(self) -> &'static str {
match self {
Self::VersionMismatch => "VersionMismatch",
Self::Unauthorized => "Unauthorized",
Self::SessionReplaced => "SessionReplaced",
Self::HandshakeFailed => "HandshakeFailed",
Self::MalformedMessage => "MalformedMessage",
Self::MessageTooLarge => "MessageTooLarge",
Self::AuthenticationFailed => "AuthenticationFailed",
Self::HandshakeTimeout => "HandshakeTimeout",
Self::ReconnectSuperseded => "ReconnectSuperseded",
Self::InternalError => "InternalError",
Self::ServiceRestarted => "ServiceRestarted",
Self::HeartbeatTimeout => "HeartbeatTimeout",
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn close_codes_are_unique_application_codes() {
let reasons = [
CloseReason::VersionMismatch,
CloseReason::Unauthorized,
CloseReason::SessionReplaced,
CloseReason::HandshakeFailed,
CloseReason::MalformedMessage,
CloseReason::MessageTooLarge,
CloseReason::AuthenticationFailed,
CloseReason::HandshakeTimeout,
CloseReason::ReconnectSuperseded,
CloseReason::InternalError,
CloseReason::ServiceRestarted,
CloseReason::HeartbeatTimeout,
];
let codes: HashSet<_> = reasons.iter().map(|reason| reason.code()).collect();
assert_eq!(codes.len(), reasons.len());
assert!(codes.iter().all(|code| (4000..5000).contains(code)));
}
}
@@ -0,0 +1,94 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::{HandshakeRejection, MAX_PRELUDE, MAX_PRODUCT_VERSION, TransportError};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ClientPrelude {
pub product_version: String,
#[serde(default)]
pub hip_protocol_version: u16,
pub service_instance_id: Uuid,
pub session_id: Uuid,
}
impl ClientPrelude {
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
if self.product_version.is_empty() || self.product_version.len() > MAX_PRODUCT_VERSION {
return Err(TransportError::MalformedMessage);
}
let encoded = serde_json::to_vec(self)?;
if encoded.len() > MAX_PRELUDE {
return Err(TransportError::MessageTooLarge);
}
Ok(encoded)
}
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
if encoded.len() > MAX_PRELUDE {
return Err(TransportError::MessageTooLarge);
}
let prelude: Self = serde_json::from_slice(encoded)?;
if prelude.product_version.is_empty() || prelude.product_version.len() > MAX_PRODUCT_VERSION {
return Err(TransportError::MalformedMessage);
}
Ok(prelude)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServerPrelude {
Ready,
Rejected(HandshakeRejection),
}
impl ServerPrelude {
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
let encoded = serde_json::to_vec(self)?;
if encoded.len() > MAX_PRELUDE {
return Err(TransportError::MessageTooLarge);
}
Ok(encoded)
}
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
if encoded.len() > MAX_PRELUDE {
return Err(TransportError::MessageTooLarge);
}
Ok(serde_json::from_slice(encoded)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preludes_reject_unknown_fields_and_invalid_versions() {
let instance = Uuid::new_v4();
let session = Uuid::new_v4();
let unknown = format!(
r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}","extra":true}}"#
);
assert!(ClientPrelude::decode(unknown.as_bytes()).is_err());
let legacy =
format!(r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}"}}"#);
assert_eq!(
ClientPrelude::decode(legacy.as_bytes()).unwrap().hip_protocol_version,
0
);
assert!(
ClientPrelude {
product_version: String::new(),
hip_protocol_version: super::super::HIP_PROTOCOL_VERSION,
service_instance_id: instance,
session_id: session,
}
.encode()
.is_err()
);
assert!(ClientPrelude::decode(&vec![b'x'; MAX_PRELUDE + 1]).is_err());
}
}
@@ -0,0 +1,195 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::hip::HipApprovalStatus;
use crate::service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpnc_script::VpncScriptMetadata};
use super::{MAX_PLAINTEXT, MAX_SERVICE_MESSAGE, ServiceErrorCode, TransportError};
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ClientMessage {
Attach { last_event_revision: Option<u64> },
Request { id: Uuid, request: WsRequest },
Resync { last_event_revision: u64 },
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServerMessage {
Attached {
connection_id: Uuid,
current_revision: u64,
snapshot: VpnEnv,
},
Reply {
id: Uuid,
result: ServiceResult,
},
Event {
revision: u64,
event: WsEvent,
},
Snapshot {
current_revision: u64,
snapshot: VpnEnv,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServiceResult {
Accepted,
StoredHipReport {
report_id: String,
},
HipUploadProgress {
upload_id: String,
},
HipPreviewChunk {
preview_id: String,
offset: usize,
xml: String,
complete: bool,
},
HipApprovalStatus(HipApprovalStatus),
NoSubmittedHipReport,
VpncScriptMetadata(Option<VpncScriptMetadata>),
Rejected(ServiceRejection),
}
impl ServiceResult {
pub fn rejected(code: ServiceErrorCode, message: impl Into<String>) -> Self {
Self::Rejected(ServiceRejection::new(code, message))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ServiceRejectionDto")]
pub struct ServiceRejection {
code: ServiceErrorCode,
message: String,
}
impl ServiceRejection {
fn new(code: ServiceErrorCode, message: impl Into<String>) -> Self {
let mut message = message.into();
if message.len() > MAX_SERVICE_MESSAGE {
let mut boundary = MAX_SERVICE_MESSAGE;
while !message.is_char_boundary(boundary) {
boundary -= 1;
}
message.truncate(boundary);
}
Self { code, message }
}
pub fn code(&self) -> ServiceErrorCode {
self.code
}
pub fn message(&self) -> &str {
&self.message
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ServiceRejectionDto {
code: ServiceErrorCode,
message: String,
}
impl TryFrom<ServiceRejectionDto> for ServiceRejection {
type Error = &'static str;
fn try_from(value: ServiceRejectionDto) -> Result<Self, Self::Error> {
if value.message.len() > MAX_SERVICE_MESSAGE {
return Err("service rejection message is too long");
}
Ok(Self {
code: value.code,
message: value.message,
})
}
}
pub(crate) fn encode<T: Serialize>(message: &T) -> Result<Vec<u8>, TransportError> {
let encoded = serde_json::to_vec(message)?;
if encoded.len() > MAX_PLAINTEXT {
return Err(TransportError::MessageTooLarge);
}
Ok(encoded)
}
pub(crate) fn decode<T: for<'de> Deserialize<'de>>(encoded: &[u8]) -> Result<T, TransportError> {
if encoded.len() > MAX_PLAINTEXT {
return Err(TransportError::MessageTooLarge);
}
Ok(serde_json::from_slice(encoded)?)
}
#[cfg(test)]
mod tests {
use crate::{
gateway::Gateway,
service::{
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, WsRequest},
vpn_state::ConnectInfo,
},
};
use super::*;
#[test]
fn rejects_oversized_messages() {
assert!(encode(&"x".repeat(MAX_PLAINTEXT)).is_err());
assert!(decode::<String>(&vec![b'x'; MAX_PLAINTEXT + 1]).is_err());
}
#[test]
fn rejection_messages_are_utf8_safely_bounded() {
let ServiceResult::Rejected(rejection) = ServiceResult::rejected(ServiceErrorCode::Internal, "界".repeat(100))
else {
panic!("expected rejection");
};
assert!(rejection.message().len() <= MAX_SERVICE_MESSAGE);
let oversized = format!(
r#"{{"type":"rejected","data":{{"code":"internal","message":"{}"}}}}"#,
"x".repeat(MAX_SERVICE_MESSAGE + 1)
);
assert!(serde_json::from_str::<ServiceResult>(&oversized).is_err());
}
#[test]
fn maximum_client_identity_fits_one_transport_message() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
let plan = crate::session::ConnectionPlan::new(
vec![crate::session::AuthenticatedGateway {
gateway: info.gateway().clone(),
binding: Some(crate::session::network::test_binding()),
authentication: crate::session::GatewayAuthentication::new(
"authcookie=token&user=user".into(),
"tunnel".into(),
)
.unwrap(),
}],
vec![],
crate::session::InternalSessionPolicy::default(),
)
.unwrap();
let request = ConnectRequest::new(info, plan)
.with_certificate_data(Some(vec![b'c'; certificate_size]))
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
let message = ClientMessage::Request {
id: Uuid::new_v4(),
request: WsRequest::Connect(Box::new(request)),
};
let encoded = encode(&message).unwrap();
assert!(encoded.len() <= MAX_PLAINTEXT);
}
}
+19
View File
@@ -0,0 +1,19 @@
mod credential;
mod error;
mod handshake;
mod message;
mod noise;
pub use credential::SessionCredential;
pub use error::{CloseReason, HandshakeRejection, ServiceErrorCode, TransportError};
pub use handshake::{ClientPrelude, ServerPrelude};
pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult};
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
pub const MAX_CREDENTIAL_FRAME: usize = 512;
pub const MAX_PRELUDE: usize = 256;
pub const MAX_PRODUCT_VERSION: usize = 64;
pub const HIP_PROTOCOL_VERSION: u16 = 1;
pub const MAX_PLAINTEXT: usize = 60 * 1024;
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
pub const MAX_SERVICE_MESSAGE: usize = 256;
+231
View File
@@ -0,0 +1,231 @@
use snow::{Builder, HandshakeState, TransportState, params::NoiseParams};
use zeroize::Zeroizing;
use super::{MAX_PLAINTEXT, MAX_PRODUCT_VERSION, MAX_WS_MESSAGE, TransportError};
const NOISE_PATTERN: &str = "Noise_NNpsk0_25519_ChaChaPoly_SHA256";
const NOISE_TAG_SIZE: usize = 16;
pub struct NoiseInitiator {
state: Option<HandshakeState>,
}
impl NoiseInitiator {
pub fn new(
product_version: &str,
service_instance_id: uuid::Uuid,
session_id: uuid::Uuid,
psk: &[u8; 32],
) -> Result<Self, TransportError> {
let params = noise_params()?;
let prologue = prologue(product_version, service_instance_id, session_id)?;
Ok(Self {
state: Some(
Builder::new(params)
.prologue(&prologue)?
.psk(0, psk)?
.build_initiator()?,
),
})
}
pub fn write_first(&mut self) -> Result<Vec<u8>, TransportError> {
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
let mut output = vec![0_u8; 128];
let len = state.write_message(&[], &mut output)?;
output.truncate(len);
Ok(output)
}
pub fn read_response(mut self, message: &[u8]) -> Result<NoiseTransport, TransportError> {
if message.len() > MAX_WS_MESSAGE {
return Err(TransportError::MessageTooLarge);
}
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
let mut output = vec![0_u8; 128];
state.read_message(message, &mut output)?;
Ok(NoiseTransport::new(state.into_transport_mode()?))
}
}
pub struct NoiseResponder {
state: Option<HandshakeState>,
}
impl NoiseResponder {
pub fn new(
product_version: &str,
service_instance_id: uuid::Uuid,
session_id: uuid::Uuid,
psk: &[u8; 32],
) -> Result<Self, TransportError> {
let params = noise_params()?;
let prologue = prologue(product_version, service_instance_id, session_id)?;
Ok(Self {
state: Some(
Builder::new(params)
.prologue(&prologue)?
.psk(0, psk)?
.build_responder()?,
),
})
}
pub fn read_first(&mut self, message: &[u8]) -> Result<(), TransportError> {
if message.len() > MAX_WS_MESSAGE {
return Err(TransportError::MessageTooLarge);
}
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
let mut output = vec![0_u8; 128];
state.read_message(message, &mut output)?;
Ok(())
}
pub fn write_response(mut self) -> Result<(Vec<u8>, NoiseTransport), TransportError> {
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
let mut output = vec![0_u8; 128];
let len = state.write_message(&[], &mut output)?;
output.truncate(len);
let transport = NoiseTransport::new(state.into_transport_mode()?);
Ok((output, transport))
}
}
pub struct NoiseTransport {
state: TransportState,
}
impl NoiseTransport {
fn new(state: TransportState) -> Self {
Self { state }
}
pub fn encrypt<T: serde::Serialize>(&mut self, message: &T) -> Result<Vec<u8>, TransportError> {
let plaintext = Zeroizing::new(super::message::encode(message)?);
let mut output = vec![0_u8; plaintext.len() + NOISE_TAG_SIZE];
let len = self.state.write_message(&plaintext, &mut output)?;
output.truncate(len);
Ok(output)
}
pub fn decrypt<T: for<'de> serde::Deserialize<'de>>(&mut self, message: &[u8]) -> Result<T, TransportError> {
if message.len() > MAX_WS_MESSAGE || message.len() < NOISE_TAG_SIZE {
return Err(if message.len() > MAX_WS_MESSAGE {
TransportError::MessageTooLarge
} else {
TransportError::MalformedMessage
});
}
let mut plaintext = Zeroizing::new(vec![0_u8; message.len()]);
let len = self.state.read_message(message, &mut plaintext)?;
plaintext.truncate(len);
if plaintext.len() > MAX_PLAINTEXT {
return Err(TransportError::MessageTooLarge);
}
super::message::decode(&plaintext)
}
}
fn noise_params() -> Result<NoiseParams, TransportError> {
NOISE_PATTERN.parse().map_err(|_| TransportError::InvalidState)
}
fn prologue(
product_version: &str,
service_instance_id: uuid::Uuid,
session_id: uuid::Uuid,
) -> Result<Vec<u8>, TransportError> {
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
return Err(TransportError::MessageTooLarge);
}
let mut value = Vec::with_capacity(5 + 2 + product_version.len() + 32);
value.extend_from_slice(b"GPWS\0");
value.extend_from_slice(&(product_version.len() as u16).to_be_bytes());
value.extend_from_slice(product_version.as_bytes());
value.extend_from_slice(service_instance_id.as_bytes());
value.extend_from_slice(session_id.as_bytes());
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Payload(String);
#[test]
fn peers_exchange_directional_messages() {
let instance = uuid::Uuid::new_v4();
let session = uuid::Uuid::new_v4();
let psk = [7_u8; 32];
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
let first = initiator.write_first().unwrap();
responder.read_first(&first).unwrap();
let (response, mut server) = responder.write_response().unwrap();
let mut client = initiator.read_response(&response).unwrap();
let encrypted = client.encrypt(&Payload("hello".into())).unwrap();
assert_eq!(server.decrypt::<Payload>(&encrypted).unwrap(), Payload("hello".into()));
assert!(server.decrypt::<Payload>(&encrypted).is_err());
let response = server.encrypt(&Payload("world".into())).unwrap();
assert_eq!(client.decrypt::<Payload>(&response).unwrap(), Payload("world".into()));
}
#[test]
fn wrong_psk_fails_handshake() {
let instance = uuid::Uuid::new_v4();
let session = uuid::Uuid::new_v4();
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &[1; 32]).unwrap();
let mut responder = NoiseResponder::new("2.6.4", instance, session, &[2; 32]).unwrap();
let first = initiator.write_first().unwrap();
assert!(responder.read_first(&first).is_err());
}
#[test]
fn transcript_identity_mismatch_fails_handshake() {
let instance = uuid::Uuid::new_v4();
let session = uuid::Uuid::new_v4();
let psk = [3_u8; 32];
for mut responder in [
NoiseResponder::new("2.6.5", instance, session, &psk).unwrap(),
NoiseResponder::new("2.6.4", uuid::Uuid::new_v4(), session, &psk).unwrap(),
NoiseResponder::new("2.6.4", instance, uuid::Uuid::new_v4(), &psk).unwrap(),
] {
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
let first = initiator.write_first().unwrap();
assert!(responder.read_first(&first).is_err());
}
}
#[test]
fn transport_rejects_tampering_truncation_and_reordering() {
let instance = uuid::Uuid::new_v4();
let session = uuid::Uuid::new_v4();
let psk = [9_u8; 32];
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
let first = initiator.write_first().unwrap();
responder.read_first(&first).unwrap();
let (response, mut server) = responder.write_response().unwrap();
let mut client = initiator.read_response(&response).unwrap();
let first = client.encrypt(&Payload("first".into())).unwrap();
let second = client.encrypt(&Payload("second".into())).unwrap();
assert!(server.decrypt::<Payload>(&second).is_err());
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
let handshake = initiator.write_first().unwrap();
responder.read_first(&handshake).unwrap();
let (response, mut server) = responder.write_response().unwrap();
let mut client = initiator.read_response(&response).unwrap();
let mut tampered = client.encrypt(&Payload("value".into())).unwrap();
tampered[0] ^= 1;
assert!(server.decrypt::<Payload>(&tampered).is_err());
assert!(server.decrypt::<Payload>(&first[..NOISE_TAG_SIZE - 1]).is_err());
}
}
-3
View File
@@ -24,9 +24,6 @@ pub struct VpnEnv {
/// The default VPN script path
pub vpnc_script: Option<String>,
/// The default CSD wrapper script path
pub csd_wrapper: Option<String>,
/// The gpauth executable path
/// Used by the client to launch gpauth for authentication
pub auth_executable: String,
+39 -1
View File
@@ -1,7 +1,12 @@
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{gateway::Gateway, session::SessionInfo};
use crate::{
gateway::Gateway,
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
};
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
@@ -15,6 +20,9 @@ pub struct ConnectInfo {
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
connected_at: u32,
members: Vec<GatewaySessionSummary>,
failures: Vec<GatewayFailureSummary>,
}
impl ConnectedInfo {
@@ -22,9 +30,26 @@ impl ConnectedInfo {
Self {
info: Box::new(info),
session_info,
connected_at: unix_timestamp(),
members: vec![],
failures: vec![],
}
}
pub fn with_members(mut self, members: Vec<GatewaySessionSummary>, failures: Vec<GatewayFailureSummary>) -> Self {
self.members = members;
self.failures = failures;
self
}
pub fn members(&self) -> &[GatewaySessionSummary] {
&self.members
}
pub fn failures(&self) -> &[GatewayFailureSummary] {
&self.failures
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
@@ -32,6 +57,17 @@ impl ConnectedInfo {
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
pub fn connected_at(&self) -> u32 {
self.connected_at
}
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
impl ConnectInfo {
@@ -52,6 +88,7 @@ impl ConnectInfo {
#[serde(rename_all = "camelCase")]
pub enum VpnState {
Disconnected,
Failed(String),
Connecting(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>),
Disconnecting,
@@ -79,5 +116,6 @@ mod tests {
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
assert!(value["connected"]["connectedAt"].as_u64().is_some());
}
}
+84
View File
@@ -0,0 +1,84 @@
use anyhow::bail;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::utils::base64;
pub const MAX_VPNC_SCRIPT_SOURCE_VALUE: usize = 32 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VpncScriptSource {
File,
Command,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct VpncScriptMetadata {
pub source: VpncScriptSource,
pub value: String,
}
impl VpncScriptMetadata {
pub fn new(source: VpncScriptSource, value: String) -> anyhow::Result<Self> {
if value.trim().is_empty() {
bail!("VPNC script source is empty");
}
if value.contains('\0') {
bail!("VPNC script source contains a null character");
}
if value.len() > MAX_VPNC_SCRIPT_SOURCE_VALUE {
bail!(
"VPNC script source exceeds the {} byte limit",
MAX_VPNC_SCRIPT_SOURCE_VALUE
);
}
Ok(Self { source, value })
}
pub fn validate(&self) -> anyhow::Result<()> {
Self::new(self.source, self.value.clone()).map(|_| ())
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct InstallVpncScriptRequest {
pub metadata: VpncScriptMetadata,
contents: String,
}
impl InstallVpncScriptRequest {
pub fn new(metadata: VpncScriptMetadata, contents: &[u8]) -> Self {
Self {
metadata,
contents: base64::encode(contents),
}
}
pub fn contents(&self) -> anyhow::Result<Vec<u8>> {
base64::decode_to_vec(&self.contents)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn install_request_round_trips_binary_contents() {
let metadata = VpncScriptMetadata::new(VpncScriptSource::File, "/tmp/vpnc-script".to_owned()).unwrap();
let request = InstallVpncScriptRequest::new(metadata, b"#!/bin/sh\n");
let encoded = serde_json::to_vec(&request).unwrap();
let decoded: InstallVpncScriptRequest = serde_json::from_slice(&encoded).unwrap();
assert_eq!(decoded.contents().unwrap(), b"#!/bin/sh\n");
}
#[test]
fn metadata_rejects_invalid_source_value() {
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, String::new()).is_err());
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "echo\0value".to_owned()).is_err());
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "x".repeat(MAX_VPNC_SCRIPT_SOURCE_VALUE + 1)).is_err());
}
}
+8
View File
@@ -4,6 +4,14 @@ use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
mod connection;
mod gateway_sessions;
pub mod network;
pub mod non_tunnel;
pub mod transport;
pub use connection::*;
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
+335
View File
@@ -0,0 +1,335 @@
use std::{fmt, time::Duration};
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use zeroize::Zeroize;
use crate::gateway::Gateway;
/// Network location and session mode are independent: an internal gateway can
/// still require a tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SessionMode {
Tunnel,
NonTunnel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MaintenanceState {
Authenticated,
Healthy,
Rejected,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GatewaySessionSummary {
pub gateway: Gateway,
pub mode: SessionMode,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub maintenance: MaintenanceState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum SessionEndReason {
InvalidCookie,
NetworkChanged,
AllMembersFailed,
AuthorizationRevoked,
}
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "GatewayAuthenticationFields")]
pub struct GatewayAuthentication {
cookie: String,
connection_type: String,
}
#[derive(Deserialize)]
struct GatewayAuthenticationFields {
cookie: String,
connection_type: String,
}
impl TryFrom<GatewayAuthenticationFields> for GatewayAuthentication {
type Error = anyhow::Error;
fn try_from(fields: GatewayAuthenticationFields) -> Result<Self, Self::Error> {
Self::new(fields.cookie, fields.connection_type)
}
}
impl GatewayAuthentication {
pub fn new(cookie: String, connection_type: String) -> anyhow::Result<Self> {
let authentication = Self {
cookie,
connection_type,
};
ensure!(
!authentication.cookie.is_empty() && authentication.cookie.len() <= 64 * 1024,
"Gateway authentication cookie is missing or too large"
);
let params = url::form_urlencoded::parse(authentication.cookie.as_bytes()).collect::<Vec<_>>();
for key in ["authcookie", "user"] {
let mut values = params.iter().filter(|(name, _)| name == key).map(|(_, value)| value);
ensure!(
values.next().is_some_and(|value| !value.is_empty()) && values.next().is_none(),
"Gateway authentication requires one nonempty {key}"
);
}
ensure!(
!authentication.connection_type.trim().is_empty()
&& authentication.connection_type != "(null)"
&& authentication.connection_type != "-1",
"Gateway connection type is missing"
);
Ok(authentication)
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn connection_type(&self) -> &str {
&self.connection_type
}
pub fn mode(&self) -> SessionMode {
if self.connection_type == "tunnel" {
SessionMode::Tunnel
} else {
SessionMode::NonTunnel
}
}
}
impl fmt::Debug for GatewayAuthentication {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GatewayAuthentication")
.field("cookie", &"<redacted>")
.field("mode", &self.mode())
.finish()
}
}
impl Drop for GatewayAuthentication {
fn drop(&mut self) {
self.cookie.zeroize();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", try_from = "InternalSessionPolicyFields")]
pub struct InternalSessionPolicy {
hip_interval_secs: u32,
collect_hip_data: bool,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct InternalSessionPolicyFields {
hip_interval_secs: u32,
collect_hip_data: bool,
}
impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
type Error = anyhow::Error;
fn try_from(fields: InternalSessionPolicyFields) -> Result<Self, Self::Error> {
Self::new(fields.hip_interval_secs, fields.collect_hip_data)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct AuthenticatedGateway {
pub gateway: Gateway,
pub authentication: GatewayAuthentication,
pub binding: Option<super::network::GatewayBinding>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum GatewayFailure {
AuthenticationRejected,
Unreachable,
TunnelFailed,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct GatewayFailureSummary {
pub gateway: Gateway,
pub failure: GatewayFailure,
}
/// Credentials remain in the interactive authentication owner; only issued
/// gateway cookies cross the runtime/service boundary.
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "ConnectionPlanFields")]
pub struct ConnectionPlan {
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
internal_detection: Option<super::network::InternalHostDetection>,
}
#[derive(Deserialize)]
struct ConnectionPlanFields {
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
internal_detection: Option<super::network::InternalHostDetection>,
}
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
type Error = anyhow::Error;
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
}
}
impl ConnectionPlan {
pub fn new(
members: Vec<AuthenticatedGateway>,
failures: Vec<GatewayFailureSummary>,
policy: InternalSessionPolicy,
) -> anyhow::Result<Self> {
ensure!(!members.is_empty(), "Connection plan has no authenticated gateways");
ensure!(
members.len() <= 64 && failures.len() <= 64,
"Connection plan exceeds its gateway limit"
);
let mode = members[0].authentication.mode();
ensure!(
members.iter().all(|member| member.authentication.mode() == mode),
"Mixed tunnel and non-tunnel sessions are unsupported"
);
ensure!(
mode != SessionMode::NonTunnel
|| members
.iter()
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
"Non-tunnel sessions require freshly discovered internal gateways"
);
ensure!(
members.len() == 1
|| members
.iter()
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
"Multiple authenticated gateways require an internal connection"
);
let mut hosts = std::collections::HashSet::new();
for member in &members {
if mode == SessionMode::NonTunnel {
let binding = member
.binding
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?;
binding.validate_server(member.gateway.server())?;
}
let host = crate::utils::normalize_server(member.gateway.server())?;
ensure!(hosts.insert(host), "Connection plan has duplicate gateways");
}
Ok(Self {
members,
failures,
policy,
internal_detection: None,
})
}
pub fn members(&self) -> &[AuthenticatedGateway] {
&self.members
}
pub fn failures(&self) -> &[GatewayFailureSummary] {
&self.failures
}
pub fn policy(&self) -> InternalSessionPolicy {
self.policy
}
pub fn mode(&self) -> SessionMode {
self.members[0].authentication.mode()
}
pub fn with_internal_detection(mut self, detection: Option<super::network::InternalHostDetection>) -> Self {
self.internal_detection = detection;
self
}
pub fn internal_detection(&self) -> Option<&super::network::InternalHostDetection> {
self.internal_detection.as_ref()
}
}
impl Default for InternalSessionPolicy {
fn default() -> Self {
Self {
hip_interval_secs: 3600,
collect_hip_data: true,
}
}
}
impl InternalSessionPolicy {
pub fn new(hip_interval_secs: u32, collect_hip_data: bool) -> anyhow::Result<Self> {
ensure!(hip_interval_secs > 0, "HIP report interval must be positive");
ensure!(
hip_interval_secs.checked_mul(1000).is_some(),
"HIP report interval exceeds the supported range"
);
Ok(Self {
hip_interval_secs,
collect_hip_data,
})
}
pub fn hip_interval(&self) -> Duration {
Duration::from_secs(u64::from(self.hip_interval_secs))
}
pub fn collect_hip_data(&self) -> bool {
self.collect_hip_data
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialization_enforces_authentication_invariants() {
for (cookie, mode) in [
("", "tunnel"),
("not-a-cookie", "tunnel"),
("user=alice", "tunnel"),
("authcookie=token", "tunnel"),
("authcookie=token&user=alice&user=bob", "tunnel"),
("authcookie=token&user=alice", ""),
] {
let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode});
assert!(serde_json::from_value::<GatewayAuthentication>(serialized).is_err());
}
let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap();
let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap();
assert_eq!(decoded.mode(), SessionMode::NonTunnel);
}
#[test]
fn deserialization_enforces_schedule_invariants() {
for interval in [0, u32::MAX] {
let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false});
assert!(serde_json::from_value::<InternalSessionPolicy>(serialized).is_err());
}
let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap();
let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap();
assert_eq!(decoded.hip_interval(), Duration::from_secs(3600));
}
}
@@ -0,0 +1,103 @@
use std::{
net::{Ipv4Addr, Ipv6Addr},
sync::Arc,
time::Duration,
};
use crate::gateway::Gateway;
use super::transport::GatewayTransport;
const LOGOUT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize, specta::Type)]
pub struct ClientAddresses {
pub ipv4: Option<Ipv4Addr>,
pub ipv6: Option<Ipv6Addr>,
}
/// One issued gateway authentication and its original request context. Session
/// mode governs execution, while every mode has the same cleanup owner.
pub struct GatewaySession {
pub gateway: Gateway,
pub transport: GatewayTransport,
pub addresses: ClientAddresses,
}
/// Owns issued gateway sessions independently of tunnel or HIP setup. Workers
/// borrow members; their owner joins them before consuming this ledger in logout.
/// This owner is deliberately not Clone: transfer or drain it exactly once.
#[derive(Default)]
pub struct GatewaySessions {
members: Vec<Arc<GatewaySession>>,
}
impl GatewaySessions {
pub fn new(members: Vec<GatewaySession>) -> Self {
Self {
members: members.into_iter().map(Arc::new).collect(),
}
}
pub fn register(&mut self, session: GatewaySession) {
self.members.push(Arc::new(session));
}
pub(crate) fn update(&mut self, session: GatewaySession) {
if let Some(member) = self
.members
.iter_mut()
.find(|member| member.gateway.server() == session.gateway.server())
{
*member = Arc::new(session);
}
}
pub fn is_empty(&self) -> bool {
self.members.is_empty()
}
/// Consume the local cleanup copies only after another owner has proved it
/// acquired responsibility for these issued sessions.
pub fn relinquish(self) {}
pub fn members(&self) -> &[Arc<GatewaySession>] {
&self.members
}
/// Transfer a selected tunnel login to OpenConnect immediately before its
/// native worker starts. OpenConnect owns the live reconnect cookie and logout.
pub fn relinquish_gateway(&mut self, server: &str) {
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
self.members.remove(index);
}
}
/// Call only after this member's worker has joined. Removing ownership before
/// awaiting logout prevents routine final cleanup from repeating the request.
pub async fn logout_gateway(&mut self, server: &str) {
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
logout(self.members.remove(index)).await;
}
}
pub async fn logout(self) {
let mut workers = tokio::task::JoinSet::new();
for session in self.members {
workers.spawn(logout(session));
}
while let Some(result) = workers.join_next().await {
if let Err(error) = result {
log::warn!("Gateway cleanup worker failed: {error}");
}
}
}
}
async fn logout(session: Arc<GatewaySession>) {
match tokio::time::timeout(LOGOUT_TIMEOUT, session.transport.logout()).await {
Ok(Ok(())) => {}
Ok(Err(error)) => log::warn!("Gateway logout failed: {error}"),
Err(_) => log::warn!("Gateway logout timed out"),
}
}
+223
View File
@@ -0,0 +1,223 @@
use std::net::{IpAddr, SocketAddr};
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use super::super::ClientAddresses;
/// Physical network context bound to the authenticated non-tunnel endpoint. Wire input is validated;
/// runtime transports use this context without performing another DNS lookup.
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "BindingFields", rename_all = "camelCase")]
pub struct GatewayBinding {
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct BindingFields {
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: Option<String>,
}
impl TryFrom<BindingFields> for GatewayBinding {
type Error = anyhow::Error;
fn try_from(fields: BindingFields) -> Result<Self, Self::Error> {
Self::new(
fields.endpoint,
fields.source,
fields.interface,
fields.interface_index,
fields.addresses,
fields.network_fingerprint,
)
}
}
impl GatewayBinding {
pub fn new(
endpoint: SocketAddr,
source: SocketAddr,
interface: String,
interface_index: u32,
addresses: ClientAddresses,
network_fingerprint: impl Into<Option<String>>,
) -> anyhow::Result<Self> {
let network_fingerprint = network_fingerprint.into();
ensure!(
network_fingerprint
.as_ref()
.is_none_or(|value| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())),
"Physical network fingerprint is invalid"
);
ensure!(
endpoint.port() != 0 && !endpoint.ip().is_unspecified() && !endpoint.ip().is_multicast(),
"Gateway endpoint is invalid"
);
ensure!(
source.port() == 0 && !source.ip().is_unspecified() && !source.ip().is_multicast(),
"Gateway source is invalid"
);
ensure!(
endpoint.is_ipv4() == source.is_ipv4(),
"Gateway address families differ"
);
ensure!(
!interface.is_empty() && interface.len() < 64 && !interface.contains('\0') && interface_index != 0,
"Gateway interface is invalid"
);
for address in [endpoint, source] {
if let SocketAddr::V6(address) = address {
ensure!(address.flowinfo() == 0, "Gateway IPv6 flow information is invalid");
ensure!(
address.scope_id() == 0 || address.scope_id() == interface_index,
"Gateway IPv6 scope differs from its interface"
);
ensure!(
!address.ip().is_unicast_link_local() || address.scope_id() == interface_index,
"Gateway IPv6 scope is missing"
);
}
}
match source.ip() {
IpAddr::V4(ip) => ensure!(
addresses.ipv4 == Some(ip),
"Gateway IPv4 source differs from its identity"
),
IpAddr::V6(ip) => ensure!(
addresses.ipv6 == Some(ip),
"Gateway IPv6 source differs from its identity"
),
}
Ok(Self {
endpoint,
source,
interface,
interface_index,
addresses,
network_fingerprint,
})
}
pub fn endpoint(&self) -> SocketAddr {
self.endpoint
}
pub fn source(&self) -> SocketAddr {
self.source
}
pub fn interface(&self) -> &str {
&self.interface
}
pub fn interface_index(&self) -> u32 {
self.interface_index
}
pub fn addresses(&self) -> ClientAddresses {
self.addresses
}
pub fn network_fingerprint(&self) -> Option<&str> {
self.network_fingerprint.as_deref()
}
pub fn validate_server(&self, server: &str) -> anyhow::Result<()> {
let origin = super::super::transport::gateway_origin(server)?;
ensure!(
origin.port_or_known_default() == Some(self.endpoint.port()),
"Gateway endpoint port differs"
);
let literal = match origin.host() {
Some(url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)),
Some(url::Host::Ipv6(ip)) => Some(IpAddr::V6(ip)),
_ => None,
};
if let Some(ip) = literal {
ensure!(self.endpoint.ip() == ip, "Literal gateway endpoint differs");
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ipv4_binding() -> GatewayBinding {
GatewayBinding::new(
"192.0.2.10:443".parse().unwrap(),
"192.0.2.5:0".parse().unwrap(),
"fixture".into(),
7,
ClientAddresses {
ipv4: Some("192.0.2.5".parse().unwrap()),
ipv6: None,
},
"a".repeat(64),
)
.unwrap()
}
#[test]
fn wire_input_rejects_inconsistent_network_identity() {
let original = serde_json::to_value(ipv4_binding()).unwrap();
for (field, value) in [
("source", serde_json::json!("192.0.2.6:0")),
("source", serde_json::json!("192.0.2.5:1234")),
("endpoint", serde_json::json!("[2001:db8::10]:443")),
("interfaceIndex", serde_json::json!(0)),
("networkFingerprint", serde_json::json!("not-a-fingerprint")),
] {
let mut invalid = original.clone();
invalid[field] = value;
assert!(
serde_json::from_value::<GatewayBinding>(invalid).is_err(),
"accepted {field}"
);
}
assert!(serde_json::from_value::<GatewayBinding>(original).is_ok());
}
#[test]
fn link_local_scope_survives_wire_round_trip_and_must_match_interface() {
let addresses = ClientAddresses {
ipv4: None,
ipv6: Some("fe80::5".parse().unwrap()),
};
let binding = GatewayBinding::new(
"[fe80::10%7]:443".parse().unwrap(),
"[fe80::5%7]:0".parse().unwrap(),
"fixture".into(),
7,
addresses,
"a".repeat(64),
)
.unwrap();
let value = serde_json::to_value(&binding).unwrap();
let restored: GatewayBinding = serde_json::from_value(value.clone()).unwrap();
assert_eq!(restored.source(), binding.source());
assert_eq!(restored.endpoint(), binding.endpoint());
for source in ["[fe80::5]:0", "[fe80::5%8]:0"] {
let mut invalid = value.clone();
invalid["source"] = serde_json::json!(source);
assert!(serde_json::from_value::<GatewayBinding>(invalid).is_err());
}
}
#[test]
fn server_origin_must_match_endpoint_port_and_literal_address() {
let binding = ipv4_binding();
assert!(binding.validate_server("gateway.example.com").is_ok());
assert!(binding.validate_server("192.0.2.10").is_ok());
assert!(binding.validate_server("192.0.2.11").is_err());
assert!(binding.validate_server("gateway.example.com:444").is_err());
}
}
+16
View File
@@ -0,0 +1,16 @@
pub(super) use super::bsd_routes::routes;
use super::*;
pub(super) fn scope_resolver_socket(
_socket: &tokio::net::UdpSocket,
_interface: &Interface,
_endpoint: SocketAddr,
) -> anyhow::Result<()> {
// resolv.conf has no per-interface resolver contexts. IPv6 zones are carried
// in the destination address instead.
anyhow::bail!("Interface-scoped resolver contexts are unsupported on BSD")
}
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
resolv_conf(control)
}
@@ -0,0 +1,60 @@
use super::*;
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos"))]
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
let mut routes = Vec::new();
for family in ["inet", "inet6"] {
routes.extend(parse_routes(&command("netstat", &["-rn", "-f", family], control)?)?);
}
Ok(routes)
}
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
let mut interface_column = None;
let mut routes = Vec::new();
for line in contents.lines() {
let fields = line.split_whitespace().collect::<Vec<_>>();
if fields.first() == Some(&"Destination") {
interface_column = Some(
fields
.iter()
.position(|field| matches!(*field, "Netif" | "Iface"))
.context("Route table has no interface column")?,
);
continue;
}
let Some(column) = interface_column else {
continue;
};
if fields.len() <= column {
continue;
}
// L/W entries are neighbor-cache or cloned host routes. Their presence,
// gateway MAC and expiry depend on traffic and must not cause rediscovery.
if fields[2].contains('L') || fields[2].contains('W') {
continue;
}
routes.push(RouteContext {
destination: fields[0].into(),
gateway: fields[1].into(),
interface: fields[column].into(),
table: String::new(),
metric: String::new(),
});
}
ensure!(interface_column.is_some(), "Route table header is missing");
Ok(routes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ignores_route_use_expiry_and_platform_column_positions() {
let darwin = parse_routes("Routing tables\nInternet:\nDestination Gateway Flags Netif Expire\ndefault 192.0.2.1 UGScg en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHLWI en0 123").unwrap();
let bsd = parse_routes("Destination Gateway Flags Refs Use Mtu Netif Expire\ndefault 192.0.2.1 UGS 4 22 1500 en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHL 0 33 1500 en0 99").unwrap();
assert_eq!(darwin, bsd);
assert_eq!(darwin.len(), 1);
assert!(parse_routes("unrecognized table").is_err());
}
}
@@ -0,0 +1,94 @@
use std::net::IpAddr;
use anyhow::ensure;
use serde::{Deserialize, Serialize};
use specta::Type;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(try_from = "DetectionFields")]
pub struct InternalHostDetection {
targets: Vec<DetectionTarget>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
struct DetectionTarget {
address: IpAddr,
hostname: String,
}
#[derive(Deserialize)]
struct DetectionFields {
targets: Vec<DetectionTarget>,
}
impl TryFrom<DetectionFields> for InternalHostDetection {
type Error = anyhow::Error;
fn try_from(fields: DetectionFields) -> anyhow::Result<Self> {
Self::new(
fields
.targets
.into_iter()
.map(|target| (target.address, target.hostname))
.collect(),
)
}
}
impl InternalHostDetection {
pub fn new(targets: Vec<(IpAddr, String)>) -> anyhow::Result<Self> {
ensure!(
!targets.is_empty() && targets.len() <= 2,
"Invalid internal detection target count"
);
let targets = targets
.into_iter()
.map(|(address, hostname)| {
validate_target(address, &hostname)?;
Ok(DetectionTarget { address, hostname })
})
.collect::<anyhow::Result<Vec<_>>>()?;
Ok(Self { targets })
}
pub async fn detect(&self, cancellation: &CancellationToken) -> anyhow::Result<bool> {
for target in &self.targets {
if super::native::detect(target.address, &target.hostname, cancellation).await? {
return Ok(true);
}
}
Ok(false)
}
}
pub(super) fn validate_target(address: IpAddr, hostname: &str) -> anyhow::Result<()> {
ensure!(
!address.is_unspecified() && !address.is_loopback() && !address.is_multicast(),
"Invalid internal detection address"
);
ensure!(
!hostname.is_empty()
&& hostname.len() <= 253
&& hostname.is_ascii()
&& hostname
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')),
"Invalid internal detection hostname"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detection_inputs_are_retained_and_validated_on_deserialization() {
let detection = InternalHostDetection::new(vec![("192.0.2.10".parse().unwrap(), "host.example".into())]).unwrap();
let value = serde_json::to_value(&detection).unwrap();
assert!(serde_json::from_value::<InternalHostDetection>(value).is_ok());
assert!(InternalHostDetection::new(vec![]).is_err());
assert!(InternalHostDetection::new(vec![("127.0.0.1".parse().unwrap(), "host.example".into())]).is_err());
}
}
+131
View File
@@ -0,0 +1,131 @@
use super::*;
#[cfg(target_os = "linux")]
pub(super) fn scope_resolver_socket(
socket: &tokio::net::UdpSocket,
interface: &Interface,
_endpoint: SocketAddr,
) -> anyhow::Result<()> {
socket2::SockRef::from(socket).bind_device(Some(interface.name.as_bytes()))?;
Ok(())
}
#[cfg(target_os = "linux")]
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
let mut routes = Vec::new();
for family in ["-4", "-6"] {
routes.extend(parse_routes(&command(
"ip",
&[family, "-j", "route", "show", "table", "all"],
control,
)?)?);
}
Ok(routes)
}
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
let value: Vec<serde_json::Value> = serde_json::from_str(contents)?;
let mut routes = Vec::new();
for route in value {
// Kernel cache and neighbor lifetimes are traffic, not network changes.
if route.get("cache").is_some() {
continue;
}
let Some(interface) = route["dev"].as_str() else {
continue;
};
let field = |name| {
route
.get(name)
.map(|value| value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()))
.unwrap_or_default()
};
routes.push(RouteContext {
destination: field("dst"),
gateway: field("gateway"),
interface: interface.into(),
table: field("table"),
metric: field("metric"),
});
}
Ok(routes)
}
#[cfg(target_os = "linux")]
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
let path = std::fs::canonicalize("/etc/resolv.conf")?;
if path.starts_with("/run/systemd/resolve") {
let dns = command("resolvectl", &["dns"], control)?;
let domains = command("resolvectl", &["domain"], control)?;
return parse_resolved(&dns, &domains);
}
resolv_conf(control)
}
fn parse_resolved(dns: &str, domains: &str) -> anyhow::Result<Vec<ResolverContext>> {
let mut resolvers = std::collections::BTreeMap::<Option<String>, ResolverContext>::new();
for (contents, is_dns) in [(dns, true), (domains, false)] {
for line in contents.lines().filter(|line| !line.trim().is_empty()) {
let (label, values) = line.split_once(':').context("Invalid systemd resolver output")?;
let interface = if label == "Global" {
None
} else {
let (_, name) = label.split_once('(').context("Invalid systemd resolver interface")?;
Some(
name
.strip_suffix(')')
.context("Invalid systemd resolver interface")?
.to_owned(),
)
};
let resolver = resolvers.entry(interface.clone()).or_insert_with(|| ResolverContext {
interface,
servers: Vec::new(),
domains: Vec::new(),
});
if is_dns {
for server in values.split_whitespace() {
server
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid systemd resolver address")?;
resolver.servers.push(server.to_owned());
}
} else {
resolver
.domains
.extend(values.split_whitespace().map(|domain| domain.to_ascii_lowercase()));
}
}
}
Ok(resolvers.into_values().collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn route_identity_retains_ipv6_and_ignores_cache() {
let routes = parse_routes(r#"[{"dst":"default","gateway":"2001:db8::1","dev":"eth0","metric":600,"table":"main"},{"dst":"2001:db8::5","dev":"eth0","cache":[]}]"#).unwrap();
assert_eq!(routes.len(), 1);
assert_eq!(routes[0].gateway, "2001:db8::1");
assert_eq!(routes[0].metric, "600");
}
#[test]
fn resolved_preserves_interface_domains_and_empty_global_context() {
let resolvers = parse_resolved(
"Global:\nLink 2 (eth0): 192.0.2.53\n\nLink 3 (tun0): 198.51.100.53\n",
"Global:\nLink 2 (eth0): CORP.EXAMPLE\nLink 3 (tun0): ~.\n",
)
.unwrap();
assert_eq!(resolvers.len(), 3);
assert!(
resolvers
.iter()
.any(|resolver| resolver.interface.as_deref() == Some("eth0")
&& resolver.domains.iter().any(|domain| domain == "corp.example"))
);
}
}
+89
View File
@@ -0,0 +1,89 @@
pub(super) use super::bsd_routes::routes;
use super::*;
pub(super) fn scope_resolver_socket(
socket: &tokio::net::UdpSocket,
interface: &Interface,
endpoint: SocketAddr,
) -> anyhow::Result<()> {
let index = std::num::NonZeroU32::new(interface.index).context("Resolver interface index is missing")?;
let socket = socket2::SockRef::from(socket);
if endpoint.is_ipv4() {
socket.bind_device_by_index_v4(Some(index))?;
} else {
socket.bind_device_by_index_v6(Some(index))?;
}
Ok(())
}
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
parse_resolvers(&command("scutil", &["--dns"], control)?)
}
fn parse_resolvers(contents: &str) -> anyhow::Result<Vec<ResolverContext>> {
let mut resolvers = Vec::new();
let mut current: Option<ResolverContext> = None;
for line in contents.lines().map(str::trim) {
if line.starts_with("resolver #") {
if let Some(resolver) = current.take() {
resolvers.push(resolver);
}
current = Some(ResolverContext {
interface: None,
servers: Vec::new(),
domains: Vec::new(),
});
continue;
}
let Some(resolver) = &mut current else {
continue;
};
let Some((field, value)) = line.split_once(':') else {
continue;
};
let field = field.trim();
let value = value.trim();
if field.starts_with("nameserver[") {
value
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid macOS resolver address")?;
resolver.servers.push(value.to_owned());
} else if field == "domain" || field.starts_with("search domain[") {
resolver.domains.push(value.to_ascii_lowercase());
} else if field == "if_index" {
if let Some((_, name)) = value.split_once('(') {
resolver.interface = Some(
name
.strip_suffix(')')
.context("Invalid macOS resolver interface")?
.to_owned(),
);
}
}
}
if let Some(resolver) = current {
resolvers.push(resolver);
}
Ok(resolvers)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolver_identity_is_scoped_and_ignores_reachability_counters() {
let a = parse_resolvers(
"resolver #1\n nameserver[0] : 192.0.2.53\n if_index : 4 (en0)\n search domain[0] : CORP.EXAMPLE\n reach : 2",
)
.unwrap();
let b = parse_resolvers(
"resolver #9\n search domain[0] : corp.example\n if_index : 4 (en0)\n nameserver[0] : 192.0.2.53\n reach : 3",
)
.unwrap();
assert_eq!(a, b);
assert_eq!(a[0].interface.as_deref(), Some("en0"));
}
}
+680
View File
@@ -0,0 +1,680 @@
use std::{
collections::BTreeSet,
io,
net::{IpAddr, SocketAddr},
time::Duration,
};
use anyhow::{Context, ensure};
use netdev::Interface;
use tokio_util::sync::CancellationToken;
use super::ClientAddresses;
use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
mod bsd;
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos", test))]
mod bsd_routes;
#[cfg(any(target_os = "linux", test))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
use bsd as platform;
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
mod binding;
mod detection;
pub mod native;
pub use binding::GatewayBinding;
pub use detection::InternalHostDetection;
const INSPECTION_TIMEOUT: Duration = Duration::from_secs(5);
const POLL_INTERVAL: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct InterfaceIdentity {
index: u32,
name: String,
mac: Option<String>,
flags: u32,
addresses: BTreeSet<(String, u32)>,
}
impl From<&Interface> for InterfaceIdentity {
fn from(interface: &Interface) -> Self {
let mut addresses = interface
.ipv4
.iter()
.map(|ip| (ip.to_string(), 0))
.collect::<BTreeSet<_>>();
addresses.extend(interface.ipv6.iter().enumerate().map(|(index, ip)| {
(
ip.to_string(),
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
)
}));
Self {
index: interface.index,
name: interface.name.clone(),
mac: interface.mac_addr.map(|mac| mac.to_string()),
flags: interface.flags,
addresses,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct RouteContext {
destination: String,
gateway: String,
interface: String,
table: String,
metric: String,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct ResolverContext {
interface: Option<String>,
servers: Vec<String>,
domains: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
struct NetworkSnapshot {
interfaces: BTreeSet<InterfaceIdentity>,
routes: BTreeSet<RouteContext>,
resolvers: Vec<ResolverContext>,
}
/// Captured before this attempt installs a tunnel. Interface counters and
/// timestamps do not participate in identity; routes and resolver context do.
#[derive(Clone)]
pub struct PhysicalNetwork {
snapshot: NetworkSnapshot,
interfaces: Vec<Interface>,
}
impl PhysicalNetwork {
pub async fn bind_authenticated_endpoint(
&self,
server: &str,
endpoint: SocketAddr,
disable_ipv6: bool,
cancellation: &CancellationToken,
) -> anyhow::Result<GatewayBinding> {
self.ensure_current(cancellation).await?;
let binding = resolve_binding(
&self.interfaces,
Some(self.fingerprint()?),
server,
disable_ipv6,
cancellation,
endpoint,
)
.await?;
self.ensure_current(cancellation).await?;
Ok(binding)
}
pub async fn validate_internal_binding(
&self,
binding: &GatewayBinding,
detection: Option<&InternalHostDetection>,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.validate_binding(binding, cancellation).await?;
physical_interface_for_source(&self.interfaces, binding.source(), binding.endpoint())?;
self.validate_internal(detection, cancellation).await
}
pub async fn validate_internal(
&self,
detection: Option<&InternalHostDetection>,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.ensure_current(cancellation).await?;
let mut resolver_count = 0;
for resolver in &self.snapshot.resolvers {
if resolver.servers.is_empty() {
continue;
}
for server in &resolver.servers {
let endpoint = resolver_endpoint(server, resolver.interface.as_deref(), &self.interfaces)?;
ensure!(
!endpoint.ip().is_loopback() && !endpoint.ip().is_unspecified(),
"Unattributed local DNS stub is unsupported"
);
let socket = tokio::net::UdpSocket::bind(if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }).await?;
if let Some(name) = &resolver.interface {
let interface = self
.interfaces
.iter()
.find(|interface| interface.name == *name)
.context("Configured resolver interface is missing")?;
platform::scope_resolver_socket(&socket, interface, endpoint)?;
}
socket.connect(endpoint).await?;
let interface = physical_interface_for_source(&self.interfaces, socket.local_addr()?, endpoint)?;
ensure!(
resolver.interface.as_deref().is_none_or(|name| name == interface.name),
"Resolver route differs from its configured interface"
);
resolver_count += 1;
}
}
ensure!(resolver_count > 0, "Physical resolver context is unavailable");
if let Some(detection) = detection {
ensure!(
detection.detect(cancellation).await?,
"Internal host detection no longer matches"
);
}
self.ensure_current(cancellation).await
}
pub async fn capture_controlled(cancellation: &CancellationToken) -> anyhow::Result<Self> {
let cancellation = cancellation.clone();
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(io::ErrorKind::Interrupted, "Network capture cancelled"));
}
budget.check()
};
Self::capture(&check)
})
.await?
}
pub async fn validate_binding(
&self,
binding: &GatewayBinding,
cancellation: &CancellationToken,
) -> anyhow::Result<()> {
self.ensure_current(cancellation).await?;
ensure!(
binding.network_fingerprint() == Some(self.fingerprint()?.as_str()),
"Physical network changed since authentication"
);
let interface = self
.interfaces
.iter()
.find(|interface| interface.index == binding.interface_index() && interface.name == binding.interface())
.context("Authenticated gateway interface is no longer present")?;
let addresses = binding.addresses();
ensure!(
addresses
.ipv4
.is_none_or(|ip| interface.ipv4.iter().any(|address| address.addr() == ip)),
"Authenticated IPv4 address changed"
);
ensure!(
addresses
.ipv6
.is_none_or(|ip| interface.ipv6.iter().any(|address| address.addr() == ip)),
"Authenticated IPv6 address changed"
);
Ok(())
}
fn fingerprint(&self) -> anyhow::Result<String> {
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
}
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
control.check()?;
let mut interfaces = netdev::get_interfaces();
for interface in &mut interfaces {
interface.ipv4.sort();
// The address and its zone must move together when native enumeration
// order changes between captures.
let mut ipv6 = interface
.ipv6
.iter()
.copied()
.enumerate()
.map(|(index, address)| {
(
address,
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
)
})
.collect::<Vec<_>>();
ipv6.sort();
interface.ipv6 = ipv6.iter().map(|(address, _)| *address).collect();
interface.ipv6_scope_ids = ipv6.into_iter().map(|(_, scope)| scope).collect();
}
let snapshot = snapshot(&interfaces, control)?;
control.check()?;
Ok(Self { snapshot, interfaces })
}
/// Validate endpoint selection against the captured network. The inspection
/// is joined even when cancellation occurs, so native collectors cannot outlive
/// the connection attempt.
pub async fn ensure_current(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let current = inspect(cancellation.clone()).await?;
ensure!(
current == self.snapshot,
"Physical network changed during gateway setup"
);
Ok(())
}
/// The owner must cancel and await this monitor, including its blocking
/// inspection. Dropping a selected future would detach the native collector.
pub async fn wait_for_change(
&self,
detection: Option<InternalHostDetection>,
cancellation: CancellationToken,
) -> anyhow::Result<bool> {
loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => return Ok(false),
_ = tokio::time::sleep(POLL_INTERVAL) => {},
}
let current = self.validate_internal(detection.as_ref(), &cancellation).await;
if cancellation.is_cancelled() {
return Ok(false);
}
if current.is_err() {
return Ok(true);
}
}
}
}
async fn resolve_binding(
interfaces: &[Interface],
fingerprint: Option<String>,
server: &str,
disable_ipv6: bool,
cancellation: &CancellationToken,
authenticated_endpoint: SocketAddr,
) -> anyhow::Result<GatewayBinding> {
let origin = super::transport::gateway_origin(server)?;
let host = origin.host_str().context("Gateway host is missing")?;
let port = origin.port_or_known_default().context("Gateway port is missing")?;
let literal = literal_gateway_address(&origin)?;
let endpoints = if let Some(ip) = literal {
vec![SocketAddr::new(ip, port)]
} else {
native::resolve(host, port, disable_ipv6, cancellation).await?
};
ensure!(
endpoints.contains(&authenticated_endpoint),
"Authenticated peer differs from the gateway's current DNS addresses; check for a proxy or changed DNS answer"
);
let endpoint = authenticated_endpoint;
ensure!(
!(disable_ipv6 && endpoint.is_ipv6()),
"Authenticated gateway uses disabled IPv6"
);
let bind = if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
let socket = tokio::net::UdpSocket::bind(bind).await?;
socket.connect(endpoint).await?;
let mut source_address = socket.local_addr()?;
source_address.set_port(0);
let source = source_address.ip();
let interface = physical_interface_for_source(interfaces, source_address, endpoint)?;
let ipv4 = match source {
IpAddr::V4(ip) => Some(ip),
_ => interface
.ipv4
.iter()
.map(|ip| ip.addr())
.find(|ip| !ip.is_loopback() && !ip.is_unspecified()),
};
let ipv6 = if disable_ipv6 {
None
} else {
match source {
IpAddr::V6(ip) => Some(ip),
_ => interface
.ipv6
.iter()
.map(|ip| ip.addr())
.find(|ip| !ip.is_loopback() && !ip.is_unspecified() && !ip.is_unicast_link_local()),
}
};
if let std::net::SocketAddr::V6(address) = &mut source_address {
if address.ip().is_unicast_link_local() && address.scope_id() == 0 {
address.set_scope_id(interface.index);
}
}
GatewayBinding::new(
endpoint,
source_address,
interface.name.clone(),
interface.index,
ClientAddresses { ipv4, ipv6 },
fingerprint.clone(),
)
}
// Default-route inventories include scoped, backup, and unrelated address-family
// routes. Attribute each actual destination by its selected source instead.
fn physical_interface_for_source(
interfaces: &[Interface],
source: SocketAddr,
endpoint: SocketAddr,
) -> anyhow::Result<&Interface> {
let mut scope = None;
for address in [source, endpoint] {
if let SocketAddr::V6(address) = address {
if address.scope_id() != 0 {
ensure!(
scope.is_none_or(|scope| scope == address.scope_id()),
"Network source and destination have different interface scopes"
);
scope = Some(address.scope_id());
}
}
}
let source = source.ip();
ensure!(
!source.is_unspecified() && !source.is_loopback(),
"Network route has no physical source address"
);
let mut matches = interfaces.iter().filter(|interface| {
scope.is_none_or(|scope| scope == interface.index)
&& (interface.ipv4.iter().any(|ip| IpAddr::V4(ip.addr()) == source)
|| interface.ipv6.iter().any(|ip| IpAddr::V6(ip.addr()) == source))
});
let interface = matches
.next()
.context("Network route has no matching physical interface")?;
ensure!(
matches.next().is_none(),
"Network route has ambiguous physical interfaces"
);
ensure!(
matches!(
interface.if_type,
netdev::prelude::InterfaceType::Ethernet
| netdev::prelude::InterfaceType::Wireless80211
| netdev::prelude::InterfaceType::FastEthernetT
| netdev::prelude::InterfaceType::FastEthernetFx
| netdev::prelude::InterfaceType::GigabitEthernet
),
"Network route uses an unsupported physical interface: {}",
interface.name
);
Ok(interface)
}
fn resolver_endpoint(server: &str, interface: Option<&str>, interfaces: &[Interface]) -> anyhow::Result<SocketAddr> {
let (address, zone) = server
.split_once('%')
.map_or((server, None), |(ip, zone)| (ip, Some(zone)));
let ip: IpAddr = address.parse().context("Invalid resolver address")?;
let mut endpoint = SocketAddr::new(ip, 53);
if let SocketAddr::V6(address) = &mut endpoint {
let zone = if zone.is_none() && address.ip().is_unicast_link_local() {
interface
} else {
zone
};
if let Some(zone) = zone {
let index = interfaces
.iter()
.find(|candidate| candidate.name == zone || candidate.index.to_string() == zone)
.context("Resolver IPv6 zone has no matching interface")?
.index;
address.set_scope_id(index);
}
ensure!(
!address.ip().is_unicast_link_local() || address.scope_id() != 0,
"Link-local resolver has no interface scope"
);
} else {
ensure!(zone.is_none(), "IPv4 resolver cannot have an interface scope");
}
Ok(endpoint)
}
async fn inspect(cancellation: CancellationToken) -> anyhow::Result<NetworkSnapshot> {
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Network inspection cancelled",
));
}
budget.check()
};
let result = snapshot(&netdev::get_interfaces(), &check)?;
check()?;
Ok(result)
})
.await?
}
fn literal_gateway_address(origin: &url::Url) -> anyhow::Result<Option<IpAddr>> {
Ok(match origin.host().context("Gateway host is missing")? {
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
url::Host::Domain(_) => None,
})
}
fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow::Result<NetworkSnapshot> {
control.check()?;
Ok(NetworkSnapshot {
interfaces: interfaces.iter().map(InterfaceIdentity::from).collect(),
routes: platform::routes(control)?.into_iter().collect(),
resolvers: platform::resolvers(control)?,
})
}
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
let output = CollectorCommands::new(control)
.run(name, args)?
.with_context(|| format!("Required network tool {name} is unavailable"))?;
ensure!(output.status.success(), "Network tool {name} failed");
String::from_utf8(output.stdout).context("Network tool output is not UTF-8")
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn resolv_conf(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
control.check()?;
let file = std::fs::File::open("/etc/resolv.conf")?;
use std::io::Read;
let mut contents = String::new();
file.take(64 * 1024 + 1).read_to_string(&mut contents)?;
ensure!(contents.len() <= 64 * 1024, "Resolver configuration is too large");
control.check()?;
Ok(vec![parse_resolv_conf(&contents)?])
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn parse_resolv_conf(contents: &str) -> anyhow::Result<ResolverContext> {
let mut resolver = ResolverContext {
interface: None,
servers: Vec::new(),
domains: Vec::new(),
};
for line in contents.lines() {
let line = line.split(['#', ';']).next().unwrap_or_default();
let mut fields = line.split_whitespace();
match fields.next() {
Some("nameserver") => {
if let Some(server) = fields.next() {
// IPv6 zone identifiers are retained for scoped physical resolvers.
server
.split('%')
.next()
.unwrap_or_default()
.parse::<IpAddr>()
.context("Invalid resolver address")?;
resolver.servers.push(server.to_owned());
}
}
Some("search" | "domain") => resolver
.domains
.extend(fields.map(|domain| domain.to_ascii_lowercase())),
_ => {}
}
}
Ok(resolver)
}
#[cfg(test)]
mod tests {
use super::*;
fn ethernet(name: &str, index: u32, address: &str) -> Interface {
let mut interface = Interface::dummy();
interface.name = name.into();
interface.index = index;
interface.if_type = netdev::prelude::InterfaceType::Ethernet;
interface.ipv4 = vec![address.parse().unwrap()];
interface.ipv6 = vec!["fe80::1/64".parse().unwrap()];
interface
}
#[test]
fn attributes_each_destination_without_requiring_a_single_uplink() {
let ethernet = ethernet("en0", 7, "192.0.2.10/24");
let mut wifi = ethernet.clone();
wifi.name = "en1".into();
wifi.index = 8;
wifi.if_type = netdev::prelude::InterfaceType::Wireless80211;
wifi.ipv4 = vec!["198.51.100.10/24".parse().unwrap()];
let mut tunnel = Interface::dummy();
tunnel.name = "utun0".into();
tunnel.index = 9;
tunnel.ipv4 = vec!["10.0.0.1/24".parse().unwrap()];
let interfaces = [ethernet, wifi, tunnel];
for (source, endpoint, expected) in [
("192.0.2.10:0", "203.0.113.1:443", "en0"),
("198.51.100.10:0", "198.51.100.53:53", "en1"),
("[fe80::1%8]:0", "[fe80::53%8]:53", "en1"),
] {
assert_eq!(
physical_interface_for_source(&interfaces, source.parse().unwrap(), endpoint.parse().unwrap())
.unwrap()
.name,
expected
);
}
// Virtual interfaces may coexist, but must never supply the selected source.
assert!(
physical_interface_for_source(
&interfaces,
"10.0.0.1:0".parse().unwrap(),
"10.0.0.53:53".parse().unwrap()
)
.is_err()
);
// Identical link-local addresses without scope are ambiguous.
assert!(
physical_interface_for_source(
&interfaces,
"[fe80::1]:0".parse().unwrap(),
"[fe80::53]:53".parse().unwrap()
)
.is_err()
);
assert!(
physical_interface_for_source(
&interfaces,
"[fe80::1%7]:0".parse().unwrap(),
"[fe80::53%8]:53".parse().unwrap()
)
.is_err()
);
}
#[test]
fn rejects_ambiguous_or_unattributed_sources() {
let interfaces = [ethernet("en0", 7, "192.0.2.10/24"), ethernet("en1", 8, "192.0.2.10/24")];
for source in ["192.0.2.10:0", "192.0.2.11:0", "127.0.0.1:0", "0.0.0.0:0"] {
assert!(
physical_interface_for_source(&interfaces, source.parse().unwrap(), "192.0.2.53:53".parse().unwrap()).is_err()
);
}
}
#[test]
fn resolver_zones_support_native_names_and_numeric_indices() {
let interfaces = [ethernet("en0", 7, "192.0.2.10/24")];
let expected: SocketAddr = "[fe80::53%7]:53".parse().unwrap();
assert_eq!(resolver_endpoint("fe80::53%en0", None, &interfaces).unwrap(), expected);
assert_eq!(resolver_endpoint("fe80::53%7", None, &interfaces).unwrap(), expected);
assert_eq!(
resolver_endpoint("fe80::53", Some("en0"), &interfaces).unwrap(),
expected
);
assert_eq!(
resolver_endpoint("192.0.2.53", Some("en0"), &interfaces).unwrap(),
"192.0.2.53:53".parse().unwrap()
);
for server in ["fe80::53", "fe80::53%missing", "fe80::53%8", "192.0.2.53%en0"] {
assert!(
resolver_endpoint(server, None, &interfaces).is_err(),
"accepted {server}"
);
}
}
#[test]
fn bracketed_ipv6_gateway_is_a_literal_endpoint() {
let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap();
assert_eq!(
literal_gateway_address(&origin).unwrap(),
Some("2001:db8::1".parse().unwrap())
);
}
#[test]
fn resolver_order_comments_and_case_do_not_change_network_identity() {
assert_eq!(
parse_resolv_conf("nameserver 192.0.2.53\nsearch CORP.EXAMPLE\n# comment").unwrap(),
parse_resolv_conf("search corp.example\nnameserver 192.0.2.53 # DHCP\n").unwrap()
);
assert_ne!(
parse_resolv_conf("nameserver 192.0.2.53").unwrap(),
parse_resolv_conf("nameserver 192.0.2.54").unwrap()
);
}
#[test]
fn interface_identity_ignores_counters_and_address_enumeration_order() {
let mut interface = Interface::dummy();
interface.index = 7;
interface.name = "bridge0".into();
interface.ipv4 = vec!["192.0.2.10/24".parse().unwrap(), "192.0.2.11/24".parse().unwrap()];
let original = InterfaceIdentity::from(&interface);
interface.ipv4.reverse();
interface.mtu = Some(1200);
interface.default = !interface.default;
assert_eq!(original, InterfaceIdentity::from(&interface));
interface.index = 8;
assert_ne!(original, InterfaceIdentity::from(&interface));
}
}
#[cfg(test)]
pub(crate) fn test_binding() -> GatewayBinding {
GatewayBinding::new(
"192.0.2.10:443".parse().unwrap(),
"192.0.2.5:0".parse().unwrap(),
"fixture".into(),
1,
ClientAddresses {
ipv4: Some("192.0.2.5".parse().unwrap()),
ipv6: None,
},
"0".repeat(64),
)
.unwrap()
}
+245
View File
@@ -0,0 +1,245 @@
use std::{net::SocketAddr, path::PathBuf};
use anyhow::{Context, ensure};
use dns_lookup::{AddrFamily, AddrInfoHints, SockType, getaddrinfo};
use tokio_util::sync::CancellationToken;
use super::*;
const MAX_ADDRESSES: usize = 64;
#[doc(hidden)]
pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Result<bool> {
super::detection::validate_target(address, hostname)?;
Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname)))
}
pub(super) async fn detect(
address: std::net::IpAddr,
hostname: &str,
cancellation: &CancellationToken,
) -> anyhow::Result<bool> {
super::detection::validate_target(address, hostname)?;
let args = vec![
"detect-internal-host".into(),
"--address".into(),
address.to_string(),
"--hostname".into(),
hostname.into(),
];
let output = run_helper(common::binary_paths::gpclient(), args, cancellation.clone()).await?;
serde_json::from_slice(&output).context("Invalid internal detection helper response")
}
/// Entry point for gpclient's isolated native resolver helper. This blocking
/// function must run in the child process, never a connection runtime thread.
#[doc(hidden)]
pub fn lookup_in_helper(host: &str, port: u16, disable_ipv6: bool) -> anyhow::Result<Vec<SocketAddr>> {
validate_host(host, port)?;
let hints = AddrInfoHints {
address: if disable_ipv6 { AddrFamily::Inet.into() } else { 0 },
socktype: SockType::Stream.into(),
..AddrInfoHints::default()
};
let service = port.to_string();
let mut addresses = Vec::new();
for result in getaddrinfo(Some(host), Some(&service), Some(hints)).map_err(io::Error::from)? {
let address = result?.sockaddr;
if !addresses.contains(&address) {
ensure!(
addresses.len() < MAX_ADDRESSES,
"Native resolver returned too many gateway addresses"
);
addresses.push(address);
}
}
validate_addresses(&addresses, port, disable_ipv6)?;
Ok(addresses)
}
pub(super) async fn resolve(
host: &str,
port: u16,
disable_ipv6: bool,
cancellation: &CancellationToken,
) -> anyhow::Result<Vec<SocketAddr>> {
validate_host(host, port)?;
let mut args = vec!["resolve-gateway".into(), host.into(), "--port".into(), port.to_string()];
if disable_ipv6 {
args.push("--disable-ipv6".into());
}
run_resolver(
common::binary_paths::gpclient(),
args,
port,
disable_ipv6,
cancellation.clone(),
)
.await
}
async fn run_resolver(
executable: PathBuf,
args: Vec<String>,
port: u16,
disable_ipv6: bool,
cancellation: CancellationToken,
) -> anyhow::Result<Vec<SocketAddr>> {
let output = run_helper(executable, args, cancellation).await?;
let addresses: Vec<SocketAddr> = serde_json::from_slice(&output).context("Invalid resolver helper response")?;
validate_addresses(&addresses, port, disable_ipv6)?;
Ok(addresses)
}
async fn run_helper(
executable: PathBuf,
args: Vec<String>,
cancellation: CancellationToken,
) -> anyhow::Result<Vec<u8>> {
// Await the owned worker even on cancellation. CollectorCommands kills and
// waits for the helper process and any descendants before returning.
tokio::task::spawn_blocking(move || {
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
let check = || {
if cancellation.is_cancelled() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Gateway resolution cancelled",
));
}
budget.check()
};
let args = args.iter().map(String::as_str).collect::<Vec<_>>();
let output = CollectorCommands::new(&check)
.run_executable(&executable, &args)?
.context("Native resolver helper is unavailable")?;
check()?;
ensure!(output.status.success(), "Native gateway resolution failed");
Ok(output.stdout)
})
.await?
}
fn validate_host(host: &str, port: u16) -> anyhow::Result<()> {
ensure!(port != 0, "Gateway port is zero");
ensure!(
!host.is_empty() && host.len() <= 253 && !host.contains('\0') && !host.contains(['/', ':']),
"Invalid gateway hostname"
);
Ok(())
}
fn validate_addresses(addresses: &[SocketAddr], port: u16, disable_ipv6: bool) -> anyhow::Result<()> {
ensure!(
!addresses.is_empty() && addresses.len() <= MAX_ADDRESSES,
"Invalid gateway address count"
);
ensure!(
addresses.iter().all(|address| {
address.port() == port && !address.ip().is_unspecified() && (!disable_ipv6 || address.is_ipv4())
}),
"Invalid gateway address from resolver helper"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn actual_helper_output_is_validated_before_admission() {
let addresses = run_resolver(
"/bin/sh".into(),
vec!["-c".into(), "printf '[\"192.0.2.1:443\"]'".into()],
443,
true,
CancellationToken::new(),
)
.await
.unwrap();
assert_eq!(addresses, vec!["192.0.2.1:443".parse::<SocketAddr>().unwrap()]);
assert!(
run_resolver(
"/bin/sh".into(),
vec!["-c".into(), "printf '[\"192.0.2.1:444\"]'".into()],
443,
true,
CancellationToken::new(),
)
.await
.is_err()
);
}
#[tokio::test]
async fn cancellation_kills_and_joins_the_running_resolver_process() {
let file = tempfile::NamedTempFile::new().unwrap();
let path = file.path().to_owned();
let cancellation = CancellationToken::new();
let worker = tokio::spawn(run_resolver(
"/bin/sh".into(),
vec![
"-c".into(),
"printf '%s' \"$$\" > \"$1\"; sleep 30 & wait".into(),
"resolver-test".into(),
path.to_string_lossy().into_owned(),
],
443,
false,
cancellation.clone(),
));
let pid = tokio::time::timeout(Duration::from_secs(2), async {
loop {
if let Ok(pid) = std::fs::read_to_string(&path).unwrap().parse::<i32>() {
break pid;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
cancellation.cancel();
let error = tokio::time::timeout(Duration::from_secs(1), worker)
.await
.unwrap()
.unwrap()
.unwrap_err();
assert_eq!(
error.downcast::<io::Error>().unwrap().kind(),
io::ErrorKind::Interrupted
);
assert_eq!(
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
Err(nix::errno::Errno::ESRCH)
);
}
#[test]
fn native_lookup_preserves_port_and_ipv4_policy() {
let addresses = lookup_in_helper("localhost", 444, true).unwrap();
assert!(
addresses
.iter()
.all(|address| address.is_ipv4() && address.ip().is_loopback() && address.port() == 444)
);
}
#[test]
fn helper_response_validation_retains_ipv6_scope_and_rejects_wrong_port() {
let addresses = vec!["[fe80::1%7]:443".parse().unwrap(), "192.0.2.1:443".parse().unwrap()];
validate_addresses(&addresses, 443, false).unwrap();
assert_eq!(
serde_json::from_str::<Vec<SocketAddr>>(&serde_json::to_string(&addresses).unwrap()).unwrap(),
addresses
);
assert!(validate_addresses(&addresses, 444, false).is_err());
assert!(validate_addresses(&addresses, 443, true).is_err());
}
#[test]
fn rejects_invalid_helper_requests_before_lookup() {
assert!(lookup_in_helper("gateway.example/path", 443, false).is_err());
assert!(lookup_in_helper("gateway.example", 0, false).is_err());
}
}
+316
View File
@@ -0,0 +1,316 @@
use std::{
future::Future,
io,
pin::Pin,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use zeroize::{Zeroize, Zeroizing};
use crate::{gateway::Gateway, process::collection::CollectionControl};
use super::{
GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason,
SessionMode, transport::GatewayRequestError,
};
const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60);
/// This request is deliberately independent of OpenConnect's callback/FFI types.
#[derive(Clone)]
pub struct SessionHipRequest {
pub gateway: Gateway,
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub collect_posture: bool,
}
impl Drop for SessionHipRequest {
fn drop(&mut self) {
self.cookie.zeroize();
}
}
pub struct SessionCollectionControl {
cancellation: CancellationToken,
deadline: Instant,
}
impl CollectionControl for SessionCollectionControl {
fn check(&self) -> io::Result<()> {
if self.cancellation.is_cancelled() {
Err(io::Error::new(io::ErrorKind::Interrupted, "HIP collection cancelled"))
} else if Instant::now() >= self.deadline {
Err(io::Error::new(io::ErrorKind::TimedOut, "HIP collection timed out"))
} else {
Ok(())
}
}
}
pub type SessionReportProducer =
dyn Fn(&SessionHipRequest, &SessionCollectionControl) -> io::Result<String> + Send + Sync;
pub type SessionReportObserver = dyn Fn(&SessionHipRequest, &str) + Send + Sync;
pub type SessionStatusObserver = dyn Fn(GatewaySessionSummary) + Send + Sync;
pub type SessionNetworkValidator =
dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> + Send + Sync;
#[derive(Clone)]
pub struct SessionCallbacks {
pub produce_report: Arc<SessionReportProducer>,
pub report_submitted: Arc<SessionReportObserver>,
pub status_changed: Arc<SessionStatusObserver>,
pub validate_network: Arc<SessionNetworkValidator>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionExit {
Disconnected,
Failed(SessionEndReason),
}
/// Owns maintenance workers until they have stopped. The session owner retains
/// its ledger and logs out after joining every worker. Interactive authentication
/// also belongs to that owner. Cancel and await this future, never abort/drop it:
/// blocking collectors must finish before cleanup releases their resources.
pub async fn maintain_non_tunnel_sessions(
sessions: &mut GatewaySessions,
policy: InternalSessionPolicy,
mut callbacks: SessionCallbacks,
cancellation: CancellationToken,
network_change: impl Future<Output = SessionEndReason>,
) -> anyhow::Result<SessionExit> {
anyhow::ensure!(!sessions.is_empty(), "Non-tunnel session set is empty");
anyhow::ensure!(
sessions
.members()
.iter()
.all(|session| session.transport.authentication().mode() == SessionMode::NonTunnel),
"Tunnel member supplied to non-tunnel runtime"
);
let workers_cancel = cancellation.child_token();
let observer = callbacks.status_changed.clone();
let status_gate = Arc::new(Mutex::new(()));
let gate = status_gate.clone();
let cancelled = workers_cancel.clone();
let worker_observer = observer.clone();
callbacks.status_changed = Arc::new(move |summary| {
let _guard = gate.lock().unwrap_or_else(|error| error.into_inner());
if !cancelled.is_cancelled() {
worker_observer(summary);
}
});
let mut workers = JoinSet::new();
for session in sessions.members() {
let session = session.clone();
let callbacks = callbacks.clone();
let cancellation = workers_cancel.clone();
workers.spawn(async move {
let server = session.gateway.server().to_owned();
(server, maintain_member(session, policy, callbacks, cancellation).await)
});
}
tokio::pin!(network_change);
let mut worker_failure = None;
let outcome = loop {
tokio::select! {
biased;
_ = cancellation.cancelled() => break SessionExit::Disconnected,
reason = &mut network_change => break SessionExit::Failed(reason),
result = workers.join_next() => match result {
Some(Ok((_, MemberExit::Terminal(reason)))) => break SessionExit::Failed(reason),
Some(Ok((server, MemberExit::Rejected))) => {
sessions.logout_gateway(&server).await;
if workers.is_empty() { break SessionExit::Failed(SessionEndReason::AllMembersFailed); }
},
Some(Ok((_, MemberExit::Cancelled))) => {},
Some(Err(error)) => { worker_failure = Some(error); break SessionExit::Disconnected; },
None => break SessionExit::Failed(SessionEndReason::AllMembersFailed),
},
}
};
workers_cancel.cancel();
if matches!(outcome, SessionExit::Failed(_)) || worker_failure.is_some() {
// Invalidate advertised health before waiting for collectors or remote
// cleanup. Cancellation prevents workers from publishing Healthy afterwards.
let _guard = status_gate.lock().unwrap_or_else(|error| error.into_inner());
for session in sessions.members() {
observer(GatewaySessionSummary {
gateway: session.gateway.clone(),
mode: SessionMode::NonTunnel,
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
maintenance: MaintenanceState::Rejected,
});
}
}
// Do not abort workers: a blocking collector must observe cancellation and be
// joined before approval/identity resources can be released by the caller.
while let Some(result) = workers.join_next().await {
if let Err(error) = result {
worker_failure.get_or_insert(error);
}
}
if let Some(error) = worker_failure {
return Err(error.into());
}
// Deliberate disconnect wins even when it arrives during coordinated cleanup.
if cancellation.is_cancelled() {
Ok(SessionExit::Disconnected)
} else {
Ok(outcome)
}
}
async fn maintain_member(
session: Arc<GatewaySession>,
policy: InternalSessionPolicy,
callbacks: SessionCallbacks,
cancellation: CancellationToken,
) -> MemberExit {
let request = SessionHipRequest {
gateway: session.gateway.clone(),
cookie: session.transport.authentication().cookie().into(),
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
md5: session.transport.hip_token(),
collect_posture: policy.collect_hip_data(),
};
let status = |maintenance| {
if !cancellation.is_cancelled() {
(callbacks.status_changed)(GatewaySessionSummary {
gateway: session.gateway.clone(),
mode: SessionMode::NonTunnel,
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
maintenance,
});
}
};
status(MaintenanceState::Authenticated);
loop {
if (callbacks.validate_network)(cancellation.clone()).await.is_err() {
return MemberExit::Terminal(SessionEndReason::NetworkChanged);
}
let sent_at = tokio::time::Instant::now();
let check = tokio::select! {
biased;
_ = cancellation.cancelled() => return MemberExit::Cancelled,
result = session.transport.check_hip(session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result,
};
let (result, delay) = match check {
Ok(check) => {
let result = if check.report_needed {
collect_and_submit(&session, &request, &callbacks, &cancellation).await
} else {
Ok(())
};
(result, check.delay)
}
Err(error) => (Err(MemberError::Gateway(error)), Duration::ZERO),
};
let next_check = match result {
Ok(()) => {
if cancellation.is_cancelled() {
return MemberExit::Cancelled;
}
status(MaintenanceState::Healthy);
let Some(next_check) = sent_at
.checked_add(policy.hip_interval())
.and_then(|time| time.checked_add(delay))
else {
status(MaintenanceState::Rejected);
return MemberExit::Rejected;
};
next_check
}
Err(MemberError::Gateway(GatewayRequestError::InvalidCookie)) => {
status(MaintenanceState::Rejected);
return MemberExit::Terminal(SessionEndReason::InvalidCookie);
}
Err(MemberError::Network) => return MemberExit::Terminal(SessionEndReason::NetworkChanged),
Err(MemberError::Authorization) => return MemberExit::Terminal(SessionEndReason::AuthorizationRevoked),
Err(error) => {
if cancellation.is_cancelled() {
return MemberExit::Cancelled;
}
status(MaintenanceState::Rejected);
log::warn!("Gateway maintenance failed: {error}");
return MemberExit::Rejected;
}
};
tokio::select! {
biased;
_ = cancellation.cancelled() => return MemberExit::Cancelled,
_ = tokio::time::sleep_until(next_check) => {},
}
}
}
enum MemberExit {
Cancelled,
Rejected,
Terminal(SessionEndReason),
}
#[derive(Debug, thiserror::Error)]
enum MemberError {
#[error("{0}")]
Gateway(#[from] GatewayRequestError),
// Collector/script errors can contain user-provided text. Do not log payloads.
#[error("HIP report collection failed")]
Collection,
#[error("Physical network validation failed")]
Network,
#[error("HIP report authorization was revoked")]
Authorization,
}
async fn collect_and_submit(
session: &GatewaySession,
request: &SessionHipRequest,
callbacks: &SessionCallbacks,
cancellation: &CancellationToken,
) -> Result<(), MemberError> {
let producer = callbacks.produce_report.clone();
let input = request.clone();
let control = SessionCollectionControl {
cancellation: cancellation.clone(),
deadline: Instant::now() + COLLECTION_TIMEOUT,
};
let report = tokio::task::spawn_blocking(move || {
control.check()?;
let report = Zeroizing::new(producer(&input, &control)?);
control.check()?;
Ok::<_, io::Error>(report)
})
.await
.map_err(|_| MemberError::Collection)?
.map_err(|error| {
if error.kind() == io::ErrorKind::PermissionDenied {
MemberError::Authorization
} else {
MemberError::Collection
}
})?;
(callbacks.validate_network)(cancellation.clone())
.await
.map_err(|_| MemberError::Network)?;
tokio::select! {
biased;
_ = cancellation.cancelled() => return Err(MemberError::Collection),
result = session.transport.submit_hip(&report, session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result?,
}
if !cancellation.is_cancelled() {
(callbacks.report_submitted)(request, &report);
}
Ok(())
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,415 @@
use std::{
future::pending,
sync::{
Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
use tokio::sync::Notify;
use super::*;
use crate::session::transport::GatewayTransport;
use crate::session::{
ClientAddresses, GatewaySessions,
transport::tests::{gateway, response},
};
async fn run_owned_sessions(
members: Vec<GatewaySession>,
policy: InternalSessionPolicy,
callbacks: SessionCallbacks,
cancellation: CancellationToken,
network_change: impl Future<Output = SessionEndReason>,
) -> anyhow::Result<SessionExit> {
let mut sessions = GatewaySessions::new(members);
let result =
maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation.clone(), network_change).await;
sessions.logout().await;
if cancellation.is_cancelled() {
Ok(SessionExit::Disconnected)
} else {
result
}
}
fn member(name: &str, transport: GatewayTransport) -> GatewaySession {
GatewaySession {
gateway: Gateway::new(name.into(), format!("{name}.example")),
transport,
addresses: ClientAddresses {
ipv4: Some("192.0.2.7".parse().unwrap()),
ipv6: None,
},
}
}
fn callbacks() -> SessionCallbacks {
SessionCallbacks {
produce_report: Arc::new(|_, _| Ok("<hip-report/>".into())),
report_submitted: Arc::new(|_, _| {}),
status_changed: Arc::new(|_| {}),
validate_network: Arc::new(|_| Box::pin(async { Ok(()) })),
}
}
#[tokio::test]
async fn network_uncertainty_prevents_hip_and_healthy_status() {
let (transport, server) = gateway(vec![response("<response status='success'/>")]).await;
let mut callbacks = callbacks();
callbacks.validate_network = Arc::new(|_| Box::pin(async { anyhow::bail!("Network changed") }));
callbacks.status_changed = Arc::new(|summary| assert_ne!(summary.maintenance, MaintenanceState::Healthy));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
assert_eq!(server.await.unwrap()[0].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn revoked_report_authorization_terminates_the_attempt() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.produce_report = Arc::new(|_, _| Err(io::ErrorKind::PermissionDenied.into()));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AuthorizationRevoked));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn invalid_cookie_terminates_only_after_logout() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
response("<response status='success'/>"),
])
.await;
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks(),
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
let requests = server.await.unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn rejection_preserves_healthy_members_and_cleanup_owns_all_members() {
let (rejected, rejected_server) = gateway(vec![
response("<response status='error'><error>Denied</error></response>"),
response("<response status='success'/>"),
])
.await;
let (healthy, healthy_server) = gateway(vec![
response("<response><hip-report-needed>no</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let ready = Arc::new(Notify::new());
let states = Arc::new(Mutex::new(Vec::new()));
let mut callbacks = callbacks();
let states_copy = states.clone();
let ready_copy = ready.clone();
callbacks.status_changed = Arc::new(move |summary| {
if summary.maintenance != MaintenanceState::Authenticated {
let mut states = states_copy.lock().unwrap();
states.push((summary.gateway.name().to_owned(), summary.maintenance));
if states.len() == 2 {
ready_copy.notify_one();
}
}
});
let exit = run_owned_sessions(
vec![member("rejected", rejected), member("healthy", healthy)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
async {
ready.notified().await;
SessionEndReason::NetworkChanged
},
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
let states = states.lock().unwrap();
assert!(states.contains(&("rejected".into(), MaintenanceState::Rejected)));
assert!(states.contains(&("healthy".into(), MaintenanceState::Healthy)));
assert_eq!(rejected_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn observes_reports_only_after_successful_submission() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
response("<response status='success'/>"),
])
.await;
let cancellation = CancellationToken::new();
let submitted = Arc::new(AtomicUsize::new(0));
let observed = submitted.clone();
let stop = cancellation.clone();
let mut callbacks = callbacks();
callbacks.report_submitted = Arc::new(move |request, report| {
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.7"));
assert_eq!(report, "<hip-report/>");
observed.fetch_add(1, Ordering::SeqCst);
stop.cancel();
});
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
cancellation,
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Disconnected);
assert_eq!(submitted.load(Ordering::SeqCst), 1);
assert_eq!(server.await.unwrap().len(), 3);
}
#[tokio::test]
async fn cancelled_collection_is_joined_before_runtime_returns() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let cancellation = CancellationToken::new();
let entered = Arc::new(Notify::new());
let stopped = Arc::new(AtomicBool::new(false));
let mut callbacks = callbacks();
let entered_copy = entered.clone();
let stopped_copy = stopped.clone();
callbacks.produce_report = Arc::new(move |_, control| {
entered_copy.notify_one();
loop {
if let Err(error) = control.check() {
stopped_copy.store(true, Ordering::SeqCst);
return Err(error);
}
std::thread::sleep(Duration::from_millis(10));
}
});
callbacks.report_submitted = Arc::new(|_, _| panic!("Cancelled report must not be observed"));
let stop = cancellation.clone();
let exit = tokio::time::timeout(
Duration::from_secs(2),
run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
cancellation,
async {
entered.notified().await;
stop.cancel();
pending().await
},
),
)
.await
.unwrap()
.unwrap();
assert_eq!(exit, SessionExit::Disconnected);
assert!(stopped.load(Ordering::SeqCst));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn all_rejected_members_are_logged_out_before_terminal_failure() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Denied</error></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.produce_report = Arc::new(|_, _| panic!("Rejected member cannot collect a report"));
let exit = run_owned_sessions(
vec![member("rejected", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn invalid_member_cookie_cancels_and_joins_another_members_collector() {
let arrived = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let collecting = Arc::new(Notify::new());
let stopped = Arc::new(AtomicBool::new(false));
let (expired, expired_server) = crate::session::transport::tests::gateway_with_first_response_gate(
vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
response("<response status='success'/>"),
],
arrived.clone(),
release.clone(),
)
.await;
let (healthy, healthy_server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
let collecting_copy = collecting.clone();
let stopped_copy = stopped.clone();
callbacks.produce_report = Arc::new(move |request, control| {
assert_eq!(request.gateway.name(), "collecting");
collecting_copy.notify_one();
loop {
if let Err(error) = control.check() {
stopped_copy.store(true, Ordering::SeqCst);
return Err(error);
}
std::thread::sleep(Duration::from_millis(10));
}
});
callbacks.report_submitted = Arc::new(|_, _| panic!("Interrupted collection must not submit"));
let exit = tokio::time::timeout(
Duration::from_secs(2),
run_owned_sessions(
vec![member("expired", expired), member("collecting", healthy)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
async {
arrived.notified().await;
collecting.notified().await;
release.notify_one();
pending().await
},
),
)
.await
.unwrap()
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
assert!(stopped.load(Ordering::SeqCst));
assert_eq!(expired_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
}
#[tokio::test]
async fn failed_submission_is_terminal_without_retry_or_observation() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
response("<response status='success'/>"),
])
.await;
let mut callbacks = callbacks();
callbacks.report_submitted = Arc::new(|_, _| panic!("Failed report must not be retained"));
let exit = run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::default(),
callbacks,
CancellationToken::new(),
pending(),
)
.await
.unwrap();
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
let requests = server.await.unwrap();
assert_eq!(
requests.iter().map(|request| request.0.as_str()).collect::<Vec<_>>(),
[
"/ssl-vpn/hipreportcheck.esp",
"/ssl-vpn/hipreport.esp",
"/ssl-vpn/logout.esp"
]
);
}
#[tokio::test]
async fn schedules_from_send_time_plus_interval_and_server_delay() {
let arrived = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let (transport, server) = crate::session::transport::tests::gateway_with_first_response_gate(
vec![
response("<response><hip-report-needed>no</hip-report-needed><delay>7</delay></response>"),
response("<response><hip-report-needed>no</hip-report-needed></response>"),
response("<response status='success'/>"),
],
arrived.clone(),
release.clone(),
)
.await;
let cancellation = CancellationToken::new();
let stop = cancellation.clone();
let (sent, mut received) = tokio::sync::mpsc::unbounded_channel();
let mut callbacks = callbacks();
callbacks.status_changed = Arc::new(move |summary| {
if summary.maintenance == MaintenanceState::Healthy {
sent.send(tokio::time::Instant::now()).unwrap();
}
});
let runtime = tokio::spawn(run_owned_sessions(
vec![member("internal", transport)],
InternalSessionPolicy::new(10, false).unwrap(),
callbacks,
cancellation,
pending(),
));
arrived.notified().await;
// Simulate three seconds spent waiting for the first response. The interval
// must be anchored before that latency, rather than after completion.
tokio::time::pause();
tokio::time::advance(Duration::from_secs(3)).await;
tokio::time::resume();
release.notify_one();
let first = received.recv().await.unwrap();
tokio::time::pause();
tokio::time::advance(Duration::from_secs(13)).await;
tokio::time::resume();
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(received.try_recv().is_err(), "Server delay must extend the interval");
tokio::time::pause();
tokio::time::advance(Duration::from_secs(1)).await;
tokio::time::resume();
let second = tokio::time::timeout(Duration::from_millis(500), received.recv())
.await
.unwrap()
.unwrap();
let elapsed = second.duration_since(first);
assert!(
elapsed >= Duration::from_millis(13_900) && elapsed < Duration::from_millis(14_500),
"Unexpected anchored interval: {elapsed:?}"
);
stop.cancel();
assert_eq!(runtime.await.unwrap().unwrap(), SessionExit::Disconnected);
assert_eq!(server.await.unwrap().len(), 3);
}
+335
View File
@@ -0,0 +1,335 @@
use std::{net::IpAddr, time::Duration};
use reqwest::{Client, StatusCode, Url, redirect::Policy};
use xmltree::Element;
use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt};
use super::{GatewayAuthentication, network::GatewayBinding};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) const MAX_GATEWAY_RESPONSE_BYTES: usize = 1024 * 1024;
pub const MAX_HIP_REPORT_BYTES: usize = 1024 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum GatewayRequestError {
#[error("Gateway authentication cookie expired")]
InvalidCookie,
#[error("Gateway request failed: {0}")]
Transport(#[from] reqwest::Error),
#[error("Gateway returned HTTP {0}")]
Http(StatusCode),
#[error("Gateway rejected the request")]
Rejected,
#[error("Gateway returned a malformed response")]
MalformedResponse,
#[error("Gateway response exceeds its size limit")]
ResponseTooLarge,
#[error("HIP report is empty, contains NUL, or exceeds its size limit")]
InvalidReport,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HipCheck {
pub report_needed: bool,
pub delay: Duration,
}
/// Authenticated HTTP requests retain the login identity. Non-tunnel maintenance
/// uses a validated physical binding; pre-tunnel cleanup uses ordinary HTTP.
pub struct GatewayTransport {
client: Client,
origin: Url,
authentication: GatewayAuthentication,
profile: OsProfile,
}
impl GatewayTransport {
pub fn new(
server: &str,
authentication: GatewayAuthentication,
params: &GpParams,
binding: Option<&GatewayBinding>,
) -> anyhow::Result<Self> {
let origin = Url::parse(&crate::utils::normalize_server(server)?)?;
let client = match binding {
Some(binding) => bound_client(server, params, binding)?,
None => Client::try_from(params)?,
};
Ok(Self {
client,
origin,
authentication,
profile: params.os_profile().clone(),
})
}
/// The login client already validated and built this transport before issuing
/// authentication. Registering its cleanup context cannot fail afterwards.
pub(crate) fn from_authenticated_login(
client: Client,
origin: Url,
authentication: GatewayAuthentication,
profile: OsProfile,
) -> Self {
Self {
client,
origin,
authentication,
profile,
}
}
pub fn authentication(&self) -> &GatewayAuthentication {
&self.authentication
}
pub fn hip_token(&self) -> String {
hip_token(self.authentication.cookie())
}
pub async fn check_hip(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Result<HipCheck, GatewayRequestError> {
let mut form = self.hip_form(ipv4, ipv6);
form.push(("md5".into(), self.hip_token()));
parse_hip_check(&self.post("hipreportcheck.esp", &form).await?)
}
pub async fn submit_hip(
&self,
report: &str,
ipv4: Option<IpAddr>,
ipv6: Option<IpAddr>,
) -> Result<(), GatewayRequestError> {
if report.is_empty() || report.len() > MAX_HIP_REPORT_BYTES || report.contains('\0') {
return Err(GatewayRequestError::InvalidReport);
}
let mut form = self.hip_form(ipv4, ipv6);
form.push(("report".into(), report.into()));
self.post("hipreport.esp", &form).await?;
Ok(())
}
pub async fn logout(&self) -> Result<(), GatewayRequestError> {
logout_cookie(&self.client, &self.origin, self.authentication.cookie(), &self.profile).await
}
fn cookie_form(&self) -> Vec<(String, String)> {
url::form_urlencoded::parse(self.authentication.cookie().as_bytes())
.into_owned()
.collect()
}
fn hip_form(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Vec<(String, String)> {
let mut form = self.cookie_form();
set_form(&mut form, "client-role", "global-protect-full");
set_form(&mut form, "computer", self.profile.computer());
set_form(&mut form, "host-id", self.profile.host_id());
set_form(&mut form, "serialno", self.profile.serialno());
if let Some(ip) = ipv4 {
set_form(&mut form, "client-ip", &ip.to_string());
}
if let Some(ip) = ipv6 {
set_form(&mut form, "client-ipv6", &ip.to_string());
}
form
}
async fn post(&self, endpoint: &str, form: &[(String, String)]) -> Result<Element, GatewayRequestError> {
post(&self.client, &self.origin, endpoint, form).await
}
}
/// Cleanup uses trustworthy issued cookie fields even when execution mode is
/// invalid. It never creates a runnable authentication with a fabricated mode.
pub(crate) async fn logout_cookie(
client: &Client,
origin: &Url,
cookie: &str,
profile: &OsProfile,
) -> Result<(), GatewayRequestError> {
let mut form = url::form_urlencoded::parse(cookie.as_bytes()).into_owned().collect();
set_form(&mut form, "computer", profile.computer());
set_form(&mut form, "clientos", profile.client_os().as_str());
set_form(&mut form, "os-version", profile.os_version());
post(client, origin, "logout.esp", &form).await?;
Ok(())
}
async fn post(
client: &Client,
origin: &Url,
endpoint: &str,
form: &[(String, String)],
) -> Result<Element, GatewayRequestError> {
let mut url = origin.clone();
url.set_path(&format!("/ssl-vpn/{endpoint}"));
let response = client.post(url).form(form).send().await?;
let status = response.status();
let invalid_cookie = status.as_u16() == 512
|| response
.headers()
.get("x-private-pan-globalprotect")
.is_some_and(|value| value == "Invalid authentication cookie");
if invalid_cookie {
return Err(GatewayRequestError::InvalidCookie);
}
if !status.is_success() {
return Err(GatewayRequestError::Http(status));
}
let body = crate::utils::request::read_bounded_response(response, MAX_GATEWAY_RESPONSE_BYTES)
.await
.map_err(|error| match error {
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
})?;
parse_response(&body)
}
pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result<Client> {
binding.validate_server(server)?;
let origin = gateway_origin(server)?;
let host = origin
.host_str()
.ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?;
let builder = params
.client_builder()?
.redirect(Policy::none())
.no_proxy()
.local_address(binding.source().ip())
.resolve(host, binding.endpoint())
.timeout(REQUEST_TIMEOUT);
let builder = bind_interface(builder, binding)?;
Ok(builder.build()?)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
Ok(builder.interface(binding.interface()))
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!(
source.scope_id() == 0,
"Scoped IPv6 source requires a native socket connector"
);
}
Ok(builder)
}
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
let server = if server.starts_with("https://") {
server.to_owned()
} else {
format!("https://{server}")
};
let origin = Url::parse(&server)?;
anyhow::ensure!(
origin.scheme() == "https"
&& origin.username().is_empty()
&& origin.password().is_none()
&& origin.path() == "/"
&& origin.query().is_none()
&& origin.fragment().is_none(),
"Gateway endpoint must be an HTTPS origin"
);
Ok(origin)
}
fn set_form(form: &mut Vec<(String, String)>, key: &str, value: &str) {
form.retain(|(name, _)| name != key);
form.push((key.into(), value.into()));
}
/// Match gpst.c::build_csd_token without decoding or reordering cookie fields.
pub fn hip_token(cookie: &str) -> String {
let stable = cookie
.split('&')
.filter(|field| {
let key = field.split('=').next().unwrap_or_default();
!matches!(key, "authcookie" | "preferred-ip" | "preferred-ipv6")
})
.collect::<Vec<_>>()
.join("&");
format!("{:x}", md5::compute(stable.as_bytes()))
}
fn parse_response(body: &[u8]) -> Result<Element, GatewayRequestError> {
let text = std::str::from_utf8(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
let lower = text.to_ascii_lowercase();
if lower.contains("<!doctype") || lower.contains("<!entity") {
return Err(GatewayRequestError::MalformedResponse);
}
if let Some(error) = javascript_error(text) {
return Err(error);
}
let root = Element::parse(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
if root.name == "html" {
return Err(
root
.descendant_text("body")
.as_deref()
.and_then(javascript_error)
.unwrap_or(GatewayRequestError::MalformedResponse),
);
}
if root.name == "prelogin-response" && root.child_text("status").as_deref() == Some("Error") {
return Err(message_error(root.child_text("msg").as_deref()));
}
if root.name != "response" {
return Err(GatewayRequestError::MalformedResponse);
}
match root.attr("status") {
Some("error") => Err(message_error(root.child_text("error").as_deref())),
None | Some("success") => Ok(root),
_ => Err(GatewayRequestError::Rejected),
}
}
fn message_error(message: Option<&str>) -> GatewayRequestError {
if message == Some("Invalid authentication cookie") {
GatewayRequestError::InvalidCookie
} else {
GatewayRequestError::Rejected
}
}
fn javascript_error(text: &str) -> Option<GatewayRequestError> {
static ERROR: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let regex = ERROR.get_or_init(|| {
regex::Regex::new(r#"(?s)^\s*var\s+respStatus\s*=\s*"Error"\s*;\s*var\s+respMsg\s*=\s*("(?:\\.|[^"\\])*")"#)
.expect("valid GlobalProtect error pattern")
});
let captures = regex.captures(text)?;
match serde_json::from_str::<String>(&captures[1]) {
Ok(message) => Some(message_error(Some(&message))),
Err(_) => Some(GatewayRequestError::MalformedResponse),
}
}
fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
let report_needed = match root.child_text("hip-report-needed").as_deref() {
Some("yes") => true,
Some("no") => false,
_ => return Err(GatewayRequestError::MalformedResponse),
};
let delay = match root.child_text("delay") {
Some(value) => value
.parse::<u32>()
.map_err(|_| GatewayRequestError::MalformedResponse)?,
None => 0,
};
// Limit this client's supported response delay to one hour. The official
// registry scheduling cap is not evidence of a wire-protocol maximum.
if delay > 3600 {
return Err(GatewayRequestError::MalformedResponse);
}
Ok(HipCheck {
report_needed,
delay: Duration::from_secs(u64::from(delay)),
})
}
#[cfg(test)]
pub(crate) mod tests;
+246
View File
@@ -0,0 +1,246 @@
use super::*;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
task::JoinHandle,
};
pub(crate) async fn gateway(responses: Vec<String>) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
gateway_fixture(responses, None).await
}
pub(crate) async fn login_gateway(responses: Vec<String>) -> (Client, Url, JoinHandle<Vec<(String, String)>>) {
let (transport, server) = gateway(responses).await;
(transport.client, transport.origin, server)
}
pub(crate) async fn gateway_with_first_response_gate(
responses: Vec<String>,
arrived: std::sync::Arc<tokio::sync::Notify>,
release: std::sync::Arc<tokio::sync::Notify>,
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
gateway_fixture(responses, Some((arrived, release))).await
}
async fn gateway_fixture(
responses: Vec<String>,
gate: Option<(std::sync::Arc<tokio::sync::Notify>, std::sync::Arc<tokio::sync::Notify>)>,
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
let server = tokio::spawn(async move {
let mut requests = Vec::new();
for (index, response) in responses.into_iter().enumerate() {
let (mut stream, _) = listener.accept().await.unwrap();
let mut bytes = Vec::new();
let (headers_end, length) = loop {
let mut chunk = [0; 1024];
let count = stream.read(&mut chunk).await.unwrap();
assert_ne!(count, 0);
bytes.extend_from_slice(&chunk[..count]);
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
let length = headers
.lines()
.find_map(|line| {
let (key, value) = line.split_once(':')?;
key
.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().unwrap())
})
.unwrap();
break (position + 4, length);
}
};
while bytes.len() < headers_end + length {
let mut chunk = [0; 1024];
let count = stream.read(&mut chunk).await.unwrap();
assert_ne!(count, 0);
bytes.extend_from_slice(&chunk[..count]);
}
let path = std::str::from_utf8(&bytes[..headers_end])
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.to_owned();
let body = String::from_utf8(bytes[headers_end..headers_end + length].to_vec()).unwrap();
requests.push((path, body));
if index == 0
&& let Some((arrived, release)) = &gate
{
arrived.notify_one();
release.notified().await;
}
stream.write_all(response.as_bytes()).await.unwrap();
}
requests
});
let transport = GatewayTransport {
client: Client::builder()
.redirect(Policy::none())
.no_proxy()
.timeout(REQUEST_TIMEOUT)
.build()
.unwrap(),
origin,
authentication: GatewayAuthentication::new(
"authcookie=test-cookie&portal=portal&user=alice&domain=example&computer=test".into(),
"non-tunnel".into(),
)
.unwrap(),
profile: OsProfile::builder(crate::os_profile::ClientOs::Linux)
.computer_name_override("test")
.build(),
};
(transport, server)
}
pub(crate) fn response(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
#[test]
fn checksum_matches_c_protocol_golden_fixture() {
for volatile in [
"authcookie=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1",
"authcookie=refreshed&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2",
] {
let cookie =
format!("user=test&{volatile}&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&computer=test");
assert_eq!(hip_token(&cookie), "20f30054f721fd212925866b5778447d");
}
assert_ne!(hip_token("user=alice%20bob"), hip_token("user=alice+bob"));
assert_ne!(hip_token("user=alice&portal=a"), hip_token("portal=a&user=alice"));
}
#[tokio::test]
async fn maintenance_uses_only_hip_and_logout_with_physical_identity() {
let (transport, server) = gateway(vec![
response("<response><hip-report-needed>yes</hip-report-needed><delay>7</delay></response>"),
response("<response status='success'/>"),
response("<response status='success'/>"),
])
.await;
let ipv4 = Some("192.0.2.7".parse().unwrap());
let ipv6 = Some("2001:db8::7".parse().unwrap());
let check = transport.check_hip(ipv4, ipv6).await.unwrap();
assert_eq!(
check,
HipCheck {
report_needed: true,
delay: Duration::from_secs(7)
}
);
transport.submit_hip("<hip-report/>", ipv4, ipv6).await.unwrap();
transport.logout().await.unwrap();
let requests = server.await.unwrap();
assert_eq!(
requests.iter().map(|(path, _)| path.as_str()).collect::<Vec<_>>(),
[
"/ssl-vpn/hipreportcheck.esp",
"/ssl-vpn/hipreport.esp",
"/ssl-vpn/logout.esp"
]
);
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[0].1).unwrap();
assert_eq!(form["authcookie"], "test-cookie");
assert_eq!(form["client-ip"], "192.0.2.7");
assert_eq!(form["client-ipv6"], "2001:db8::7");
assert_eq!(form["md5"], transport.hip_token());
}
#[tokio::test]
async fn rejects_redirects_without_forwarding_authentication() {
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
let (transport, server) = gateway(vec![format!(
"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{}/stolen\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
destination.local_addr().unwrap()
)])
.await;
assert!(
matches!(transport.check_hip(None, None).await, Err(GatewayRequestError::Http(status)) if status.as_u16() == 307)
);
assert!(
tokio::time::timeout(Duration::from_millis(100), destination.accept())
.await
.is_err()
);
assert_eq!(server.await.unwrap().len(), 1);
}
#[tokio::test]
async fn distinguishes_expired_cookie_from_transport_and_protocol_errors() {
let (transport, server) = gateway(vec![
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
"HTTP/1.1 512 Invalid Cookie\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
response("<response><hip-report-needed>maybe</hip-report-needed></response>"),
response("<response status='error'><error>server-private-payload</error></response>"),
])
.await;
for _ in 0..2 {
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::InvalidCookie)
));
}
assert!(matches!(
transport.check_hip(None, None).await.unwrap_err(),
GatewayRequestError::Http(StatusCode::SERVICE_UNAVAILABLE)
));
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::MalformedResponse)
));
let error = transport.check_hip(None, None).await.unwrap_err();
assert!(!format!("{error:?}").contains("server-private-payload"));
server.await.unwrap();
}
#[tokio::test]
async fn bounds_response_size_before_reading_body() {
let (transport, server) = gateway(vec![format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
MAX_GATEWAY_RESPONSE_BYTES + 1
)])
.await;
assert!(matches!(
transport.check_hip(None, None).await,
Err(GatewayRequestError::ResponseTooLarge)
));
server.await.unwrap();
}
#[test]
fn rejects_invalid_delays_and_unsafe_response_xml() {
for delay in ["-1", "3601", "4294967296", "invalid"] {
let root = parse_response(
format!("<response><hip-report-needed>no</hip-report-needed><delay>{delay}</delay></response>").as_bytes(),
)
.unwrap();
assert!(parse_hip_check(&root).is_err());
}
assert!(parse_response(b"<!DOCTYPE response><response/>").is_err());
}
#[test]
fn recognizes_cookie_expiry_in_official_error_formats() {
for body in [
r#"var respStatus = "Error"; var respMsg = "Invalid authentication\u0020cookie"; thisForm.inputStr.value = "";"#,
r#"<html><head/><body>var respStatus = "Error"; var respMsg = "Invalid authentication cookie";</body></html>"#,
"<prelogin-response><status>Error</status><msg>Invalid authentication cookie</msg></prelogin-response>",
] {
assert!(matches!(
parse_response(body.as_bytes()),
Err(GatewayRequestError::InvalidCookie)
));
}
assert!(matches!(
parse_response(b"<response status='error'><error>Denied</error></response>"),
Err(GatewayRequestError::Rejected)
));
}
+27 -8
View File
@@ -1,19 +1,38 @@
use super::lock_file::gpservice_lock_info;
use std::path::Path;
async fn read_port() -> anyhow::Result<String> {
let lock_info = gpservice_lock_info().await?;
Ok(lock_info.port.to_string())
}
use super::lock_file::{gpservice_lock_info, gpservice_lock_info_at};
pub async fn http_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
let port = gpservice_lock_info().await?.port;
Ok(format!("http://127.0.0.1:{}", port))
}
pub async fn ws_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
let port = gpservice_lock_info().await?.port;
Ok(format!("ws://127.0.0.1:{}/ws", port))
}
pub async fn ws_endpoint_from_lock_file(path: impl AsRef<Path>) -> anyhow::Result<String> {
let port = gpservice_lock_info_at(path).await?.port;
Ok(format!("ws://127.0.0.1:{}/ws", port))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn websocket_endpoint_uses_the_selected_lock_file() {
let temp = tempfile::tempdir().unwrap();
let lock_file = temp.path().join("gpservice.lock");
std::fs::write(&lock_file, "123:4242").unwrap();
assert_eq!(
ws_endpoint_from_lock_file(lock_file).await.unwrap(),
"ws://127.0.0.1:4242/ws"
);
}
}
+1 -40
View File
@@ -1,53 +1,14 @@
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::io::Write;
use std::path::Path;
use log::info;
use tempfile::NamedTempFile;
pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> {
let mut env_file = NamedTempFile::new()?;
let content = env::vars()
.map(|(key, value)| format!("{}={}", key, value))
.chain(
extra
.unwrap_or_default()
.into_iter()
.map(|(key, value)| format!("{}={}", key, value)),
)
.collect::<Vec<String>>()
.join("\n");
writeln!(env_file, "{}", content)?;
Ok(env_file)
}
pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> {
let content = std::fs::read_to_string(env_file)?;
let mut env_vars: HashMap<String, String> = HashMap::new();
for line in content.lines() {
if let Some((key, value)) = line.split_once('=') {
env_vars.insert(key.to_string(), value.to_string());
}
}
Ok(env_vars)
}
pub fn patch_gui_runtime_env(hidpi: bool) {
// This is to avoid blank screen on some systems
unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") };
if is_wayland_session(
env::var_os("WAYLAND_DISPLAY").as_deref(),
env::var("XDG_SESSION_TYPE").ok().as_deref(),
) {
info!("Wayland session detected, enabling Linux WebKit rendering fallbacks");
set_env_if_missing("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
info!("Wayland session detected, enabling software GL");
set_env_if_missing("LIBGL_ALWAYS_SOFTWARE", "1");
}
+65 -4
View File
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use common::constants::GP_SERVICE_LOCK_FILE;
use thiserror::Error;
@@ -9,6 +9,10 @@ pub struct LockFile {
pid: u32,
}
pub fn dev_service_lock_file_path(bootstrap_socket: impl AsRef<Path>) -> PathBuf {
bootstrap_socket.as_ref().with_file_name("gpservice.lock")
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
Self { path: path.into(), pid }
@@ -25,8 +29,15 @@ impl LockFile {
}
pub fn unlock(&self) -> anyhow::Result<()> {
std::fs::remove_file(&self.path)?;
Ok(())
match std::fs::read_to_string(&self.path) {
Ok(content) if LockInfo::parse(&content).is_ok_and(|info| info.pid == self.pid) => {
std::fs::remove_file(&self.path)?;
Ok(())
}
Ok(_) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
pub async fn check_health(&self) -> bool {
@@ -95,7 +106,11 @@ impl LockInfo {
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(GP_SERVICE_LOCK_FILE).await
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
}
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
LockInfo::from_file(path).await
}
#[cfg(test)]
@@ -126,4 +141,50 @@ mod tests {
Err(LockFileError::InvalidPort(_))
));
}
#[test]
fn dev_service_lock_file_is_next_to_the_bootstrap_socket() {
assert_eq!(
dev_service_lock_file_path("/var/run/gpservice-dev-123/dev-bootstrap.sock"),
PathBuf::from("/var/run/gpservice-dev-123/gpservice.lock")
);
}
#[test]
fn unlock_removes_lock_owned_by_process() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let lock = LockFile::new(&path, 1234);
lock.lock("8080").unwrap();
lock.unlock().unwrap();
assert!(!path.exists());
}
#[test]
fn unlock_preserves_lock_owned_by_another_process() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let owner = LockFile::new(&path, 1234);
let other = LockFile::new(&path, 5678);
owner.lock("8080").unwrap();
other.unlock().unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), "1234:8080");
}
#[test]
fn unlock_ignores_missing_or_malformed_lock() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let lock = LockFile::new(&path, 1234);
lock.unlock().unwrap();
std::fs::write(&path, "not-a-lock").unwrap();
lock.unlock().unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), "not-a-lock");
}
}
+431 -56
View File
@@ -1,10 +1,9 @@
use std::{borrow::Cow, fs};
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::bail;
use log::warn;
use openssl::pkey::PKey;
use pem::parse_many;
use anyhow::{Context, ensure};
use openssl::{pkey::PKey, x509::X509};
use reqwest::Identity;
use zeroize::Zeroizing;
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
@@ -16,103 +15,453 @@ pub enum RequestIdentityError {
DecryptError(&'static str),
}
/// Create an identity object from a certificate and key
/// The file is expected to be the PKCS#8 PEM or PKCS#12 format
/// When using a PKCS#12 file, the key is NOT required, but a passphrase is required
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
if cert.ends_with(".p12") || cert.ends_with(".pfx") {
create_identity_from_pkcs12(cert, passphrase)
} else {
create_identity_from_pem(cert, key, passphrase)
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
/// retains its original bytes and passphrase so each native backend imports the
/// same identity and chain. Debug never exposes retained material.
#[derive(Clone)]
pub struct ClientIdentity {
material: Arc<IdentityMaterial>,
identity: Identity,
}
struct IdentityMaterial {
certificate: Zeroizing<Vec<u8>>,
key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<Zeroizing<String>>,
}
impl fmt::Debug for ClientIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClientIdentity")
.field("material", &"<redacted>")
.finish()
}
}
fn create_identity_from_pem(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
let cert_pem = fs::read(cert).map_err(|err| anyhow::anyhow!("Failed to read certificate file: {}", err))?;
impl ClientIdentity {
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
let certificate_bytes = read_identity_file(certificate)?;
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
return Self::from_data(certificate_bytes, None, Some(passphrase));
}
let key_bytes = match key {
Some(path) => read_identity_file(path)?,
None => certificate_bytes.clone(),
};
// Keep the previous first-private-key rule: unrelated later blocks must not
// change which key is selected or whether the caller is prompted.
let key = pem::parse_many(&*key_bytes)?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
let key_pem = Zeroizing::new(pem::encode(&key));
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
} else {
Zeroizing::new(key_pem.as_bytes().to_vec())
};
// Strip private-key blocks before importing the certificate chain: macOS
// otherwise imports the same key twice for combined PEM files.
let mut certificate = Zeroizing::new(Vec::new());
for cert in X509::stack_from_pem(&certificate_bytes)? {
certificate.extend(cert.to_pem()?);
}
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
key: Some(key),
passphrase: None,
}),
identity,
})
}
// Use the certificate as the key if no key is provided
let key_pem_file = match key {
Some(key) => Cow::Owned(fs::read(key).map_err(|err| anyhow::anyhow!("Failed to read key file: {}", err))?),
None => Cow::Borrowed(&cert_pem),
};
/// A separate key denotes decrypted PEM; no separate key denotes original
/// PKCS#12 bytes. Input-size limits belong to the service transport boundary.
pub fn from_data(
certificate: Zeroizing<Vec<u8>>,
key: Option<Zeroizing<Vec<u8>>>,
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key {
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
None => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
(
Identity::from_pkcs12_der(&certificate, passphrase)?,
Some(Zeroizing::new(passphrase.to_owned())),
)
}
};
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
key,
passphrase,
}),
identity,
})
}
// Find the private key in the pem file
let key_pem = parse_many(key_pem_file.as_ref())?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
pub fn certificate_data(&self) -> &[u8] {
&self.material.certificate
}
pub fn key_data(&self) -> Option<&[u8]> {
self.material.key.as_ref().map(|key| key.as_slice())
}
pub fn key_password(&self) -> Option<&str> {
self.material.passphrase.as_ref().map(|value| value.as_str())
}
pub(crate) fn request_identity(&self) -> Identity {
self.identity.clone()
}
// The key pem could be encrypted, so we need to decrypt it
let decrypted_key_pem = if key_pem.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or_else(|| {
warn!("Key is encrypted but no passphrase provided");
RequestIdentityError::NoPassphrase("PEM")
})?;
let pem_content = pem::encode(&key_pem);
let key = PKey::private_key_from_pem_passphrase(pem_content.as_bytes(), passphrase.as_bytes()).map_err(|err| {
warn!("Failed to decrypt key: {}", err);
RequestIdentityError::DecryptError("PEM")
})?;
key.private_key_to_pem_pkcs8()?
} else {
pem::encode(&key_pem).into()
};
let identity = Identity::from_pkcs8_pem(&cert_pem, &decrypted_key_pem)?;
Ok(identity)
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
let suffix = if self.material.key.is_some() { ".pem" } else { ".p12" };
let certificate = write_identity_file(self.certificate_data(), directory, suffix)?;
let key = self
.key_data()
.map(|key| write_identity_file(key, directory, ".pem"))
.transpose()?;
Ok(ClientIdentityFiles { certificate, key })
}
}
fn create_identity_from_pkcs12(pkcs12: &str, passphrase: Option<&str>) -> anyhow::Result<Identity> {
let pkcs12 = fs::read(pkcs12)?;
/// Named files are private and remain owned until native workers and logout
/// finish. The original configured files are never reopened by these workers.
pub struct ClientIdentityFiles {
certificate: tempfile::NamedTempFile,
key: Option<tempfile::NamedTempFile>,
}
let Some(passphrase) = passphrase else {
bail!(RequestIdentityError::NoPassphrase("PKCS#12"));
impl ClientIdentityFiles {
pub fn certificate(&self) -> &str {
self.certificate.path().to_str().expect("identity path is UTF-8")
}
pub fn key(&self) -> Option<&str> {
self
.key
.as_ref()
.map(|key| key.path().to_str().expect("identity path is UTF-8"))
}
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?,
))
}
fn write_identity_file(
bytes: &[u8],
directory: Option<&Path>,
suffix: &str,
) -> anyhow::Result<tempfile::NamedTempFile> {
let mut builder = tempfile::Builder::new();
builder.prefix("gp-identity-").suffix(suffix);
let mut file = match directory {
Some(directory) => builder.tempfile_in(directory)?,
None => builder.tempfile()?,
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
}
ensure!(file.path().to_str().is_some(), "Client identity path is not UTF-8");
file.write_all(bytes)?;
file.flush()?;
Ok(file)
}
let identity = Identity::from_pkcs12_der(&pkcs12, passphrase)?;
Ok(identity)
/// General request clients may load an identity directly. Session owners call
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::pkcs12::Pkcs12;
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "identity-fixture").unwrap();
let name = name.build();
let mut certificate = X509::builder().unwrap();
certificate.set_version(2).unwrap();
certificate.set_subject_name(&name).unwrap();
certificate.set_issuer_name(&name).unwrap();
certificate.set_pubkey(&key).unwrap();
certificate
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
.unwrap();
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
certificate.sign(&key, MessageDigest::sha256()).unwrap();
(
certificate.build().to_pem().unwrap(),
key.private_key_to_pem_pkcs8().unwrap(),
)
}
#[test]
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
let (certificate, key) = generated_identity();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
.unwrap();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&encrypted).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.key_data().unwrap(), key);
}
#[test]
fn pem_without_key_reports_missing_key_even_with_passphrase() {
let (certificate, _) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
for passphrase in [None, Some("unused")] {
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
assert!(matches!(
error.downcast_ref::<RequestIdentityError>(),
Some(RequestIdentityError::NoKey)
));
}
}
#[test]
fn local_identity_loading_is_not_limited_by_service_message_size() {
let (certificate, key) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
}
#[test]
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
let (certificate, key) = generated_identity();
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
cert_file.write_all(&certificate).unwrap();
let mut key_file = tempfile::NamedTempFile::new().unwrap();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
.unwrap();
key_file.write_all(&encrypted).unwrap();
let cert = cert_file.path().to_str().unwrap();
let key_path = Some(key_file.path().to_str().unwrap());
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
match error.downcast_ref::<RequestIdentityError>().unwrap() {
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
other => panic!("Unexpected identity error: {other}"),
}
}
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
assert_eq!(loaded.key_data().unwrap(), key);
fs::write(key_file.path(), &key).unwrap();
for passphrase in [None, Some("ignored for unencrypted key")] {
assert_eq!(
ClientIdentity::load(cert, key_path, passphrase)
.unwrap()
.key_data()
.unwrap(),
key
);
}
}
#[test]
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
use std::os::unix::fs::PermissionsExt;
let (certificate, key) = generated_identity();
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("combined.pem");
let mut combined = certificate.clone();
combined.extend(&key);
fs::write(&source, &combined).unwrap();
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
fs::write(&source, "changed after authentication").unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
let files = identity.write_files(Some(directory.path())).unwrap();
let certificate_path = files.certificate().to_owned();
let key_path = files.key().unwrap().to_owned();
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
assert_eq!(fs::read(&key_path).unwrap(), key);
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&certificate_path).exists());
assert!(!Path::new(&key_path).exists());
// The request identity remains valid after its original files disappear.
fs::remove_file(&source).unwrap();
reqwest::Client::builder()
.identity(identity.request_identity())
.build()
.unwrap();
}
#[test]
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
let (certificate, key) = generated_identity();
let certificate = X509::from_pem(&certificate).unwrap();
let key = PKey::private_key_from_pem(&key).unwrap();
let mut builder = Pkcs12::builder();
builder.name("identity-fixture").pkey(&key).cert(&certificate);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
for suffix in [".p12", ".pfx"] {
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
source.write_all(&encoded).unwrap();
let path = source.path().to_str().unwrap();
assert!(ClientIdentity::load(path, None, None).is_err());
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
// PKCS#12 has always ignored a separately configured key path.
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
fs::write(source.path(), b"replaced after login").unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
assert_eq!(identity.key_password(), Some("fixture-password"));
assert!(!format!("{identity:?}").contains("fixture-password"));
let files = identity.write_files(None).unwrap();
assert!(files.certificate().ends_with(".p12"));
assert!(files.key().is_none());
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
let owned_path = files.certificate().to_owned();
drop(files);
assert!(!Path::new(&owned_path).exists());
}
let empty_password = builder.build2("").unwrap().to_der().unwrap();
// Empty-password support varies by native backend and PKCS#12 algorithms.
// Match the previous native import instead of introducing another parser.
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
assert_eq!(
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
previously_accepted
);
}
#[test]
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
rsa::Rsa,
stack::Stack,
x509::{X509NameBuilder, extension::BasicConstraints},
};
fn certificate(
name: &str,
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
ca: bool,
) -> (X509, PKey<openssl::pkey::Private>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut subject = X509NameBuilder::new().unwrap();
subject.append_entry_by_text("CN", name).unwrap();
let subject = subject.build();
let mut cert = X509::builder().unwrap();
cert.set_version(2).unwrap();
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
.unwrap()
.to_asn1_integer()
.unwrap();
cert.set_serial_number(&serial).unwrap();
cert.set_subject_name(&subject).unwrap();
cert
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
.unwrap();
cert.set_pubkey(&key).unwrap();
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
if ca {
cert
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
.unwrap();
}
cert
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
.unwrap();
(cert.build(), key)
}
let (root, root_key) = certificate("root", None, true);
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
// This is the reverse CA stack consumed by the previous native-tls path.
let mut ca = Stack::new().unwrap();
ca.push(root.clone()).unwrap();
ca.push(intermediate.clone()).unwrap();
let mut builder = Pkcs12::builder();
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
source.write_all(&encoded).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
ClientIdentity::from_data(
Zeroizing::new(identity.certificate_data().to_vec()),
None,
identity.key_password(),
)
.unwrap();
}
#[test]
fn create_identity_from_pem_requires_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let identity = create_identity_from_pem(cert, None, None);
let identity = create_identity(cert, None, None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[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_from_pem(cert, None, Some(passphrase));
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_from_pem(cert, None, None);
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_from_pem(cert, Some(key), Some(passphrase));
let identity = create_identity(cert, Some(key), Some(passphrase));
assert!(identity.is_ok());
}
@@ -122,19 +471,45 @@ mod tests {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let identity = create_identity_from_pem(cert, Some(key), None);
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[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_from_pem(cert, Some(key), None);
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_ok());
}
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ResponseBodyError {
#[error("Response read failed: {0}")]
Transport(#[from] reqwest::Error),
#[error("Response exceeds its size limit")]
TooLarge,
}
pub(crate) async fn read_bounded_response(
mut response: reqwest::Response,
limit: usize,
) -> Result<Vec<u8>, ResponseBodyError> {
if response.content_length().is_some_and(|length| length > limit as u64) {
return Err(ResponseBodyError::TooLarge);
}
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await? {
if chunk.len() > limit.saturating_sub(body.len()) {
return Err(ResponseBodyError::TooLarge);
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
+73 -1
View File
@@ -1,11 +1,65 @@
use tauri::WebviewWindow;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WindowTypeHint {
Dialog,
Utility,
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn is_screen_composited() -> bool {
gtk::gdk::Screen::default().is_some_and(|screen| screen.is_composited())
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn set_window_type_hint(window: &WebviewWindow, hint: WindowTypeHint) -> anyhow::Result<()> {
use gtk::{gdk, traits::GtkWindowExt};
let hint = match hint {
WindowTypeHint::Dialog => gdk::WindowTypeHint::Dialog,
WindowTypeHint::Utility => gdk::WindowTypeHint::Utility,
};
window.gtk_window()?.set_type_hint(hint);
Ok(())
}
/// Returns the frame-to-content height difference for a standard titled macOS window.
/// This is nonzero only on macOS.
pub fn get_title_bar_height() -> f64 {
#[cfg(target_os = "macos")]
{
macos_title_bar_height(os_info::get().version())
}
#[cfg(not(target_os = "macos"))]
{
0.0
}
}
#[cfg(target_os = "macos")]
fn macos_title_bar_height(version: &os_info::Version) -> f64 {
if version.ge(&os_info::Version::from_string("26.0.0")) {
32.0
} else {
28.0
}
}
pub trait WindowExt {
fn raise(&self) -> anyhow::Result<()>;
}
impl WindowExt for WebviewWindow {
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[cfg(target_os = "macos")]
fn raise(&self) -> anyhow::Result<()> {
self.show()?;
self.set_focus()?;
Ok(())
}
#[cfg(target_os = "windows")]
fn raise(&self) -> anyhow::Result<()> {
self.show()?;
Ok(())
@@ -17,6 +71,24 @@ impl WindowExt for WebviewWindow {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "macos")]
#[test]
fn uses_the_current_macos_title_bar_height() {
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("25.9.0")), 28.0);
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("26.0.0")), 32.0);
}
#[cfg(not(target_os = "macos"))]
#[test]
fn native_title_bar_height_is_zero_without_a_native_macos_title_bar() {
assert_eq!(get_title_bar_height(), 0.0);
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod unix {
use std::{process::ExitStatus, time::Duration};
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "gphip"
rust-version.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
gpapi = { path = "../gpapi" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
netdev.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
uuid = { workspace = true, features = ["v5"] }
uzers.workspace = true
xmltree.workspace = true
File diff suppressed because it is too large. Load diff
+149
View File
@@ -0,0 +1,149 @@
use std::{
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::Path,
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINELCTL: &str = "/Library/Sentinel/sentinel-agent.bundle/Contents/MacOS/sentinelctl";
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
if !trusted_cli(Path::new(SENTINELCTL)) {
return Ok(None);
}
let Some(status) = run(commands, &["status"])? else {
return Ok(None);
};
let Some(status) = parse_status(&status) else {
return Ok(None);
};
let real_time_protection = if status.active {
let Some(scan_status) = run(commands, &["scan-on-write"])? else {
return Ok(None);
};
let Some(enabled) = scan_status.trim().strip_prefix("scan-on-write:").and_then(parse_yes_no) else {
return Ok(None);
};
enabled
} else {
false
};
let firewall_enabled = run(commands, &["firewall", "enabled"])?
.as_deref()
.and_then(parse_yes_no);
Ok(Some(SentinelInfo {
version: status.version,
real_time_protection,
firewall_enabled,
}))
}
fn trusted_cli(path: &Path) -> bool {
path.ancestors().take_while(|part| part.as_os_str() != "/").all(|part| {
let Ok(metadata) = fs::symlink_metadata(part) else {
return false;
};
if metadata.uid() != 0 || metadata.permissions().mode() & 0o022 != 0 || metadata.file_type().is_symlink() {
return false;
}
if part == path {
metadata.is_file()
} else {
metadata.is_dir()
}
})
}
fn run(commands: &CollectorCommands<'_>, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(Path::new(SENTINELCTL), args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
struct AgentStatus {
version: String,
active: bool,
}
fn parse_status(output: &str) -> Option<AgentStatus> {
let version = status_value(output, "Version:")?;
if version.is_empty()
|| version.len() > 64
|| !version
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_'))
{
return None;
}
let operational = parse_status_bool(output, "Agent Operational State:", "enabled", "disabled")?;
let ready = parse_status_bool(output, "Ready:", "yes", "no")?;
let protected = parse_status_bool(output, "Protection:", "enabled", "disabled")?;
Some(AgentStatus {
version: version.to_string(),
active: operational && ready && protected,
})
}
fn status_value<'a>(output: &'a str, label: &str) -> Option<&'a str> {
output
.lines()
.find_map(|line| line.trim().strip_prefix(label).map(str::trim))
}
fn parse_status_bool(output: &str, label: &str, yes: &str, no: &str) -> Option<bool> {
match status_value(output, label)? {
value if value == yes => Some(true),
value if value == no => Some(false),
_ => None,
}
}
fn parse_yes_no(output: &str) -> Option<bool> {
match output.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_running_agent_status() {
let status = parse_status(
"Agent\n Version: 25.3.4.8365\n Agent Operational State: enabled\n Ready: yes\n Protection: enabled\n",
)
.unwrap();
assert_eq!(status.version, "25.3.4.8365");
assert!(status.active);
}
#[test]
fn rejects_unknown_agent_state() {
assert!(parse_status("Version: 25.3.4.8365\nProtection: maybe\n").is_none());
assert!(
!parse_status("Version: 25.3.4.8365\nAgent Operational State: disabled\nReady: yes\nProtection: enabled\n")
.unwrap()
.active
);
}
#[test]
fn parses_scan_and_firewall_states() {
assert_eq!(
parse_yes_no("scan-on-write:\tyes\n".trim().strip_prefix("scan-on-write:").unwrap()),
Some(true)
);
assert_eq!(parse_yes_no("no\n"), Some(false));
assert_eq!(parse_yes_no("unknown\n"), None);
}
}
+152
View File
@@ -0,0 +1,152 @@
use std::{
fs, io,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
};
use gpapi::process::collection::CollectorCommands;
use super::SentinelInfo;
const SENTINEL_DIR: &str = "/opt/sentinelone";
pub(super) fn detect(commands: &CollectorCommands<'_>) -> io::Result<Option<SentinelInfo>> {
let Some(cli) = trusted_cli() else {
return Ok(None);
};
let Some(version) = run(commands, &cli, &["version"])?.as_deref().and_then(parse_version) else {
return Ok(None);
};
let Some(agent_enabled) = run(commands, &cli, &["control", "status"])?
.as_deref()
.and_then(|status| parse_enabled(status, "Agent state"))
else {
return Ok(None);
};
let real_time_protection = if agent_enabled {
let Some(policy) = run(commands, &cli, &["policy", "status"])? else {
return Ok(None);
};
let (Some(on_write), Some(on_execute)) = (
parse_enabled(&policy, "On-Write:"),
parse_enabled(&policy, "On-Execute:"),
) else {
return Ok(None);
};
on_write || on_execute
} else {
false
};
Ok(Some(SentinelInfo {
version,
real_time_protection,
firewall_enabled: None,
}))
}
fn trusted_cli() -> Option<PathBuf> {
let agent_uid = uzers::get_user_by_name("sentinelone")?.uid();
let agent_dir = Path::new(SENTINEL_DIR);
if !trusted_dir(Path::new("/opt"), 0) {
return None;
}
let link = fs::symlink_metadata(agent_dir).ok()?;
if link.file_type().is_symlink() && link.uid() != 0 {
return None;
}
let resolved_dir = fs::canonicalize(agent_dir).ok()?;
for ancestor in resolved_dir.ancestors().skip(1) {
if !trusted_dir(ancestor, 0) {
return None;
}
}
if !(trusted_dir(&resolved_dir, 0) || trusted_dir(&resolved_dir, agent_uid))
|| !trusted_dir(&resolved_dir.join("bin"), 0)
{
return None;
}
let cli = resolved_dir.join("bin/sentinelctl");
let metadata = fs::symlink_metadata(&cli).ok()?;
if !metadata.is_file()
|| metadata.uid() != 0
|| metadata.permissions().mode() & 0o022 != 0
|| metadata.permissions().mode() & 0o111 == 0
{
return None;
}
Some(cli)
}
fn trusted_dir(path: &Path, owner: u32) -> bool {
let Ok(metadata) = fs::symlink_metadata(path) else {
return false;
};
metadata.is_dir() && metadata.uid() == owner && metadata.permissions().mode() & 0o022 == 0
}
fn run(commands: &CollectorCommands<'_>, cli: &Path, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run_path(cli, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn parse_version(output: &str) -> Option<String> {
let version = value(output, "Agent version:")?;
if version.is_empty()
|| version.len() > 64
|| !version
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_'))
{
return None;
}
Some(version.to_string())
}
fn parse_enabled(output: &str, label: &str) -> Option<bool> {
match value(output, label)? {
"Enabled" => Some(true),
"Disabled" => Some(false),
_ => None,
}
}
fn value<'a>(output: &'a str, label: &str) -> Option<&'a str> {
output
.lines()
.find_map(|line| line.trim().strip_prefix(label).map(str::trim))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_observed_agent_and_policy_status() {
assert_eq!(
parse_version("Agent version: 25.2.2.14\nSentinelCTL version: 25.2.2.14\n"),
Some("25.2.2.14".into())
);
assert_eq!(parse_enabled("Agent state Enabled\n", "Agent state"), Some(true));
assert_eq!(
parse_enabled("On-Write: Enabled\nOn-Execute: Disabled\n", "On-Write:"),
Some(true)
);
assert_eq!(
parse_enabled("On-Write: Enabled\nOn-Execute: Disabled\n", "On-Execute:"),
Some(false)
);
}
#[test]
fn rejects_unknown_or_invalid_status() {
assert_eq!(parse_version("Agent version: 25.2.2.14\"/>\n"), None);
assert_eq!(parse_enabled("Agent state Unknown\n", "Agent state"), None);
assert_eq!(parse_enabled("On-Write: Unknown\n", "On-Write:"), None);
}
}
+333
View File
@@ -0,0 +1,333 @@
<?xml version="1.0" encoding="UTF-8"?>
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
<ipv6-address>{{ host_info.default_ipv6() }}</ipv6-address>
<generate-time>{{ generate_time }}</generate-time>
<hip-report-version>4</hip-report-version>
<categories>
<entry name="host-info">
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
{% for iface in host_info.network_interfaces.iter() -%}
<entry name="{{ iface.name }}">
<description>{{ iface.description }}</description>
{% if let Some(mac) = iface.mac_address -%}
<mac-address>{{ mac }}</mac-address>
{% endif -%}
{% if let Some(ipv4) = iface.ipv4 -%}
<ip-address>
<entry name="{{ ipv4 }}"/>
</ip-address>
{% endif -%}
{% if let Some(ipv6) = iface.ipv6 -%}
<ipv6-address>
<entry name="{{ ipv6 }}"/>
</ipv6-address>
{% endif -%}
</entry>
{% endfor -%}
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Gatekeeper" version="{{ host_info.software_version }}" defver="" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Time Machine" version="1.3"/>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="FileVault" version="{{ host_info.software_version }}"/>
<drives>
<entry>
<drive-name>Macintosh HD</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>Data</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>All</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
{% if let Some(firewall_enabled) = sentinel.firewall_enabled %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}"/>
<is-enabled>{% if firewall_enabled %}yes{% else %}no{% endif %}</is-enabled>
</ProductInfo>
</entry>
{% endif -%}
{% endif -%}
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="OpenBSD" name="Packet Filter" version="{{ host_info.software_version }}"/>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Software Update" version="3.0"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
{% if let Some(defender) = &host_info.defender %}
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
{% if let Some(clamav) = &host_info.clamav %}
<entry>
<ProductInfo>
<Prod vendor="Cisco Systems, Inc." name="ClamAV" version="{{ clamav.version }}"{% if let Some(definitions_version) = &clamav.definitions_version %} defver="{{ definitions_version }}"{% endif %} engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
<real-time-protection>{% if clamav.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
</list>
</entry>
<entry name="disk-backup">
<list/>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="cryptsetup" version="2.3.3" vendor="GitLab Inc.">
</Prod>
<drives>
<entry>
<drive-name>/</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
{% if let Some(ufw) = &host_info.ufw %}
<entry>
<ProductInfo>
<Prod vendor="Canonical Ltd." name="UFW" version="{{ ufw.version }}"/>
<is-enabled>{% if ufw.is_enabled %}yes{% else %}no{% endif %}</is-enabled>
</ProductInfo>
</entry>
{% endif -%}
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
</Prod>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="nftables" version="0.9.3" vendor="The Netfilter Project">
</Prod>
<is-enabled>n/a</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
+2 -1
View File
@@ -2,11 +2,12 @@
name = "openconnect"
version.workspace = true
edition.workspace = true
license.workspace = true
license = "MIT"
links = "openconnect"
[dependencies]
log.workspace = true
libc = "0.2"
is_executable.workspace = true
[build-dependencies]
+21 -674
View File
@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
MIT License
Copyright (c) 2024 Kevin Yue
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+67 -69
View File
@@ -1,37 +1,8 @@
use std::{env, path::PathBuf, process::Command};
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
let patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory")
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().extension().and_then(|s| s.to_str()) == Some("patch"))
.map(|entry| entry.path())
.collect::<Vec<_>>();
// Sort patches to ensure they are applied in order
let mut patches = patches;
patches.sort();
for patch in patches {
println!("cargo:rerun-if-changed={}", patch.display());
println!("Applying patch: {}", patch.display());
let status = Command::new("patch")
.arg("-p1") // Strip one level of path (standard for git diffs)
.arg("-i") // Input file
.arg(&patch)
.current_dir(build_src) // Run INSIDE the copied dir
.status()
.expect("Failed to execute patch command");
if !status.success() {
panic!("Failed to apply patch file: {}", patch.display());
}
}
}
use std::{env, path::PathBuf};
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2");
let install_dir = out_dir.join("libxml2_install");
// The temporary location where we will build
let build_src = out_dir.join("libxml2_build");
@@ -44,6 +15,10 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
@@ -55,24 +30,28 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the libxml2 library using autotools
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
// Disable optional features that complicate static builds
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
// Ensure position-independent code (safe for static linking)
.cflag("-fPIC")
.build();
let dst = {
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.enable_static()
.disable_shared()
// Disable optional features that complicate static builds
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
// Ensure position-independent code (safe for static linking)
.cflag("-fPIC");
config.build()
};
let lib_dir = dst.join("lib");
let include_dir = dst.join("include/libxml2");
@@ -91,12 +70,12 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches");
let install_dir = out_dir.join("openconnect_install");
// The temporary location where we will build
let build_src = out_dir.join("openconnect_build");
// Track changes so cargo rebuilds if patch or submodule changes
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
// Prepare the build directory
@@ -104,6 +83,10 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
if install_dir.exists() {
std::fs::remove_dir_all(&install_dir).unwrap();
}
std::fs::create_dir_all(&install_dir).unwrap();
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
@@ -114,18 +97,13 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Apply all patches from the patches directory
apply_patches(&patches_dir, &build_src);
// Build the OpenConnect library using autotools
// We explicitly enable static and disable shared to ensure we get a .a file.
// .reconf("-ivf") is CRITICAL for git submodules because 'configure'
// usually doesn't exist yet and needs to be generated.
// Build the OpenConnect library using autotools. Keep the upstream LGPL
// library dynamically linked on macOS so it remains replaceable in the app
// bundle. Other platforms retain the existing static-link behavior.
let mut config = autotools::Config::new(&build_src);
config
.out_dir(&install_dir)
.reconf("-ivf")
.enable_static()
.disable_shared()
.disable("nls", None) // disable translations to save space
.disable("docs", None)
.disable("dsa-tests", None)
@@ -139,10 +117,14 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
#[cfg(target_os = "macos")]
{
config.disable_static().enable_shared().without("gnutls", None);
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
#[cfg(not(target_os = "macos"))]
config.enable_static().disable_shared();
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
{
config.ldflag("-L/usr/local/lib");
@@ -155,10 +137,12 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
// Tell rustc where to find the static library
println!("cargo:rustc-link-search=native={}", lib_dir.display());
// Static linking of openconnect
#[cfg(target_os = "macos")]
println!("cargo:rustc-link-lib=dylib=openconnect");
#[cfg(not(target_os = "macos"))]
println!("cargo:rustc-link-lib=static=openconnect");
// Export include path for downstream use (bindgen / cc)
@@ -173,6 +157,14 @@ fn main() {
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
oc_dst.join("build").display()
);
println!(
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
out_dir.join("openconnect_build").display()
);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
@@ -184,14 +176,20 @@ fn main() {
// Using pkg-config to find system deps
pkg_config::probe_library("zlib").unwrap();
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
#[cfg(target_os = "macos")]
pkg_config::probe_library("openssl").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
#[cfg(not(target_os = "macos"))]
{
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
}
// Compile the vpn.c file
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
@@ -1,114 +0,0 @@
From a8d5ec198ca9ae47a0e6b4f1ea244d2738acf055 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:02 +0800
Subject: [PATCH 1/4] Add support for GlobalProtect app version handling
- Introduced `gp_app_version` field in `openconnect_info` structure.
- Implemented `openconnect_set_gp_app_version` and `openconnect_get_gp_app_version` functions.
- Updated `gpst_get_config` to use the app version in requests.
- Free `gp_app_version` in `openconnect_vpninfo_free` to prevent memory leaks.
---
gpst.c | 8 +++++---
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 2 ++
4 files changed, 26 insertions(+), 3 deletions(-)
diff --git a/gpst.c b/gpst.c
index 244aaf04..5c24bbd2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
/* submit getconfig request */
+ const char *app_version = openconnect_get_gp_app_version(vpninfo);
+ vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version);
+
buf_append(request_body, "client-type=1&protocol-version=p1&internal=no");
- append_opt(request_body, "app-version", vpninfo->csd_ticket ? : "6.3.0-33");
+ append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
append_opt(request_body, "os-version", vpninfo->platname);
@@ -1040,8 +1043,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
* accept new ones.
*/
unsetenv("APP_VERSION");
- if (vpninfo->csd_ticket)
- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1))
+ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index b5e74e9b..18334c76 100644
--- a/library.c
+++ b/library.c
@@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
+ free(vpninfo->gp_app_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
return 0;
}
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version)
+{
+ UTF8CHECK(gp_app_version);
+
+ STRDUP(vpninfo->gp_app_version, gp_app_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..988f85f0 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -786,6 +786,7 @@ struct openconnect_info {
int is_dyndns; /* Attempt to redo DNS lookup on each CSTP reconnect */
char *useragent;
char *version_string;
+ char *gp_app_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo);
/* hpke.c */
int handle_external_browser(struct openconnect_info *vpninfo);
+/* Get the app version */
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 136f181a..7d4f3399 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -470,6 +470,8 @@ int openconnect_set_http_proxy(struct openconnect_info *vpninfo,
int openconnect_set_useragent(struct openconnect_info *vpninfo,
const char *useragent);
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version);
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -1,32 +0,0 @@
From 8591eba702f52dae335601c997271786be50dff7 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:52 +0800
Subject: [PATCH 2/4] Update user agent for common headers in GlobalProtect
authentication
---
auth-globalprotect.c | 7 -------
1 file changed, 7 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 8d094273..27e41c2b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -34,14 +34,7 @@ struct login_context {
void gpst_common_headers(struct openconnect_info *vpninfo,
struct oc_text_buf *buf)
{
- char *orig_ua = vpninfo->useragent;
-
- /* XX: more recent servers don't appear to require this specific UA value,
- * but we don't have any good way to detect them.
- */
- vpninfo->useragent = (char *)"PAN GlobalProtect";
http_common_headers(vpninfo, buf);
- vpninfo->useragent = orig_ua;
}
/* Translate platform names (derived from AnyConnect) into the values
--
2.50.1 (Apple Git-155)
@@ -1,121 +0,0 @@
From dda2aceca7e614af65b968e632065ef223cb6612 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:14:08 +0800
Subject: [PATCH 3/4] Add support for OS version handling in GlobalProtect
authentication
---
auth-globalprotect.c | 2 +-
gpst.c | 4 ++--
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 3 +++
5 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 27e41c2b..59d6de3b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -731,7 +731,7 @@ static int gpst_login(struct openconnect_info *vpninfo, int portal, struct login
buf_append(request_body, "jnlpReady=jnlpReady&ok=Login&direct=yes&clientVer=4100&prot=https:&internal=no");
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "server", vpninfo->hostname);
append_opt(request_body, "computer", vpninfo->localname);
if (ctx->portal_userauthcookie)
diff --git a/gpst.c b/gpst.c
index 5c24bbd2..0373fce0 100644
--- a/gpst.c
+++ b/gpst.c
@@ -657,7 +657,7 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "hmac-algo", "sha1,md5,sha256");
append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc");
if (old_addr || old_addr6) {
@@ -1044,7 +1044,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
*/
unsetenv("APP_VERSION");
if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
- goto out;
+ goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index 18334c76..e2169054 100644
--- a/library.c
+++ b/library.c
@@ -897,6 +897,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
free(vpninfo->gp_app_version);
+ free(vpninfo->gp_os_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1034,6 +1035,20 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
}
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version)
+{
+ UTF8CHECK(gp_os_version);
+
+ STRDUP(vpninfo->gp_os_version, gp_os_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_os_version ?: vpninfo->platname;
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index 988f85f0..5c8d2909 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -787,6 +787,7 @@ struct openconnect_info {
char *useragent;
char *version_string;
char *gp_app_version;
+ char *gp_os_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1681,6 +1682,9 @@ int handle_external_browser(struct openconnect_info *vpninfo);
/* Get the app version */
const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+/* Get the OS version string for GP */
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 7d4f3399..aa96a53b 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -472,6 +472,9 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
const char *gp_app_version);
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version);
+
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -1,39 +0,0 @@
From 3915a51c81831a1a9b087d82f0c760365682f23b Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Mon, 15 Dec 2025 19:20:44 +0800
Subject: [PATCH 4/4] Add client version and OS information to HIP script
arguments
---
gpst.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/gpst.c b/gpst.c
index 0373fce0..d04c42c2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -1013,6 +1013,12 @@ static int run_hip_script(struct openconnect_info *vpninfo)
exit(1);
hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper);
+ hip_argv[i++] = "--client-version";
+ hip_argv[i++] = openconnect_get_gp_app_version(vpninfo);
+ hip_argv[i++] = "--client-os";
+ hip_argv[i++] = gpst_os_name(vpninfo);
+ hip_argv[i++] = "--os-version";
+ hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
hip_argv[i++] = "--cookie";
hip_argv[i++] = vpninfo->cookie;
if (vpninfo->ip_info.addr) {
@@ -1025,8 +1031,6 @@ static int run_hip_script(struct openconnect_info *vpninfo)
}
hip_argv[i++] = "--md5";
hip_argv[i++] = vpninfo->csd_token;
- hip_argv[i++] = "--client-os";
- hip_argv[i++] = gpst_os_name(vpninfo);
hip_argv[i++] = NULL;
/* XX: Sending the above parameters as --long-options was a mistake that was
--
2.50.1 (Apple Git-155)
@@ -1,124 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..78c16d1c 100644
--- a/gpst.c
+++ b/gpst.c
@@ -438,8 +438,19 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
new_ip_info.mtu = atoi(s);
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
+ vpninfo->gp_session_lifetime = atoi(s);
vpninfo->auth_expiration = time(NULL) + atol(s);
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
+ vpninfo->gp_user_expires = atol(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
+ free(vpninfo->gp_lifetime_notify_message);
+ vpninfo->gp_lifetime_notify_message = s;
+ s = NULL;
+ }
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
if (strcmp(s, "no"))
vpn_progress(vpninfo, PRG_DEBUG,
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
index f036c071..44110486 100644
--- a/libopenconnect.map.in
+++ b/libopenconnect.map.in
@@ -113,6 +113,10 @@ OPENCONNECT_5_7 {
openconnect_set_cookie;
openconnect_set_allow_insecure_crypto;
openconnect_get_auth_expiration;
+ openconnect_get_gp_session_lifetime;
+ openconnect_get_gp_user_expires;
+ openconnect_get_gp_lifetime_notify_prior;
+ openconnect_get_gp_lifetime_notify_message;
openconnect_disable_dtls;
openconnect_get_connect_url;
openconnect_set_webview_callback;
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
index 7cb04d05..2c7af781 100644
--- a/libopenconnect5.symbols
+++ b/libopenconnect5.symbols
@@ -94,6 +94,10 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
openconnect_set_cookie@OPENCONNECT_5_7 8.20
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
diff --git a/library.c b/library.c
index b5e74e9b..03f47004 100644
--- a/library.c
+++ b/library.c
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->dtls_cipher);
free(vpninfo->peer_cert_hash);
free(vpninfo->ciphersuite_config);
+ free(vpninfo->gp_lifetime_notify_message);
#if defined(OPENCONNECT_OPENSSL)
free(vpninfo->cstp_cipher);
#if defined(HAVE_BIO_METH_FREE)
@@ -1137,6 +1138,26 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
return vpninfo->auth_expiration;
}
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_session_lifetime;
+}
+
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_user_expires;
+}
+
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_prior;
+}
+
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_message;
+}
+
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
const struct oc_ip_info **info,
const struct oc_vpn_option **cstp_options,
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..dd5507ca 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -647,6 +647,10 @@ struct openconnect_info {
int dtls_attempt_period;
int udp_probes_sent;
time_t auth_expiration;
+ int gp_session_lifetime;
+ time_t gp_user_expires;
+ int gp_lifetime_notify_prior;
+ char *gp_lifetime_notify_message;
time_t new_dtls_started;
#if defined(OPENCONNECT_OPENSSL)
SSL_CTX *dtls_ctx;
diff --git a/openconnect.h b/openconnect.h
index 136f181a..febf15cc 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -655,6 +655,10 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
int openconnect_get_idle_timeout(struct openconnect_info *);
time_t openconnect_get_auth_expiration(struct openconnect_info *);
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
/* The returned structures are owned by the library and may be freed/replaced
due to rekey or reconnect. Assume that once the mainloop starts, the
@@ -1,101 +0,0 @@
From 78078b21f53801b31fef352ec0de40d319edcae9 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sat, 13 Jun 2026 12:00:00 +0800
Subject: [PATCH 6/6] Add host ID to GlobalProtect HIP script arguments
---
gpst.c | 4 ++++
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 3 +++
4 files changed, 26 insertions(+)
diff --git a/gpst.c b/gpst.c
index 78c16d1c..f1e1f6bb 100644
--- a/gpst.c
+++ b/gpst.c
@@ -1019,6 +1019,10 @@ static int run_hip_script(struct openconnect_info *vpninfo)
hip_argv[i++] = "--client-os";
hip_argv[i++] = gpst_os_name(vpninfo);
hip_argv[i++] = "--os-version";
hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
+ if (openconnect_get_gp_host_id(vpninfo)) {
+ hip_argv[i++] = "--host-id";
+ hip_argv[i++] = openconnect_get_gp_host_id(vpninfo);
+ }
hip_argv[i++] = "--cookie";
hip_argv[i++] = vpninfo->cookie;
if (vpninfo->ip_info.addr) {
diff --git a/library.c b/library.c
index 03f47004..9e585119 100644
--- a/library.c
+++ b/library.c
@@ -900,6 +900,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->useragent);
free(vpninfo->gp_app_version);
free(vpninfo->gp_os_version);
+ free(vpninfo->gp_host_id);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1049,6 +1050,20 @@ const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
return vpninfo->gp_os_version ?: vpninfo->platname;
}
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
+ const char *gp_host_id)
+{
+ UTF8CHECK(gp_host_id);
+
+ STRDUP(vpninfo->gp_host_id, gp_host_id);
+ return 0;
+}
+
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_host_id;
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index a7e80659..76034fbd 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -788,6 +788,7 @@ struct openconnect_info {
char *version_string;
char *gp_app_version;
char *gp_os_version;
+ char *gp_host_id;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1684,6 +1685,9 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
/* Get the OS version string for GP */
const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
+/* Get the host ID string for GP */
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 40de2811..3c65c090 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -472,8 +472,11 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
const char *gp_app_version);
int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
const char *gp_os_version);
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
+ const char *gp_host_id);
+
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -1,15 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..fb8d945d 100644
--- a/gpst.c
+++ b/gpst.c
@@ -669,6 +669,10 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
free(vpninfo->urlpath);
vpninfo->urlpath = orig_path;
+ if (result >= 0 && xml_buf)
+ vpn_progress(vpninfo, PRG_DEBUG,
+ "GlobalProtect getconfig.esp response:\n%s\n",
+ xml_buf);
/* parse getconfig result */
if (result >= 0)
+513
View File
@@ -0,0 +1,513 @@
use crate::{HipControl, HipRequest, HipScript, HipSource, Vpn};
use std::{
ffi::{CString, c_char, c_int, c_void},
io,
marker::PhantomData,
panic::{AssertUnwindSafe, catch_unwind},
};
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_collect_hip_report(
script: *const HipScriptRaw,
request: *const HipRequestRaw,
control: *const HipControlRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int;
}
#[repr(C)]
pub(crate) struct HipRequestRaw {
cookie: *const c_char,
client_ip: *const c_char,
client_ipv6: *const c_char,
md5: *const c_char,
client_version: *const c_char,
client_os: *const c_char,
os_version: *const c_char,
host_id: *const c_char,
local_hostname: *const c_char,
}
#[repr(C)]
pub(crate) struct HipControlRaw {
pub data: *mut c_void,
pub check: unsafe extern "C" fn(*mut c_void) -> c_int,
}
pub(crate) type HipGenerateFn =
extern "C" fn(*mut c_void, *const HipRequestRaw, *const HipControlRaw, *mut c_char, usize, *mut usize) -> c_int;
#[repr(C)]
#[derive(Debug)]
pub(crate) struct HipScriptRaw {
pub path: *const c_char,
pub uid: u32,
pub uid_present: c_int,
pub validation_data: *mut c_void,
pub validate: Option<extern "C" fn(*mut c_void, *const HipControlRaw) -> c_int>,
pub environment: *const *const c_char,
pub cwd: *const c_char,
}
impl Default for HipScriptRaw {
fn default() -> Self {
Self {
path: std::ptr::null(),
uid: 0,
uid_present: 0,
validation_data: std::ptr::null_mut(),
validate: None,
environment: std::ptr::null(),
cwd: std::ptr::null(),
}
}
}
impl HipScriptRaw {
pub fn from_script(script: &HipScript) -> Self {
Self {
path: script.path.as_ptr(),
uid: script.user.unwrap_or(0),
uid_present: script.user.is_some().into(),
validation_data: script as *const _ as *mut _,
validate: script.validator.as_ref().map(|_| validate_hip_script as _),
environment: std::ptr::null(),
cwd: script.cwd.as_ref().map_or(std::ptr::null(), |value| value.as_ptr()),
}
}
}
pub(crate) fn script_environment(script: &HipScript) -> Vec<*const c_char> {
match &script.environment {
Some(values) => values
.iter()
.map(|value| value.as_ptr())
.chain(std::iter::once(std::ptr::null()))
.collect(),
None => Vec::new(),
}
}
fn error_code(error: io::Error) -> c_int {
let errno = error.raw_os_error().unwrap_or_else(|| match error.kind() {
io::ErrorKind::Interrupted => libc::EINTR,
io::ErrorKind::TimedOut => libc::ETIMEDOUT,
io::ErrorKind::InvalidInput | io::ErrorKind::InvalidData => libc::EINVAL,
io::ErrorKind::PermissionDenied => libc::EPERM,
io::ErrorKind::NotFound => libc::ENOENT,
_ => libc::EIO,
});
-errno
}
unsafe fn request_string(pointer: *const c_char) -> io::Result<Option<String>> {
if pointer.is_null() {
return Ok(None);
}
unsafe { std::ffi::CStr::from_ptr(pointer) }
.to_str()
.map(|s| Some(s.to_owned()))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid HIP request encoding"))
}
unsafe fn read_hip_request(raw: &HipRequestRaw) -> io::Result<HipRequest> {
unsafe {
Ok(HipRequest {
cookie: request_string(raw.cookie)?.unwrap_or_default(),
client_ip: request_string(raw.client_ip)?,
client_ipv6: request_string(raw.client_ipv6)?,
md5: request_string(raw.md5)?.unwrap_or_default(),
client_version: request_string(raw.client_version)?.unwrap_or_default(),
client_os: request_string(raw.client_os)?.unwrap_or_default(),
os_version: request_string(raw.os_version)?.unwrap_or_default(),
host_id: request_string(raw.host_id)?,
local_hostname: request_string(raw.local_hostname)?,
})
}
}
pub(crate) extern "C" fn generate_hip_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let vpn = unsafe { &*(data as *const Vpn) };
generate_source_report(
vpn.hip_source.as_ref() as *const HipSource as *mut _,
request,
control,
output,
capacity,
written,
)
}
extern "C" fn generate_source_report(
data: *mut c_void,
request: *const HipRequestRaw,
control: *const HipControlRaw,
output: *mut c_char,
capacity: usize,
written: *mut usize,
) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
let source = unsafe { &*(data as *const HipSource) };
let HipSource::Generator(generate) = source else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
};
let request = unsafe { read_hip_request(&*request)? };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
let report = generate(&request, &control)?;
control.check()?;
if report.len() > capacity {
return Err(io::Error::from_raw_os_error(libc::E2BIG));
}
unsafe {
std::ptr::copy_nonoverlapping(report.as_ptr(), output.cast(), report.len());
*written = report.len();
}
Ok(())
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlRaw) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let script = unsafe { &*(data as *const HipScript) };
let control = HipControl {
raw: unsafe { &*control },
_thread: PhantomData,
};
control.check()?;
if let Some(validate) = &script.validator {
validate(&control)?;
}
control.check()
}));
match result {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
pub(crate) fn collect_hip_source(
source: &HipSource,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
match source {
HipSource::Disabled => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP collection is disabled",
)),
HipSource::Script(script) => collect_hip_script(script, request, check),
HipSource::Generator(_) => collect_hip_report(
&HipScriptRaw::default(),
Some(generate_source_report),
source as *const _ as *mut _,
request,
check,
),
}
}
pub(crate) fn collect_hip_script(
script: &HipScript,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let mut raw = HipScriptRaw::from_script(script);
let environment = script_environment(script);
if !environment.is_empty() {
raw.environment = environment.as_ptr();
}
collect_hip_report(&raw, None, std::ptr::null_mut(), request, check)
}
fn collect_hip_report(
script_raw: &HipScriptRaw,
generate: Option<HipGenerateFn>,
data: *mut c_void,
request: &HipRequest,
check: &dyn Fn() -> io::Result<()>,
) -> io::Result<String> {
let values = [
Some(request.cookie.as_str()),
request.client_ip.as_deref(),
request.client_ipv6.as_deref(),
Some(request.md5.as_str()),
Some(request.client_version.as_str()),
Some(request.client_os.as_str()),
Some(request.os_version.as_str()),
request.host_id.as_deref(),
request.local_hostname.as_deref(),
]
.into_iter()
.map(|value| value.map(CString::new).transpose())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP request contains NUL"))?;
let ptr = |i: usize| values[i].as_ref().map_or(std::ptr::null(), |value| value.as_ptr());
let raw = HipRequestRaw {
cookie: ptr(0),
client_ip: ptr(1),
client_ipv6: ptr(2),
md5: ptr(3),
client_version: ptr(4),
client_os: ptr(5),
os_version: ptr(6),
host_id: ptr(7),
local_hostname: ptr(8),
};
let control = HipControlRaw {
data: &check as *const _ as *mut _,
check: collection_check,
};
let mut output = vec![0u8; 1024 * 1024 + 1];
let mut written = 0;
let result = unsafe {
vpn_collect_hip_report(
script_raw,
&raw,
&control,
generate,
data,
output.as_mut_ptr().cast(),
1024 * 1024,
&mut written,
)
};
if result < 0 {
return Err(io::Error::from_raw_os_error(-result));
}
output.truncate(written);
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
}
unsafe extern "C" fn collection_check(data: *mut c_void) -> c_int {
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
match catch_unwind(AssertUnwindSafe(check)) {
Ok(Ok(())) => 0,
Ok(Err(error)) => error_code(error),
Err(_) => -libc::EIO,
}
}
#[cfg(test)]
mod hip_tests {
use super::*;
use std::{
fs,
os::unix::fs::PermissionsExt,
sync::atomic::{AtomicUsize, Ordering},
time::{Duration, Instant},
};
fn provider(generate: impl Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync + 'static) -> Vpn {
Vpn::builder("vpn.example", "cookie")
.script_path("/bin/sh".to_owned())
.hip_source(HipSource::Generator(std::sync::Arc::new(generate)))
.build()
.unwrap()
}
fn collect(vpn: &Vpn, script: &HipScriptRaw, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
collect_hip_report(
script,
Some(generate_hip_report),
vpn as *const _ as *mut _,
&HipRequest::default(),
check,
)
}
struct ScriptFixture(std::path::PathBuf);
impl ScriptFixture {
fn new(contents: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let directory = std::env::temp_dir().join(format!(
"gp-hip-script-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&directory).unwrap();
let path = directory.join("script");
fs::write(&path, format!("#!/bin/sh\n{contents}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
Self(directory)
}
fn script(&self, user: Option<u32>) -> HipScript {
HipScript::new(self.0.join("script").to_str().unwrap().to_owned(), user).unwrap()
}
}
impl Drop for ScriptFixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn standalone_source_uses_bounded_executor_without_a_vpn() {
let source = HipSource::Generator(std::sync::Arc::new(|request, control| {
control.check()?;
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.42"));
assert_eq!(request.md5, "physical-session-token");
Ok("<hip-report/>".into())
}));
let request = HipRequest {
client_ip: Some("192.0.2.42".into()),
md5: "physical-session-token".into(),
..Default::default()
};
assert_eq!(source.collect(&request, &|| Ok(())).unwrap(), "<hip-report/>");
let too_large = HipSource::Generator(std::sync::Arc::new(|_, _| Ok("x".repeat(1024 * 1024 + 1))));
assert_eq!(
too_large.collect(&request, &|| Ok(())).unwrap_err().raw_os_error(),
Some(libc::E2BIG)
);
assert!(HipSource::Disabled.collect(&request, &|| Ok(())).is_err());
}
#[test]
fn standalone_source_checks_cancellation_before_generation() {
let source = HipSource::Generator(std::sync::Arc::new(|_, _| panic!("Cancelled source must not run")));
assert_eq!(
source
.collect(&HipRequest::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn callback_outputs_are_bounded_and_validated_by_c() {
let raw = HipScriptRaw::default();
for (report, errno) in [
(String::new(), libc::EINVAL),
("x\0x".to_owned(), libc::EINVAL),
("x".repeat(1024 * 1024 + 1), libc::E2BIG),
] {
let vpn = provider(move |_, _| Ok(report.clone()));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap_err().raw_os_error(), Some(errno));
}
let vpn = provider(|_, _| Ok("x".repeat(1024 * 1024)));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap().len(), 1024 * 1024);
}
#[test]
fn callback_panics_and_control_errors_do_not_cross_ffi() {
let vpn = provider(|_, _| panic!("test generator panic"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
let vpn = provider(|_, _| Err(io::Error::from(io::ErrorKind::TimedOut)));
assert_eq!(
collect(&vpn, &Default::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::ETIMEDOUT)
);
let vpn = provider(|_, _| panic!("Canceled provider must not run"));
assert_eq!(
collect(&vpn, &Default::default(), &|| Err(io::Error::from(
io::ErrorKind::Interrupted
)))
.unwrap_err()
.raw_os_error(),
Some(libc::EINTR)
);
}
#[test]
fn explicit_script_wins_and_uid_presence_is_preserved() {
let fixture = ScriptFixture::new("printf '<script/>'");
let script = fixture.script(None);
let raw = HipScriptRaw::from_script(&script);
assert_eq!(raw.uid_present, 0);
let vpn = provider(|_, _| panic!("Script must win"));
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
let script = fixture.script(Some(unsafe { libc::getuid() }));
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
assert_eq!(script.collect(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
}
#[test]
fn validator_refusal_prevents_execution_and_errors_propagate() {
let fixture = ScriptFixture::new("touch executed; printf '<script/>'");
let script = fixture
.script(None)
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
assert_eq!(
script
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EPERM)
);
assert!(!fixture.0.join("executed").exists());
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
assert_eq!(
script
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EIO)
);
}
#[test]
fn child_environment_and_cwd_are_explicit_without_parent_mutation() {
let fixture = ScriptFixture::new("printf '%s:%s' \"$HIP_TEST_VALUE\" \"$PWD\"");
let cwd = fs::canonicalize(&fixture.0).unwrap().to_str().unwrap().to_owned();
let script = fixture
.script(None)
.with_environment(crate::HipScriptEnvironment {
variables: vec![("HIP_TEST_VALUE".into(), "child".into())],
cwd: cwd.clone(),
})
.unwrap();
assert_eq!(
script.collect(&HipRequest::default(), &|| Ok(())).unwrap(),
format!("child:{cwd}")
);
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
}
#[test]
fn script_empty_nul_and_nonzero_outputs_fail() {
for contents in ["true", "printf '\\000'", "printf '<script/>'; exit 1"] {
let fixture = ScriptFixture::new(contents);
assert_eq!(
fixture
.script(None)
.collect(&HipRequest::default(), &|| Ok(()))
.unwrap_err()
.raw_os_error(),
Some(libc::EINVAL)
);
}
}
#[test]
fn cancellation_and_deadline_kill_descendants_and_reap_child() {
for errno in [libc::EINTR, libc::ETIMEDOUT] {
let fixture = ScriptFixture::new("sleep 20 &\nwait\nprintf '<script/>'");
let start = Instant::now();
let check = || {
if start.elapsed() > Duration::from_millis(80) {
Err(io::Error::from_raw_os_error(errno))
} else {
Ok(())
}
};
assert_eq!(
fixture
.script(None)
.collect(&HipRequest::default(), &check)
.unwrap_err()
.raw_os_error(),
Some(errno)
);
assert!(start.elapsed() < Duration::from_secs(2));
}
}
}
+43 -6
View File
@@ -1,12 +1,19 @@
mod hip;
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};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
#[derive(Debug)]
pub(crate) struct ConnectOptions {
pub user_data: *mut c_void,
pub on_hip_report_submitted: Option<extern "C" fn(*mut c_void, *const c_char, usize)>,
pub server: *const c_char,
pub cookie: *const c_char,
@@ -27,8 +34,8 @@ pub(crate) struct ConnectOptions {
pub key_password: *const c_char,
pub servercert: *const c_char,
pub csd_uid: u32,
pub csd_wrapper: *const c_char,
pub hip_script: HipScriptRaw,
pub generate_hip: Option<HipGenerateFn>,
pub reconnect_timeout: u32,
pub mtu: u32,
@@ -47,26 +54,56 @@ pub(crate) struct VpnSessionInfoRaw {
pub user_expires: c_long,
pub lifetime_warning_prior: c_int,
pub lifetime_warning_message: *const c_char,
pub nlb_enabled: c_int,
pub nlb_connected_gw_ip: *const c_char,
}
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_write_cancel(fd: c_int) -> c_int;
#[link_name = "vpn_connect"]
fn vpn_connect(
options: *const ConnectOptions,
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
) -> c_int;
#[link_name = "vpn_disconnect"]
fn vpn_disconnect();
}
pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
let error = unsafe { vpn_write_cancel(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()
}
#[unsafe(no_mangle)]
extern "C" fn vpn_detach_command_pipe(vpn: *mut c_void) {
unsafe { &*(vpn as *const Vpn) }.detach_command_pipe();
}
pub(crate) fn connect(options: &ConnectOptions) -> i32 {
unsafe { vpn_connect(options, on_vpn_connected) }
}
pub(crate) fn disconnect() {
unsafe { vpn_disconnect() }
#[unsafe(no_mangle)]
pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *const c_char, length: usize) {
let vpn = unsafe { &*(vpn as *const Vpn) };
if report.is_null() || length > 1024 * 1024 {
return;
}
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
if let Ok(report) = std::str::from_utf8(bytes) {
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
warn!("HIP submission observer failed");
}
}
}
#[unsafe(no_mangle)]
+79 -45
View File
@@ -1,4 +1,5 @@
#include <openconnect.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -7,13 +8,12 @@
#include "vpn.h"
void *g_user_data;
static int g_cmd_pipe_fd;
static const char *g_vpnc_script;
static const char *g_vpnc_interface;
static int g_script_tun;
static vpn_connected_callback on_vpn_connected;
struct vpn_context {
struct openconnect_info *vpninfo;
int command_fd;
const vpn_options *options;
vpn_connected_callback on_connected;
};
/* Validate the peer certificate */
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
@@ -40,14 +40,17 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
}
}
static void setup_tun_handler(void *_vpninfo)
static void setup_tun_handler(void *private_data)
{
struct vpn_context *context = private_data;
struct openconnect_info *_vpninfo = context->vpninfo;
const vpn_options *options = context->options;
int ret;
if (g_script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
if (options->script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, options->script);
} else {
ret = openconnect_setup_tun_device(_vpninfo, g_vpnc_script,
g_vpnc_interface);
ret = openconnect_setup_tun_device(_vpninfo, options->script,
options->interface);
}
if (!ret) {
@@ -59,8 +62,11 @@ static void setup_tun_handler(void *_vpninfo)
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
.lifetime_warning_message =
openconnect_get_gp_lifetime_notify_message(_vpninfo),
.nlb_enabled = openconnect_get_gp_nlb_enabled(_vpninfo),
.nlb_connected_gw_ip =
openconnect_get_gp_nlb_connected_gw_ip(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
context->on_connected(context->command_fd, &session_info, options->user_data);
}
}
@@ -71,20 +77,17 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
struct utsname utsbuf;
const char *effective_local_hostname = NULL;
g_user_data = options->user_data;
g_vpnc_script = options->script;
g_vpnc_interface = options->interface;
g_script_tun = options->script_tun;
on_vpn_connected = callback;
struct vpn_context context = { .options = options, .on_connected = callback };
int result = 1;
INFO("USER_AGENT: %s", options->user_agent);
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("SCRIPT_TUN: %d", g_script_tun);
INFO("CSD_USER: %d", options->csd_uid);
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->hip_script.uid);
INFO("CSD_WRAPPER: %s", options->hip_script.path);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
INFO("MTU: %d", options->mtu);
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
@@ -94,13 +97,28 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
vpninfo =
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
NULL, NULL, print_progress, NULL);
NULL, NULL, print_progress, &context);
if (!vpninfo) {
ERROR("openconnect_vpninfo_new failed");
return 1;
}
context.vpninfo = vpninfo;
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
options->on_hip_report_submitted);
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
if (context.command_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
goto cleanup;
}
/* An earlier disconnect remains latched on this attempt. */
if (vpn_attach_command_pipe(options->user_data, context.command_fd)) {
INFO("VPN attempt canceled before startup");
result = -EINTR;
goto cleanup;
}
openconnect_set_loglevel(vpninfo, PRG_TRACE);
openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp");
@@ -150,9 +168,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper);
openconnect_set_gp_hip_generator(vpninfo, options->user_data, options->generate_hip);
if (options->hip_script.path) {
result = openconnect_set_gp_hip_script(vpninfo, options->hip_script.path,
options->hip_script.uid_present, options->hip_script.uid,
options->hip_script.validation_data, options->hip_script.validate,
options->hip_script.environment, options->hip_script.cwd);
if (result)
goto cleanup;
}
if (options->mtu > 0) {
@@ -167,23 +190,15 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (options->dpd_interval > 0) {
openconnect_set_dpd(vpninfo, options->dpd_interval);
}
g_cmd_pipe_fd = openconnect_setup_cmd_pipe(vpninfo);
if (g_cmd_pipe_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
return 1;
}
// Essential step
if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed");
return 1;
goto cleanup;
}
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
openconnect_disable_dtls(vpninfo);
}
// Essential step
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
@@ -193,23 +208,42 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (ret) {
INFO("openconnect_mainloop returned %d, exiting", ret);
openconnect_vpninfo_free(vpninfo);
return ret;
result = ret;
goto cleanup;
}
INFO("openconnect_mainloop returned 0, reconnecting");
}
cleanup:
vpn_detach_command_pipe(options->user_data);
openconnect_vpninfo_free(vpninfo);
return result;
}
/* Stop the VPN connection */
void vpn_disconnect()
/* Called with the attempt cancellation mutex held, never after detach/free. */
int vpn_write_cancel(int fd)
{
char cmd = OC_CMD_CANCEL;
char command = OC_CMD_CANCEL;
ssize_t written;
do {
written = write(fd, &command, 1);
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
INFO("Stopping VPN connection: %d", g_cmd_pipe_fd);
if (write(g_cmd_pipe_fd, &cmd, 1) < 0) {
ERROR("Failed to write to command pipe, VPN connection may not "
"be stopped");
}
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,
char *output, size_t capacity, size_t *written)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("HIP preview", NULL, NULL, NULL, print_progress, NULL);
int result;
if (!vpninfo)
return -ENOMEM;
openconnect_set_gp_hip_generator(vpninfo, data, generate);
result = openconnect_set_gp_hip_script(vpninfo, script->path, script->uid_present,
script->uid, script->validation_data, script->validate, script->environment, script->cwd);
if (!result) result = openconnect_collect_gp_hip_report(vpninfo, request, control, output, capacity, written);
openconnect_vpninfo_free(vpninfo);
return result;
}
+22 -3
View File
@@ -9,14 +9,29 @@ typedef struct vpn_session_info {
long user_expires;
int lifetime_warning_prior;
const char *lifetime_warning_message;
int nlb_enabled;
const char *nlb_connected_gw_ip;
} vpn_session_info;
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
size_t length);
typedef struct vpn_hip_script {
const char *path;
uid_t uid;
int uid_present;
void *validation_data;
openconnect_gp_hip_validate_fn validate;
const char *const *environment;
const char *cwd;
} vpn_hip_script;
typedef struct vpn_options {
void *user_data;
vpn_hip_report_callback on_hip_report_submitted;
const char *server;
const char *cookie;
@@ -37,8 +52,8 @@ typedef struct vpn_options {
const char *key_password;
const char *servercert;
const uid_t csd_uid;
const char *csd_wrapper;
vpn_hip_script hip_script;
openconnect_gp_hip_generate_fn generate_hip;
const int reconnect_timeout;
const int mtu;
@@ -50,7 +65,11 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
void vpn_disconnect();
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
extern void vpn_log(int level, const char *msg);
+123
View File
@@ -0,0 +1,123 @@
use std::{ffi::CString, io, marker::PhantomData, rc::Rc, sync::Arc};
use crate::{ffi, vpn_utils::check_executable};
pub type HipGenerator = dyn Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync;
type HipValidator = dyn Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync;
#[derive(Default)]
pub enum HipSource {
#[default]
Disabled,
Generator(Arc<HipGenerator>),
Script(HipScript),
}
impl HipSource {
/// Collect through the same bounded executor used by tunnel submissions.
/// Disabled posture is a caller policy; this method never invents a report.
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_source(self, request, check)
}
}
/// Current gateway and negotiated identity inputs for one report invocation.
#[derive(Clone, Default)]
pub struct HipRequest {
pub cookie: String,
pub client_ip: Option<String>,
pub client_ipv6: Option<String>,
pub md5: String,
pub client_version: String,
pub client_os: String,
pub os_version: String,
pub host_id: Option<String>,
pub local_hostname: Option<String>,
}
/// Borrowed cancellation and deadline control. It must stay on the invocation thread.
pub struct HipControl<'a> {
pub(crate) raw: &'a ffi::HipControlRaw,
pub(crate) _thread: PhantomData<Rc<()>>,
}
impl HipControl<'_> {
pub fn check(&self) -> io::Result<()> {
let result = unsafe { (self.raw.check)(self.raw.data) };
if result < 0 {
Err(io::Error::from_raw_os_error(-result))
} else {
Ok(())
}
}
}
pub struct HipScriptEnvironment {
pub variables: Vec<(String, String)>,
pub cwd: String,
}
pub struct HipScript {
pub(crate) path: CString,
pub(crate) user: Option<u32>,
pub(crate) validator: Option<Arc<HipValidator>>,
pub(crate) environment: Option<Vec<CString>>,
pub(crate) cwd: Option<CString>,
}
impl HipScript {
pub fn new(path: String, user: Option<u32>) -> io::Result<Self> {
if !std::fs::metadata(&path)?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"HIP executable is not a regular file",
));
}
check_executable(&path)?;
let path = c_string(path)?;
Ok(Self {
path,
user,
validator: None,
environment: None,
cwd: None,
})
}
pub fn with_validator(
mut self,
validator: impl Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync + 'static,
) -> Self {
self.validator = Some(Arc::new(validator));
self
}
/// A child-local replacement environment and working directory, never process-global changes.
pub fn with_environment(mut self, environment: HipScriptEnvironment) -> io::Result<Self> {
let variables = environment
.variables
.into_iter()
.map(|(key, value)| {
if key.is_empty() || key.contains('=') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid HIP environment key",
));
}
c_string(format!("{key}={value}"))
})
.collect::<io::Result<Vec<_>>>()?;
self.environment = Some(variables);
self.cwd = Some(c_string(environment.cwd)?);
Ok(self)
}
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
ffi::collect_hip_script(self, request, check)
}
}
fn c_string(value: String) -> io::Result<CString> {
CString::new(value).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP value contains NUL"))
}
+2
View File
@@ -1,6 +1,8 @@
mod ffi;
mod hip;
mod vpn;
mod vpn_utils;
pub use hip::*;
pub use vpn::*;
pub use vpn_utils::*;
+369 -55
View File
@@ -1,21 +1,24 @@
use std::{
ffi::{CStr, CString, c_char},
fmt,
sync::{Arc, RwLock},
fmt, io,
sync::{Arc, Mutex, RwLock},
};
use log::info;
use log::{info, warn};
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
use crate::vpn_utils::{check_executable, find_vpnc_script};
use crate::{HipSource, ffi};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub lifetime_warning: Option<VpnSessionWarning>,
pub nlb_enabled: bool,
pub nlb_connected_gw_ip: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -41,6 +44,8 @@ pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSe
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
_ => None,
},
nlb_enabled: raw.nlb_enabled != 0,
nlb_connected_gw_ip: unsafe { optional_c_string(raw.nlb_connected_gw_ip) },
}
}
@@ -56,7 +61,45 @@ fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
// The descriptor is borrowed only between attach and detach. Serialize writes
// against teardown and retain cancellation before the pipe exists.
#[derive(Default)]
struct Cancellation {
state: Mutex<CancellationState>,
}
#[derive(Default)]
struct CancellationState {
requested: bool,
command_fd: Option<i32>,
}
impl Cancellation {
fn attach(&self, fd: i32) -> bool {
let mut state = self.state.lock().unwrap();
state.command_fd = Some(fd);
state.requested
}
fn detach(&self) {
self.state.lock().unwrap().command_fd = None;
}
fn cancel(&self) -> io::Result<()> {
let mut state = self.state.lock().unwrap();
if state.requested {
return Ok(());
}
state.requested = true;
if let Some(fd) = state.command_fd {
ffi::write_cancel(fd)?;
}
Ok(())
}
}
pub struct Vpn {
cancellation: Cancellation,
server: CString,
cookie: CString,
@@ -76,8 +119,7 @@ pub struct Vpn {
key_password: Option<CString>,
servercert: Option<CString>,
csd_uid: u32,
csd_wrapper: Option<CString>,
pub(crate) hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -88,6 +130,7 @@ pub struct Vpn {
no_xmlpost: bool,
callback: OnConnectedCallback,
hip_report_callback: OnHipReportCallback,
}
impl Vpn {
@@ -96,12 +139,47 @@ impl Vpn {
}
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
match self.hip_source.as_ref() {
HipSource::Disabled => info!("HIP reporting: disabled"),
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
HipSource::Script(script) => {
#[cfg(unix)]
{
let uid = script.user.unwrap_or_else(|| unsafe { libc::geteuid() });
info!("HIP reporting: enabled, source=script, uid={uid}");
}
#[cfg(not(unix))]
match script.user {
Some(uid) => info!("HIP reporting: enabled, source=script, uid={uid}"),
None => info!("HIP reporting: enabled, source=script, user=process-user"),
}
}
}
self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options();
let mut options = self.build_connect_options();
let environment = match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::script_environment(script),
_ => Vec::new(),
};
if !environment.is_empty() {
options.hip_script.environment = environment.as_ptr();
}
ffi::connect(&options)
}
/// Receives a borrowed report after the gateway accepts its HIP submission.
/// The callback must copy the XML if it needs to retain it.
pub fn set_hip_report_callback(&self, callback: impl Fn(&str) + Send + Sync + 'static) {
*self.hip_report_callback.write().unwrap() = Some(Arc::new(callback));
}
pub(crate) fn on_hip_report_submitted(&self, report: &str) {
let callback = self.hip_report_callback.read().unwrap().clone();
if let Some(callback) = callback {
callback(report);
}
}
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
@@ -110,13 +188,24 @@ impl Vpn {
}
}
pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool {
self.cancellation.attach(fd)
}
pub(crate) fn detach_command_pipe(&self) {
self.cancellation.detach();
}
pub fn disconnect(&self) {
ffi::disconnect();
if let Err(error) = self.cancellation.cancel() {
warn!("Failed to signal VPN cancellation: {error}");
}
}
fn build_connect_options(&self) -> ffi::ConnectOptions {
ffi::ConnectOptions {
user_data: self as *const _ as *mut _,
on_hip_report_submitted: Some(ffi::on_hip_report_submitted),
server: self.server.as_ptr(),
cookie: self.cookie.as_ptr(),
@@ -137,8 +226,14 @@ impl Vpn {
key_password: Self::option_to_ptr(&self.key_password),
servercert: Self::option_to_ptr(&self.servercert),
csd_uid: self.csd_uid,
csd_wrapper: Self::option_to_ptr(&self.csd_wrapper),
hip_script: match self.hip_source.as_ref() {
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
_ => Default::default(),
},
generate_hip: match self.hip_source.as_ref() {
HipSource::Generator(_) => Some(ffi::generate_hip_report),
_ => None,
},
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -180,6 +275,7 @@ pub struct VpnBuilder {
server: String,
cookie: String,
script: Option<String>,
script_is_path: bool,
interface: Option<String>,
script_tun: bool,
@@ -194,9 +290,7 @@ pub struct VpnBuilder {
sslkey: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: Arc<HipSource>,
reconnect_timeout: u32,
mtu: u32,
@@ -213,6 +307,7 @@ impl VpnBuilder {
server: server.to_string(),
cookie: cookie.to_string(),
script: None,
script_is_path: false,
interface: None,
script_tun: false,
@@ -227,9 +322,7 @@ impl VpnBuilder {
sslkey: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
@@ -242,6 +335,13 @@ impl VpnBuilder {
pub fn script<T: Into<Option<String>>>(mut self, script: T) -> Self {
self.script = script.into();
self.script_is_path = false;
self
}
pub fn script_path<T: Into<Option<String>>>(mut self, script: T) -> Self {
self.script = script.into();
self.script_is_path = true;
self
}
@@ -300,18 +400,8 @@ impl VpnBuilder {
self
}
pub fn hip(mut self, hip: bool) -> Self {
self.hip = hip;
self
}
pub fn csd_uid(mut self, csd_uid: u32) -> Self {
self.csd_uid = csd_uid;
self
}
pub fn csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.csd_wrapper = csd_wrapper.into();
pub fn hip_source(mut self, hip_source: impl Into<Arc<HipSource>>) -> Self {
self.hip_source = hip_source.into();
self
}
@@ -345,41 +435,32 @@ impl VpnBuilder {
self
}
fn determine_script(&self) -> Result<&str, VpnError> {
fn determine_script(&self) -> Result<String, VpnError> {
match &self.script {
Some(script) => {
if self.script_is_path && !std::path::Path::new(script).exists() {
return Err(VpnError::new(format!("VPN script does not exist: {script}")));
}
check_executable(script).map_err(|e| VpnError::new(e.to_string()))?;
Ok(script)
Ok(script.clone())
}
None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))),
}
}
fn determine_csd_wrapper(&self) -> Result<Option<&str>, VpnError> {
if !self.hip {
return Ok(None);
}
match &self.csd_wrapper {
Some(csd_wrapper) if !csd_wrapper.is_empty() => {
check_executable(csd_wrapper).map_err(|e| VpnError::new(e.to_string()))?;
Ok(Some(csd_wrapper))
}
_ => {
let s = find_csd_wrapper().ok_or_else(|| VpnError::new(String::from("Failed to find csd wrapper")))?;
Ok(Some(s))
}
}
}
pub fn build(self) -> Result<Vpn, VpnError> {
let script = self.determine_script()?.to_owned();
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
let script = self.determine_script()?;
let script = if self.script_is_path || self.script.is_none() {
shell_quote_path(&script)
} else {
script
};
let user_agent = self.user_agent.unwrap_or_default();
let os = self.os.unwrap_or("linux".to_string());
Ok(Vpn {
cancellation: Cancellation::default(),
server: Self::to_cstring(&self.server),
cookie: Self::to_cstring(&self.cookie),
@@ -399,8 +480,7 @@ impl VpnBuilder {
key_password: self.key_password.as_deref().map(Self::to_cstring),
servercert: None,
csd_uid: self.csd_uid,
csd_wrapper: csd_wrapper.as_deref().map(Self::to_cstring),
hip_source: self.hip_source,
reconnect_timeout: self.reconnect_timeout,
mtu: self.mtu,
@@ -410,6 +490,7 @@ impl VpnBuilder {
no_xmlpost: self.no_xmlpost,
callback: Default::default(),
hip_report_callback: Default::default(),
})
}
@@ -418,20 +499,57 @@ impl VpnBuilder {
}
}
fn shell_quote_path(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
#[test]
fn quotes_vpnc_script_path_for_the_shell() {
assert_eq!(
shell_quote_path("/Applications/GP Connect.app/Contents/Helpers/vpnc-script"),
"'/Applications/GP Connect.app/Contents/Helpers/vpnc-script'"
);
assert_eq!(shell_quote_path("/tmp/user's script"), "'/tmp/user'\\''s script'");
}
#[test]
fn preserves_vpnc_script_commands() {
let command = "\"/tmp/script with spaces\" --option";
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script(command.to_string())
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), command);
}
#[test]
fn quotes_explicit_vpnc_script_paths() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
assert_eq!(vpn.script.to_str().unwrap(), "'/bin/sh'");
}
#[test]
fn maps_session_info_from_callback_payload() {
let message = CString::new("Session expires soon").unwrap();
let connected_gw = CString::new("10.1.2.3").unwrap();
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 0,
lifetime_secs: 43_200,
user_expires: 1_776_828_409,
lifetime_warning_prior: 1_800,
lifetime_warning_message: message.as_ptr(),
nlb_enabled: 1,
nlb_connected_gw_ip: connected_gw.as_ptr(),
};
let info = session_info_from_raw(&raw);
@@ -445,6 +563,8 @@ mod tests {
message: "Session expires soon".to_string(),
})
);
assert!(info.nlb_enabled);
assert_eq!(info.nlb_connected_gw_ip.as_deref(), Some("10.1.2.3"));
}
#[test]
@@ -455,6 +575,8 @@ mod tests {
user_expires: 0,
lifetime_warning_prior: 0,
lifetime_warning_message: std::ptr::null(),
nlb_enabled: 0,
nlb_connected_gw_ip: std::ptr::null(),
};
let info = session_info_from_raw(&raw);
@@ -467,6 +589,7 @@ mod tests {
#[test]
fn connect_options_include_host_id() {
let vpn = Vpn {
cancellation: Cancellation::default(),
server: CString::new("gateway.example.com").unwrap(),
cookie: CString::new("cookie").unwrap(),
user_agent: CString::new("agent").unwrap(),
@@ -482,8 +605,7 @@ mod tests {
sslkey: None,
key_password: None,
servercert: None,
csd_uid: 0,
csd_wrapper: None,
hip_source: Arc::new(HipSource::Disabled),
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
@@ -491,6 +613,7 @@ mod tests {
dpd_interval: 0,
no_xmlpost: false,
callback: Default::default(),
hip_report_callback: Default::default(),
};
let options = vpn.build_connect_options();
@@ -498,4 +621,195 @@ mod tests {
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
assert_eq!(host_id, "profile-host-id");
}
#[test]
fn hip_report_callback_copies_only_bounded_utf8() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
let reports = Arc::new(Mutex::new(Vec::new()));
let received = Arc::clone(&reports);
vpn.set_hip_report_callback(move |report| received.lock().unwrap().push(report.to_owned()));
let options = vpn.build_connect_options();
let callback = options.on_hip_report_submitted.unwrap();
callback(options.user_data, b"<report/>".as_ptr().cast(), 9);
callback(options.user_data, b"\xff".as_ptr().cast(), 1);
callback(options.user_data, b"x".as_ptr().cast(), 1024 * 1024 + 1);
assert_eq!(*reports.lock().unwrap(), ["<report/>"]);
}
#[test]
fn disconnect_before_connect_is_retained_without_contacting_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
vpn.disconnect();
vpn.disconnect();
assert_ne!(vpn.connect(|_| panic!("Canceled attempt connected")), 0);
assert_eq!(listener.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[test]
fn command_pipe_failure_preserves_stdin() {
use std::{
ffi::{c_int, c_void},
fs::File,
os::fd::AsFd,
process::{Command, Stdio},
};
const CHILD: &str = "OPENCONNECT_TEST_PIPE_FAILURE";
if std::env::var_os(CHILD).is_none() {
// Limit descriptors only in a subprocess, leaving the test runner untouched.
let output = Command::new("sh")
.args([
"-c",
"ulimit -n 64 && exec \"$1\" --exact vpn::tests::command_pipe_failure_preserves_stdin --nocapture",
"sh",
])
.arg(std::env::current_exe().unwrap())
.env(CHILD, "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
unsafe extern "C" {
fn openconnect_vpninfo_new(
agent: *const c_char,
validate: Option<unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int>,
config: Option<unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int>,
auth: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
progress: Option<unsafe extern "C" fn(*mut c_void, c_int, *const c_char, ...)>,
data: *mut c_void,
) -> *mut c_void;
fn openconnect_setup_cmd_pipe(info: *mut c_void) -> c_int;
fn openconnect_vpninfo_free(info: *mut c_void);
}
// Construct first so resource exhaustion targets pipe creation specifically.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
let mut descriptors = Vec::new();
loop {
match File::open("/dev/null") {
Ok(file) => descriptors.push(file),
Err(error) => {
assert_eq!(error.raw_os_error(), Some(24)); // EMFILE on supported Unix platforms.
break;
}
}
}
assert!(unsafe { openconnect_setup_cmd_pipe(info) } < 0);
unsafe { openconnect_vpninfo_free(info) };
// Constructor resource acquisition may also fail before selecting a protocol.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
if !info.is_null() {
unsafe { openconnect_vpninfo_free(info) };
}
drop(descriptors);
std::io::stdin()
.as_fd()
.try_clone_to_owned()
.expect("Cleanup closed stdin");
}
#[test]
fn disconnect_interrupts_in_progress_tls_and_cannot_cancel_another_attempt() {
use std::{io::Read, sync::mpsc, thread, time::Duration};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Arc::new(
Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap(),
);
let (tx, rx) = mpsc::channel();
let worker_vpn = vpn.clone();
let worker = thread::spawn(move || {
tx.send(worker_vpn.connect(|_| panic!("Test peer never completes TLS")))
.unwrap();
});
let deadline = std::time::Instant::now() + Duration::from_secs(3);
let peer = loop {
match listener.accept() {
Ok((peer, _)) => break peer,
Err(error) if error.kind() == io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => {
thread::sleep(Duration::from_millis(5));
}
other => {
vpn.disconnect();
worker.join().unwrap();
panic!("Connection did not reach test peer: {other:?}");
}
}
};
vpn.disconnect();
let result = rx.recv_timeout(Duration::from_secs(2));
drop(peer); // Release the peer even if cancellation regresses.
worker.join().unwrap();
assert_ne!(result.expect("Cancellation did not interrupt TLS"), 0);
use std::os::{fd::AsRawFd, unix::net::UnixStream};
let next = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!next.attach(writer.as_raw_fd()));
vpn.disconnect(); // A late stop of the old attempt cannot affect the new one.
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
next.detach();
}
#[test]
fn cancellation_racing_pipe_attachment_is_never_lost() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
thread,
};
for _ in 0..100 {
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
let pending = thread::scope(|scope| {
let cancel = scope.spawn(|| cancellation.cancel().unwrap());
let pending = cancellation.attach(writer.as_raw_fd());
cancel.join().unwrap();
pending
});
if !pending {
let mut command = [0];
assert_eq!(reader.read(&mut command).unwrap(), 1);
assert_eq!(command[0], b'x');
}
cancellation.detach();
}
}
#[test]
fn disconnect_after_detach_never_writes_to_the_old_descriptor() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
};
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!cancellation.attach(writer.as_raw_fd()));
cancellation.detach();
cancellation.cancel().unwrap();
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
}
+24 -19
View File
@@ -19,21 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/local/libexec/gpclient/hipreport.sh",
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
for location in locations.iter() {
let path = Path::new(location);
@@ -45,12 +30,18 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
None
}
pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS)
pub fn find_vpnc_script() -> Option<String> {
if let Some(path) = std::env::var_os("GP_VPNC_SCRIPT").filter(|path| !path.is_empty()) {
return configured_script(Path::new(&path));
}
find_executable(VPNC_SCRIPT_LOCATIONS).map(str::to_owned)
}
pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS)
fn configured_script(path: &Path) -> Option<String> {
if path.is_absolute() && path.is_file() && path.is_executable() {
return path.to_str().map(str::to_owned);
}
None
}
/// If file exists, check if it is executable
@@ -66,3 +57,17 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn configured_script_requires_an_absolute_executable_path() {
assert_eq!(configured_script(Path::new("/bin/sh")), Some("/bin/sh".to_owned()));
assert!(configured_script(Path::new("bin/sh")).is_none());
assert!(configured_script(Path::new("/missing-openconnect-vpnc-script")).is_none());
assert!(configured_script(Path::new("/etc/passwd")).is_none());
assert!(configured_script(Path::new("/tmp")).is_none());
}
}
+84
View File
@@ -0,0 +1,84 @@
"""Local TLS GlobalProtect fixture accepting HIP and raw SSL tunnel setup."""
import socket
import ssl
import sys
import threading
from urllib.parse import parse_qs
cert, key, records = sys.argv[1:]
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen()
state = {"configs": 0, "checks": 0, "reports": 0}
lock = threading.Lock()
def serve(connection):
try:
connection.settimeout(5)
with context.wrap_socket(connection, server_side=True) as stream:
buffer = b""
while True:
while b"\r\n\r\n" not in buffer:
data = stream.recv(4096)
if not data:
return
buffer += data
headers, buffer = buffer.split(b"\r\n\r\n", 1)
method, path, _ = headers.split(b"\r\n", 1)[0].decode().split()
print(f"Gateway received {method} {path.split('?')[0]}", file=sys.stderr, flush=True)
if method == "GET" and path.startswith("/ssl-tunnel-connect.sslvpn?"):
stream.sendall(b"START_TUNNEL")
while stream.recv(4096):
pass
return
length = 0
for header in headers.split(b"\r\n")[1:]:
name, value = header.split(b":", 1)
if name.lower() == b"content-length":
length = int(value)
while len(buffer) < length:
data = stream.recv(4096)
if not data:
raise EOFError(f"Incomplete body for {path}: {len(buffer)}/{length}")
buffer += data
body, buffer = buffer[:length], buffer[length:]
form = parse_qs(body.decode())
status = "200 OK"
with lock:
if path == "/ssl-vpn/getconfig.esp":
state["configs"] += 1
ip = "10.0.0.1"
response = f"<response><ip-address>{ip}</ip-address><gw-address>127.0.0.1</gw-address><ssl-tunnel-url>/ssl-tunnel-connect.sslvpn</ssl-tunnel-url></response>"
elif path == "/ssl-vpn/hipreportcheck.esp":
state["checks"] += 1
needed = "no" if state["checks"] == 4 else "yes"
response = f"<response><hip-report-needed>{needed}</hip-report-needed></response>"
elif path == "/ssl-vpn/hipreport.esp":
state["reports"] += 1
seq = state["reports"]
expected_ip = "10.0.0.1"
assert form.get("authcookie") == ["test" if seq < 3 else "refreshed"]
expected = f'<hip seq="{seq}" ip="{expected_ip}"/>'
assert form.get("report") == [expected], form
assert form.get("client-ip") == [expected_ip], form
with open(records, "a", encoding="utf-8") as output:
output.write(expected + "\n")
if seq == 4:
status = "403 Forbidden"
response = "<response/>"
else:
raise AssertionError(path)
payload = response.encode()
stream.sendall(f"HTTP/1.1 {status}\r\nContent-Length: {len(payload)}\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\n\r\n".encode() + payload)
print(f"Gateway responded {status} to {path.split('?')[0]}", file=sys.stderr, flush=True)
except (ConnectionError, ssl.SSLError):
pass
print(listener.getsockname()[1], flush=True)
while True:
connection, _ = listener.accept()
threading.Thread(target=serve, args=(connection,), daemon=True).start()
+157
View File
@@ -0,0 +1,157 @@
/* Integration harness: exercise setup and the actual connected periodic branch. */
#include <config.h>
#include "openconnect-internal.h"
#include <assert.h>
#include <stdarg.h>
struct state { int generated, accepted; };
static int accept_cert(void *data, const char *reason) { return 0; }
static void progress(void *data, int level, const char *format, ...) {
if (level > PRG_INFO) return;
va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args);
}
static int generate(void *data, const struct openconnect_gp_hip_request *request,
const struct openconnect_gp_hip_control *control, char *output, size_t capacity, size_t *written)
{
struct state *state = data;
int length;
assert(!control->check(control->data));
assert(!strcmp(request->client_os, "Linux"));
assert(!strcmp(request->client_version, "6.3.3"));
assert(!strcmp(request->host_id, "test-host"));
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
/* Shared golden fixture with gpapi's non-tunnel HIP transport. */
assert(!strcmp(request->md5, "20f30054f721fd212925866b5778447d"));
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
state->generated++;
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
assert(length > 0 && length < capacity);
*written = length;
return 0;
}
static void submitted(void *data, const char *report, size_t length) {
struct state *state = data;
assert(report && length > 0);
state->accepted++;
}
static int periodic(struct openconnect_info *vpninfo) {
int timeout = 1000;
vpninfo->trojan_interval = 1;
vpninfo->last_trojan = time(NULL) - 2;
return gpst_mainloop(vpninfo, &timeout, 0);
}
static int validate_script(void *data, const struct openconnect_gp_hip_control *control)
{
return control->check(control->data);
}
static void script_registration_lifecycle(struct openconnect_info *vpninfo)
{
const char *environment[] = { "PATH=/usr/bin:/bin", NULL };
char *path, **saved_environment, *cwd;
int validator_data;
uid_t uid = getuid();
gid_t gid;
assert(!openconnect_set_gp_hip_script(vpninfo, "/bin/true", 1, uid,
&validator_data, validate_script, environment, "/"));
path = vpninfo->csd_wrapper;
saved_environment = vpninfo->gp_hip_environment;
cwd = vpninfo->gp_hip_cwd;
gid = vpninfo->gid_csd;
/* A refused update must preserve the entire registered policy. */
assert(openconnect_set_gp_hip_script(vpninfo, "/bin/false", 1, (uid_t)-1,
NULL, NULL, NULL, NULL) < 0);
assert(vpninfo->csd_wrapper == path);
assert(vpninfo->gp_hip_environment == saved_environment);
assert(vpninfo->gp_hip_cwd == cwd);
assert(vpninfo->uid_csd_given == 1 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
assert(vpninfo->gp_hip_validate == validate_script);
assert(vpninfo->gp_hip_validate_data == &validator_data);
/* Re-registration may use pointers borrowed from the existing policy. */
assert(!openconnect_set_gp_hip_script(vpninfo, path, 0, 0,
&validator_data, validate_script, (const char *const *)saved_environment, cwd));
assert(!strcmp(vpninfo->csd_wrapper, "/bin/true"));
assert(!strcmp(vpninfo->gp_hip_environment[0], environment[0]));
assert(!strcmp(vpninfo->gp_hip_cwd, "/"));
assert(!vpninfo->uid_csd_given);
/* Legacy replacement must not retain another script's approval policy. */
assert(!openconnect_setup_csd(vpninfo, uid, 1, "/bin/false"));
assert(!strcmp(vpninfo->csd_wrapper, "/bin/false"));
assert(vpninfo->uid_csd_given == 2 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
assert(!vpninfo->gp_hip_validate && !vpninfo->gp_hip_validate_data);
assert(!vpninfo->gp_hip_environment && !vpninfo->gp_hip_cwd);
assert(!openconnect_set_gp_hip_script(vpninfo, NULL, 0, 0, NULL, NULL, NULL, NULL));
assert(!vpninfo->csd_wrapper);
}
static int close_count;
static int count_session_close(struct openconnect_info *vpninfo, const char *reason)
{
assert(!strcmp(reason, "fixture exit"));
close_count++;
return 0;
}
static void native_session_logout(void)
{
struct openconnect_info *vpninfo = openconnect_vpninfo_new("logout owner test",
accept_cert, NULL, NULL, progress, NULL);
const struct vpn_proto *original;
struct vpn_proto protocol;
assert(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
original = vpninfo->proto;
protocol = *original;
protocol.vpn_close_session = count_session_close;
vpninfo->proto = &protocol;
vpninfo->quit_reason = "fixture exit";
/* All exit causes use this same mainloop cleanup path. */
openconnect_mainloop(vpninfo, 0, 0);
assert(close_count == 1);
openconnect_mainloop(vpninfo, 0, 0);
assert(close_count == 2);
vpninfo->proto = original;
openconnect_vpninfo_free(vpninfo);
}
int main(int argc, char **argv) {
struct state state = {0};
struct openconnect_info *vpninfo;
assert(argc == 2);
native_session_logout();
openconnect_init_ssl();
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
assert(vpninfo);
script_registration_lifecycle(vpninfo);
assert(!openconnect_set_protocol(vpninfo, "gp"));
assert(!openconnect_set_reported_os(vpninfo, "linux"));
assert(!openconnect_parse_url(vpninfo, argv[1]));
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1&computer=test"));
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
openconnect_disable_dtls(vpninfo);
openconnect_set_gp_hip_generator(vpninfo, &state, generate);
openconnect_set_gp_hip_report_callback(vpninfo, &state, submitted);
assert(!openconnect_make_cstp_connection(vpninfo));
assert(vpninfo->ssl_fd >= 0 && state.generated == 1 && state.accepted == 1);
assert(!periodic(vpninfo));
assert(state.generated == 2 && state.accepted == 2);
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
openconnect_close_https(vpninfo, 0);
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2&computer=test"));
assert(!openconnect_make_cstp_connection(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fourth gateway check says no report needed. */
assert(!periodic(vpninfo));
assert(state.generated == 3 && state.accepted == 3);
/* Fifth submission is rejected; observer must not see it. */
assert(periodic(vpninfo));
assert(state.generated == 4 && state.accepted == 3);
openconnect_vpninfo_free(vpninfo);
return 0;
}
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff. Show more