mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -0,0 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod platform;
|
||||
|
||||
fn main() {
|
||||
platform::run();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpservice::hip_approval::{self, InstallRequest};
|
||||
use nix::unistd::Uid;
|
||||
|
||||
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
Install,
|
||||
Revoke { approval_id: String },
|
||||
}
|
||||
|
||||
fn try_run() -> anyhow::Result<()> {
|
||||
ensure!(Uid::effective().is_root(), "HIP script installer must run as root");
|
||||
let approving_uid = std::env::var("PKEXEC_UID")
|
||||
.context("HIP script installer requires pkexec authorization")?
|
||||
.parse::<u32>()
|
||||
.context("Invalid pkexec user identity")?;
|
||||
ensure!(approving_uid != 0, "HIP script installer requires a desktop user");
|
||||
|
||||
match Cli::parse().command {
|
||||
Command::Install => {
|
||||
let mut input = Vec::new();
|
||||
std::io::stdin()
|
||||
.lock()
|
||||
.take(MAX_INSTALL_REQUEST_SIZE + 1)
|
||||
.read_to_end(&mut input)?;
|
||||
ensure!(
|
||||
input.len() as u64 <= MAX_INSTALL_REQUEST_SIZE,
|
||||
"HIP install request is too large"
|
||||
);
|
||||
let request: InstallRequest = serde_json::from_slice(&input).context("Invalid HIP install request")?;
|
||||
let info = hip_approval::install(request, approving_uid)?;
|
||||
serde_json::to_writer(std::io::stdout().lock(), &info)?;
|
||||
println!();
|
||||
}
|
||||
Command::Revoke { approval_id } => hip_approval::revoke(&approval_id, approving_uid)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn run() {
|
||||
if let Err(err) = try_run() {
|
||||
eprintln!("HIP approval failed: {err:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub(super) fn run() {
|
||||
eprintln!("Root HIP script approvals are unavailable on this platform");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod platform;
|
||||
|
||||
fn main() {
|
||||
platform::run();
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use std::io::Read;
|
||||
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpapi::service::vpnc_script::InstallVpncScriptRequest;
|
||||
use nix::unistd::Uid;
|
||||
|
||||
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
Install,
|
||||
Remove,
|
||||
}
|
||||
|
||||
fn try_run() -> anyhow::Result<()> {
|
||||
if !Uid::effective().is_root() {
|
||||
bail!("The VPNC script installer must run as root");
|
||||
}
|
||||
|
||||
match Cli::parse().command {
|
||||
Command::Install => {
|
||||
let input = std::io::stdin().lock().take(MAX_INSTALL_REQUEST_SIZE);
|
||||
let request = serde_json::from_reader::<_, InstallVpncScriptRequest>(input)?;
|
||||
gpservice::vpnc_script::install(request)
|
||||
}
|
||||
Command::Remove => gpservice::vpnc_script::remove(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run() {
|
||||
if let Err(err) = try_run() {
|
||||
eprintln!("Error: {err:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub(super) fn run() {
|
||||
eprintln!("The VPNC script installer is only available on Linux, FreeBSD, and OpenBSD");
|
||||
std::process::exit(1);
|
||||
}
|
||||
+244
-83
@@ -1,20 +1,29 @@
|
||||
use std::sync::Arc;
|
||||
use std::{collections::HashMap, io::Write};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use clap::Parser;
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use gpapi::clap::InfoLevelVerbosity;
|
||||
use gpapi::logger;
|
||||
#[cfg(debug_assertions)]
|
||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
||||
use gpapi::{
|
||||
process::gui_launcher::GuiLauncher,
|
||||
service::{request::WsRequest, vpn_state::VpnState},
|
||||
utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
service::vpn_state::VpnState,
|
||||
utils::{lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
use log::{Log, Metadata, Record};
|
||||
use log::{info, warn};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{vpn_task::VpnTask, ws_server::WsServer};
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
|
||||
};
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
@@ -25,17 +34,47 @@ const VERSION: &str = concat!(
|
||||
")"
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct RedactingMacosLogger {
|
||||
logger: logger::MacosLogger,
|
||||
redaction: Arc<Redaction>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Log for RedactingMacosLogger {
|
||||
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
|
||||
self.logger.enabled(metadata)
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record<'_>) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let message = self.redaction.redact_str(&record.args().to_string());
|
||||
self.logger.write(record.level(), record.target(), &message);
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version = VERSION)]
|
||||
struct Cli {
|
||||
#[clap(long)]
|
||||
minimized: bool,
|
||||
#[clap(long)]
|
||||
env_file: Option<String>,
|
||||
#[cfg_attr(debug_assertions, clap(conflicts_with = "dev_standalone"))]
|
||||
#[cfg_attr(target_os = "macos", clap(conflicts_with = "macos_brokered"))]
|
||||
desktop_credentials: bool,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long)]
|
||||
no_gui: bool,
|
||||
|
||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
||||
dev_standalone: bool,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires = "dev_standalone")]
|
||||
dev_uid: Option<u32>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[clap(long, requires = "dev_standalone")]
|
||||
dev_bootstrap_socket: Option<PathBuf>,
|
||||
#[cfg(target_os = "macos")]
|
||||
#[clap(long, conflicts_with = "dev_standalone")]
|
||||
macos_brokered: bool,
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
}
|
||||
@@ -46,57 +85,144 @@ impl Cli {
|
||||
info!("gpservice started: {}", VERSION);
|
||||
|
||||
let pid = std::process::id();
|
||||
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
|
||||
let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid));
|
||||
|
||||
if lock_file.check_health().await {
|
||||
bail!("Another instance of the service is already running");
|
||||
}
|
||||
|
||||
let api_key = self.prepare_api_key();
|
||||
|
||||
// Channel for sending requests to the VPN task
|
||||
let (ws_req_tx, ws_req_rx) = mpsc::channel::<WsRequest>(32);
|
||||
// Channel for receiving the VPN state from the VPN task
|
||||
// Channel for receiving VPN state from the lifecycle actor
|
||||
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||
|
||||
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx);
|
||||
let ws_server = WsServer::new(api_key.clone(), ws_req_tx, vpn_state_rx, lock_file.clone(), redaction);
|
||||
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let externally_brokered = self.externally_brokered();
|
||||
let desktop_uid = if self.desktop_credentials {
|
||||
anyhow::ensure!(
|
||||
nix::unistd::Uid::effective().is_root(),
|
||||
"Desktop credentials require a privileged service"
|
||||
);
|
||||
let uid: u32 = std::env::var("PKEXEC_UID")
|
||||
.context("Desktop credentials require a pkexec-authenticated user")?
|
||||
.parse()
|
||||
.context("Invalid pkexec user")?;
|
||||
anyhow::ensure!(uid != 0, "Desktop credentials require a non-root user");
|
||||
anyhow::ensure!(
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.is_some(),
|
||||
"Desktop user is unavailable"
|
||||
);
|
||||
Some(uid)
|
||||
} else {
|
||||
crate::runtime_user::desktop_uid()
|
||||
};
|
||||
let desktop_channel = if self.desktop_credentials {
|
||||
Some(crate::desktop_client::DesktopClient::from_stdio()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let brokered_scripts_dir = if externally_brokered {
|
||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
||||
let contents_dir = executable
|
||||
.parent()
|
||||
.and_then(std::path::Path::parent)
|
||||
.context("gpservice is not inside a macOS application bundle")?;
|
||||
Some(contents_dir.join("Resources/Scripts"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, Arc::clone(®istry));
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
lifecycle.clone(),
|
||||
Arc::clone(&gui_restart_requested),
|
||||
Arc::clone(&redaction),
|
||||
!externally_brokered,
|
||||
brokered_scripts_dir,
|
||||
));
|
||||
#[cfg(target_os = "macos")]
|
||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
||||
let ws_server = WsServer::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
vpn_state_rx,
|
||||
lock_file.clone(),
|
||||
);
|
||||
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
|
||||
let shutdown_tx_clone = shutdown_tx.clone();
|
||||
let vpn_task_cancel_token = vpn_task.cancel_token();
|
||||
let server_token = ws_server.cancel_token();
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let vpn_ctx = vpn_task.context();
|
||||
let ws_ctx = ws_server.context();
|
||||
|
||||
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
|
||||
}
|
||||
|
||||
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
let no_gui = self.no_gui;
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
let no_gui = false;
|
||||
|
||||
if no_gui {
|
||||
info!("GUI is disabled");
|
||||
} else {
|
||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
||||
|
||||
let minimized = self.minimized;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if externally_brokered {
|
||||
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(®istry));
|
||||
let credential_token = server_token.clone();
|
||||
let credential_shutdown = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
launch_gui(envs, api_key, minimized).await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
if let Err(err) = credential_server.start(credential_token).await {
|
||||
warn!("Broker credential server stopped: {err}");
|
||||
let _ = credential_shutdown.send(()).await;
|
||||
}
|
||||
});
|
||||
|
||||
let idle_registry = Arc::clone(®istry);
|
||||
let idle_shutdown = shutdown_tx.clone();
|
||||
let idle_token = server_token.clone();
|
||||
tokio::spawn(async move {
|
||||
wait_for_brokered_idle(idle_vpn_state_rx, idle_registry, idle_token).await;
|
||||
let _ = idle_shutdown.send(()).await;
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if self.dev_standalone {
|
||||
let Some(dev_bootstrap_socket) = self.dev_bootstrap_socket.clone() else {
|
||||
bail!("--dev-bootstrap-socket is required with --dev-standalone");
|
||||
};
|
||||
let Some(dev_uid) = self.dev_uid else {
|
||||
bail!("--dev-uid is required with --dev-standalone");
|
||||
};
|
||||
let bootstrap = crate::dev_bootstrap::DevBootstrap::new(dev_bootstrap_socket, dev_uid, Arc::clone(®istry));
|
||||
let bootstrap_token = server_token.clone();
|
||||
let bootstrap_shutdown = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = bootstrap.start(bootstrap_token).await {
|
||||
warn!("Debug bootstrap stopped: {err}");
|
||||
let _ = bootstrap_shutdown.send(()).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let lifecycle = lifecycle.clone();
|
||||
let ws_ctx = ws_server.context();
|
||||
|
||||
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
|
||||
}
|
||||
|
||||
let desktop_cancel = server_token.clone();
|
||||
let shutdown_token = server_token.clone();
|
||||
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
|
||||
let (ws_ready_tx, ws_ready_rx) = tokio::sync::oneshot::channel();
|
||||
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
|
||||
|
||||
let desktop_client_handle = if let Some(channel) = desktop_channel {
|
||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
||||
let desktop_uid = desktop_uid.context("Desktop user is unavailable")?;
|
||||
Some(tokio::spawn(async move {
|
||||
if let Err(err) = channel
|
||||
.serve(registry, desktop_uid, gui_restart_requested, desktop_cancel)
|
||||
.await
|
||||
{
|
||||
warn!("Desktop credential channel ended: {err}");
|
||||
}
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}))
|
||||
} else {
|
||||
info!("Running with an externally launched GUI");
|
||||
None
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown_signal() => {
|
||||
info!("Shutdown signal received");
|
||||
@@ -107,7 +233,11 @@ impl Cli {
|
||||
}
|
||||
|
||||
vpn_task_cancel_token.cancel();
|
||||
shutdown_token.cancel();
|
||||
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
|
||||
if let Some(handle) = desktop_client_handle {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
lock_file.unlock()?;
|
||||
|
||||
@@ -116,8 +246,43 @@ impl Cli {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn externally_brokered(&self) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
return self.macos_brokered;
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
false
|
||||
}
|
||||
|
||||
fn service_lock_file_path(&self) -> anyhow::Result<PathBuf> {
|
||||
#[cfg(debug_assertions)]
|
||||
if self.dev_standalone {
|
||||
let socket = self
|
||||
.dev_bootstrap_socket
|
||||
.as_ref()
|
||||
.context("--dev-bootstrap-socket is required with --dev-standalone")?;
|
||||
return Ok(dev_service_lock_file_path(socket));
|
||||
}
|
||||
|
||||
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
|
||||
}
|
||||
|
||||
fn init_logger(&self) -> Arc<Redaction> {
|
||||
let redaction = Arc::new(Redaction::new());
|
||||
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if logger::macos_unified_log_enabled() {
|
||||
logger::init_with_logger(
|
||||
level,
|
||||
RedactingMacosLogger {
|
||||
logger: logger::MacosLogger::new("com.yuezk.gpgui", "gpservice"),
|
||||
redaction: Arc::clone(&redaction),
|
||||
},
|
||||
);
|
||||
return redaction;
|
||||
}
|
||||
|
||||
let redaction_clone = Arc::clone(&redaction);
|
||||
|
||||
let inner_logger = env_logger::builder()
|
||||
@@ -136,20 +301,41 @@ impl Cli {
|
||||
})
|
||||
.build();
|
||||
|
||||
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
|
||||
|
||||
logger::init_with_logger(level, inner_logger);
|
||||
|
||||
redaction
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_api_key(&self) -> Vec<u8> {
|
||||
#[cfg(debug_assertions)]
|
||||
if self.no_gui {
|
||||
return gpapi::GP_API_KEY.to_vec();
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn wait_for_brokered_idle(
|
||||
mut vpn_state_rx: watch::Receiver<VpnState>,
|
||||
registry: Arc<SessionRegistry>,
|
||||
cancel: tokio_util::sync::CancellationToken,
|
||||
) {
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const CHECK_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
let mut idle_since = None;
|
||||
let mut interval = tokio::time::interval(CHECK_INTERVAL);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = vpn_state_rx.changed() => {},
|
||||
_ = interval.tick() => {},
|
||||
}
|
||||
|
||||
generate_key().to_vec()
|
||||
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected | VpnState::Failed(_)) && registry.is_empty();
|
||||
if !idle {
|
||||
idle_since = None;
|
||||
continue;
|
||||
}
|
||||
|
||||
let started = idle_since.get_or_insert_with(tokio::time::Instant::now);
|
||||
if started.elapsed() >= IDLE_TIMEOUT {
|
||||
info!("Brokered service idle timeout reached");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,12 +345,12 @@ mod signals {
|
||||
|
||||
use log::{info, warn};
|
||||
|
||||
use crate::vpn_task::VpnTaskContext;
|
||||
use crate::vpn_task::LifecycleHandle;
|
||||
use crate::ws_server::WsServerContext;
|
||||
|
||||
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
|
||||
|
||||
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
|
||||
pub async fn handle_signals(lifecycle: LifecycleHandle, ws_ctx: Arc<WsServerContext>) {
|
||||
use gpapi::service::event::WsEvent;
|
||||
use tokio::signal::unix::{Signal, SignalKind, signal};
|
||||
|
||||
@@ -184,7 +370,7 @@ mod signals {
|
||||
tokio::select! {
|
||||
_ = user_sig1.recv() => {
|
||||
info!("Received SIGUSR1 signal");
|
||||
if vpn_ctx.disconnect().await {
|
||||
if lifecycle.disconnect_and_wait().await {
|
||||
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
|
||||
let pid = std::process::id();
|
||||
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
||||
@@ -201,31 +387,6 @@ mod signals {
|
||||
}
|
||||
}
|
||||
|
||||
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
|
||||
loop {
|
||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)
|
||||
.envs(envs.clone())
|
||||
.minimized(minimized);
|
||||
|
||||
match gui_launcher.launch().await {
|
||||
Ok(exit_status) => {
|
||||
// Exit code 99 means that the GUI needs to be restarted
|
||||
if exit_status.code() != Some(99) {
|
||||
info!("GUI exited with code {:?}", exit_status.code());
|
||||
break;
|
||||
}
|
||||
|
||||
info!("GUI exited with code 99, restarting");
|
||||
minimized = false;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to launch GUI: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run() {
|
||||
let mut cli = Cli::parse();
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::UnixStream,
|
||||
};
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
|
||||
pub(crate) async fn serve(
|
||||
mut stream: UnixStream,
|
||||
registry: Arc<SessionRegistry>,
|
||||
desktop_uid: Option<u32>,
|
||||
) -> anyhow::Result<()> {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid)?;
|
||||
let session_id = credential.session_id();
|
||||
let result = async {
|
||||
stream.write_all(&credential.encode_frame()?).await?;
|
||||
|
||||
let mut buffer = [0_u8; 1];
|
||||
loop {
|
||||
match stream.read(&mut buffer).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
registry.revoke(session_id);
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::{
|
||||
io,
|
||||
os::fd::OwnedFd,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, FdFlag, OFlag, fcntl},
|
||||
sys::stat::{SFlag, fstat},
|
||||
unistd::{dup, read, write},
|
||||
};
|
||||
use tokio::io::unix::AsyncFd;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
|
||||
/// Private parent/service pipes; credentials never pass through argv, environment or files.
|
||||
pub(crate) struct DesktopClient {
|
||||
input: AsyncFd<OwnedFd>,
|
||||
output: AsyncFd<OwnedFd>,
|
||||
}
|
||||
|
||||
impl DesktopClient {
|
||||
pub(crate) fn from_stdio() -> anyhow::Result<Self> {
|
||||
let channel = Self::new(dup(std::io::stdin())?, dup(std::io::stdout())?)?;
|
||||
// Only the owned CLOEXEC descriptors carry credentials. VPN subprocesses inherit /dev/null.
|
||||
let null = std::fs::OpenOptions::new().read(true).write(true).open("/dev/null")?;
|
||||
nix::unistd::dup2_stdin(&null)?;
|
||||
nix::unistd::dup2_stdout(&null)?;
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
fn new(input: OwnedFd, output: OwnedFd) -> anyhow::Result<Self> {
|
||||
fn pipe(fd: OwnedFd) -> anyhow::Result<AsyncFd<OwnedFd>> {
|
||||
ensure!(
|
||||
SFlag::from_bits_truncate(fstat(&fd)?.st_mode).contains(SFlag::S_IFIFO),
|
||||
"Desktop credentials require private pipes"
|
||||
);
|
||||
fcntl(&fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
|
||||
let flags = OFlag::from_bits_truncate(fcntl(&fd, FcntlArg::F_GETFL)?);
|
||||
fcntl(&fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))?;
|
||||
Ok(AsyncFd::new(fd)?)
|
||||
}
|
||||
Ok(Self {
|
||||
input: pipe(input)?,
|
||||
output: pipe(output)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn serve(
|
||||
self,
|
||||
registry: Arc<SessionRegistry>,
|
||||
uid: u32,
|
||||
restart: Arc<AtomicBool>,
|
||||
cancel: CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
|
||||
let session_id = credential.session_id();
|
||||
let result = tokio::select! {
|
||||
_ = cancel.cancelled() => Ok(false),
|
||||
result = async {
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
self.gui_exited().await
|
||||
} => result,
|
||||
};
|
||||
registry.revoke(session_id);
|
||||
if !result? || !restart.swap(false, Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_frame(&self, mut bytes: &[u8]) -> anyhow::Result<()> {
|
||||
while !bytes.is_empty() {
|
||||
let mut ready = self.output.writable().await?;
|
||||
match ready.try_io(|fd| write(fd.get_ref(), bytes).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
let length = result?;
|
||||
ensure!(length != 0, "Desktop credential pipe closed");
|
||||
bytes = &bytes[length..];
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn gui_exited(&self) -> anyhow::Result<bool> {
|
||||
loop {
|
||||
let mut ready = self.input.readable().await?;
|
||||
let mut byte = [0];
|
||||
match ready.try_io(|fd| read(fd.get_ref(), &mut byte).map_err(io::Error::from)) {
|
||||
Ok(result) => {
|
||||
if result.context("Desktop control pipe failed")? == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
ensure!(byte[0] == 0, "Invalid desktop control message");
|
||||
return Ok(true);
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_stdio_is_not_inherited_by_subprocesses() {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--ignored", "--exact", "desktop_client::tests::stdio_child"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(text.contains("PRIVATE_FRAME"));
|
||||
assert!(!text.contains("CHILD_OUTPUT"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "subprocess fixture for credential_stdio_is_not_inherited_by_subprocesses"]
|
||||
async fn stdio_child() {
|
||||
let channel = DesktopClient::from_stdio().unwrap();
|
||||
assert!(
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", "printf CHILD_OUTPUT"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
channel.write_frame(b"PRIVATE_FRAME").await.unwrap();
|
||||
}
|
||||
use gpapi::service::transport::SessionCredential;
|
||||
use nix::unistd::pipe;
|
||||
use std::{fs::File, io::Read, time::Duration};
|
||||
|
||||
fn pipes() -> (DesktopClient, OwnedFd, File) {
|
||||
let (input, control) = pipe().unwrap();
|
||||
let (credentials, output) = pipe().unwrap();
|
||||
(DesktopClient::new(input, output).unwrap(), control, credentials.into())
|
||||
}
|
||||
|
||||
async fn credential(mut reader: File) -> (File, SessionCredential) {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut header = [0; 2];
|
||||
reader.read_exact(&mut header).unwrap();
|
||||
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header)) + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).unwrap();
|
||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
||||
(reader, credential)
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_revokes_and_reissues_on_restart_then_closes_on_parent_exit() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let restart = Arc::new(AtomicBool::new(false));
|
||||
let task = tokio::spawn(channel.serve(registry.clone(), 1000, restart.clone(), CancellationToken::new()));
|
||||
let (reader, first) = credential(reader).await;
|
||||
restart.store(true, Ordering::SeqCst);
|
||||
write(&control, &[0]).unwrap();
|
||||
let (_, second) = credential(reader).await;
|
||||
assert_ne!(first.session_id(), second.session_id());
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_err());
|
||||
drop(control);
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(second.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_shutdown_cancels_pipe_wait_and_revokes_credential() {
|
||||
let (channel, _control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let cancel = CancellationToken::new();
|
||||
let task = tokio::spawn(channel.serve(registry.clone(), 1000, Arc::new(AtomicBool::new(false)), cancel.clone()));
|
||||
let (_, issued) = credential(reader).await;
|
||||
cancel.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_rejects_invalid_control_messages_and_revokes() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let task = tokio::spawn(channel.serve(
|
||||
registry.clone(),
|
||||
1000,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
CancellationToken::new(),
|
||||
));
|
||||
let (_, issued) = credential(reader).await;
|
||||
write(&control, &[1]).unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::{
|
||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use log::{info, warn};
|
||||
use nix::unistd::{Uid, chown};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
||||
|
||||
pub struct DevBootstrap {
|
||||
path: PathBuf,
|
||||
allowed_uid: u32,
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
|
||||
impl DevBootstrap {
|
||||
pub fn new(path: PathBuf, allowed_uid: u32, registry: Arc<SessionRegistry>) -> Self {
|
||||
Self {
|
||||
path,
|
||||
allowed_uid,
|
||||
registry,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
create_default_parent(&self.path, self.allowed_uid)?;
|
||||
let path = prepare_socket_path(&self.path, self.allowed_uid)?;
|
||||
let listener = UnixListener::bind(&path)
|
||||
.with_context(|| format!("Failed to bind debug bootstrap socket at {}", path.display()))?;
|
||||
chown(&path, Some(Uid::from_raw(self.allowed_uid)), None)?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
info!("Debug credential bootstrap listening at {}", path.display());
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted?;
|
||||
let peer_uid = match peer_uid(&stream) {
|
||||
Ok(uid) => uid,
|
||||
Err(err) => {
|
||||
warn!("Could not verify debug credential client UID: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if peer_uid != self.allowed_uid {
|
||||
warn!("Rejected debug credential client with unexpected UID");
|
||||
continue;
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry, Some(self.allowed_uid)).await {
|
||||
warn!("Debug credential client ended: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if path.exists() {
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn create_default_parent(path: &Path, allowed_uid: u32) -> anyhow::Result<()> {
|
||||
let default = default_socket_path(allowed_uid);
|
||||
if path != default {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Debug bootstrap socket has no parent directory")?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o711))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn default_socket_path(allowed_uid: u32) -> PathBuf {
|
||||
PathBuf::from(format!("/var/run/gpservice-dev-{allowed_uid}/dev-bootstrap.sock"))
|
||||
}
|
||||
|
||||
fn prepare_socket_path(path: &Path, allowed_uid: u32) -> anyhow::Result<PathBuf> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Debug bootstrap socket has no parent directory")?;
|
||||
let parent = std::fs::canonicalize(parent)
|
||||
.with_context(|| format!("Debug bootstrap directory does not exist: {}", parent.display()))?;
|
||||
let metadata = std::fs::symlink_metadata(&parent)?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
bail!("Debug bootstrap parent must be a real directory");
|
||||
}
|
||||
if metadata.uid() != 0 || metadata.permissions().mode() & 0o777 != 0o711 {
|
||||
bail!("Debug bootstrap parent must be owned by root with mode 0711");
|
||||
}
|
||||
|
||||
let file_name = path.file_name().context("Debug bootstrap socket has no file name")?;
|
||||
let path = parent.join(file_name);
|
||||
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => {
|
||||
if metadata.file_type().is_symlink()
|
||||
|| !metadata.file_type().is_socket()
|
||||
|| metadata.uid() != allowed_uid
|
||||
|| metadata.permissions().mode() & 0o777 != 0o600
|
||||
{
|
||||
bail!("Refusing unsafe existing debug bootstrap path");
|
||||
}
|
||||
std::fs::remove_file(&path)?;
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
use nix::sys::socket::{getsockopt, sockopt};
|
||||
|
||||
let credentials = getsockopt(stream, sockopt::PeerCredentials)?;
|
||||
Ok(credentials.uid())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
||||
Ok(uid.as_raw())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
|
||||
use gpapi::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_developer_owned_parent() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let socket = temp.path().join("bootstrap.sock");
|
||||
|
||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlink_socket_path() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let target = temp.path().join("target");
|
||||
std::fs::write(&target, "not a socket").unwrap();
|
||||
let socket = temp.path().join("bootstrap.sock");
|
||||
symlink(target, &socket).unwrap();
|
||||
|
||||
assert!(prepare_socket_path(&socket, Uid::current().as_raw()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_parent_is_not_created_by_the_service() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let parent = temp.path().join("missing");
|
||||
let socket = parent.join("bootstrap.sock");
|
||||
|
||||
create_default_parent(&socket, Uid::current().as_raw()).unwrap();
|
||||
|
||||
assert!(!parent.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_socket_path_is_stable() {
|
||||
assert_eq!(
|
||||
default_socket_path(1234),
|
||||
PathBuf::from("/var/run/gpservice-dev-1234/dev-bootstrap.sock")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anchor_eof_revokes_issued_credential() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let (service, mut client) = UnixStream::pair().unwrap();
|
||||
let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry), Some(1234)));
|
||||
|
||||
let mut header = [0_u8; 2];
|
||||
client.read_exact(&mut header).await.unwrap();
|
||||
let payload_len = u16::from_be_bytes(header) as usize;
|
||||
assert!(payload_len + 2 <= MAX_CREDENTIAL_FRAME);
|
||||
let mut frame = vec![0_u8; payload_len + 2];
|
||||
frame[..2].copy_from_slice(&header);
|
||||
client.read_exact(&mut frame[2..]).await.unwrap();
|
||||
let credential = SessionCredential::decode_frame(&frame).unwrap();
|
||||
drop(client);
|
||||
task.await.unwrap().unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version()
|
||||
),
|
||||
Err(crate::session_registry::SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_uid_matches_current_process() {
|
||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
//! Root-owned Unix installation identity. Failure affects GUI issuance only.
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::device_anchor::{AnchorSource, DeviceAnchor};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Record {
|
||||
version: u32,
|
||||
anchor: DeviceAnchor,
|
||||
}
|
||||
|
||||
pub fn resolve() -> anyhow::Result<DeviceAnchor> {
|
||||
resolve_in(Path::new("/var/lib/gp"), 0, collect_unix).context("cannot resolve persistent GUI device anchor")
|
||||
}
|
||||
|
||||
fn collect_unix() -> anyhow::Result<DeviceAnchor> {
|
||||
collect_from(mac_address::get_mac_address()?, || {
|
||||
let mut random = [0_u8; 32];
|
||||
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
|
||||
Ok(random)
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_from(
|
||||
mac: Option<mac_address::MacAddress>,
|
||||
random: impl FnOnce() -> anyhow::Result<[u8; 32]>,
|
||||
) -> anyhow::Result<DeviceAnchor> {
|
||||
if let Some(mac) = mac {
|
||||
let bytes = mac.bytes();
|
||||
if bytes != [0; 6] && bytes[0] & 1 == 0 {
|
||||
return Ok(DeviceAnchor::derive(AnchorSource::UnixMac, bytes));
|
||||
}
|
||||
}
|
||||
Ok(DeviceAnchor::derive(AnchorSource::UnixRandom, random()?))
|
||||
}
|
||||
|
||||
fn validate_metadata(metadata: &fs::Metadata, owner: u32, directory: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
if directory {
|
||||
metadata.is_dir()
|
||||
} else {
|
||||
metadata.is_file()
|
||||
},
|
||||
"unexpected device anchor state type"
|
||||
);
|
||||
ensure!(metadata.uid() == owner, "unexpected device anchor state owner");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o777 == if directory { 0o700 } else { 0o600 },
|
||||
"unsafe device anchor state permissions"
|
||||
);
|
||||
if !directory {
|
||||
ensure!(metadata.nlink() == 1, "device anchor state must not have hard links");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_record(path: &Path, owner: u32) -> anyhow::Result<Option<DeviceAnchor>> {
|
||||
let mut file = match OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK)
|
||||
.open(path)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
validate_metadata(&file.metadata()?, owner, false)?;
|
||||
ensure!(file.metadata()?.len() <= 4096, "oversized device anchor record");
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes)?;
|
||||
let record: Record = serde_json::from_slice(&bytes).context("malformed device anchor record")?;
|
||||
ensure!(
|
||||
record.version == 1 && record.anchor.validate(),
|
||||
"unsupported or invalid device anchor record"
|
||||
);
|
||||
ensure!(
|
||||
matches!(record.anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
|
||||
"invalid Unix device anchor source"
|
||||
);
|
||||
Ok(Some(record.anchor))
|
||||
}
|
||||
|
||||
fn resolve_in(
|
||||
directory: &Path,
|
||||
owner: u32,
|
||||
collect: impl FnOnce() -> anyhow::Result<DeviceAnchor>,
|
||||
) -> anyhow::Result<DeviceAnchor> {
|
||||
match fs::DirBuilder::new().mode(0o700).create(directory) {
|
||||
Ok(()) => {
|
||||
if let Some(parent) = directory.parent() {
|
||||
File::open(parent)?.sync_all()?;
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
validate_metadata(&fs::symlink_metadata(directory)?, owner, true)?;
|
||||
let path = directory.join("hardware-id");
|
||||
let lock = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK)
|
||||
.open(directory.join("hardware-id.lock"))?;
|
||||
validate_metadata(&lock.metadata()?, owner, false)?;
|
||||
lock.lock()?;
|
||||
if let Some(anchor) = read_record(&path, owner)? {
|
||||
return Ok(anchor);
|
||||
}
|
||||
let anchor = collect()?;
|
||||
ensure!(
|
||||
anchor.validate() && matches!(anchor.source, AnchorSource::UnixMac | AnchorSource::UnixRandom),
|
||||
"invalid collected Unix device anchor"
|
||||
);
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
|
||||
temporary.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
temporary.write_all(&serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor.clone(),
|
||||
})?)?;
|
||||
temporary.as_file().sync_all()?;
|
||||
temporary.persist_noclobber(&path)?;
|
||||
File::open(directory)?.sync_all()?;
|
||||
Ok(anchor)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn anchor() -> anyhow::Result<DeviceAnchor> {
|
||||
Ok(DeviceAnchor {
|
||||
hardware_id: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned(),
|
||||
source: AnchorSource::UnixMac,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_reuses_the_existing_record_without_rediscovery() {
|
||||
let _ = resolve as fn() -> anyhow::Result<DeviceAnchor>;
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = temporary.path().join("state");
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
assert_eq!(resolve_in(&path, owner, anchor).unwrap(), anchor().unwrap());
|
||||
assert_eq!(
|
||||
resolve_in(&path, owner, || anyhow::bail!("must not rediscover")).unwrap(),
|
||||
anchor().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_preserves_an_eligible_mac_and_randomizes_ineligible_addresses() {
|
||||
use mac_address::MacAddress;
|
||||
|
||||
let eligible = collect_from(Some(MacAddress::new([0, 17, 34, 51, 68, 85])), || {
|
||||
anyhow::bail!("must not randomize")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
eligible,
|
||||
DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85])
|
||||
);
|
||||
|
||||
for rejected in [[0; 6], [1, 2, 3, 4, 5, 6], [0xff; 6]] {
|
||||
assert_eq!(
|
||||
collect_from(Some(MacAddress::new(rejected)), || Ok([9; 32])).unwrap(),
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [9; 32])
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
collect_from(None, || Ok([8; 32])).unwrap(),
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [8; 32])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_record_recreates_the_same_mac_anchor() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = temporary.path().join("state");
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
let first = resolve_in(&path, owner, anchor).unwrap();
|
||||
fs::remove_file(path.join("hardware-id")).unwrap();
|
||||
assert_eq!(resolve_in(&path, owner, anchor).unwrap(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_first_start_converges_on_one_record() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let path = Arc::new(temporary.path().join("state"));
|
||||
fs::create_dir(&*path).unwrap();
|
||||
fs::set_permissions(&*path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
let barrier = Arc::new(Barrier::new(2));
|
||||
let handles: Vec<_> = [AnchorSource::UnixMac, AnchorSource::UnixRandom]
|
||||
.into_iter()
|
||||
.map(|source| {
|
||||
let path = Arc::clone(&path);
|
||||
let barrier = Arc::clone(&barrier);
|
||||
std::thread::spawn(move || {
|
||||
barrier.wait();
|
||||
resolve_in(&path, owner, || Ok(DeviceAnchor::derive(source, [source.into()])))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<_> = handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().unwrap().unwrap())
|
||||
.collect();
|
||||
assert_eq!(results[0], results[1]);
|
||||
assert_eq!(
|
||||
read_record(&path.join("hardware-id"), owner).unwrap(),
|
||||
Some(results[0].clone())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_linked_and_unsafe_records() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
for case in ["malformed", "symlink", "hard-link", "permissions"] {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let record = directory.join("hardware-id");
|
||||
match case {
|
||||
"malformed" => fs::write(&record, b"not-json").unwrap(),
|
||||
"symlink" => {
|
||||
let target = temporary.path().join("target");
|
||||
fs::write(
|
||||
&target,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
symlink(target, &record).unwrap();
|
||||
}
|
||||
"hard-link" => {
|
||||
fs::write(
|
||||
&record,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::hard_link(&record, temporary.path().join("second-link")).unwrap();
|
||||
}
|
||||
"permissions" => {
|
||||
fs::write(
|
||||
&record,
|
||||
serde_json::to_vec(&Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
})
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&record, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
if case != "symlink" && case != "permissions" {
|
||||
fs::set_permissions(&record, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovers_with_an_interrupted_temporary_file_present() {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(directory.join(".hardware-id.interrupted"), b"partial").unwrap();
|
||||
assert_eq!(
|
||||
resolve_in(&directory, nix::unistd::Uid::current().as_raw(), anchor).unwrap(),
|
||||
anchor().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_directory_and_lock_metadata_and_read_only_storage() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let owner = nix::unistd::Uid::current().as_raw();
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert!(resolve_in(&directory, owner.wrapping_add(1), anchor).is_err());
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::write(&directory, b"not-a-directory").unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
|
||||
for case in ["symlink", "hard-link", "permissions"] {
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let lock = directory.join("hardware-id.lock");
|
||||
match case {
|
||||
"symlink" => {
|
||||
let target = temporary.path().join("target");
|
||||
fs::write(&target, b"").unwrap();
|
||||
symlink(target, &lock).unwrap();
|
||||
}
|
||||
"hard-link" => {
|
||||
fs::write(&lock, b"").unwrap();
|
||||
fs::set_permissions(&lock, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::hard_link(&lock, temporary.path().join("second-link")).unwrap();
|
||||
}
|
||||
"permissions" => {
|
||||
fs::write(&lock, b"").unwrap();
|
||||
fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err(), "accepted {case} lock");
|
||||
}
|
||||
|
||||
let temporary = tempfile::tempdir().unwrap();
|
||||
let directory = temporary.path().join("state");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
assert!(resolve_in(&directory, owner, anchor).is_err());
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_serializes_source_as_a_number_and_rejects_unknown_codes() {
|
||||
let record = Record {
|
||||
version: 1,
|
||||
anchor: anchor().unwrap(),
|
||||
};
|
||||
let json = serde_json::to_value(&record).unwrap();
|
||||
assert_eq!(json["anchor"]["source"], 1);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&record).unwrap(),
|
||||
r#"{"version":1,"anchor":{"hardware_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","source":1}}"#
|
||||
);
|
||||
|
||||
for source in [0, 4] {
|
||||
let json = serde_json::json!({
|
||||
"version": 1,
|
||||
"anchor": {
|
||||
"hardware_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"source": source
|
||||
}
|
||||
});
|
||||
assert!(serde_json::from_value::<Record>(json).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,12 @@
|
||||
use std::{
|
||||
fs::{File, Permissions},
|
||||
io::BufReader,
|
||||
ops::ControlFlow,
|
||||
os::unix::fs::PermissionsExt,
|
||||
sync::Arc,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::bail;
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{
|
||||
State, WebSocketUpgrade,
|
||||
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
|
||||
},
|
||||
http::StatusCode,
|
||||
extract::{State, WebSocketUpgrade},
|
||||
response::IntoResponse,
|
||||
};
|
||||
use common::binary_paths;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, request::UpdateGuiRequest},
|
||||
utils::checksum::verify_checksum,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tar::Archive;
|
||||
use tokio::fs;
|
||||
use xz2::read::XzDecoder;
|
||||
use gpapi::service::{event::WsEvent, transport::MAX_WS_MESSAGE};
|
||||
|
||||
use crate::ws_server::WsServerContext;
|
||||
use crate::{ws_connection::WsConnection, ws_server::WsServerContext};
|
||||
|
||||
pub(crate) async fn health() -> impl IntoResponse {
|
||||
"OK"
|
||||
@@ -37,133 +16,8 @@ pub(crate) async fn active_gui(State(ctx): State<Arc<WsServerContext>>) -> impl
|
||||
ctx.send_event(WsEvent::ActiveGui).await;
|
||||
}
|
||||
|
||||
pub async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
|
||||
let payload = match ctx.decrypt::<UpdateGuiRequest>(body.to_vec()) {
|
||||
Ok(payload) => payload,
|
||||
Err(err) => {
|
||||
warn!("Failed to decrypt update payload: {}", err);
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
};
|
||||
|
||||
info!("Update GUI: {:?}", payload);
|
||||
let UpdateGuiRequest { path, checksum } = payload;
|
||||
|
||||
info!("Verifying checksum");
|
||||
verify_checksum(&path, &checksum).map_err(|err| {
|
||||
warn!("Failed to verify checksum: {}", err);
|
||||
StatusCode::BAD_REQUEST
|
||||
})?;
|
||||
|
||||
info!("Installing GUI");
|
||||
install_gui(&path).await.map_err(|err| {
|
||||
warn!("Failed to install GUI: {}", err);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Unpack GPGUI archive, gpgui_2.0.0_{arch}.bin.tar.xz and install it
|
||||
async fn install_gui(src: &str) -> anyhow::Result<()> {
|
||||
let target = binary_paths::gpgui();
|
||||
let Some(dir) = target.parent() else {
|
||||
bail!("Failed to get parent directory of GUI binary");
|
||||
};
|
||||
|
||||
fs::create_dir_all(dir).await?;
|
||||
|
||||
// Unpack the archive
|
||||
info!("Unpacking GUI archive");
|
||||
let tar = XzDecoder::new(BufReader::new(File::open(src)?));
|
||||
let mut ar = Archive::new(tar);
|
||||
|
||||
for entry in ar.entries()? {
|
||||
let mut entry = entry?;
|
||||
let entry_path = entry.path()?;
|
||||
|
||||
if let Some(name) = entry_path.file_name() {
|
||||
let name = name.to_string_lossy();
|
||||
|
||||
if name == "gpgui" {
|
||||
let mut file = File::create(&target)?;
|
||||
std::io::copy(&mut entry, &mut file)?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make the binary executable
|
||||
fs::set_permissions(target, Permissions::from_mode(0o755)).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn ws_handler(ws: WebSocketUpgrade, State(ctx): State<Arc<WsServerContext>>) -> impl IntoResponse {
|
||||
ws.on_upgrade(move |socket| handle_socket(socket, ctx))
|
||||
}
|
||||
|
||||
async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
|
||||
// Send ping message
|
||||
if let Err(err) = socket.send(Message::Ping("Hi".into())).await {
|
||||
warn!("Failed to send ping: {}", err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for pong message
|
||||
if socket.recv().await.is_none() {
|
||||
warn!("Failed to receive pong");
|
||||
return;
|
||||
}
|
||||
|
||||
info!("New client connected");
|
||||
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
let (connection, mut msg_rx) = ctx.add_connection().await;
|
||||
|
||||
let send_task = tokio::spawn(async move {
|
||||
while let Some(msg) = msg_rx.recv().await {
|
||||
if let Err(err) = sender.send(msg).await {
|
||||
info!("Failed to send message: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let close_msg = Message::Close(Some(CloseFrame {
|
||||
code: ws::close_code::NORMAL,
|
||||
reason: Utf8Bytes::from("Goodbye"),
|
||||
}));
|
||||
|
||||
if let Err(err) = sender.send(close_msg).await {
|
||||
warn!("Failed to close socket: {}", err);
|
||||
}
|
||||
});
|
||||
|
||||
let conn = Arc::clone(&connection);
|
||||
let ctx_clone = Arc::clone(&ctx);
|
||||
let recv_task = tokio::spawn(async move {
|
||||
while let Some(Ok(msg)) = receiver.next().await {
|
||||
let ControlFlow::Continue(ws_req) = conn.recv_msg(msg) else {
|
||||
break;
|
||||
};
|
||||
|
||||
if let Err(err) = ctx_clone.forward_req(ws_req).await {
|
||||
info!("Failed to forward request: {}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
tokio::select! {
|
||||
_ = send_task => {
|
||||
info!("WS server send task completed");
|
||||
},
|
||||
_ = recv_task => {
|
||||
info!("WS server recv task completed");
|
||||
}
|
||||
}
|
||||
|
||||
info!("Client disconnected");
|
||||
|
||||
ctx.remove_connection(connection).await;
|
||||
ws.max_message_size(MAX_WS_MESSAGE)
|
||||
.max_frame_size(MAX_WS_MESSAGE)
|
||||
.on_upgrade(move |socket| WsConnection::accept(socket, ctx))
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use gpapi::hip::HipApprovalStatus;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::Builder;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const APPROVAL_DIRECTORY: &str = "/var/lib/gpclient/hip-approvals";
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub const APPROVAL_DIRECTORY: &str = "/var/db/gpclient/hip-approvals";
|
||||
pub const MAX_SCRIPT_SIZE: usize = common::constants::MAX_HIP_SCRIPT_SIZE;
|
||||
const MAX_METADATA_SIZE: u64 = 8 * 1024;
|
||||
const METADATA_VERSION: u8 = 1;
|
||||
const SCRIPT_NAME: &str = "script";
|
||||
const METADATA_NAME: &str = "metadata.json";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallRequest {
|
||||
pub original_path: String,
|
||||
pub contents_base64: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ApprovalInfo {
|
||||
pub approval_id: String,
|
||||
pub owner_uid: u32,
|
||||
pub sha256: String,
|
||||
pub original_path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApprovedScript {
|
||||
pub info: ApprovalInfo,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct StoredMetadata {
|
||||
version: u8,
|
||||
info: ApprovalInfo,
|
||||
}
|
||||
|
||||
impl InstallRequest {
|
||||
fn contents(&self) -> anyhow::Result<Vec<u8>> {
|
||||
ensure!(self.original_path.len() <= 4096, "HIP script path is too long");
|
||||
ensure!(
|
||||
Path::new(&self.original_path).is_absolute(),
|
||||
"HIP script path must be absolute"
|
||||
);
|
||||
ensure!(
|
||||
!self.original_path.contains('\0'),
|
||||
"HIP script path contains a NUL byte"
|
||||
);
|
||||
ensure!(
|
||||
self.contents_base64.len() <= (MAX_SCRIPT_SIZE + 2).div_ceil(3) * 4,
|
||||
"HIP script exceeds 1 MiB"
|
||||
);
|
||||
let contents = STANDARD
|
||||
.decode(&self.contents_base64)
|
||||
.context("Invalid HIP script content encoding")?;
|
||||
ensure!(
|
||||
!contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE,
|
||||
"HIP script must be 1 MiB or smaller"
|
||||
);
|
||||
Ok(contents)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
ensure!(approving_uid != 0, "Root cannot approve a desktop HIP script");
|
||||
let contents = request.contents()?;
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
fs::create_dir_all(base).context("Cannot create HIP approval directory")?;
|
||||
validate_approval_ancestors(base)?;
|
||||
fs::set_permissions(base, fs::Permissions::from_mode(0o700))?;
|
||||
install_at(base, &contents, request.original_path, approving_uid, 0)
|
||||
}
|
||||
|
||||
pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_with_control(approval_id, desktop_uid, &budget)
|
||||
}
|
||||
|
||||
pub fn resolve_with_control(
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_approval_ancestors(base)?;
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, 0, control)
|
||||
}
|
||||
|
||||
pub fn revoke(approval_id: &str, approving_uid: u32) -> anyhow::Result<()> {
|
||||
ensure!(approving_uid != 0, "Root cannot revoke another user's HIP approval");
|
||||
let base = Path::new(APPROVAL_DIRECTORY);
|
||||
validate_approval_ancestors(base)?;
|
||||
revoke_at(base, approval_id, approving_uid, 0)
|
||||
}
|
||||
|
||||
pub fn status(approval_id: &str, desktop_uid: u32) -> anyhow::Result<HipApprovalStatus> {
|
||||
status_at(Path::new(APPROVAL_DIRECTORY), approval_id, desktop_uid, 0, true)
|
||||
}
|
||||
|
||||
fn status_at(
|
||||
base: &Path,
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
file_owner: u32,
|
||||
validate_root_ancestors: bool,
|
||||
) -> anyhow::Result<HipApprovalStatus> {
|
||||
ensure!(desktop_uid != 0, "HIP approval status requires a desktop user");
|
||||
validate_id(approval_id)?;
|
||||
for path in [
|
||||
base.to_path_buf(),
|
||||
base.join(approval_id),
|
||||
base.join(approval_id).join(METADATA_NAME),
|
||||
] {
|
||||
match fs::symlink_metadata(&path) {
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(HipApprovalStatus::Revoked),
|
||||
Err(_) => return Ok(HipApprovalStatus::Corrupt),
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
if validate_private_dir(base, file_owner).is_err()
|
||||
|| (validate_root_ancestors && validate_approval_ancestors(base).is_err())
|
||||
{
|
||||
return Ok(HipApprovalStatus::Corrupt);
|
||||
}
|
||||
let info = match read_metadata_unbound_at(base, approval_id, file_owner) {
|
||||
Ok(info) => info,
|
||||
Err(_) => return Ok(HipApprovalStatus::Corrupt),
|
||||
};
|
||||
if info.owner_uid != desktop_uid {
|
||||
return Ok(HipApprovalStatus::OtherUser);
|
||||
}
|
||||
Ok(if resolve_at(base, approval_id, desktop_uid, file_owner).is_ok() {
|
||||
HipApprovalStatus::Valid
|
||||
} else {
|
||||
HipApprovalStatus::Corrupt
|
||||
})
|
||||
}
|
||||
|
||||
fn install_at(
|
||||
base: &Path,
|
||||
contents: &[u8],
|
||||
original_path: String,
|
||||
approving_uid: u32,
|
||||
file_owner: u32,
|
||||
) -> anyhow::Result<ApprovalInfo> {
|
||||
validate_private_dir(base, file_owner)?;
|
||||
ensure!(
|
||||
!contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE,
|
||||
"HIP script must be 1 MiB or smaller"
|
||||
);
|
||||
let approval_id = Uuid::new_v4().to_string();
|
||||
let info = ApprovalInfo {
|
||||
approval_id: approval_id.clone(),
|
||||
owner_uid: approving_uid,
|
||||
sha256: sha256::digest(contents),
|
||||
original_path,
|
||||
};
|
||||
let staged = Builder::new().prefix(".install-").tempdir_in(base)?;
|
||||
fs::set_permissions(staged.path(), fs::Permissions::from_mode(0o700))?;
|
||||
validate_private_dir(staged.path(), file_owner)?;
|
||||
|
||||
let script = staged.path().join(SCRIPT_NAME);
|
||||
write_new(&script, contents, 0o500)?;
|
||||
let metadata = staged.path().join(METADATA_NAME);
|
||||
let stored = StoredMetadata {
|
||||
version: METADATA_VERSION,
|
||||
info: info.clone(),
|
||||
};
|
||||
let encoded = serde_json::to_vec(&stored)?;
|
||||
ensure!(
|
||||
encoded.len() as u64 <= MAX_METADATA_SIZE,
|
||||
"HIP approval metadata is too large"
|
||||
);
|
||||
write_new(&metadata, &encoded, 0o600)?;
|
||||
File::open(staged.path())?.sync_all()?;
|
||||
|
||||
let target = base.join(&approval_id);
|
||||
ensure!(!target.exists(), "HIP approval ID collision");
|
||||
fs::rename(staged.path(), &target).context("Cannot publish HIP approval")?;
|
||||
File::open(base)?.sync_all()?;
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovedScript> {
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60));
|
||||
resolve_at_with_control(base, approval_id, desktop_uid, file_owner, &budget)
|
||||
}
|
||||
|
||||
fn resolve_at_with_control(
|
||||
base: &Path,
|
||||
approval_id: &str,
|
||||
desktop_uid: u32,
|
||||
file_owner: u32,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> anyhow::Result<ApprovedScript> {
|
||||
control.check()?;
|
||||
let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?;
|
||||
control.check()?;
|
||||
let script = base.join(approval_id).join(SCRIPT_NAME);
|
||||
validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?;
|
||||
let mut file = File::open(&script)?;
|
||||
let mut contents = Vec::new();
|
||||
let mut chunk = [0_u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
let read = file.read(&mut chunk)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
contents.len() + read <= MAX_SCRIPT_SIZE,
|
||||
"Approved HIP script is too large"
|
||||
);
|
||||
contents.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
ensure!(!contents.is_empty(), "Approved HIP script is empty");
|
||||
ensure!(
|
||||
sha256::digest(&contents) == info.sha256,
|
||||
"Approved HIP script digest mismatch"
|
||||
);
|
||||
control.check()?;
|
||||
Ok(ApprovedScript { info, path: script })
|
||||
}
|
||||
|
||||
fn read_metadata_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
let info = read_metadata_unbound_at(base, approval_id, file_owner)?;
|
||||
ensure!(info.owner_uid == desktop_uid, "HIP approval belongs to another user");
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn read_metadata_unbound_at(base: &Path, approval_id: &str, file_owner: u32) -> anyhow::Result<ApprovalInfo> {
|
||||
validate_id(approval_id)?;
|
||||
validate_private_dir(base, file_owner)?;
|
||||
let directory = base.join(approval_id);
|
||||
validate_private_dir(&directory, file_owner)?;
|
||||
let metadata_path = directory.join(METADATA_NAME);
|
||||
validate_file(&metadata_path, file_owner, 0o600, MAX_METADATA_SIZE)?;
|
||||
let stored: StoredMetadata = serde_json::from_slice(&fs::read(metadata_path)?)?;
|
||||
ensure!(stored.version == METADATA_VERSION, "Unsupported HIP approval version");
|
||||
ensure!(stored.info.approval_id == approval_id, "HIP approval ID mismatch");
|
||||
ensure!(
|
||||
stored.info.sha256.len() == 64 && stored.info.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||
"Invalid HIP approval digest"
|
||||
);
|
||||
|
||||
Ok(stored.info)
|
||||
}
|
||||
|
||||
fn revoke_at(base: &Path, approval_id: &str, approving_uid: u32, file_owner: u32) -> anyhow::Result<()> {
|
||||
validate_id(approval_id)?;
|
||||
let directory = base.join(approval_id);
|
||||
// The GUI may retry after removal succeeds but saving its settings fails.
|
||||
if let Err(err) = fs::symlink_metadata(&directory) {
|
||||
if err.kind() == std::io::ErrorKind::NotFound {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(err).context("Cannot inspect HIP approval directory");
|
||||
}
|
||||
read_metadata_at(base, approval_id, approving_uid, file_owner)?;
|
||||
// Renaming first makes revocation atomic for the runner. Cleanup is separate:
|
||||
// a failed cleanup cannot make this approval executable again.
|
||||
let revoked = base.join(format!(".revoked-{approval_id}"));
|
||||
fs::rename(&directory, &revoked).context("Cannot revoke HIP approval")?;
|
||||
File::open(base)?.sync_all()?;
|
||||
if let Err(err) = fs::remove_dir_all(&revoked) {
|
||||
log::warn!("HIP approval was revoked but its snapshot could not be removed: {err}");
|
||||
} else {
|
||||
File::open(base)?.sync_all()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, bytes: &[u8], mode: u32) -> anyhow::Result<()> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).mode(mode).open(path)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_id(value: &str) -> anyhow::Result<()> {
|
||||
let parsed = Uuid::parse_str(value).context("Invalid HIP approval ID")?;
|
||||
ensure!(parsed.to_string() == value, "HIP approval ID must use canonical form");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_private_dir(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||
"HIP approval directory is not a directory"
|
||||
);
|
||||
ensure!(
|
||||
metadata.uid() == owner_uid && metadata.permissions().mode() & 0o077 == 0,
|
||||
"HIP approval directory {} is not private (owner {}, mode {:o})",
|
||||
path.display(),
|
||||
metadata.uid(),
|
||||
metadata.permissions().mode() & 0o777
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file(path: &Path, owner_uid: u32, mode: u32, max_size: u64) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||
"HIP approval file is not regular"
|
||||
);
|
||||
ensure!(
|
||||
metadata.uid() == owner_uid && metadata.permissions().mode() & 0o777 == mode,
|
||||
"HIP approval file has unsafe ownership or mode"
|
||||
);
|
||||
ensure!(metadata.len() <= max_size, "HIP approval file is too large");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check every component because a trusted file below a writable parent can
|
||||
/// be replaced before a later HIP refresh.
|
||||
fn validate_approval_ancestors(path: &Path) -> anyhow::Result<()> {
|
||||
ensure!(path.is_absolute(), "HIP approval path must be absolute");
|
||||
for component in path.ancestors().take_while(|part| part.as_os_str() != "/") {
|
||||
let metadata =
|
||||
fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?;
|
||||
ensure!(
|
||||
!metadata.file_type().is_symlink(),
|
||||
"HIP approval path contains a symlink"
|
||||
);
|
||||
ensure!(metadata.uid() == 0, "HIP approval path is not root-owned");
|
||||
ensure!(
|
||||
metadata.permissions().mode() & 0o022 == 0,
|
||||
"HIP approval path is writable by another user"
|
||||
);
|
||||
ensure!(metadata.is_dir(), "HIP approval parent is not a directory");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, u32) {
|
||||
let base = tempfile::tempdir().unwrap();
|
||||
fs::set_permissions(base.path(), fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let owner = fs::symlink_metadata(base.path()).unwrap().uid();
|
||||
(base, owner)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_request_rejects_oversized_or_relative_script() {
|
||||
let request = InstallRequest {
|
||||
original_path: "hip.sh".into(),
|
||||
contents_base64: STANDARD.encode(b"#!/bin/sh\n"),
|
||||
};
|
||||
assert!(request.contents().is_err());
|
||||
let oversized = InstallRequest {
|
||||
original_path: "/home/user/hip.sh".into(),
|
||||
contents_base64: STANDARD.encode(vec![b'x'; MAX_SCRIPT_SIZE + 1]),
|
||||
};
|
||||
assert!(oversized.contents().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approval_binds_owner_and_exact_script_digest() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(
|
||||
base.path(),
|
||||
b"#!/bin/sh\necho ok\n",
|
||||
"/home/user/hip.sh".into(),
|
||||
1000,
|
||||
owner,
|
||||
)
|
||||
.unwrap();
|
||||
let approved = resolve_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert_eq!(approved.info.sha256, info.sha256);
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1001, owner).is_err());
|
||||
fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&approved.path, b"#!/bin/sh\necho changed\n").unwrap();
|
||||
fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoked_approval_is_unavailable() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
assert!(revoke_at(base.path(), &info.approval_id, 1001, owner).is_err());
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_distinguishes_owner_corruption_and_revocation() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(
|
||||
base.path(),
|
||||
b"#!/bin/sh\necho ok\n",
|
||||
"/home/user/hip.sh".into(),
|
||||
1000,
|
||||
owner,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Valid
|
||||
);
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1001, owner, false).unwrap(),
|
||||
HipApprovalStatus::OtherUser
|
||||
);
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Corrupt
|
||||
);
|
||||
fs::remove_file(base.path().join(&info.approval_id).join(METADATA_NAME)).unwrap();
|
||||
assert_eq!(
|
||||
status_at(base.path(), &info.approval_id, 1000, owner, false).unwrap(),
|
||||
HipApprovalStatus::Revoked
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoke_succeeds_if_script_was_corrupted() {
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&script, b"changed").unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap();
|
||||
assert!(!base.path().join(&info.approval_id).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlinked_script() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let (base, owner) = fixture();
|
||||
let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap();
|
||||
let script = base.path().join(&info.approval_id).join(SCRIPT_NAME);
|
||||
fs::remove_file(&script).unwrap();
|
||||
symlink("/bin/sh", &script).unwrap();
|
||||
assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
use std::{collections::HashMap, io, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
request::PreviewHipReportRequest,
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
};
|
||||
use openconnect::HipRequest;
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
task::JoinHandle,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{session_registry::SessionRegistry, ws_connection::ConnectionControl};
|
||||
|
||||
const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const MAX_ACTIVE_PREVIEWS: usize = 4;
|
||||
|
||||
struct PreviewTask {
|
||||
connection_id: Uuid,
|
||||
cancellation: CancellationToken,
|
||||
worker: JoinHandle<()>,
|
||||
}
|
||||
|
||||
pub(crate) struct PreviewJob {
|
||||
pub session_id: Uuid,
|
||||
pub request_id: Uuid,
|
||||
pub request: PreviewHipReportRequest,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub identity: HostIdentity,
|
||||
pub registry: Arc<SessionRegistry>,
|
||||
pub connection: ConnectionControl,
|
||||
}
|
||||
|
||||
pub(crate) struct HipPreviews {
|
||||
tasks: Mutex<HashMap<Uuid, PreviewTask>>,
|
||||
slots: Arc<Semaphore>,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
impl HipPreviews {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
tasks: Mutex::new(HashMap::new()),
|
||||
slots: Arc::new(Semaphore::new(MAX_ACTIVE_PREVIEWS)),
|
||||
shutdown: CancellationToken::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self, job: PreviewJob) -> bool {
|
||||
let PreviewJob {
|
||||
session_id,
|
||||
request_id,
|
||||
request,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity,
|
||||
registry,
|
||||
connection,
|
||||
} = job;
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if self.shutdown.is_cancelled() || tasks.get(&session_id).is_some_and(|task| !task.worker.is_finished()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(completed) = tasks.remove(&session_id) {
|
||||
let _ = completed.worker.await;
|
||||
}
|
||||
let Ok(slot) = Arc::clone(&self.slots).try_acquire_owned() else {
|
||||
return false;
|
||||
};
|
||||
let cancellation = self.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let connection_id = connection.connection_id();
|
||||
let worker = tokio::spawn(async move {
|
||||
let _slot = slot;
|
||||
let generated = tokio::task::spawn_blocking(move || {
|
||||
generate(request, edited_report, desktop_uid, identity, worker_cancellation)
|
||||
})
|
||||
.await;
|
||||
let result = match generated {
|
||||
Ok(Ok(xml)) => preview_result(®istry, session_id, xml),
|
||||
Ok(Err(error)) => {
|
||||
log::warn!("HIP preview failed: {error:#}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("HIP preview worker failed: {error}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
|
||||
}
|
||||
};
|
||||
// A bounded connection queue must not prevent preview teardown.
|
||||
let _ = connection.send(crate::ws_connection::ConnectionCommand::Reply { id: request_id, result });
|
||||
});
|
||||
tasks.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_connection(&self, session_id: Uuid, connection_id: Uuid) {
|
||||
let mut tasks = self.tasks.lock().await;
|
||||
if !tasks
|
||||
.get(&session_id)
|
||||
.is_some_and(|task| task.connection_id == connection_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(task) = tasks.remove(&session_id) {
|
||||
task.cancellation.cancel();
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
let tasks = std::mem::take(&mut *self.tasks.lock().await);
|
||||
for task in tasks.into_values() {
|
||||
let _ = task.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
|
||||
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
|
||||
registry
|
||||
.hip_preview_chunk(session_id, preview_id, 0)
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
});
|
||||
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
|
||||
}
|
||||
|
||||
fn generate(
|
||||
request: PreviewHipReportRequest,
|
||||
edited_report: Option<Arc<str>>,
|
||||
desktop_uid: Option<u32>,
|
||||
identity: HostIdentity,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<String> {
|
||||
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
|
||||
ensure!(
|
||||
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
|
||||
"Invalid HIP host ID"
|
||||
);
|
||||
let budget = gpapi::process::collection::CollectionBudget::new(PREVIEW_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "HIP preview cancelled"));
|
||||
}
|
||||
gpapi::process::collection::CollectionControl::check(&budget)
|
||||
};
|
||||
check()?;
|
||||
let profile = crate::hip_source::profile(
|
||||
&identity,
|
||||
request.client_os,
|
||||
Some(request.client_version.clone()),
|
||||
None,
|
||||
request.host_id.clone(),
|
||||
None,
|
||||
&check,
|
||||
)?;
|
||||
let input = HipRequest {
|
||||
cookie: "user=preview&domain=preview&computer=preview".into(),
|
||||
client_ip: Some("192.0.2.1".into()),
|
||||
client_ipv6: None,
|
||||
md5: "00000000000000000000000000000000".into(),
|
||||
client_version: request.client_version,
|
||||
client_os: request.client_os.as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: request.host_id,
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
};
|
||||
let xml = match &request.source {
|
||||
HipSource::Disabled => bail!("HIP is disabled"),
|
||||
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report is unavailable")?;
|
||||
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
|
||||
}
|
||||
source => {
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, false, None, Some(profile))?;
|
||||
let openconnect::HipSource::Script(script) = execution.source else {
|
||||
bail!("HIP preview executable is unavailable");
|
||||
};
|
||||
let xml = script.collect(&input, &check)?;
|
||||
gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?;
|
||||
xml
|
||||
}
|
||||
};
|
||||
check()?;
|
||||
Ok(xml)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
fn job(session_id: Uuid) -> PreviewJob {
|
||||
let (tx, _) = tokio::sync::mpsc::channel(1);
|
||||
let (connection, _) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
PreviewJob {
|
||||
session_id,
|
||||
request_id: Uuid::new_v4(),
|
||||
request: PreviewHipReportRequest {
|
||||
source: HipSource::Generated,
|
||||
client_os: ClientOs::Linux,
|
||||
client_version: "6.3.3".into(),
|
||||
host_id: None,
|
||||
},
|
||||
edited_report: None,
|
||||
desktop_uid: None,
|
||||
identity: HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
registry: Arc::new(SessionRegistry::new(Uuid::new_v4())),
|
||||
connection,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preview_admission_rejects_duplicate_session_and_global_capacity() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let worker = tokio::spawn(async move { worker_cancellation.cancelled().await });
|
||||
let connection_id = Uuid::new_v4();
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
let _all_slots = Arc::clone(&previews.slots)
|
||||
.acquire_many_owned(MAX_ACTIVE_PREVIEWS as u32)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!previews.start(job(Uuid::new_v4())).await);
|
||||
previews.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_preview_owner_waits_for_worker_teardown() {
|
||||
let previews = HipPreviews::new();
|
||||
let session_id = Uuid::new_v4();
|
||||
let connection_id = Uuid::new_v4();
|
||||
let cancellation = previews.shutdown.child_token();
|
||||
let worker_cancellation = cancellation.clone();
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let worker_stopped = Arc::clone(&stopped);
|
||||
let worker = tokio::spawn(async move {
|
||||
worker_cancellation.cancelled().await;
|
||||
tokio::task::yield_now().await;
|
||||
worker_stopped.store(true, Ordering::SeqCst);
|
||||
});
|
||||
previews.tasks.lock().await.insert(
|
||||
session_id,
|
||||
PreviewTask {
|
||||
connection_id,
|
||||
cancellation,
|
||||
worker,
|
||||
},
|
||||
);
|
||||
previews.cancel_connection(session_id, Uuid::new_v4()).await;
|
||||
assert!(!stopped.load(Ordering::SeqCst));
|
||||
previews.cancel_connection(session_id, connection_id).await;
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert!(previews.tasks.lock().await.is_empty());
|
||||
previews.shutdown().await;
|
||||
assert!(!previews.start(job(session_id)).await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_preview_does_not_start_collection() {
|
||||
let preview = job(Uuid::new_v4());
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
let error = generate(preview.request, None, None, preview.identity, cancelled).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use std::{fs, io, os::unix::fs::PermissionsExt, path::PathBuf, sync::Arc};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile, OsProfileBuilder},
|
||||
};
|
||||
use gphip::{ReportContext, ReportInput};
|
||||
use openconnect::{HipRequest, HipScript, HipScriptEnvironment};
|
||||
|
||||
pub(crate) struct HipExecution {
|
||||
pub source: openconnect::HipSource,
|
||||
approval: HipApproval,
|
||||
}
|
||||
|
||||
impl HipExecution {
|
||||
pub(crate) fn into_parts(self) -> (openconnect::HipSource, HipApproval) {
|
||||
(self.source, self.approval)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct HipApproval {
|
||||
identity: Option<(String, u32)>,
|
||||
}
|
||||
|
||||
impl HipApproval {
|
||||
pub(crate) fn approval_is_valid(&self) -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
if let Some((id, uid)) = &self.identity {
|
||||
return gpservice::hip_approval::resolve(id, *uid).is_ok();
|
||||
}
|
||||
self.identity.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(
|
||||
source: &HipSource,
|
||||
desktop_uid: Option<u32>,
|
||||
brokered_macos: bool,
|
||||
edited_report: Option<Arc<str>>,
|
||||
profile: Option<OsProfile>,
|
||||
) -> anyhow::Result<HipExecution> {
|
||||
let approval;
|
||||
let source = match source {
|
||||
HipSource::Disabled => {
|
||||
approval = None;
|
||||
openconnect::HipSource::Disabled
|
||||
}
|
||||
HipSource::Generated | HipSource::Edited { .. } => {
|
||||
let profile = profile.context("HIP generator identity is unavailable")?;
|
||||
approval = None;
|
||||
let xml = match source {
|
||||
HipSource::Edited { .. } => {
|
||||
let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?;
|
||||
gphip::validate_edited_report(&xml)?;
|
||||
Some(xml)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
openconnect::HipSource::Generator(Arc::new(move |request, control| {
|
||||
generate(&profile, xml.as_deref(), request, &|| control.check(), false).map_err(generation_error)
|
||||
}))
|
||||
}
|
||||
HipSource::UserScript { path } => {
|
||||
approval = None;
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?;
|
||||
ensure!(uid != 0, "HIP custom scripts require a non-root desktop user");
|
||||
let path = PathBuf::from(path);
|
||||
ensure!(path.is_absolute(), "HIP custom script path must be absolute");
|
||||
let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?;
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0,
|
||||
"HIP custom script must be an executable regular file"
|
||||
);
|
||||
let script =
|
||||
HipScript::new(path.to_string_lossy().into_owned(), Some(uid))?.with_environment(script_environment(uid)?)?;
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
HipSource::ApprovedRootScript { approval_id } => {
|
||||
ensure_custom_available(brokered_macos)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?;
|
||||
let approved = gpservice::hip_approval::resolve(approval_id, owner_uid)?;
|
||||
let id = approval_id.clone();
|
||||
let path = approved.path;
|
||||
let expected = path.clone();
|
||||
let script = HipScript::new(path.to_string_lossy().into_owned(), Some(0))?
|
||||
.with_environment(script_environment(0)?)?
|
||||
.with_validator(move |control| {
|
||||
control.check()?;
|
||||
let current = gpservice::hip_approval::resolve_with_control(&id, owner_uid, &|| control.check())
|
||||
.map_err(generation_error)?;
|
||||
if current.path != expected {
|
||||
return Err(io::Error::other("Approved HIP executable changed"));
|
||||
}
|
||||
control.check()
|
||||
});
|
||||
approval = Some((approval_id.clone(), owner_uid));
|
||||
openconnect::HipSource::Script(script)
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (approval_id, desktop_uid);
|
||||
anyhow::bail!("Root HIP script approvals are unavailable on this platform")
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(HipExecution {
|
||||
source,
|
||||
approval: HipApproval { identity: approval },
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_custom_available(brokered_macos: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!cfg!(target_os = "macos") && !brokered_macos,
|
||||
"Custom HIP scripts are unavailable on macOS"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn generate(
|
||||
profile: &OsProfile,
|
||||
edited: Option<&str>,
|
||||
request: &HipRequest,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
preview: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
control.check()?;
|
||||
let context = if preview {
|
||||
ReportContext::Preview
|
||||
} else {
|
||||
ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
}
|
||||
};
|
||||
let input = ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
};
|
||||
match edited {
|
||||
Some(xml) => gphip::refresh_edited_report_with_control(xml, &input, control),
|
||||
None => gphip::generate_report_with_control(&input, control),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn script_environment(uid: u32) -> anyhow::Result<HipScriptEnvironment> {
|
||||
let user =
|
||||
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.context("HIP execution user is unavailable")?;
|
||||
let home = user.dir.to_string_lossy().into_owned();
|
||||
Ok(HipScriptEnvironment {
|
||||
variables: vec![
|
||||
(
|
||||
"PATH".into(),
|
||||
gpapi::process::collection::command_path(uid == 0)?
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("HIP command path is not valid UTF-8"))?,
|
||||
),
|
||||
("LC_ALL".into(), "C".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), user.name.clone()),
|
||||
("LOGNAME".into(), user.name),
|
||||
],
|
||||
cwd: home,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn profile(
|
||||
identity: &HostIdentity,
|
||||
os: ClientOs,
|
||||
version: Option<String>,
|
||||
os_version: Option<String>,
|
||||
host_id: Option<String>,
|
||||
hostname: Option<String>,
|
||||
control: &dyn gpapi::process::collection::CollectionControl,
|
||||
) -> io::Result<OsProfile> {
|
||||
let identity = HostIdentity::from_parts(
|
||||
hostname.unwrap_or_else(|| identity.computer().into()),
|
||||
host_id.unwrap_or_else(|| identity.host_id().into()),
|
||||
identity.serialno().into(),
|
||||
identity.mac_addr().into(),
|
||||
);
|
||||
let mut builder = OsProfileBuilder::new(os).host_identity(identity);
|
||||
if let Some(version) = version {
|
||||
builder = builder.client_version(version);
|
||||
}
|
||||
if let Some(os_version) = os_version {
|
||||
builder = builder.os_version(os_version);
|
||||
}
|
||||
builder.build_with_control(control)
|
||||
}
|
||||
|
||||
fn generation_error(error: anyhow::Error) -> io::Error {
|
||||
match error.downcast::<io::Error>() {
|
||||
Ok(error) => error,
|
||||
Err(error) => io::Error::other(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::os_profile::ClientOs;
|
||||
|
||||
fn fixture_profile() -> OsProfile {
|
||||
profile(
|
||||
&HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
),
|
||||
ClientOs::Linux,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-version".into()),
|
||||
None,
|
||||
None,
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_configuration_needs_no_files_or_root_identity() {
|
||||
let generated = resolve(&HipSource::Generated, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(generated.source, openconnect::HipSource::Generator(_)));
|
||||
let disabled = resolve(&HipSource::Disabled, None, true, None, Some(fixture_profile())).unwrap();
|
||||
assert!(matches!(disabled.source, openconnect::HipSource::Disabled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_retains_negotiated_identity_and_os_version() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"original".into(),
|
||||
"original-id".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = profile(
|
||||
&identity,
|
||||
ClientOs::Mac,
|
||||
Some("6.3.3".into()),
|
||||
Some("negotiated-os".into()),
|
||||
Some("negotiated-host".into()),
|
||||
Some("negotiated-name".into()),
|
||||
&gpapi::process::collection::CollectionBudget::new(std::time::Duration::from_secs(60)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(profile.os_version(), "negotiated-os");
|
||||
assert_eq!(profile.host_identity().host_id(), "negotiated-host");
|
||||
assert_eq!(profile.host_identity().computer(), "negotiated-name");
|
||||
assert_eq!(profile.host_identity().serialno(), "serial");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_errors_preserve_cancellation() {
|
||||
let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into());
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_source_cannot_run_on_macos_or_choose_root_without_approval() {
|
||||
let source = HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
};
|
||||
assert!(resolve(&source, None, false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(0), false, None, None).is_err());
|
||||
assert!(resolve(&source, Some(1000), true, None, Some(fixture_profile())).is_err());
|
||||
#[cfg(target_os = "macos")]
|
||||
assert!(resolve(&source, Some(1000), false, None, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod hip_approval;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub mod vpnc_script;
|
||||
@@ -0,0 +1,122 @@
|
||||
use std::{
|
||||
os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use log::{info, warn};
|
||||
use nix::unistd::Uid;
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{credential_lease, session_registry::SessionRegistry};
|
||||
|
||||
pub(crate) const CREDENTIAL_SOCKET: &str = "/var/run/com.yuezk.gpgui/credential.sock";
|
||||
|
||||
pub(crate) struct CredentialServer {
|
||||
registry: Arc<SessionRegistry>,
|
||||
}
|
||||
|
||||
impl CredentialServer {
|
||||
pub(crate) fn new(registry: Arc<SessionRegistry>) -> Self {
|
||||
Self { registry }
|
||||
}
|
||||
|
||||
pub(crate) async fn start(self, cancel: CancellationToken) -> anyhow::Result<()> {
|
||||
if !Uid::effective().is_root() {
|
||||
bail!("macOS brokered mode requires root privileges");
|
||||
}
|
||||
|
||||
let path = prepare_socket(Path::new(CREDENTIAL_SOCKET), 0)?;
|
||||
let listener = UnixListener::bind(&path)
|
||||
.with_context(|| format!("Failed to bind broker credential socket at {}", path.display()))?;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
info!("Broker credential socket listening at {}", path.display());
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted?;
|
||||
if peer_uid(&stream)? != 0 {
|
||||
warn!("Rejected non-root broker credential client");
|
||||
continue;
|
||||
}
|
||||
let registry = Arc::clone(&self.registry);
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = credential_lease::serve(stream, registry, None).await {
|
||||
warn!("Broker credential lease ended: {err}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drop(listener);
|
||||
remove_socket(&path, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_socket(path: &Path, owner_uid: u32) -> anyhow::Result<PathBuf> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("Broker credential socket has no parent directory")?;
|
||||
if !parent.exists() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let metadata = std::fs::symlink_metadata(parent)?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() || metadata.uid() != owner_uid {
|
||||
bail!("Broker credential directory must be a real root-owned directory");
|
||||
}
|
||||
if metadata.permissions().mode() & 0o077 != 0 {
|
||||
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
|
||||
remove_socket(path, owner_uid)?;
|
||||
Ok(path.to_path_buf())
|
||||
}
|
||||
|
||||
fn remove_socket(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_socket() && metadata.uid() == owner_uid => {
|
||||
std::fs::remove_file(path)?;
|
||||
}
|
||||
Ok(_) => bail!("Refusing to replace an unsafe broker credential path"),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {
|
||||
let (uid, _) = nix::unistd::getpeereid(stream)?;
|
||||
Ok(uid.as_raw())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prepares_private_owner_directory_and_removes_owned_socket_only() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let owner = Uid::current().as_raw();
|
||||
let parent = temp.path().join("runtime");
|
||||
let socket = parent.join("credential.sock");
|
||||
|
||||
assert_eq!(prepare_socket(&socket, owner).unwrap(), socket);
|
||||
assert_eq!(std::fs::metadata(&parent).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
|
||||
std::fs::write(&socket, "not a socket").unwrap();
|
||||
assert!(prepare_socket(&socket, owner).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_uid_matches_current_process() {
|
||||
let (stream, _peer) = UnixStream::pair().unwrap();
|
||||
assert_eq!(peer_uid(&stream).unwrap(), Uid::current().as_raw());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,21 @@
|
||||
mod cli;
|
||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||
mod credential_lease;
|
||||
mod desktop_client;
|
||||
#[cfg(debug_assertions)]
|
||||
mod dev_bootstrap;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||
mod device_anchor;
|
||||
mod handlers;
|
||||
mod hip_preview;
|
||||
mod hip_source;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_broker;
|
||||
mod request_dispatcher;
|
||||
mod routes;
|
||||
mod runtime_user;
|
||||
mod session_registry;
|
||||
mod vpn_script;
|
||||
mod vpn_task;
|
||||
mod ws_connection;
|
||||
mod ws_server;
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions, Permissions},
|
||||
io::{BufReader, Read, Write},
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
transport::{ServiceErrorCode, ServiceResult},
|
||||
},
|
||||
utils::{checksum::verify_checksum, redact::Redaction},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use tar::Archive;
|
||||
use tempfile::NamedTempFile;
|
||||
use tokio::sync::Mutex;
|
||||
use xz2::read::XzDecoder;
|
||||
|
||||
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
||||
const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||
|
||||
pub(crate) struct SessionAuthority {
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub session_id: uuid::Uuid,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
pub(crate) enum PendingDispatch {
|
||||
Connect {
|
||||
preparation: ConnectionPreparation,
|
||||
request: Box<gpapi::service::request::ConnectRequest>,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
},
|
||||
Drain(Option<crate::vpn_task::AttemptDrain>),
|
||||
Other(WsRequest),
|
||||
}
|
||||
|
||||
pub(crate) struct ConnectionPreparation {
|
||||
authority: SessionAuthority,
|
||||
non_tunnel: bool,
|
||||
reservation: Option<crate::vpn_task::ConnectReservation>,
|
||||
}
|
||||
|
||||
impl ConnectionPreparation {
|
||||
fn cancellation(&self) -> tokio_util::sync::CancellationToken {
|
||||
self
|
||||
.reservation
|
||||
.as_ref()
|
||||
.expect("preparation retains reservation")
|
||||
.cancellation()
|
||||
}
|
||||
|
||||
fn commit(
|
||||
mut self,
|
||||
connection: crate::vpn_task::PreparedConnection,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
) -> ServiceResult {
|
||||
let reservation = self.reservation.take().expect("preparation retains reservation");
|
||||
self.authority.registry.commit_connection(
|
||||
self.authority.session_id,
|
||||
self.authority.generation,
|
||||
self.non_tunnel,
|
||||
|| reservation.commit(connection, desktop_uid, edited_report, Some(self.authority.session_id)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RequestDispatcher {
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
install_lock: Mutex<()>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl RequestDispatcher {
|
||||
pub fn new(
|
||||
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||
gui_restart_requested: Arc<AtomicBool>,
|
||||
redaction: Arc<Redaction>,
|
||||
gui_management_enabled: bool,
|
||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle,
|
||||
gui_restart_requested,
|
||||
redaction,
|
||||
install_lock: Mutex::new(()),
|
||||
gui_management_enabled,
|
||||
brokered_scripts_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch_lifecycle(
|
||||
&self,
|
||||
request: WsRequest,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_report: Option<Arc<str>>,
|
||||
authority: Option<SessionAuthority>,
|
||||
) -> Result<PendingDispatch, ServiceResult> {
|
||||
match request {
|
||||
WsRequest::Connect(request) => {
|
||||
if let Err(message) = self.validate_connect_paths(&request) {
|
||||
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||
}
|
||||
let redaction_values = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.flat_map(|member| [member.gateway.server(), member.authentication.cookie()])
|
||||
.collect::<Vec<_>>();
|
||||
if let Err(err) = self.redaction.add_values(&redaction_values) {
|
||||
warn!("Failed to update log redaction: {err}");
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::Internal,
|
||||
"Request could not be accepted",
|
||||
));
|
||||
}
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
let reservation =
|
||||
authority
|
||||
.registry
|
||||
.reserve_connection(authority.session_id, authority.generation, non_tunnel, || {
|
||||
self.lifecycle.reserve_connect()
|
||||
})?;
|
||||
let preparation = ConnectionPreparation {
|
||||
authority,
|
||||
non_tunnel,
|
||||
reservation: Some(reservation),
|
||||
};
|
||||
let edited_report = if let gpapi::hip::HipSource::Edited { report_id } = request.args().hip_source() {
|
||||
let report_id = uuid::Uuid::parse_str(report_id)
|
||||
.map_err(|_| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"))?;
|
||||
Some(
|
||||
preparation
|
||||
.authority
|
||||
.registry
|
||||
.edited_hip_report(preparation.authority.session_id, report_id)
|
||||
.map_err(|_| {
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
)
|
||||
})?,
|
||||
)
|
||||
} else {
|
||||
edited_report
|
||||
};
|
||||
Ok(PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
})
|
||||
}
|
||||
WsRequest::StopNonTunnelAttachment { connection_id } => {
|
||||
let authority = authority
|
||||
.ok_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection session is missing"))?;
|
||||
let drain =
|
||||
authority
|
||||
.registry
|
||||
.stop_non_tunnel_attachment(authority.session_id, authority.generation, connection_id)?;
|
||||
Ok(PendingDispatch::Drain(drain))
|
||||
}
|
||||
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
||||
request => Ok(PendingDispatch::Other(request)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||
match self.dispatch_lifecycle(request, None, None, None) {
|
||||
Ok(request) => self.dispatch_pending(request).await,
|
||||
Err(result) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn dispatch_pending(&self, request: PendingDispatch) -> ServiceResult {
|
||||
let request = match request {
|
||||
PendingDispatch::Connect {
|
||||
preparation,
|
||||
request,
|
||||
desktop_uid,
|
||||
edited_report,
|
||||
} => {
|
||||
let prepared = crate::vpn_task::prepare_connection(
|
||||
*request,
|
||||
self.brokered_scripts_dir.is_some(),
|
||||
preparation.cancellation(),
|
||||
)
|
||||
.await;
|
||||
return match prepared {
|
||||
Ok(connection) => preparation.commit(connection, desktop_uid, edited_report),
|
||||
Err(error) => {
|
||||
warn!("Connection preparation failed: {error:#}");
|
||||
ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Connection resources could not be prepared",
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
PendingDispatch::Drain(drain) => {
|
||||
if let Some(drain) = drain {
|
||||
drain.wait().await;
|
||||
}
|
||||
return ServiceResult::Accepted;
|
||||
}
|
||||
PendingDispatch::Other(request) => request,
|
||||
};
|
||||
|
||||
match request {
|
||||
WsRequest::RestartGui => {
|
||||
if !self.gui_management_enabled {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI restart is unavailable on macOS");
|
||||
}
|
||||
info!("GUI restart requested");
|
||||
self
|
||||
.gui_restart_requested
|
||||
.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
WsRequest::UpdateGui(request) => {
|
||||
if !self.gui_management_enabled {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "GUI update is unavailable on macOS");
|
||||
}
|
||||
self.update_gui(request).await
|
||||
}
|
||||
WsRequest::GetVpncScriptMetadata => {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
match gpservice::vpnc_script::metadata() {
|
||||
Ok(metadata) => ServiceResult::VpncScriptMetadata(metadata),
|
||||
Err(err) => {
|
||||
warn!("Failed to read VPNC script metadata: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::Internal, "Failed to read VPNC script metadata")
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
ServiceResult::VpncScriptMetadata(None)
|
||||
}
|
||||
}
|
||||
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
|
||||
let level = level.parse().unwrap_or(log::Level::Info);
|
||||
info!("Updating log level to: {level}");
|
||||
if let Err(err) = gpapi::logger::set_max_level(level) {
|
||||
warn!("Failed to update log level: {err}");
|
||||
}
|
||||
ServiceResult::Accepted
|
||||
}
|
||||
WsRequest::Connect(_)
|
||||
| WsRequest::StopNonTunnelAttachment { .. }
|
||||
| WsRequest::Disconnect(_)
|
||||
| WsRequest::StoreEditedHipReportChunk(_)
|
||||
| WsRequest::PreviewHipReport(_)
|
||||
| WsRequest::GetHipApprovalStatus { .. }
|
||||
| WsRequest::ReadHipPreviewChunk(_)
|
||||
| WsRequest::GetLastSubmittedHipReport => {
|
||||
unreachable!("session-bound request was already dispatched")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
|
||||
let Some(scripts) = &self.brokered_scripts_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
|
||||
if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) {
|
||||
return Err("macOS VPN script must be the bundled script");
|
||||
}
|
||||
if matches!(
|
||||
request.args().hip_source(),
|
||||
gpapi::hip::HipSource::UserScript { .. } | gpapi::hip::HipSource::ApprovedRootScript { .. }
|
||||
) {
|
||||
return Err("macOS does not support custom HIP scripts");
|
||||
}
|
||||
if request.args().certificate().is_some() || request.args().sslkey().is_some() {
|
||||
return Err("macOS client identity must be provided as protected data, not root-readable paths");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||
let _install = self.install_lock.lock().await;
|
||||
let path = request.path;
|
||||
let checksum = request.checksum;
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui(&path, &checksum)).await;
|
||||
match installed {
|
||||
Ok(Ok(())) => ServiceResult::Accepted,
|
||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
||||
warn!("Failed to verify GUI update checksum: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::ChecksumFailed, "GUI update checksum failed")
|
||||
}
|
||||
Ok(Err(GuiInstallError::Install(err))) => {
|
||||
warn!("Failed to install GUI update: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("GUI update task failed: {err}");
|
||||
ServiceResult::rejected(ServiceErrorCode::InstallFailed, "GUI update installation failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GuiInstallError {
|
||||
Checksum(anyhow::Error),
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
fn install_gui(src: &str, checksum: &str) -> Result<(), GuiInstallError> {
|
||||
install_gui_at(Path::new(src), checksum, &binary_paths::gpgui_update_target())
|
||||
}
|
||||
|
||||
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"Failed to get parent directory of GUI binary"
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
|
||||
let staged_archive = stage_gui_archive(src, dir)?;
|
||||
let archive_path = staged_archive.path().to_string_lossy();
|
||||
verify_checksum(&archive_path, checksum).map_err(GuiInstallError::Checksum)?;
|
||||
|
||||
let tar = XzDecoder::new(BufReader::new(
|
||||
staged_archive
|
||||
.reopen()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?,
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let file = extract_gui_binary(&mut archive, dir)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
file
|
||||
.persist(&target)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
File::open(dir)
|
||||
.and_then(|directory| directory.sync_all())
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
let mut source = OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(nix::libc::O_NONBLOCK | nix::libc::O_NOFOLLOW)
|
||||
.open(src)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let metadata = source.metadata().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let source_size = metadata.len();
|
||||
if !metadata.file_type().is_file() || source_size == 0 || source_size > MAX_GUI_ARCHIVE_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive must be a non-empty regular file no larger than {MAX_GUI_ARCHIVE_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut staged = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut (&mut source).take(MAX_GUI_ARCHIVE_SIZE + 1), &mut staged)
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != source_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive changed while it was being read"
|
||||
)));
|
||||
}
|
||||
staged.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
staged
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == "gpgui");
|
||||
if is_gui && entry.header().entry_type().is_file() {
|
||||
let declared_size = entry.size();
|
||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary must be non-empty and no larger than {MAX_GUI_BINARY_SIZE} bytes"
|
||||
)));
|
||||
}
|
||||
let mut file = NamedTempFile::new_in(dir).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let copied = std::io::copy(&mut entry, &mut file).map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
if copied != declared_size {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI binary size does not match its archive header"
|
||||
)));
|
||||
}
|
||||
file.flush().map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
return Ok(file);
|
||||
}
|
||||
}
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular gpgui file"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::vpn_task::test_connect_request as test_request;
|
||||
use std::{io::Cursor, os::unix::fs::PermissionsExt};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
service::transport::{ServiceErrorCode, ServiceResult},
|
||||
};
|
||||
use tar::{Builder, EntryType, Header};
|
||||
use xz2::write::XzEncoder;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn archive_with_entry(entry_type: EntryType, contents: &[u8]) -> Vec<u8> {
|
||||
let mut data = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut data);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(entry_type);
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
builder.append_data(&mut header, "gpgui", contents).unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn compressed_gui_archive(contents: &[u8]) -> NamedTempFile {
|
||||
let tar = archive_with_entry(EntryType::Regular, contents);
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 6);
|
||||
encoder.write_all(&tar).unwrap();
|
||||
let compressed = encoder.finish().unwrap();
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&compressed).unwrap();
|
||||
archive.flush().unwrap();
|
||||
archive
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_file_and_empty_gui_entries() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
||||
let data = archive_with_entry(entry_type, contents);
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_non_empty_regular_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
let extracted = extract_gui_binary(&mut archive, output.path()).unwrap();
|
||||
let contents = std::fs::read(extracted.path()).unwrap();
|
||||
assert_eq!(contents, b"gui binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_archive_sources() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
assert!(stage_gui_archive(output.path(), output.path()).is_err());
|
||||
|
||||
let oversized = output.path().join("oversized.tar.xz");
|
||||
File::create(&oversized)
|
||||
.unwrap()
|
||||
.set_len(MAX_GUI_ARCHIVE_SIZE + 1)
|
||||
.unwrap();
|
||||
assert!(stage_gui_archive(&oversized, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_gui_entry() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(MAX_GUI_BINARY_SIZE + 1);
|
||||
header.set_mode(0o755);
|
||||
header.set_path("gpgui").unwrap();
|
||||
header.set_cksum();
|
||||
let mut data = header.as_bytes().to_vec();
|
||||
data.resize(512 * 3, 0);
|
||||
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_gui_at_the_supplied_target() {
|
||||
let archive = compressed_gui_archive(b"gui binary");
|
||||
let checksum = sha256::try_digest(archive.path()).unwrap();
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
|
||||
install_gui_at(archive.path(), &checksum, &target).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"gui binary");
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let target = output.path().join("gpclient/gpgui");
|
||||
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
|
||||
assert!(install_gui_at(archive.path(), "invalid", &target).is_err());
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
|
||||
panic!("brokered mode accepted GUI restart");
|
||||
};
|
||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
||||
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let request = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_certificate(Some("/Users/example/client.pem".to_string()));
|
||||
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
|
||||
panic!("brokered mode accepted a root-readable identity path");
|
||||
};
|
||||
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
||||
let dispatcher = RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
false,
|
||||
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
|
||||
);
|
||||
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
|
||||
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
|
||||
let bundled =
|
||||
test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()));
|
||||
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
|
||||
|
||||
let old_layout = test_request(info.clone()).with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()));
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&old_layout),
|
||||
Err("macOS VPN script must be the bundled script")
|
||||
);
|
||||
|
||||
let custom = test_request(info)
|
||||
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
|
||||
.with_hip_source(gpapi::hip::HipSource::UserScript {
|
||||
path: "/tmp/hip.sh".into(),
|
||||
});
|
||||
assert_eq!(
|
||||
dispatcher.validate_connect_paths(&custom),
|
||||
Err("macOS does not support custom HIP scripts")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ pub(crate) fn routes(ctx: Arc<WsServerContext>) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(handlers::health))
|
||||
.route("/active-gui", post(handlers::active_gui))
|
||||
.route("/update-gui", post(handlers::update_gui))
|
||||
.route("/ws", get(handlers::ws_handler))
|
||||
.with_state(ctx)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub(crate) fn desktop_uid() -> Option<u32> {
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
|
||||
pub(crate) use platform::desktop_uid;
|
||||
@@ -0,0 +1,9 @@
|
||||
pub(crate) fn desktop_uid() -> Option<u32> {
|
||||
match gpapi::process::users::get_non_root_user() {
|
||||
Ok(user) => Some(user.uid()),
|
||||
Err(err) => {
|
||||
log::warn!("No verified desktop user is available for custom HIP scripts: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,922 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex, Weak},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use gpapi::service::transport::{ServiceErrorCode, ServiceResult, SessionCredential};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::ws_connection::ConnectionControl;
|
||||
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const MAX_PENDING_SESSIONS: usize = 16;
|
||||
const HIP_PREVIEW_CHUNK_BYTES: usize = 16 * 1024;
|
||||
|
||||
pub struct HandshakePermit {
|
||||
pub session_id: Uuid,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub observed_generation: u64,
|
||||
pub secret: Zeroizing<[u8; 32]>,
|
||||
token: Uuid,
|
||||
registry: Weak<SessionRegistry>,
|
||||
}
|
||||
|
||||
pub struct PreparedAttach {
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum SessionError {
|
||||
#[error("credential belongs to another service instance")]
|
||||
ServiceRestarted { service_instance_id: Uuid },
|
||||
#[error("session is unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("too many pending sessions")]
|
||||
TooManyPending,
|
||||
#[error("another reconnect completed first")]
|
||||
ReconnectSuperseded,
|
||||
#[error("session registry is unavailable")]
|
||||
Unavailable,
|
||||
#[error("invalid HIP report upload")]
|
||||
InvalidHipUpload,
|
||||
}
|
||||
|
||||
pub enum HipUploadResult {
|
||||
Progress(Uuid),
|
||||
Stored(Uuid),
|
||||
}
|
||||
|
||||
enum SessionStatus {
|
||||
Pending {
|
||||
activation_deadline: Instant,
|
||||
handshake_token: Option<Uuid>,
|
||||
},
|
||||
Active {
|
||||
generation: u64,
|
||||
connection: Option<ConnectionControl>,
|
||||
reconnect_token: Option<Uuid>,
|
||||
},
|
||||
}
|
||||
|
||||
struct SessionRecord {
|
||||
non_tunnel: Option<AttachmentAttempt>,
|
||||
closed_attachment: Option<Uuid>,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
desktop_uid: Option<u32>,
|
||||
edited_hip_report: Option<(Uuid, Arc<str>)>,
|
||||
edited_hip_upload: Option<(Uuid, String)>,
|
||||
hip_preview: Option<(Uuid, Arc<str>)>,
|
||||
last_successful_hip_report: Option<Arc<str>>,
|
||||
status: SessionStatus,
|
||||
}
|
||||
|
||||
/// Only live preparation/execution is retained, never acceptance history.
|
||||
struct AttachmentAttempt {
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
drain: crate::vpn_task::AttemptDrain,
|
||||
}
|
||||
|
||||
pub struct SessionRegistry {
|
||||
service_instance_id: Uuid,
|
||||
sessions: Mutex<HashMap<Uuid, SessionRecord>>,
|
||||
}
|
||||
|
||||
fn unavailable_connection() -> ServiceResult {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Connection attachment is unavailable")
|
||||
}
|
||||
|
||||
fn current_connection(record: &SessionRecord, expected: u64) -> Result<Uuid, ServiceResult> {
|
||||
match &record.status {
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
connection: Some(connection),
|
||||
..
|
||||
} if *generation == expected && !connection.is_closed() => Ok(connection.connection_id()),
|
||||
_ => Err(unavailable_connection()),
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionRegistry {
|
||||
pub(crate) fn reserve_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
reserve: impl FnOnce() -> Result<crate::vpn_task::ConnectReservation, ServiceResult>,
|
||||
) -> Result<crate::vpn_task::ConnectReservation, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let connection_id = current_connection(record, generation)?;
|
||||
if non_tunnel && record.closed_attachment == Some(connection_id) {
|
||||
return Err(ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Non-tunnel attachment is closing",
|
||||
));
|
||||
}
|
||||
if record
|
||||
.non_tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|attempt| attempt.drain.is_complete())
|
||||
{
|
||||
record.non_tunnel = None;
|
||||
}
|
||||
let reservation = reserve()?;
|
||||
if non_tunnel {
|
||||
record.non_tunnel = Some(AttachmentAttempt {
|
||||
generation,
|
||||
connection_id,
|
||||
drain: reservation.drain(),
|
||||
});
|
||||
}
|
||||
Ok(reservation)
|
||||
}
|
||||
|
||||
pub(crate) fn commit_connection(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
non_tunnel: bool,
|
||||
commit: impl FnOnce() -> ServiceResult,
|
||||
) -> ServiceResult {
|
||||
let Ok(sessions) = self.sessions.lock() else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
let Some(record) = sessions.get(&session_id) else {
|
||||
return unavailable_connection();
|
||||
};
|
||||
if non_tunnel {
|
||||
let connection_id = match current_connection(record, generation) {
|
||||
Ok(id) => id,
|
||||
Err(result) => return result,
|
||||
};
|
||||
if record.closed_attachment == Some(connection_id) {
|
||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Non-tunnel attachment is closing");
|
||||
}
|
||||
} else if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return unavailable_connection();
|
||||
}
|
||||
// Non-tunnel attachment invalidation takes this same lock. An authorized
|
||||
// tunnel reservation survives attachment loss as before; revoked sessions
|
||||
// cannot commit either mode. Queue insertion transfers cleanup ownership.
|
||||
commit()
|
||||
}
|
||||
|
||||
pub(crate) fn stop_non_tunnel_attachment(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
generation: u64,
|
||||
connection_id: Uuid,
|
||||
) -> Result<Option<crate::vpn_task::AttemptDrain>, ServiceResult> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| unavailable_connection())?;
|
||||
let record = sessions.get_mut(&session_id).ok_or_else(unavailable_connection)?;
|
||||
let current_id = current_connection(record, generation)?;
|
||||
if current_id == connection_id {
|
||||
record.closed_attachment = Some(connection_id);
|
||||
}
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.connection_id == connection_id {
|
||||
attempt.drain.cancel();
|
||||
return Ok(Some(attempt.drain.clone()));
|
||||
}
|
||||
}
|
||||
// No retained live work belongs to that attachment. Never stop a successor.
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn new(service_instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
service_instance_id,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn issue(&self, product_version: &str, desktop_uid: Option<u32>) -> Result<Arc<SessionCredential>, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, record| {
|
||||
!matches!(
|
||||
record.status,
|
||||
SessionStatus::Pending {
|
||||
activation_deadline, ..
|
||||
} if now > activation_deadline
|
||||
)
|
||||
});
|
||||
let pending = sessions
|
||||
.values()
|
||||
.filter(|record| matches!(record.status, SessionStatus::Pending { .. }))
|
||||
.count();
|
||||
if pending >= MAX_PENDING_SESSIONS {
|
||||
return Err(SessionError::TooManyPending);
|
||||
}
|
||||
|
||||
let credential =
|
||||
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let credential = {
|
||||
let anchor = crate::device_anchor::resolve().map_err(|error| {
|
||||
log::warn!("GUI device anchor unavailable: {error:#}");
|
||||
SessionError::Unavailable
|
||||
})?;
|
||||
credential
|
||||
.with_device_anchor(anchor)
|
||||
.map_err(|_| SessionError::Unavailable)?
|
||||
};
|
||||
let credential = Arc::new(credential);
|
||||
sessions.insert(
|
||||
credential.session_id(),
|
||||
SessionRecord {
|
||||
non_tunnel: None,
|
||||
closed_attachment: None,
|
||||
secret: Zeroizing::new(*credential.secret()),
|
||||
product_version: credential.product_version().to_owned(),
|
||||
desktop_uid,
|
||||
edited_hip_report: None,
|
||||
edited_hip_upload: None,
|
||||
hip_preview: None,
|
||||
last_successful_hip_report: None,
|
||||
status: SessionStatus::Pending {
|
||||
activation_deadline: Instant::now() + ACTIVATION_TIMEOUT,
|
||||
handshake_token: None,
|
||||
},
|
||||
},
|
||||
);
|
||||
Ok(credential)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return false;
|
||||
};
|
||||
let now = Instant::now();
|
||||
sessions.retain(|_, record| {
|
||||
!matches!(
|
||||
record.status,
|
||||
SessionStatus::Pending {
|
||||
activation_deadline, ..
|
||||
} if now > activation_deadline
|
||||
)
|
||||
});
|
||||
sessions.is_empty()
|
||||
}
|
||||
|
||||
pub fn begin_handshake(
|
||||
self: &Arc<Self>,
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
product_version: &str,
|
||||
) -> Result<HandshakePermit, SessionError> {
|
||||
if service_instance_id != self.service_instance_id {
|
||||
return Err(SessionError::ServiceRestarted {
|
||||
service_instance_id: self.service_instance_id,
|
||||
});
|
||||
}
|
||||
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let Some(record) = sessions.get_mut(&session_id) else {
|
||||
return Err(SessionError::Unauthorized);
|
||||
};
|
||||
if record.product_version != product_version {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
|
||||
let token = Uuid::new_v4();
|
||||
let observed_generation = match &mut record.status {
|
||||
SessionStatus::Pending {
|
||||
activation_deadline,
|
||||
handshake_token,
|
||||
} => {
|
||||
if Instant::now() > *activation_deadline {
|
||||
sessions.remove(&session_id);
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
if handshake_token.is_some() {
|
||||
return Err(SessionError::ReconnectSuperseded);
|
||||
}
|
||||
*handshake_token = Some(token);
|
||||
0
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} => {
|
||||
if reconnect_token.is_some() {
|
||||
return Err(SessionError::ReconnectSuperseded);
|
||||
}
|
||||
*reconnect_token = Some(token);
|
||||
*generation
|
||||
}
|
||||
};
|
||||
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
Ok(HandshakePermit {
|
||||
session_id,
|
||||
desktop_uid: record.desktop_uid,
|
||||
observed_generation,
|
||||
secret: Zeroizing::new(*record.secret),
|
||||
token,
|
||||
registry: Arc::downgrade(self),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn prepare_attach(&self, permit: &HandshakePermit) -> Result<PreparedAttach, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
||||
let generation = match &record.status {
|
||||
SessionStatus::Pending { handshake_token, .. }
|
||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
||||
{
|
||||
1
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
generation.checked_add(1).ok_or(SessionError::Unavailable)?
|
||||
}
|
||||
_ => return Err(SessionError::ReconnectSuperseded),
|
||||
};
|
||||
Ok(PreparedAttach { generation })
|
||||
}
|
||||
|
||||
pub fn commit_attach(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
connection: ConnectionControl,
|
||||
) -> Result<Option<ConnectionControl>, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&permit.session_id).ok_or(SessionError::Unauthorized)?;
|
||||
|
||||
match &mut record.status {
|
||||
SessionStatus::Pending { handshake_token, .. }
|
||||
if permit.observed_generation == 0 && *handshake_token == Some(permit.token) =>
|
||||
{
|
||||
record.status = SessionStatus::Active {
|
||||
generation: 1,
|
||||
connection: Some(connection),
|
||||
reconnect_token: None,
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
connection: current,
|
||||
reconnect_token,
|
||||
} if *generation == permit.observed_generation && *reconnect_token == Some(permit.token) => {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
record.closed_attachment = None;
|
||||
*generation = generation.checked_add(1).ok_or(SessionError::Unavailable)?;
|
||||
*reconnect_token = None;
|
||||
Ok(current.replace(connection))
|
||||
}
|
||||
_ => Err(SessionError::ReconnectSuperseded),
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_handshake(&self, session_id: Uuid, observed_generation: u64, token: Uuid) {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
let Some(record) = sessions.get_mut(&session_id) else {
|
||||
return;
|
||||
};
|
||||
match &mut record.status {
|
||||
SessionStatus::Pending { handshake_token, .. } if observed_generation == 0 && *handshake_token == Some(token) => {
|
||||
sessions.remove(&session_id);
|
||||
}
|
||||
SessionStatus::Active {
|
||||
generation,
|
||||
reconnect_token,
|
||||
..
|
||||
} if *generation == observed_generation && *reconnect_token == Some(token) => {
|
||||
*reconnect_token = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_current(&self, session_id: Uuid, generation: u64) -> bool {
|
||||
let Ok(sessions) = self.sessions.lock() else {
|
||||
return false;
|
||||
};
|
||||
matches!(
|
||||
sessions.get(&session_id).map(|record| &record.status),
|
||||
Some(SessionStatus::Active { generation: current, .. }) if *current == generation
|
||||
)
|
||||
}
|
||||
|
||||
pub fn append_edited_hip_report_chunk(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
upload_id: Option<Uuid>,
|
||||
offset: usize,
|
||||
chunk: String,
|
||||
complete: bool,
|
||||
) -> Result<HipUploadResult, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
if upload_id.is_none() {
|
||||
if offset != 0 {
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
record.edited_hip_upload = Some((Uuid::new_v4(), String::new()));
|
||||
}
|
||||
let (current_id, xml) = record
|
||||
.edited_hip_upload
|
||||
.as_mut()
|
||||
.ok_or(SessionError::InvalidHipUpload)?;
|
||||
if upload_id.is_some_and(|id| id != *current_id) || offset != xml.len() || chunk.len() > 8 * 1024 {
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
if xml.len() + chunk.len() > gphip::MAX_EDITED_REPORT_BYTES {
|
||||
record.edited_hip_upload = None;
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
xml.push_str(&chunk);
|
||||
if !complete {
|
||||
return Ok(HipUploadResult::Progress(*current_id));
|
||||
}
|
||||
if gphip::validate_edited_report(xml).is_err() {
|
||||
record.edited_hip_upload = None;
|
||||
return Err(SessionError::InvalidHipUpload);
|
||||
}
|
||||
let (_, xml) = record.edited_hip_upload.take().ok_or(SessionError::InvalidHipUpload)?;
|
||||
let report_id = Uuid::new_v4();
|
||||
record.edited_hip_report = Some((report_id, Arc::from(xml)));
|
||||
Ok(HipUploadResult::Stored(report_id))
|
||||
}
|
||||
|
||||
pub fn edited_hip_report(&self, session_id: Uuid, report_id: Uuid) -> Result<Arc<str>, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
record
|
||||
.edited_hip_report
|
||||
.as_ref()
|
||||
.filter(|(id, _)| *id == report_id)
|
||||
.map(|(_, xml)| Arc::clone(xml))
|
||||
.ok_or(SessionError::Unauthorized)
|
||||
}
|
||||
|
||||
pub fn store_hip_preview(&self, session_id: Uuid, xml: String) -> Result<Uuid, SessionError> {
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
let preview_id = Uuid::new_v4();
|
||||
record.hip_preview = Some((preview_id, Arc::from(xml)));
|
||||
Ok(preview_id)
|
||||
}
|
||||
|
||||
pub fn hip_preview_chunk(
|
||||
&self,
|
||||
session_id: Uuid,
|
||||
preview_id: Uuid,
|
||||
offset: usize,
|
||||
) -> Result<(String, bool), SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
let (_, xml) = record
|
||||
.hip_preview
|
||||
.as_ref()
|
||||
.filter(|(id, _)| *id == preview_id)
|
||||
.ok_or(SessionError::Unauthorized)?;
|
||||
if offset > xml.len() || !xml.is_char_boundary(offset) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
let mut end = (offset + HIP_PREVIEW_CHUNK_BYTES).min(xml.len());
|
||||
while !xml.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
Ok((xml[offset..end].to_owned(), end == xml.len()))
|
||||
}
|
||||
|
||||
pub fn store_successful_hip_report(&self, session_id: Uuid, xml: &str) -> Result<(), SessionError> {
|
||||
if xml.len() > 1024 * 1024 {
|
||||
return Err(SessionError::Unavailable);
|
||||
}
|
||||
let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
if !matches!(record.status, SessionStatus::Active { .. }) {
|
||||
return Err(SessionError::Unauthorized);
|
||||
}
|
||||
record.last_successful_hip_report = Some(Arc::from(xml));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn last_successful_hip_report(&self, session_id: Uuid) -> Result<Option<Arc<str>>, SessionError> {
|
||||
let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?;
|
||||
let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?;
|
||||
Ok(record.last_successful_hip_report.as_ref().map(Arc::clone))
|
||||
}
|
||||
|
||||
pub fn clear_successful_hip_report(&self, session_id: Uuid) {
|
||||
if let Ok(mut sessions) = self.sessions.lock()
|
||||
&& let Some(record) = sessions.get_mut(&session_id)
|
||||
{
|
||||
record.last_successful_hip_report = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect_if_current(&self, session_id: Uuid, generation: u64) {
|
||||
let Ok(mut sessions) = self.sessions.lock() else {
|
||||
return;
|
||||
};
|
||||
if let Some(record) = sessions.get_mut(&session_id) {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
if attempt.generation == generation {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(SessionRecord {
|
||||
status: SessionStatus::Active {
|
||||
generation: current,
|
||||
connection,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = sessions.get_mut(&session_id)
|
||||
&& *current == generation
|
||||
{
|
||||
connection.take();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn revoke(&self, session_id: Uuid) {
|
||||
let connection = self
|
||||
.sessions
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut sessions| sessions.remove(&session_id))
|
||||
.and_then(|record| {
|
||||
if let Some(attempt) = &record.non_tunnel {
|
||||
attempt.drain.cancel();
|
||||
}
|
||||
match record.status {
|
||||
SessionStatus::Active { connection, .. } => connection,
|
||||
SessionStatus::Pending { .. } => None,
|
||||
}
|
||||
});
|
||||
if let Some(connection) = connection {
|
||||
connection.close(gpapi::service::transport::CloseReason::Unauthorized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HandshakePermit {
|
||||
fn drop(&mut self) {
|
||||
if let Some(registry) = self.registry.upgrade() {
|
||||
registry.cancel_handshake(self.session_id, self.observed_generation, self.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::*;
|
||||
use crate::ws_connection::ConnectionCommand;
|
||||
|
||||
fn control() -> ConnectionControl {
|
||||
let (tx, _rx) = mpsc::channel::<ConnectionCommand>(1);
|
||||
ConnectionControl::new(Uuid::new_v4(), tx).0
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attachment_replacement_cancels_preparation_and_retains_drain_until_release() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let first_control = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let old_id = first_control.connection_id();
|
||||
registry.commit_attach(&first, first_control).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = reservation.drain();
|
||||
let cancel = reservation.cancellation();
|
||||
|
||||
let next = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&next, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
assert!(cancel.is_cancelled());
|
||||
assert!(!drain.is_complete());
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.is_err()
|
||||
);
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("stale start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
|
||||
let next_reservation = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert!(
|
||||
registry
|
||||
.stop_non_tunnel_attachment(session, 2, old_id)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!next_reservation.cancellation().is_cancelled());
|
||||
registry.disconnect_if_current(session, 2);
|
||||
assert!(next_reservation.cancellation().is_cancelled());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scoped_stop_closes_attachment_to_delayed_starts_without_receipt_history() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
let connection = ConnectionControl::new(Uuid::new_v4(), tx).0;
|
||||
let id = connection.connection_id();
|
||||
registry.commit_attach(&permit, connection).unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
let drain = registry.stop_non_tunnel_attachment(session, 1, id).unwrap().unwrap();
|
||||
assert!(reservation.cancellation().is_cancelled());
|
||||
assert!(matches!(
|
||||
registry.commit_connection(session, 1, true, || panic!("closing start committed")),
|
||||
ServiceResult::Rejected(_)
|
||||
));
|
||||
assert!(!drain.is_complete());
|
||||
drop(reservation);
|
||||
drain.wait().await;
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, true, || panic!("closed attachment reserved"))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tunnel_reservation_survives_attachment_loss_but_non_tunnel_revocation_cancels() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let (state, _state_rx) = tokio::sync::watch::channel(gpapi::service::vpn_state::VpnState::Disconnected);
|
||||
let (_task, lifecycle) = crate::vpn_task::VpnTask::new(state, false, registry.clone());
|
||||
let tunnel = registry
|
||||
.reserve_connection(session, 1, false, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.disconnect_if_current(session, 1);
|
||||
assert!(!tunnel.cancellation().is_cancelled());
|
||||
assert_eq!(
|
||||
registry.commit_connection(session, 1, false, || ServiceResult::Accepted),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
drop(tunnel);
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _next_rx) = mpsc::channel(4);
|
||||
registry
|
||||
.commit_attach(&permit, ConnectionControl::new(Uuid::new_v4(), tx).0)
|
||||
.unwrap();
|
||||
let session_work = registry
|
||||
.reserve_connection(session, 2, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
registry.revoke(session);
|
||||
assert!(session_work.cancellation().is_cancelled());
|
||||
assert!(!session_work.drain().is_complete());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_retains_verified_desktop_user_across_reconnect() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert_eq!(first.desktop_uid, Some(1000));
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert_eq!(reconnect.desktop_uid, Some(1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_hip_report_is_session_bound_and_replaced_without_affecting_pinned_content() {
|
||||
fn upload(registry: &SessionRegistry, session_id: Uuid, xml: &str) -> Uuid {
|
||||
let mut upload_id = None;
|
||||
let mut offset = 0;
|
||||
while offset < xml.len() {
|
||||
let mut end = (offset + 8 * 1024).min(xml.len());
|
||||
while !xml.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
let complete = end == xml.len();
|
||||
match registry
|
||||
.append_edited_hip_report_chunk(session_id, upload_id, offset, xml[offset..end].into(), complete)
|
||||
.unwrap()
|
||||
{
|
||||
HipUploadResult::Progress(id) => upload_id = Some(id),
|
||||
HipUploadResult::Stored(id) => return id,
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
panic!("upload did not complete")
|
||||
}
|
||||
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let first_credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let second_credential = registry.issue("2.6.4", Some(1001)).unwrap();
|
||||
for credential in [&first_credential, &second_credential] {
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
registry.commit_attach(&permit, control()).unwrap();
|
||||
}
|
||||
|
||||
let valid = gphip::generate_report(&gphip::ReportInput {
|
||||
profile: gpapi::os_profile::OsProfile::builder(gpapi::os_profile::ClientOs::Linux).build(),
|
||||
context: gphip::ReportContext::Preview,
|
||||
})
|
||||
.unwrap();
|
||||
let first_id = upload(®istry, first_credential.session_id(), &valid);
|
||||
let pinned = registry
|
||||
.edited_hip_report(first_credential.session_id(), first_id)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(second_credential.session_id(), first_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
let second_id = upload(®istry, first_credential.session_id(), &valid);
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(first_credential.session_id(), first_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
assert_eq!(
|
||||
&*registry
|
||||
.edited_hip_report(first_credential.session_id(), second_id)
|
||||
.unwrap(),
|
||||
valid
|
||||
);
|
||||
assert_eq!(&*pinned, valid);
|
||||
registry.revoke(first_credential.session_id());
|
||||
assert!(matches!(
|
||||
registry.edited_hip_report(first_credential.session_id(), second_id),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submitted_report_changes_only_after_success_callback_and_is_session_bound() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", Some(1000)).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
registry.commit_attach(&permit, control()).unwrap();
|
||||
assert!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
registry
|
||||
.store_successful_hip_report(credential.session_id(), "first")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
let preview_id = registry
|
||||
.store_hip_preview(credential.session_id(), "é".repeat(8193))
|
||||
.unwrap();
|
||||
let (first_chunk, complete) = registry
|
||||
.hip_preview_chunk(credential.session_id(), preview_id, 0)
|
||||
.unwrap();
|
||||
assert!(!complete);
|
||||
assert!(first_chunk.len() <= HIP_PREVIEW_CHUNK_BYTES);
|
||||
assert!(
|
||||
registry
|
||||
.hip_preview_chunk(credential.session_id(), preview_id, 1)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("first")
|
||||
);
|
||||
registry.clear_successful_hip_report(credential.session_id());
|
||||
assert!(
|
||||
registry
|
||||
.last_successful_hip_report(credential.session_id())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnect_uses_generation_compare_and_swap() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert_eq!(registry.prepare_attach(&first).unwrap().generation, 1);
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let candidate_a = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
||||
Err(SessionError::ReconnectSuperseded)
|
||||
));
|
||||
assert_eq!(registry.prepare_attach(&candidate_a).unwrap().generation, 2);
|
||||
registry.commit_attach(&candidate_a, control()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_initial_handshake_only_revokes_its_own_reservation() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
drop(first);
|
||||
assert!(matches!(
|
||||
registry.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4"),
|
||||
Err(SessionError::Unauthorized)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_reconnect_keeps_active_connection_authoritative() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue("2.6.4", None).unwrap();
|
||||
let first = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
registry.commit_attach(&first, control()).unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.unwrap();
|
||||
drop(reconnect);
|
||||
assert!(registry.is_current(credential.session_id(), 1));
|
||||
assert!(
|
||||
registry
|
||||
.begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4")
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
Ok(Vpn::builder(server, cookie).script_path(args.vpnc_script()))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[path = "privileged_unix.rs"]
|
||||
mod platform;
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
#[path = "default.rs"]
|
||||
mod platform;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
mod selection;
|
||||
|
||||
pub(crate) use platform::builder;
|
||||
@@ -0,0 +1,16 @@
|
||||
use gpapi::service::request::ConnectArgs;
|
||||
use openconnect::{Vpn, VpnBuilder};
|
||||
|
||||
use super::selection::{ScriptSource, select};
|
||||
|
||||
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> anyhow::Result<VpnBuilder> {
|
||||
let installed = gpservice::vpnc_script::installed_script()?;
|
||||
let legacy = args.vpnc_script();
|
||||
match select(installed.as_deref(), legacy.as_deref()) {
|
||||
ScriptSource::Installed(path) => {
|
||||
Ok(Vpn::builder(server, cookie).script_path(Some(path.to_string_lossy().into_owned())))
|
||||
}
|
||||
ScriptSource::Legacy(script) => Ok(Vpn::builder(server, cookie).script(Some(script.to_owned()))),
|
||||
ScriptSource::Default => Ok(Vpn::builder(server, cookie).script_path(None)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum ScriptSource<'a> {
|
||||
Installed(&'a Path),
|
||||
Legacy(&'a str),
|
||||
Default,
|
||||
}
|
||||
|
||||
pub(super) fn select<'a>(installed: Option<&'a Path>, legacy: Option<&'a str>) -> ScriptSource<'a> {
|
||||
if let Some(path) = installed {
|
||||
return ScriptSource::Installed(path);
|
||||
}
|
||||
if let Some(script) = legacy {
|
||||
return ScriptSource::Legacy(script);
|
||||
}
|
||||
ScriptSource::Default
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installed_script_takes_precedence_over_legacy() {
|
||||
let installed = Path::new("/var/lib/gpclient/scripts/vpnc-script");
|
||||
assert_eq!(
|
||||
select(Some(installed), Some("legacy-command")),
|
||||
ScriptSource::Installed(installed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_script_is_used_before_default() {
|
||||
assert_eq!(
|
||||
select(None, Some("legacy-command")),
|
||||
ScriptSource::Legacy("legacy-command")
|
||||
);
|
||||
assert_eq!(select(None, None), ScriptSource::Default);
|
||||
}
|
||||
}
|
||||
+1161
-144
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,192 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::process::collection::CollectionControl;
|
||||
use gpapi::session::{
|
||||
GatewaySessionSummary, MaintenanceState, SessionEndReason,
|
||||
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
|
||||
};
|
||||
use log::warn;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
LifecycleEvent,
|
||||
runtime::{AttemptInput, stop_for_revoked_approval},
|
||||
};
|
||||
|
||||
/// Borrow the accepted ledger. The outer attempt owner retains identity/source
|
||||
/// resources and joins this runtime before draining the remaining members.
|
||||
pub(super) async fn run(
|
||||
input: &mut AttemptInput,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
let request = &input.connection.request;
|
||||
let args = request.args();
|
||||
let resources = &input.connection.resources;
|
||||
let sessions = &mut input.connection.sessions;
|
||||
let network = resources
|
||||
.network
|
||||
.as_ref()
|
||||
.context("Physical network context is missing")?;
|
||||
let posture_enabled =
|
||||
request.plan().policy().collect_hip_data() && !matches!(args.hip_source(), gpapi::hip::HipSource::Disabled);
|
||||
let profile = resources.profile.clone();
|
||||
let initial = sessions
|
||||
.members()
|
||||
.iter()
|
||||
.map(|session| GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: gpapi::session::SessionMode::NonTunnel,
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
maintenance: MaintenanceState::Authenticated,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let (status, mut changed) = watch::channel(initial);
|
||||
let registry = input.registry.clone();
|
||||
let session_id = input.session_id;
|
||||
let validation_network = network.clone();
|
||||
let validation_detection = request.plan().internal_detection().cloned();
|
||||
let callbacks = SessionCallbacks {
|
||||
validate_network: Arc::new(move |cancel| {
|
||||
let network = validation_network.clone();
|
||||
let detection = validation_detection.clone();
|
||||
Box::pin(async move { network.validate_internal(detection.as_ref(), &cancel).await })
|
||||
}),
|
||||
produce_report: Arc::new(move |request, control| {
|
||||
control.check()?;
|
||||
let context = gphip::ReportContext::Connected {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
};
|
||||
if !posture_enabled {
|
||||
return gphip::generate_identity_report(&gphip::ReportInput {
|
||||
profile: profile.clone(),
|
||||
context,
|
||||
})
|
||||
.map_err(std::io::Error::other);
|
||||
}
|
||||
source.collect(
|
||||
&openconnect::HipRequest {
|
||||
cookie: request.cookie.clone(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
md5: request.md5.clone(),
|
||||
client_version: profile.client_version().into(),
|
||||
client_os: profile.client_os().as_str().into(),
|
||||
os_version: profile.os_version().into(),
|
||||
host_id: Some(profile.host_id().into()),
|
||||
local_hostname: Some(profile.computer().into()),
|
||||
},
|
||||
&|| control.check(),
|
||||
)
|
||||
}),
|
||||
report_submitted: Arc::new(move |_, xml| {
|
||||
if let Some(session_id) = session_id {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
}
|
||||
}),
|
||||
status_changed: Arc::new(move |summary| {
|
||||
status.send_modify(|members| {
|
||||
if let Some(member) = members
|
||||
.iter_mut()
|
||||
.find(|member| member.gateway.server() == summary.gateway.server())
|
||||
{
|
||||
*member = summary;
|
||||
}
|
||||
});
|
||||
}),
|
||||
};
|
||||
let monitor_cancel = cancellation.child_token();
|
||||
let monitor_token = monitor_cancel.clone();
|
||||
let network = network.clone();
|
||||
let detection = request.plan().internal_detection().cloned();
|
||||
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
|
||||
let monitor = tokio::spawn(async move {
|
||||
match network.wait_for_change(detection, monitor_token).await {
|
||||
Ok(false) => {}
|
||||
Ok(true) => {
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Physical network inspection failed: {error}");
|
||||
let _ = network_changed.send(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut approval_revoked = false;
|
||||
let result = {
|
||||
let lifecycle_cancel = cancellation.clone();
|
||||
let maintenance = maintain_non_tunnel_sessions(
|
||||
sessions,
|
||||
request.plan().policy(),
|
||||
callbacks,
|
||||
lifecycle_cancel,
|
||||
async move { network_signal.await.unwrap_or(SessionEndReason::NetworkChanged) },
|
||||
);
|
||||
tokio::pin!(maintenance);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut publish = true;
|
||||
let result = loop {
|
||||
if publish && !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
publish = false;
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut maintenance => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
approval_revoked = true;
|
||||
stop_for_revoked_approval(&input.lifecycle, &cancellation);
|
||||
},
|
||||
result = changed.changed() => { if result.is_ok() { publish = true; } },
|
||||
}
|
||||
};
|
||||
// Maintenance can invalidate every member and finish in the same poll.
|
||||
// Forward that last snapshot before monitor/remote cleanup, even when the
|
||||
// completed maintenance branch won over the watch notification.
|
||||
if !cancellation.is_cancelled() {
|
||||
let members = changed.borrow_and_update().clone();
|
||||
let _ = events
|
||||
.send(LifecycleEvent::MembersChanged {
|
||||
attempt: input.attempt,
|
||||
members,
|
||||
failures: request.plan().failures().to_vec(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
result
|
||||
};
|
||||
monitor_cancel.cancel();
|
||||
monitor.await.context("Network monitor worker failed")?;
|
||||
if approval_revoked {
|
||||
let _ = events
|
||||
.send(LifecycleEvent::Failed {
|
||||
attempt: input.attempt,
|
||||
reason: "HIP script approval was revoked".into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
// resources and approval remain owned until maintenance/logout and monitor
|
||||
// inspection are drained. Deliberate disconnect wins throughout cleanup.
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use gpapi::{
|
||||
gateway::Gateway,
|
||||
gp_params::GpParams,
|
||||
service::{
|
||||
transport::ServiceResult,
|
||||
vpn_state::{ConnectInfo, VpnState},
|
||||
},
|
||||
session::{ClientAddresses, GatewayAuthentication, GatewaySession, GatewaySessions, transport::GatewayTransport},
|
||||
};
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
pkey::PKey,
|
||||
rsa::Rsa,
|
||||
ssl::{SslAcceptor, SslMethod},
|
||||
x509::{X509, X509NameBuilder},
|
||||
};
|
||||
use tokio::sync::{oneshot, watch};
|
||||
|
||||
use super::{LifecycleEvent, PreparedConnection, VpnTask, test_connect_request};
|
||||
|
||||
fn tls_acceptor() -> SslAcceptor {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "localhost").unwrap();
|
||||
let name = name.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
cert.set_subject_name(&name).unwrap();
|
||||
cert.set_issuer_name(&name).unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
cert.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
acceptor.set_private_key(&key).unwrap();
|
||||
acceptor.set_certificate(&cert.build()).unwrap();
|
||||
acceptor.check_private_key().unwrap();
|
||||
acceptor.build()
|
||||
}
|
||||
|
||||
/// Exercise the real HTTPS logout transport without any production network,
|
||||
/// host collectors, or user identity files. The response gate proves admission
|
||||
/// stays owned until the server request finishes.
|
||||
#[tokio::test]
|
||||
async fn cancelled_pending_owner_logs_out_and_releases_admission_after_response() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = listener.local_addr().unwrap();
|
||||
let server_name = format!("https://{endpoint}");
|
||||
let mut gateway = serde_json::to_value(Gateway::new("fixture".into(), server_name.clone())).unwrap();
|
||||
gateway["kind"] = serde_json::json!("internal");
|
||||
let gateway: Gateway = serde_json::from_value(gateway).unwrap();
|
||||
let registry = Arc::new(crate::session_registry::SessionRegistry::new(uuid::Uuid::new_v4()));
|
||||
let credential = registry.issue("fixture", None).unwrap();
|
||||
let session_id = credential.session_id();
|
||||
let permit = registry
|
||||
.begin_handshake(credential.service_instance_id(), session_id, "fixture")
|
||||
.unwrap();
|
||||
let (tx, _rx) = tokio::sync::mpsc::channel(4);
|
||||
let control = crate::ws_connection::ConnectionControl::new(uuid::Uuid::new_v4(), tx).0;
|
||||
let connection_id = control.connection_id();
|
||||
registry.commit_attach(&permit, control).unwrap();
|
||||
let fixture = test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![]));
|
||||
let mut member = fixture.plan().members()[0].clone();
|
||||
member.authentication =
|
||||
GatewayAuthentication::new("authcookie=fixture&user=fixture".into(), "internal".into()).unwrap();
|
||||
let plan = gpapi::session::ConnectionPlan::new(vec![member], vec![], fixture.plan().policy()).unwrap();
|
||||
let request = gpapi::service::request::ConnectRequest::new(fixture.info().clone(), plan);
|
||||
let mut prepared = PreparedConnection::lifecycle_fixture(request);
|
||||
let mut params = GpParams::builder(prepared.resources.profile.clone());
|
||||
params.ignore_tls_errors(true);
|
||||
prepared.sessions = GatewaySessions::new(vec![GatewaySession {
|
||||
gateway,
|
||||
transport: GatewayTransport::new(
|
||||
&server_name,
|
||||
prepared.request.plan().members()[0].authentication.clone(),
|
||||
¶ms.build(),
|
||||
prepared.request.plan().members()[0].binding.as_ref(),
|
||||
)
|
||||
.unwrap(),
|
||||
addresses: ClientAddresses::default(),
|
||||
}]);
|
||||
let acceptor = tls_acceptor();
|
||||
let (arrived, arrival) = oneshot::channel();
|
||||
let (release, response_gate) = oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = tokio::time::timeout(Duration::from_secs(3), listener.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let socket = socket.into_std().unwrap();
|
||||
socket.set_nonblocking(false).unwrap();
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
socket.set_write_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let request = tokio::task::spawn_blocking(move || {
|
||||
let mut stream = acceptor.accept(socket).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let (headers_end, body_len) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
key
|
||||
.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
break (position + 4, length);
|
||||
}
|
||||
};
|
||||
while bytes.len() < headers_end + body_len {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
arrived.send(()).unwrap();
|
||||
response_gate.blocking_recv().unwrap();
|
||||
let body = "<response status=\"success\"/>";
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
stream.flush().unwrap();
|
||||
String::from_utf8(bytes).unwrap()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// A single accepted authentication must produce a single logout.
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
request
|
||||
});
|
||||
let (state, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let (mut task, lifecycle) = VpnTask::new(state, false, registry.clone());
|
||||
let reservation = registry
|
||||
.reserve_connection(session_id, 1, true, || lifecycle.reserve_connect())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.commit_connection(session_id, 1, true, || reservation.commit(
|
||||
prepared,
|
||||
None,
|
||||
None,
|
||||
Some(session_id)
|
||||
)),
|
||||
ServiceResult::Accepted
|
||||
);
|
||||
let drain = registry
|
||||
.stop_non_tunnel_attachment(session_id, 1, connection_id)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let drain_waiter = tokio::spawn(async move {
|
||||
drain.wait().await;
|
||||
});
|
||||
let start = task.events.recv().await.unwrap();
|
||||
assert!(matches!(&start, LifecycleEvent::Start { .. }));
|
||||
task.handle_event(start).await;
|
||||
tokio::time::timeout(Duration::from_secs(3), arrival)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(lifecycle.has_attempt(0));
|
||||
assert!(!drain_waiter.is_finished());
|
||||
assert!(lifecycle.reserve_connect().is_err());
|
||||
assert!(!task.active.as_ref().unwrap().task.is_finished());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
release.send(()).unwrap();
|
||||
while task.active.is_some() {
|
||||
let event = tokio::time::timeout(Duration::from_secs(3), task.events.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
task.handle_event(event).await;
|
||||
}
|
||||
assert!(!lifecycle.has_attempt(0));
|
||||
drain_waiter.await.unwrap();
|
||||
assert!(lifecycle.reserve_connect().is_ok());
|
||||
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||
let request = server.await.unwrap();
|
||||
assert!(request.starts_with("POST /ssl-vpn/logout.esp "));
|
||||
let form = request.split_once("\r\n\r\n").unwrap().1;
|
||||
let fields = url_form(form);
|
||||
assert_eq!(fields.get("user").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("computer").map(String::as_str), Some("fixture"));
|
||||
assert_eq!(fields.get("clientos").map(String::as_str), Some("Linux"));
|
||||
}
|
||||
|
||||
fn url_form(form: &str) -> std::collections::HashMap<String, String> {
|
||||
form
|
||||
.split('&')
|
||||
.map(|field| {
|
||||
let (key, value) = field.split_once('=').unwrap();
|
||||
(key.to_owned(), value.to_owned())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
use gpapi::{
|
||||
gp_params::GpParams,
|
||||
os_profile::OsProfile,
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::{GatewaySession, GatewaySessions, network::PhysicalNetwork, transport::GatewayTransport},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct PreparedConnection {
|
||||
pub(super) request: ConnectRequest,
|
||||
pub(super) resources: Arc<ConnectionResources>,
|
||||
pub(super) sessions: GatewaySessions,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionResources {
|
||||
pub profile: OsProfile,
|
||||
pub identity: Option<gpapi::utils::request::ClientIdentity>,
|
||||
pub identity_files: Option<gpapi::utils::request::ClientIdentityFiles>,
|
||||
pub network: Option<PhysicalNetwork>,
|
||||
}
|
||||
|
||||
/// Preparation sends no authenticated gateway requests. Rejection leaves the
|
||||
/// authentication owner responsible for logout; only queued admission transfers
|
||||
/// the complete ledger and its retained identity resources to the service.
|
||||
pub(crate) async fn prepare_connection(
|
||||
request: ConnectRequest,
|
||||
brokered_macos: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<PreparedConnection> {
|
||||
let args = request.args();
|
||||
let non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == gpapi::session::SessionMode::NonTunnel);
|
||||
anyhow::ensure!(
|
||||
non_tunnel || request.plan().members().len() == 1,
|
||||
"Only one selected tunnel gateway can execute"
|
||||
);
|
||||
for member in request.plan().members() {
|
||||
if non_tunnel {
|
||||
let binding = member.binding.as_ref().context("Internal gateway binding is missing")?;
|
||||
anyhow::ensure!(
|
||||
!args.disable_ipv6() || (binding.endpoint().is_ipv4() && binding.addresses().ipv6.is_none()),
|
||||
"IPv6 gateway transport or identity is disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
let setup_request = request.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let resources = tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if setup_cancel.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Connection preparation cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = setup_request.args();
|
||||
let identity = super::prepare_identity(args, brokered_macos || non_tunnel)?;
|
||||
let directory = brokered_macos.then(|| std::path::Path::new("/var/run/com.yuezk.gpgui"));
|
||||
let identity_files = identity
|
||||
.as_ref()
|
||||
.map(|identity| identity.write_files(directory))
|
||||
.transpose()?;
|
||||
let host = args.host_identity().context("Authenticated host identity is missing")?;
|
||||
let profile = crate::hip_source::profile(
|
||||
host,
|
||||
args.os().context("Authenticated client OS is missing")?,
|
||||
args.client_version(),
|
||||
args.os_version(),
|
||||
args.host_id(),
|
||||
args.local_hostname(),
|
||||
&check,
|
||||
)?;
|
||||
let network = if non_tunnel {
|
||||
Some(PhysicalNetwork::capture(&check)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
check()?;
|
||||
Ok::<_, anyhow::Error>(Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity,
|
||||
identity_files,
|
||||
network,
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
let args = request.args();
|
||||
let mut builder = GpParams::builder(resources.profile.clone());
|
||||
builder
|
||||
.ignore_tls_errors(args.ignore_tls_errors())
|
||||
.client_identity(resources.identity.clone());
|
||||
let params = builder.build();
|
||||
let mut sessions = Vec::new();
|
||||
for member in request.plan().members() {
|
||||
let binding = if non_tunnel {
|
||||
Some(member.binding.as_ref().context("Internal gateway binding is missing")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(network) = &resources.network {
|
||||
network
|
||||
.validate_internal_binding(
|
||||
binding.context("Internal gateway binding is missing")?,
|
||||
request.plan().internal_detection(),
|
||||
&cancellation,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let transport = GatewayTransport::new(member.gateway.server(), member.authentication.clone(), ¶ms, binding)?;
|
||||
sessions.push(GatewaySession {
|
||||
gateway: member.gateway.clone(),
|
||||
transport,
|
||||
addresses: binding.map(|binding| binding.addresses()).unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
if let Some(network) = &resources.network {
|
||||
network.ensure_current(&cancellation).await?;
|
||||
}
|
||||
Ok(PreparedConnection {
|
||||
request,
|
||||
resources,
|
||||
sessions: GatewaySessions::new(sessions),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PreparedConnection {
|
||||
/// Lifecycle-only fixtures own no issued server sessions. Protocol ownership
|
||||
/// checks use actual gateway transports rather than this actor-state fixture.
|
||||
pub(crate) fn lifecycle_fixture(request: ConnectRequest) -> Self {
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
Self {
|
||||
request,
|
||||
resources: Arc::new(ConnectionResources {
|
||||
profile,
|
||||
identity: None,
|
||||
identity_files: None,
|
||||
network: None,
|
||||
}),
|
||||
sessions: GatewaySessions::new(vec![]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpapi::{gateway::Gateway, service::vpn_state::ConnectInfo};
|
||||
|
||||
#[tokio::test]
|
||||
async fn brokered_macos_and_non_tunnel_identity_reject_path_handoff() {
|
||||
for (brokered_macos, non_tunnel) in [(true, false), (false, true), (true, true)] {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_certificate(Some("/identity.pem".into()));
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
if non_tunnel {
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
}
|
||||
let request = serde_json::from_value(wire).unwrap();
|
||||
let error = prepare_connection(request, brokered_macos, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "Client identity must be a protected snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_ipv6_rejects_ipv6_report_identity_before_setup() {
|
||||
let gateway = Gateway::new("fixture".into(), "gateway.example.com".into());
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["gateway"]["kind"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["authentication"]["connection_type"] = serde_json::json!("internal");
|
||||
wire["plan"]["members"][0]["binding"]["addresses"]["ipv6"] = serde_json::json!("2001:db8::5");
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
// The fixture has no host identity or usable physical interface. Policy
|
||||
// rejection must happen before those collectors or transport setup run.
|
||||
let error = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.to_string(), "IPv6 gateway transport or identity is disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_preparation_needs_no_physical_binding_or_resolver() {
|
||||
let gateway = Gateway::new("fixture".into(), "does-not-resolve.invalid".into());
|
||||
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Linux)
|
||||
.host_identity(gpapi::os_profile::HostIdentity::from_parts(
|
||||
"fixture".into(),
|
||||
"fixture-host".into(),
|
||||
"fixture-serial".into(),
|
||||
"02:00:00:00:00:01".into(),
|
||||
))
|
||||
.build();
|
||||
let request = super::super::test_connect_request(ConnectInfo::new("portal.example.com".into(), gateway, vec![]))
|
||||
.with_os_profile(&profile)
|
||||
.with_disable_ipv6(true);
|
||||
let mut wire = serde_json::to_value(request).unwrap();
|
||||
wire["plan"]["members"][0]["binding"] = serde_json::Value::Null;
|
||||
let request: ConnectRequest = serde_json::from_value(wire).unwrap();
|
||||
let prepared = prepare_connection(request, false, CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(prepared.resources.network.is_none());
|
||||
assert_eq!(prepared.sessions.members().len(), 1);
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv4.is_none());
|
||||
assert!(prepared.sessions.members()[0].addresses.ipv6.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use gpapi::{
|
||||
process::collection::{CollectionBudget, CollectionControl},
|
||||
service::request::ConnectRequest,
|
||||
session::SessionMode,
|
||||
};
|
||||
use log::warn;
|
||||
use openconnect::Vpn;
|
||||
use tokio::{sync::mpsc, task::JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{LifecycleEvent, LifecycleHandle, PreparedConnection, preparation::ConnectionResources};
|
||||
|
||||
pub(super) struct AttemptInput {
|
||||
pub attempt: u64,
|
||||
pub connection: PreparedConnection,
|
||||
pub desktop_uid: Option<u32>,
|
||||
pub edited_report: Option<Arc<str>>,
|
||||
pub session_id: Option<Uuid>,
|
||||
pub brokered_macos: bool,
|
||||
pub registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
pub lifecycle: LifecycleHandle,
|
||||
}
|
||||
|
||||
struct TunnelInput {
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
source: Arc<openconnect::HipSource>,
|
||||
session_id: Option<Uuid>,
|
||||
registry: Arc<crate::session_registry::SessionRegistry>,
|
||||
}
|
||||
|
||||
struct PreparedTunnel {
|
||||
vpn: Arc<Vpn>,
|
||||
}
|
||||
|
||||
/// The accepted attempt owns cleanup through fallible setup. Non-tunnel workers
|
||||
/// borrow that ledger; a native tunnel takes its cleanup ownership when started.
|
||||
/// Cancellation joins execution before draining any remaining issued sessions.
|
||||
pub(super) fn spawn(
|
||||
mut input: AttemptInput,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let attempt = input.attempt;
|
||||
let non_tunnel = input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let mut failure = None;
|
||||
let mut approval = None;
|
||||
if !cancellation.is_cancelled() {
|
||||
let request = input.connection.request.clone();
|
||||
let resources = input.connection.resources.clone();
|
||||
let desktop_uid = input.desktop_uid;
|
||||
let brokered = input.brokered_macos;
|
||||
let edited = input.edited_report.clone();
|
||||
let setup_cancel = cancellation.clone();
|
||||
let execution = tokio::task::spawn_blocking(move || {
|
||||
prepare_execution(request, resources, desktop_uid, brokered, edited, &setup_cancel)
|
||||
})
|
||||
.await;
|
||||
match execution {
|
||||
Ok(Ok(execution)) => {
|
||||
let (source, guard) = execution.into_parts();
|
||||
approval = Some(guard);
|
||||
let source = Arc::new(source);
|
||||
let guard = approval.as_ref().expect("execution approval is retained");
|
||||
if input
|
||||
.connection
|
||||
.request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel)
|
||||
{
|
||||
match super::non_tunnel::run(&mut input, source, guard, cancellation.clone(), events.clone()).await {
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Disconnected) => {}
|
||||
Ok(gpapi::session::non_tunnel::SessionExit::Failed(reason)) => {
|
||||
let message = match reason {
|
||||
gpapi::session::SessionEndReason::InvalidCookie => {
|
||||
"Internal gateway authentication expired; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::NetworkChanged => {
|
||||
"Physical network changed or could not be verified; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AllMembersFailed => {
|
||||
"All internal gateway sessions failed; connect again"
|
||||
}
|
||||
gpapi::session::SessionEndReason::AuthorizationRevoked => "HIP execution authorization was revoked",
|
||||
};
|
||||
failure = Some(message.into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("Non-tunnel maintenance failed: {error:#}");
|
||||
failure = Some("Internal session maintenance failed".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let tunnel_input = TunnelInput {
|
||||
request: input.connection.request.clone(),
|
||||
resources: input.connection.resources.clone(),
|
||||
source,
|
||||
session_id: input.session_id,
|
||||
registry: input.registry.clone(),
|
||||
};
|
||||
let setup_cancel = cancellation.clone();
|
||||
let prepared = tokio::task::spawn_blocking(move || prepare_tunnel(tunnel_input, &setup_cancel)).await;
|
||||
match prepared {
|
||||
Ok(Ok(prepared)) => {
|
||||
run_tunnel(
|
||||
attempt,
|
||||
&prepared,
|
||||
guard,
|
||||
&input.lifecycle,
|
||||
&mut input.connection.sessions,
|
||||
cancellation.clone(),
|
||||
events.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
Ok(Err(error)) => warn!("Failed to prepare tunnel: {error:#}"),
|
||||
Err(error) => warn!("Tunnel setup worker failed: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
warn!("Failed to prepare HIP execution: {error:#}");
|
||||
failure = Some("HIP execution could not be prepared".into());
|
||||
}
|
||||
Err(error) => {
|
||||
warn!("HIP setup worker failed: {error}");
|
||||
failure = Some("HIP setup worker failed".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
input.connection.sessions.logout().await;
|
||||
// Identity and approval remain alive through worker drain and logout. Ended
|
||||
// only releases admission after the actor also joins this task.
|
||||
drop(approval);
|
||||
if non_tunnel && !cancellation.is_cancelled() {
|
||||
if let Some(reason) = failure {
|
||||
let _ = events.send(LifecycleEvent::Failed { attempt, reason }).await;
|
||||
}
|
||||
}
|
||||
let _ = events.send(LifecycleEvent::Ended { attempt }).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_execution(
|
||||
request: ConnectRequest,
|
||||
resources: Arc<ConnectionResources>,
|
||||
desktop_uid: Option<u32>,
|
||||
brokered: bool,
|
||||
edited: Option<Arc<str>>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<crate::hip_source::HipExecution> {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"HIP setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
let args = request.args();
|
||||
let pure_non_tunnel = request
|
||||
.plan()
|
||||
.members()
|
||||
.iter()
|
||||
.all(|member| member.authentication.mode() == SessionMode::NonTunnel);
|
||||
let disabled = pure_non_tunnel && !request.plan().policy().collect_hip_data();
|
||||
let source = if disabled {
|
||||
&gpapi::hip::HipSource::Disabled
|
||||
} else {
|
||||
args.hip_source()
|
||||
};
|
||||
let execution = crate::hip_source::resolve(source, desktop_uid, brokered, edited, Some(resources.profile.clone()))?;
|
||||
check()?;
|
||||
Ok(execution)
|
||||
}
|
||||
|
||||
fn prepare_tunnel(input: TunnelInput, cancellation: &CancellationToken) -> anyhow::Result<PreparedTunnel> {
|
||||
let args = input.request.args();
|
||||
let budget = CollectionBudget::new(Duration::from_secs(60));
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Tunnel setup cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
check()?;
|
||||
ensure!(
|
||||
input.request.plan().members().len() == 1
|
||||
&& input.request.plan().members()[0].authentication.mode() == SessionMode::Tunnel,
|
||||
"Tunnel execution requires one selected tunnel gateway"
|
||||
);
|
||||
let member = &input.request.plan().members()[0];
|
||||
let identity_files = &input.resources.identity_files;
|
||||
let vpn = Arc::new(
|
||||
crate::vpn_script::builder(member.gateway.server(), member.authentication.cookie(), args)?
|
||||
.user_agent(args.user_agent())
|
||||
.os(args.openconnect_os())
|
||||
.os_version(args.os_version())
|
||||
.client_version(args.client_version())
|
||||
.host_id(args.host_id())
|
||||
.certificate(identity_files.as_ref().map(|files| files.certificate().to_owned()))
|
||||
.sslkey(identity_files.as_ref().and_then(|files| files.key()).map(str::to_owned))
|
||||
.key_password(
|
||||
input
|
||||
.resources
|
||||
.identity
|
||||
.as_ref()
|
||||
.and_then(|identity| identity.key_password())
|
||||
.map(str::to_owned),
|
||||
)
|
||||
.hip_source(input.source)
|
||||
.reconnect_timeout(args.reconnect_timeout())
|
||||
.mtu(args.mtu())
|
||||
.disable_ipv6(args.disable_ipv6())
|
||||
.no_dtls(args.no_dtls())
|
||||
.local_hostname(args.local_hostname())
|
||||
.dpd_interval(args.force_dpd())
|
||||
.no_xmlpost(args.no_xmlpost())
|
||||
.build()
|
||||
.context("Failed to create tunnel worker")?,
|
||||
);
|
||||
check()?;
|
||||
if let Some(session_id) = input.session_id {
|
||||
let registry = input.registry;
|
||||
vpn.set_hip_report_callback(move |xml| {
|
||||
if let Err(error) = registry.store_successful_hip_report(session_id, xml) {
|
||||
warn!("Could not retain submitted HIP report: {error}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(PreparedTunnel { vpn })
|
||||
}
|
||||
|
||||
async fn run_tunnel(
|
||||
attempt: u64,
|
||||
prepared: &PreparedTunnel,
|
||||
approval: &crate::hip_source::HipApproval,
|
||||
lifecycle: &LifecycleHandle,
|
||||
sessions: &mut gpapi::session::GatewaySessions,
|
||||
cancellation: CancellationToken,
|
||||
events: mpsc::Sender<LifecycleEvent>,
|
||||
) {
|
||||
if cancellation.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let vpn = prepared.vpn.clone();
|
||||
// The native tunnel keeps its reconnect endpoint and cookie current and owns
|
||||
// normal logout. The ledger remains responsible only before native execution.
|
||||
// Service admission permits exactly one tunnel member.
|
||||
std::mem::take(sessions).relinquish();
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
vpn.connect(move |session| {
|
||||
let _ = events.blocking_send(LifecycleEvent::Established { attempt, session });
|
||||
})
|
||||
});
|
||||
tokio::pin!(worker);
|
||||
let mut approval_poll = tokio::time::interval(Duration::from_secs(1));
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => { prepared.vpn.disconnect(); break (&mut worker).await; },
|
||||
result = &mut worker => break result,
|
||||
_ = approval_poll.tick() => if !approval.approval_is_valid() {
|
||||
stop_for_revoked_approval(lifecycle, &cancellation);
|
||||
prepared.vpn.disconnect();
|
||||
break (&mut worker).await;
|
||||
},
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(0 | -4) => {}
|
||||
Ok(code) => warn!("Tunnel worker exited with status {code}"),
|
||||
Err(error) => warn!("Tunnel worker failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stop_for_revoked_approval(lifecycle: &LifecycleHandle, cancellation: &CancellationToken) {
|
||||
let result = lifecycle.request_disconnect();
|
||||
if !matches!(result, gpapi::service::transport::ServiceResult::Accepted) {
|
||||
warn!("Could not enqueue approval revocation stop: {result:?}");
|
||||
}
|
||||
cancellation.cancel();
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
use std::{
|
||||
fs::{self, File, Metadata, Permissions},
|
||||
io::{self, Read, Write},
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use common::constants::{INSTALLED_VPNC_SCRIPT, INSTALLED_VPNC_SCRIPT_METADATA, MAX_VPNC_SCRIPT_SIZE};
|
||||
use gpapi::service::vpnc_script::{InstallVpncScriptRequest, VpncScriptMetadata};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
const DIRECTORY_MODE: u32 = 0o755;
|
||||
const SCRIPT_MODE: u32 = 0o755;
|
||||
const METADATA_MODE: u32 = 0o600;
|
||||
const METADATA_VERSION: u8 = 1;
|
||||
const MAX_METADATA_SIZE: u64 = 40 * 1024;
|
||||
const ROOT_UID: u32 = 0;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct StoredMetadata {
|
||||
version: u8,
|
||||
metadata: VpncScriptMetadata,
|
||||
}
|
||||
|
||||
pub fn installed_script() -> anyhow::Result<Option<PathBuf>> {
|
||||
let path = PathBuf::from(INSTALLED_VPNC_SCRIPT);
|
||||
match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => {
|
||||
validate_script(&path, &metadata, ROOT_UID)?;
|
||||
let directory = path.parent().context("Installed VPNC script has no parent directory")?;
|
||||
validate_directory(directory, ROOT_UID)?;
|
||||
validate_directory(
|
||||
directory
|
||||
.parent()
|
||||
.context("Installed VPNC script directory has no parent directory")?,
|
||||
ROOT_UID,
|
||||
)?;
|
||||
Ok(Some(path))
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(err).context("Failed to inspect the installed VPNC script"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn metadata() -> anyhow::Result<Option<VpncScriptMetadata>> {
|
||||
if installed_script()?.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
read_metadata_at(Path::new(INSTALLED_VPNC_SCRIPT_METADATA), ROOT_UID)
|
||||
}
|
||||
|
||||
pub fn install(request: InstallVpncScriptRequest) -> anyhow::Result<()> {
|
||||
request.metadata.validate()?;
|
||||
let contents = request.contents()?;
|
||||
let target = Path::new(INSTALLED_VPNC_SCRIPT);
|
||||
let metadata_target = Path::new(INSTALLED_VPNC_SCRIPT_METADATA);
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("Installed VPNC script has no parent directory")?;
|
||||
let state_directory = directory
|
||||
.parent()
|
||||
.context("Installed VPNC script directory has no parent directory")?;
|
||||
let state_parent = state_directory
|
||||
.parent()
|
||||
.context("VPNC script state directory has no parent directory")?;
|
||||
validate_directory(state_parent, ROOT_UID)?;
|
||||
ensure_directory(state_directory, ROOT_UID)?;
|
||||
ensure_directory(directory, ROOT_UID)?;
|
||||
install_at(&contents, &request.metadata, target, metadata_target, ROOT_UID)
|
||||
}
|
||||
|
||||
pub fn remove() -> anyhow::Result<()> {
|
||||
if installed_script()?.is_some() {
|
||||
remove_at(Path::new(INSTALLED_VPNC_SCRIPT), ROOT_UID, validate_script)?;
|
||||
}
|
||||
remove_at(Path::new(INSTALLED_VPNC_SCRIPT_METADATA), ROOT_UID, validate_metadata)
|
||||
}
|
||||
|
||||
fn install_at(
|
||||
contents: &[u8],
|
||||
metadata: &VpncScriptMetadata,
|
||||
target: &Path,
|
||||
metadata_target: &Path,
|
||||
owner_uid: u32,
|
||||
) -> anyhow::Result<()> {
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("Installed VPNC script has no parent directory")?;
|
||||
ensure_directory(directory, owner_uid)?;
|
||||
|
||||
if let Ok(existing) = fs::symlink_metadata(target) {
|
||||
validate_script(target, &existing, owner_uid)?;
|
||||
}
|
||||
if let Ok(existing) = fs::symlink_metadata(metadata_target) {
|
||||
validate_metadata(metadata_target, &existing, owner_uid)?;
|
||||
}
|
||||
if contents.is_empty() {
|
||||
bail!("VPNC script is empty");
|
||||
}
|
||||
if contents.len() > MAX_VPNC_SCRIPT_SIZE {
|
||||
bail!("VPNC script exceeds the {} byte limit", MAX_VPNC_SCRIPT_SIZE);
|
||||
}
|
||||
metadata.validate()?;
|
||||
|
||||
let mut staged_script = NamedTempFile::new_in(directory).context("Failed to stage the VPNC script")?;
|
||||
staged_script
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(SCRIPT_MODE))
|
||||
.context("Failed to set VPNC script permissions")?;
|
||||
staged_script
|
||||
.write_all(contents)
|
||||
.context("Failed to write the VPNC script")?;
|
||||
staged_script
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.context("Failed to sync the VPNC script")?;
|
||||
|
||||
let stored_metadata = StoredMetadata {
|
||||
version: METADATA_VERSION,
|
||||
metadata: metadata.clone(),
|
||||
};
|
||||
let mut staged_metadata = NamedTempFile::new_in(directory).context("Failed to stage VPNC script metadata")?;
|
||||
staged_metadata
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(METADATA_MODE))
|
||||
.context("Failed to set VPNC script metadata permissions")?;
|
||||
serde_json::to_writer(&mut staged_metadata, &stored_metadata).context("Failed to write VPNC script metadata")?;
|
||||
staged_metadata
|
||||
.as_file()
|
||||
.sync_all()
|
||||
.context("Failed to sync VPNC script metadata")?;
|
||||
|
||||
staged_script
|
||||
.persist(target)
|
||||
.map_err(|err| err.error)
|
||||
.context("Failed to install the VPNC script")?;
|
||||
staged_metadata
|
||||
.persist(metadata_target)
|
||||
.map_err(|err| err.error)
|
||||
.context("Failed to install VPNC script metadata")?;
|
||||
sync_directory(directory)?;
|
||||
|
||||
let script_metadata = fs::symlink_metadata(target).context("Failed to inspect the installed VPNC script")?;
|
||||
validate_script(target, &script_metadata, owner_uid)?;
|
||||
let installed_metadata = fs::symlink_metadata(metadata_target).context("Failed to inspect VPNC script metadata")?;
|
||||
validate_metadata(metadata_target, &installed_metadata, owner_uid)
|
||||
}
|
||||
|
||||
fn read_metadata_at(target: &Path, owner_uid: u32) -> anyhow::Result<Option<VpncScriptMetadata>> {
|
||||
let metadata = match fs::symlink_metadata(target) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err).context("Failed to inspect VPNC script metadata"),
|
||||
};
|
||||
validate_metadata(target, &metadata, owner_uid)?;
|
||||
|
||||
let file = File::open(target).context("Failed to open VPNC script metadata")?;
|
||||
let stored: StoredMetadata =
|
||||
serde_json::from_reader(file.take(MAX_METADATA_SIZE)).context("Failed to parse VPNC script metadata")?;
|
||||
if stored.version != METADATA_VERSION {
|
||||
bail!("Unsupported VPNC script metadata version {}", stored.version);
|
||||
}
|
||||
stored.metadata.validate()?;
|
||||
Ok(Some(stored.metadata))
|
||||
}
|
||||
|
||||
fn remove_at(
|
||||
target: &Path,
|
||||
owner_uid: u32,
|
||||
validate: fn(&Path, &Metadata, u32) -> anyhow::Result<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
let directory = target
|
||||
.parent()
|
||||
.context("VPNC script state file has no parent directory")?;
|
||||
validate_directory(directory, owner_uid)?;
|
||||
|
||||
match fs::symlink_metadata(target) {
|
||||
Ok(metadata) => {
|
||||
validate(target, &metadata, owner_uid)?;
|
||||
fs::remove_file(target).context("Failed to remove VPNC script state")?;
|
||||
sync_directory(directory)
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err).context("Failed to inspect VPNC script state"),
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_directory(directory: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
match fs::symlink_metadata(directory) {
|
||||
Ok(_) => validate_directory(directory, owner_uid),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
if let Some(parent) = directory.parent() {
|
||||
ensure_directory(parent, owner_uid)?;
|
||||
}
|
||||
fs::create_dir(directory).context("Failed to create the VPNC script directory")?;
|
||||
fs::set_permissions(directory, Permissions::from_mode(DIRECTORY_MODE))
|
||||
.context("Failed to set VPNC script directory permissions")?;
|
||||
validate_directory(directory, owner_uid)
|
||||
}
|
||||
Err(err) => Err(err).context("Failed to inspect the VPNC script directory"),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_directory(path: &Path, owner_uid: u32) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path)
|
||||
.with_context(|| format!("Failed to inspect VPNC script directory {}", path.display()))?;
|
||||
if metadata.file_type().is_symlink() || !metadata.is_dir() {
|
||||
bail!("VPNC script directory {} is not a real directory", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, &metadata, owner_uid)
|
||||
}
|
||||
|
||||
fn validate_script(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
bail!("Installed VPNC script {} is not a regular file", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, metadata, owner_uid)?;
|
||||
if metadata.mode() & 0o111 == 0 {
|
||||
bail!("Installed VPNC script {} is not executable", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_metadata(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
bail!("VPNC script metadata {} is not a regular file", path.display());
|
||||
}
|
||||
validate_ownership_and_mode(path, metadata, owner_uid)?;
|
||||
if metadata.mode() & 0o777 != METADATA_MODE {
|
||||
bail!("VPNC script metadata {} must have mode 0600", path.display());
|
||||
}
|
||||
if metadata.len() > MAX_METADATA_SIZE {
|
||||
bail!("VPNC script metadata {} is too large", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_ownership_and_mode(path: &Path, metadata: &Metadata, owner_uid: u32) -> anyhow::Result<()> {
|
||||
if metadata.uid() != owner_uid {
|
||||
bail!("{} must be owned by uid {}", path.display(), owner_uid);
|
||||
}
|
||||
if metadata.mode() & 0o022 != 0 {
|
||||
bail!("{} must not be writable by group or other users", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_directory(directory: &Path) -> anyhow::Result<()> {
|
||||
File::open(directory)
|
||||
.and_then(|file| file.sync_all())
|
||||
.context("Failed to sync the VPNC script directory")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::service::vpnc_script::VpncScriptSource;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn source(value: &str) -> VpncScriptMetadata {
|
||||
VpncScriptMetadata::new(VpncScriptSource::Command, value.to_owned()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_metadata_and_removes_both_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let directory = temp.path().join("scripts");
|
||||
let target = directory.join("vpnc-script");
|
||||
let metadata_target = directory.join("vpnc-script.metadata");
|
||||
let source = source("exit 0");
|
||||
|
||||
install_at(b"#!/bin/sh\nexit 0\n", &source, &target, &metadata_target, owner_uid).unwrap();
|
||||
let metadata = fs::symlink_metadata(&target).unwrap();
|
||||
assert!(metadata.is_file());
|
||||
assert_eq!(metadata.mode() & 0o777, SCRIPT_MODE);
|
||||
assert_eq!(read_metadata_at(&metadata_target, owner_uid).unwrap(), Some(source));
|
||||
|
||||
remove_at(&target, owner_uid, validate_script).unwrap();
|
||||
remove_at(&metadata_target, owner_uid, validate_metadata).unwrap();
|
||||
assert!(!target.exists());
|
||||
assert!(!metadata_target.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_metadata_is_allowed() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
read_metadata_at(&temp.path().join("missing"), metadata.uid()).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_script() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let target = temp.path().join("scripts/vpnc-script");
|
||||
let metadata_target = temp.path().join("scripts/vpnc-script.metadata");
|
||||
let input = vec![b'x'; MAX_VPNC_SCRIPT_SIZE + 1];
|
||||
|
||||
assert!(install_at(&input, &source("/tmp/script"), &target, &metadata_target, owner_uid).is_err());
|
||||
assert!(!target.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlink_target() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let metadata = fs::symlink_metadata(temp.path()).unwrap();
|
||||
let owner_uid = metadata.uid();
|
||||
let directory = temp.path().join("scripts");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let target = directory.join("vpnc-script");
|
||||
let metadata_target = directory.join("vpnc-script.metadata");
|
||||
symlink("/bin/sh", &target).unwrap();
|
||||
|
||||
assert!(
|
||||
install_at(
|
||||
b"exit 0\n",
|
||||
&source("/tmp/script"),
|
||||
&target,
|
||||
&metadata_target,
|
||||
owner_uid
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,708 @@
|
||||
use std::{ops::ControlFlow, sync::Arc};
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
use axum::extract::ws::{CloseFrame, Message};
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, request::WsRequest},
|
||||
utils::crypto::Crypto,
|
||||
use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket};
|
||||
use futures::StreamExt;
|
||||
use gpapi::service::transport::{
|
||||
ClientMessage, ClientPrelude, CloseReason, HandshakeRejection, NoiseResponder, NoiseTransport, ServerMessage,
|
||||
ServerPrelude, ServiceErrorCode, ServiceResult,
|
||||
};
|
||||
use gpapi::{hip::HipSource, service::request::WsRequest};
|
||||
use log::{info, warn};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::Instant;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) struct WsConnection {
|
||||
crypto: Arc<Crypto>,
|
||||
tx: mpsc::Sender<Message>,
|
||||
use crate::{
|
||||
session_registry::{HandshakePermit, SessionError},
|
||||
ws_server::WsServerContext,
|
||||
};
|
||||
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
|
||||
const PONG_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CONNECTION_QUEUE: usize = 64;
|
||||
const MAX_PENDING_REQUESTS: usize = 64;
|
||||
|
||||
pub(crate) enum ConnectionCommand {
|
||||
Send(ServerMessage),
|
||||
Reply { id: Uuid, result: ServiceResult },
|
||||
}
|
||||
|
||||
impl WsConnection {
|
||||
pub fn new(crypto: Arc<Crypto>, tx: mpsc::Sender<Message>) -> Self {
|
||||
Self { crypto, tx }
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ConnectionControl {
|
||||
connection_id: Uuid,
|
||||
tx: mpsc::Sender<ConnectionCommand>,
|
||||
close_tx: watch::Sender<Option<CloseReason>>,
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> {
|
||||
let encrypted = self.crypto.encrypt(event)?;
|
||||
let msg = Message::Binary(encrypted.into());
|
||||
|
||||
self.tx.send(msg).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> {
|
||||
match msg {
|
||||
Message::Binary(data) => match self.crypto.decrypt(data.into()) {
|
||||
Ok(ws_req) => ControlFlow::Continue(ws_req),
|
||||
Err(err) => {
|
||||
info!("Failed to decrypt message: {}", err);
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
impl ConnectionControl {
|
||||
pub fn new(connection_id: Uuid, tx: mpsc::Sender<ConnectionCommand>) -> (Self, watch::Receiver<Option<CloseReason>>) {
|
||||
let (close_tx, close_rx) = watch::channel(None);
|
||||
(
|
||||
Self {
|
||||
connection_id,
|
||||
tx,
|
||||
close_tx,
|
||||
},
|
||||
Message::Close(cf) => {
|
||||
if let Some(CloseFrame { code, reason }) = cf {
|
||||
info!("Client sent close, code {} and reason `{}`", code, reason);
|
||||
} else {
|
||||
info!("Client somehow sent close message without CloseFrame");
|
||||
close_rx,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn connection_id(&self) -> Uuid {
|
||||
self.connection_id
|
||||
}
|
||||
|
||||
pub fn send(&self, command: ConnectionCommand) -> Result<(), ()> {
|
||||
self.tx.try_send(command).map_err(|_| ())
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.tx.is_closed() || self.close_tx.borrow().is_some()
|
||||
}
|
||||
|
||||
pub fn close(&self, reason: CloseReason) {
|
||||
self.close_tx.send_replace(Some(reason));
|
||||
}
|
||||
|
||||
pub async fn send_reply(&self, id: Uuid, result: ServiceResult) {
|
||||
let _ = self.tx.send(ConnectionCommand::Reply { id, result }).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WsConnection;
|
||||
|
||||
impl WsConnection {
|
||||
pub async fn accept(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
|
||||
let Some(slot) = ctx.try_handshake_slot() else {
|
||||
send_close(&mut socket, CloseReason::InternalError).await;
|
||||
return;
|
||||
};
|
||||
|
||||
let established = tokio::time::timeout(HANDSHAKE_TIMEOUT, establish(&mut socket, &ctx)).await;
|
||||
let (mut noise, permit, control, mut command_rx, mut close_rx, generation) = match established {
|
||||
Ok(Ok(established)) => established,
|
||||
Ok(Err(reason)) => {
|
||||
send_close(&mut socket, reason).await;
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
ctx.remove_closed_connections().await;
|
||||
send_close(&mut socket, CloseReason::HandshakeTimeout).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
drop(slot);
|
||||
|
||||
info!("Authenticated GUI connection {}", control.connection_id());
|
||||
let mut pending_requests = HashSet::new();
|
||||
let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
|
||||
let mut last_outbound = Instant::now();
|
||||
let mut pong_deadline = None;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
command = command_rx.recv() => {
|
||||
let Some(command) = command else { break };
|
||||
match command {
|
||||
ConnectionCommand::Send(message) => {
|
||||
if send_encrypted(&mut socket, &mut noise, &message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
ConnectionCommand::Reply { id, result } => {
|
||||
if !pending_requests.remove(&id) {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
let message = ServerMessage::Reply { id, result };
|
||||
if send_encrypted(&mut socket, &mut noise, &message).await.is_err() {
|
||||
break;
|
||||
}
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
changed = close_rx.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
let reason = *close_rx.borrow_and_update();
|
||||
if let Some(reason) = reason {
|
||||
send_close(&mut socket, reason).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
frame = socket.next() => {
|
||||
let Some(frame) = frame else { break };
|
||||
match frame {
|
||||
Ok(Message::Binary(data)) => {
|
||||
let message = match noise.decrypt::<ClientMessage>(&data) {
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
warn!("Failed to authenticate WS message: {err}");
|
||||
send_close(&mut socket, CloseReason::AuthenticationFailed).await;
|
||||
break;
|
||||
}
|
||||
};
|
||||
if handle_client_message(
|
||||
message,
|
||||
&ctx,
|
||||
&control,
|
||||
permit.session_id,
|
||||
permit.desktop_uid,
|
||||
generation,
|
||||
&mut pending_requests,
|
||||
).await.is_err() {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Message::Ping(data)) => {
|
||||
if send_frame(&mut socket, Message::Pong(data)).await.is_err() { break; }
|
||||
last_outbound = Instant::now();
|
||||
}
|
||||
Ok(Message::Pong(_)) => pong_deadline = None,
|
||||
Ok(Message::Close(_)) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
send_close(&mut socket, CloseReason::MalformedMessage).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
let now = Instant::now();
|
||||
if pong_deadline.is_some_and(|deadline| now >= deadline) {
|
||||
send_close(&mut socket, CloseReason::HeartbeatTimeout).await;
|
||||
break;
|
||||
}
|
||||
if pong_deadline.is_none() && now.duration_since(last_outbound) >= HEARTBEAT_INTERVAL {
|
||||
if send_frame(&mut socket, Message::Ping(Vec::new().into())).await.is_err() { break; }
|
||||
last_outbound = now;
|
||||
pong_deadline = Some(now + PONG_TIMEOUT);
|
||||
}
|
||||
}
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
_ => {
|
||||
warn!("WS server received unexpected message: {:?}", msg);
|
||||
ControlFlow::Break(())
|
||||
}
|
||||
|
||||
ctx
|
||||
.remove_connection(control.connection_id(), permit.session_id, generation)
|
||||
.await;
|
||||
ctx
|
||||
.hip_previews
|
||||
.cancel_connection(permit.session_id, control.connection_id())
|
||||
.await;
|
||||
info!("GUI connection {} closed", control.connection_id());
|
||||
}
|
||||
}
|
||||
|
||||
async fn establish(
|
||||
socket: &mut WebSocket,
|
||||
ctx: &Arc<WsServerContext>,
|
||||
) -> Result<
|
||||
(
|
||||
NoiseTransport,
|
||||
HandshakePermit,
|
||||
ConnectionControl,
|
||||
mpsc::Receiver<ConnectionCommand>,
|
||||
watch::Receiver<Option<CloseReason>>,
|
||||
u64,
|
||||
),
|
||||
CloseReason,
|
||||
> {
|
||||
let prelude = receive_prelude(socket).await?;
|
||||
if prelude.product_version != ctx.product_version() {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::VersionMismatch {
|
||||
client: prelude.product_version,
|
||||
service: ctx.product_version().to_owned(),
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::VersionMismatch);
|
||||
}
|
||||
if prelude.hip_protocol_version != gpapi::service::transport::HIP_PROTOCOL_VERSION {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::HipProtocolMismatch {
|
||||
client: prelude.hip_protocol_version,
|
||||
service: gpapi::service::transport::HIP_PROTOCOL_VERSION,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::VersionMismatch);
|
||||
}
|
||||
|
||||
let permit = match ctx.registry().begin_handshake(
|
||||
prelude.service_instance_id,
|
||||
prelude.session_id,
|
||||
&prelude.product_version,
|
||||
) {
|
||||
Ok(permit) => permit,
|
||||
Err(SessionError::ServiceRestarted { service_instance_id }) => {
|
||||
send_server_prelude(
|
||||
socket,
|
||||
ServerPrelude::Rejected(HandshakeRejection::ServiceRestarted { service_instance_id }),
|
||||
)
|
||||
.await?;
|
||||
return Err(CloseReason::ServiceRestarted);
|
||||
}
|
||||
Err(SessionError::ReconnectSuperseded) => {
|
||||
send_server_prelude(socket, ServerPrelude::Rejected(HandshakeRejection::ReconnectSuperseded)).await?;
|
||||
return Err(CloseReason::ReconnectSuperseded);
|
||||
}
|
||||
Err(_) => {
|
||||
send_server_prelude(socket, ServerPrelude::Rejected(HandshakeRejection::Unauthorized)).await?;
|
||||
return Err(CloseReason::Unauthorized);
|
||||
}
|
||||
};
|
||||
|
||||
send_server_prelude(socket, ServerPrelude::Ready).await?;
|
||||
let handshake = async {
|
||||
let mut responder = NoiseResponder::new(
|
||||
ctx.product_version(),
|
||||
prelude.service_instance_id,
|
||||
prelude.session_id,
|
||||
&permit.secret,
|
||||
)
|
||||
.map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
let first = receive_binary(socket).await?;
|
||||
responder.read_first(&first).map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
let (response, mut noise) = responder.write_response().map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
socket
|
||||
.send(Message::Binary(response.into()))
|
||||
.await
|
||||
.map_err(|_| CloseReason::HandshakeFailed)?;
|
||||
|
||||
let attach = receive_binary(socket).await?;
|
||||
match noise
|
||||
.decrypt::<ClientMessage>(&attach)
|
||||
.map_err(|_| CloseReason::AuthenticationFailed)?
|
||||
{
|
||||
ClientMessage::Attach { .. } => {}
|
||||
_ => return Err(CloseReason::MalformedMessage),
|
||||
}
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(CONNECTION_QUEUE);
|
||||
let (control, close_rx) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
let prepared = ctx
|
||||
.prepare_connection(&permit, control.clone())
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
SessionError::ReconnectSuperseded => CloseReason::ReconnectSuperseded,
|
||||
SessionError::Unauthorized => CloseReason::Unauthorized,
|
||||
_ => CloseReason::InternalError,
|
||||
})?;
|
||||
|
||||
let Some(ConnectionCommand::Send(attached @ ServerMessage::Attached { .. })) = rx.recv().await else {
|
||||
ctx.abandon_connection(control.connection_id()).await;
|
||||
return Err(CloseReason::InternalError);
|
||||
};
|
||||
if send_encrypted(socket, &mut noise, &attached).await.is_err() {
|
||||
ctx.abandon_connection(control.connection_id()).await;
|
||||
return Err(CloseReason::InternalError);
|
||||
}
|
||||
let replaced = ctx
|
||||
.commit_connection(&permit, &control)
|
||||
.await
|
||||
.map_err(|err| match err {
|
||||
SessionError::ReconnectSuperseded => CloseReason::ReconnectSuperseded,
|
||||
SessionError::Unauthorized => CloseReason::Unauthorized,
|
||||
_ => CloseReason::InternalError,
|
||||
})?;
|
||||
if let Some(replaced) = replaced {
|
||||
replaced.close(CloseReason::SessionReplaced);
|
||||
}
|
||||
Ok((noise, control, rx, close_rx, prepared.generation))
|
||||
}
|
||||
.await;
|
||||
|
||||
handshake.map(|(noise, control, rx, close_rx, generation)| (noise, permit, control, rx, close_rx, generation))
|
||||
}
|
||||
|
||||
async fn handle_client_message(
|
||||
message: ClientMessage,
|
||||
ctx: &Arc<WsServerContext>,
|
||||
control: &ConnectionControl,
|
||||
session_id: Uuid,
|
||||
desktop_uid: Option<u32>,
|
||||
generation: u64,
|
||||
pending_requests: &mut HashSet<Uuid>,
|
||||
) -> Result<(), ()> {
|
||||
match message {
|
||||
ClientMessage::Attach { .. } => Err(()),
|
||||
ClientMessage::Resync { .. } => ctx.send_snapshot(control).await,
|
||||
ClientMessage::Request { id, request } => {
|
||||
if pending_requests.len() >= MAX_PENDING_REQUESTS || !pending_requests.insert(id) {
|
||||
return Err(());
|
||||
}
|
||||
if !ctx.registry().is_current(session_id, generation) {
|
||||
pending_requests.remove(&id);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
if let WsRequest::StoreEditedHipReportChunk(report) = request {
|
||||
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
|
||||
let result = if report.upload_id.is_some() && upload_id.is_none() {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP upload ID")
|
||||
} else {
|
||||
match ctx.registry().append_edited_hip_report_chunk(
|
||||
session_id,
|
||||
upload_id,
|
||||
report.offset,
|
||||
report.xml,
|
||||
report.complete,
|
||||
) {
|
||||
Ok(crate::session_registry::HipUploadResult::Progress(upload_id)) => ServiceResult::HipUploadProgress {
|
||||
upload_id: upload_id.to_string(),
|
||||
},
|
||||
Ok(crate::session_registry::HipUploadResult::Stored(report_id)) => ServiceResult::StoredHipReport {
|
||||
report_id: report_id.to_string(),
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report upload"),
|
||||
}
|
||||
};
|
||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||
pending_requests.remove(&id);
|
||||
control.close(CloseReason::InternalError);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::ReadHipPreviewChunk(chunk) = request {
|
||||
let result = Uuid::parse_str(&chunk.preview_id)
|
||||
.ok()
|
||||
.and_then(|preview_id| {
|
||||
ctx
|
||||
.registry()
|
||||
.hip_preview_chunk(session_id, preview_id, chunk.offset)
|
||||
.ok()
|
||||
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: chunk.offset,
|
||||
xml,
|
||||
complete,
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::GetLastSubmittedHipReport = request {
|
||||
let result = match ctx.registry().last_successful_hip_report(session_id) {
|
||||
Ok(Some(report)) => match ctx.registry().store_hip_preview(session_id, report.to_string()) {
|
||||
Ok(preview_id) => match ctx.registry().hip_preview_chunk(session_id, preview_id, 0) {
|
||||
Ok((xml, complete)) => ServiceResult::HipPreviewChunk {
|
||||
preview_id: preview_id.to_string(),
|
||||
offset: 0,
|
||||
xml,
|
||||
complete,
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
|
||||
},
|
||||
Ok(None) => ServiceResult::NoSubmittedHipReport,
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Session is unavailable"),
|
||||
};
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::GetHipApprovalStatus { approval_id } = request {
|
||||
let result = if let Some(uid) = desktop_uid.filter(|uid| *uid != 0) {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
match gpservice::hip_approval::status(&approval_id, uid) {
|
||||
Ok(status) => ServiceResult::HipApprovalStatus(status),
|
||||
Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP approval ID"),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
{
|
||||
let _ = (uid, approval_id);
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP script approvals are unavailable")
|
||||
}
|
||||
} else {
|
||||
ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Desktop user is unavailable")
|
||||
};
|
||||
control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let WsRequest::PreviewHipReport(preview) = request {
|
||||
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
|
||||
let report_id = match Uuid::parse_str(report_id) {
|
||||
Ok(id) => id,
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
match ctx.registry().edited_hip_report(session_id, report_id) {
|
||||
Ok(report) => Some(report),
|
||||
Err(_) => {
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"HIP report is unavailable for this session",
|
||||
),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !ctx
|
||||
.hip_previews
|
||||
.start(crate::hip_preview::PreviewJob {
|
||||
session_id,
|
||||
request_id: id,
|
||||
request: preview,
|
||||
edited_report,
|
||||
desktop_uid,
|
||||
identity: ctx.host_identity().await,
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
connection: control.clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
control
|
||||
.send(ConnectionCommand::Reply {
|
||||
id,
|
||||
result: ServiceResult::rejected(ServiceErrorCode::Busy, "HIP preview is already running"),
|
||||
})
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dispatcher = ctx.dispatcher();
|
||||
let request = match dispatcher.dispatch_lifecycle(
|
||||
request,
|
||||
desktop_uid,
|
||||
None,
|
||||
Some(crate::request_dispatcher::SessionAuthority {
|
||||
registry: Arc::clone(ctx.registry()),
|
||||
session_id,
|
||||
generation,
|
||||
}),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(result) => {
|
||||
if control.send(ConnectionCommand::Reply { id, result }).is_err() {
|
||||
pending_requests.remove(&id);
|
||||
control.close(CloseReason::InternalError);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = dispatcher.dispatch_pending(request).await;
|
||||
control.send_reply(id, result).await;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_prelude(socket: &mut WebSocket) -> Result<ClientPrelude, CloseReason> {
|
||||
let data = receive_binary(socket).await?;
|
||||
ClientPrelude::decode(&data).map_err(|_| CloseReason::MalformedMessage)
|
||||
}
|
||||
|
||||
async fn receive_binary(socket: &mut WebSocket) -> Result<Vec<u8>, CloseReason> {
|
||||
match socket.next().await {
|
||||
Some(Ok(Message::Binary(data))) => Ok(data.to_vec()),
|
||||
Some(Ok(_)) => Err(CloseReason::MalformedMessage),
|
||||
Some(Err(_)) | None => Err(CloseReason::HandshakeFailed),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_server_prelude(socket: &mut WebSocket, prelude: ServerPrelude) -> Result<(), CloseReason> {
|
||||
let data = prelude.encode().map_err(|_| CloseReason::InternalError)?;
|
||||
socket
|
||||
.send(Message::Binary(data.into()))
|
||||
.await
|
||||
.map_err(|_| CloseReason::HandshakeFailed)
|
||||
}
|
||||
|
||||
async fn send_encrypted(
|
||||
socket: &mut WebSocket,
|
||||
noise: &mut NoiseTransport,
|
||||
message: &ServerMessage,
|
||||
) -> anyhow::Result<()> {
|
||||
let encrypted = noise.encrypt(message)?;
|
||||
send_frame(socket, Message::Binary(encrypted.into())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_frame(socket: &mut WebSocket, frame: Message) -> anyhow::Result<()> {
|
||||
tokio::time::timeout(WRITE_TIMEOUT, socket.send(frame))
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("WebSocket write timed out"))??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_close(socket: &mut WebSocket, reason: CloseReason) {
|
||||
let _ = send_frame(
|
||||
socket,
|
||||
Message::Close(Some(CloseFrame {
|
||||
code: reason.code(),
|
||||
reason: Utf8Bytes::from_static(reason.reason()),
|
||||
})),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
transport::{ClientMessage, ClientPrelude, NoiseInitiator, ServerMessage, ServerPrelude, ServiceResult},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
utils::redact::Redaction,
|
||||
};
|
||||
use tokio::sync::watch;
|
||||
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientFrame};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher, routes, session_registry::SessionRegistry, ws_server::WsServerContext,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, routes::routes(context)).await.unwrap();
|
||||
});
|
||||
|
||||
let (mut socket, _) = connect_async(format!("ws://{address}/ws")).await.unwrap();
|
||||
let prelude = ClientPrelude {
|
||||
product_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION,
|
||||
service_instance_id: credential.service_instance_id(),
|
||||
session_id: credential.session_id(),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(prelude.encode().unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let ready = receive_client_binary(&mut socket).await;
|
||||
assert_eq!(ServerPrelude::decode(&ready).unwrap(), ServerPrelude::Ready);
|
||||
|
||||
let mut initiator = NoiseInitiator::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.secret(),
|
||||
)
|
||||
.unwrap();
|
||||
socket
|
||||
.send(ClientFrame::Binary(initiator.write_first().unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let response = receive_client_binary(&mut socket).await;
|
||||
let mut noise = initiator.read_response(&response).unwrap();
|
||||
let attach = noise
|
||||
.encrypt(&ClientMessage::Attach {
|
||||
last_event_revision: None,
|
||||
})
|
||||
.unwrap();
|
||||
socket.send(ClientFrame::Binary(attach.into())).await.unwrap();
|
||||
let attached = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(attached, ServerMessage::Attached { .. }));
|
||||
|
||||
let request_id = Uuid::new_v4();
|
||||
let request = ClientMessage::Request {
|
||||
id: request_id,
|
||||
request: WsRequest::UpdateLogLevel(UpdateLogLevelRequest("info".to_owned())),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
reply,
|
||||
ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::Accepted,
|
||||
} if id == request_id
|
||||
));
|
||||
|
||||
let update_id = Uuid::new_v4();
|
||||
let update_file = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(update_file.path(), b"invalid archive").unwrap();
|
||||
let update = ClientMessage::Request {
|
||||
id: update_id,
|
||||
request: WsRequest::UpdateGui(UpdateGuiRequest {
|
||||
path: update_file.path().to_string_lossy().into_owned(),
|
||||
checksum: "invalid".to_owned(),
|
||||
}),
|
||||
};
|
||||
socket
|
||||
.send(ClientFrame::Binary(noise.encrypt(&update).unwrap().into()))
|
||||
.await
|
||||
.unwrap();
|
||||
let reply = noise
|
||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
reply,
|
||||
ServerMessage::Reply {
|
||||
id,
|
||||
result: ServiceResult::Rejected(ref rejection),
|
||||
} if id == update_id && rejection.code() == gpapi::service::transport::ServiceErrorCode::ChecksumFailed
|
||||
));
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
async fn receive_client_binary(
|
||||
socket: &mut tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
|
||||
) -> Vec<u8> {
|
||||
match socket.next().await.unwrap().unwrap() {
|
||||
ClientFrame::Binary(data) => data.to_vec(),
|
||||
frame => panic!("unexpected frame: {frame:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+306
-101
@@ -1,110 +1,191 @@
|
||||
use std::sync::Arc;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use axum::extract::ws::Message;
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
event::WsEvent,
|
||||
request::WsRequest,
|
||||
transport::{CloseReason, ServerMessage},
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
|
||||
utils::lock_file::LockFile,
|
||||
};
|
||||
use log::{info, warn};
|
||||
use openconnect::{find_csd_wrapper, find_vpnc_script};
|
||||
use serde::de::DeserializeOwned;
|
||||
use openconnect::find_vpnc_script;
|
||||
use tokio::{
|
||||
net::TcpListener,
|
||||
sync::{RwLock, mpsc, watch},
|
||||
sync::{Mutex, Semaphore, mpsc, oneshot, watch},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{routes, ws_connection::WsConnection};
|
||||
use crate::{
|
||||
request_dispatcher::RequestDispatcher,
|
||||
routes,
|
||||
session_registry::{HandshakePermit, PreparedAttach, SessionError, SessionRegistry},
|
||||
ws_connection::{ConnectionCommand, ConnectionControl},
|
||||
};
|
||||
|
||||
struct ServiceState {
|
||||
revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
connections: HashMap<Uuid, ConnectionControl>,
|
||||
}
|
||||
|
||||
pub(crate) struct WsServerContext {
|
||||
crypto: Arc<Crypto>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
redaction: Arc<Redaction>,
|
||||
connections: RwLock<Vec<Arc<WsConnection>>>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
state: Mutex<ServiceState>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
|
||||
}
|
||||
|
||||
impl WsServerContext {
|
||||
pub fn new(
|
||||
api_key: Vec<u8>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
redaction: Arc<Redaction>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
vpn_state_rx: &watch::Receiver<VpnState>,
|
||||
) -> Self {
|
||||
Self {
|
||||
crypto: Arc::new(Crypto::new(api_key)),
|
||||
ws_req_tx,
|
||||
vpn_state_rx,
|
||||
redaction,
|
||||
connections: Default::default(),
|
||||
product_version,
|
||||
registry,
|
||||
dispatcher,
|
||||
state: Mutex::new(ServiceState {
|
||||
revision: 0,
|
||||
snapshot: build_snapshot(vpn_state_rx.borrow().clone()),
|
||||
connections: HashMap::new(),
|
||||
}),
|
||||
handshake_slots: Arc::new(Semaphore::new(16)),
|
||||
hip_previews: crate::hip_preview::HipPreviews::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decrypt<T: DeserializeOwned>(&self, encrypted: Vec<u8>) -> anyhow::Result<T> {
|
||||
self.crypto.decrypt(encrypted)
|
||||
pub fn product_version(&self) -> &'static str {
|
||||
self.product_version
|
||||
}
|
||||
|
||||
pub async fn host_identity(&self) -> HostIdentity {
|
||||
self.state.lock().await.snapshot.host_info.host_identity.clone()
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Arc<SessionRegistry> {
|
||||
&self.registry
|
||||
}
|
||||
|
||||
pub fn dispatcher(&self) -> Arc<RequestDispatcher> {
|
||||
Arc::clone(&self.dispatcher)
|
||||
}
|
||||
|
||||
pub fn try_handshake_slot(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
|
||||
Arc::clone(&self.handshake_slots).try_acquire_owned().ok()
|
||||
}
|
||||
|
||||
pub async fn prepare_connection(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
control: ConnectionControl,
|
||||
) -> Result<PreparedAttach, SessionError> {
|
||||
let mut state = self.state.lock().await;
|
||||
let prepared = self.registry.prepare_attach(permit)?;
|
||||
|
||||
control
|
||||
.send(ConnectionCommand::Send(ServerMessage::Attached {
|
||||
connection_id: control.connection_id(),
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
.map_err(|_| SessionError::Unavailable)?;
|
||||
state.connections.insert(control.connection_id(), control);
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
pub async fn commit_connection(
|
||||
&self,
|
||||
permit: &HandshakePermit,
|
||||
connection: &ConnectionControl,
|
||||
) -> Result<Option<ConnectionControl>, SessionError> {
|
||||
let mut state = self.state.lock().await;
|
||||
if !state
|
||||
.connections
|
||||
.get(&connection.connection_id())
|
||||
.is_some_and(|candidate| !candidate.is_closed())
|
||||
{
|
||||
return Err(SessionError::Unavailable);
|
||||
}
|
||||
match self.registry.commit_attach(permit, connection.clone()) {
|
||||
Ok(replaced) => {
|
||||
if let Some(replaced) = &replaced {
|
||||
state.connections.remove(&replaced.connection_id());
|
||||
}
|
||||
Ok(replaced)
|
||||
}
|
||||
Err(err) => {
|
||||
state.connections.remove(&connection.connection_id());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn abandon_connection(&self, connection_id: Uuid) {
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
}
|
||||
|
||||
pub async fn remove_closed_connections(&self) {
|
||||
self
|
||||
.state
|
||||
.lock()
|
||||
.await
|
||||
.connections
|
||||
.retain(|_, connection| !connection.is_closed());
|
||||
}
|
||||
|
||||
pub async fn send_snapshot(&self, control: &ConnectionControl) -> Result<(), ()> {
|
||||
let state = self.state.lock().await;
|
||||
control.send(ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: state.revision,
|
||||
snapshot: state.snapshot.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
|
||||
self.registry.disconnect_if_current(session_id, generation);
|
||||
self.state.lock().await.connections.remove(&connection_id);
|
||||
}
|
||||
|
||||
pub async fn send_event(&self, event: WsEvent) {
|
||||
let connections = self.connections.read().await;
|
||||
|
||||
for conn in connections.iter() {
|
||||
let _ = conn.send_event(&event).await;
|
||||
let mut state = self.state.lock().await;
|
||||
if let WsEvent::VpnEnv(env) = &event {
|
||||
state.snapshot = env.clone();
|
||||
} else if let WsEvent::VpnState(vpn_state) = &event {
|
||||
state.snapshot.vpn_state = vpn_state.clone();
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add_connection(&self) -> (Arc<WsConnection>, mpsc::Receiver<Message>) {
|
||||
let (tx, rx) = mpsc::channel::<Message>(32);
|
||||
let conn = Arc::new(WsConnection::new(Arc::clone(&self.crypto), tx));
|
||||
|
||||
// Send current VPN state to new client
|
||||
info!("Sending current environment to new client");
|
||||
let host_info = HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
let Some(revision) = state.revision.checked_add(1) else {
|
||||
for connection in state.connections.values() {
|
||||
connection.close(CloseReason::InternalError);
|
||||
}
|
||||
state.connections.clear();
|
||||
return;
|
||||
};
|
||||
state.revision = revision;
|
||||
|
||||
let vpn_env = VpnEnv {
|
||||
vpn_state: self.vpn_state_rx.borrow().clone(),
|
||||
vpnc_script: find_vpnc_script().map(|s| s.to_owned()),
|
||||
csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info,
|
||||
};
|
||||
|
||||
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
|
||||
warn!("Failed to send VPN state to new client: {}", err);
|
||||
}
|
||||
|
||||
self.connections.write().await.push(Arc::clone(&conn));
|
||||
|
||||
(conn, rx)
|
||||
}
|
||||
|
||||
pub async fn remove_connection(&self, conn: Arc<WsConnection>) {
|
||||
let mut connections = self.connections.write().await;
|
||||
connections.retain(|c| !Arc::ptr_eq(c, &conn));
|
||||
}
|
||||
|
||||
fn vpn_state_rx(&self) -> watch::Receiver<VpnState> {
|
||||
self.vpn_state_rx.clone()
|
||||
}
|
||||
|
||||
pub async fn forward_req(&self, req: WsRequest) -> anyhow::Result<()> {
|
||||
if let WsRequest::Connect(ref req) = req {
|
||||
self
|
||||
.redaction
|
||||
.add_values(&[req.gateway().server(), req.args().cookie()])?
|
||||
}
|
||||
|
||||
self.ws_req_tx.send(req).await?;
|
||||
|
||||
Ok(())
|
||||
state.connections.retain(|_, connection| {
|
||||
if connection
|
||||
.send(ConnectionCommand::Send(ServerMessage::Event {
|
||||
revision,
|
||||
event: event.clone(),
|
||||
}))
|
||||
.is_ok()
|
||||
{
|
||||
true
|
||||
} else {
|
||||
connection.close(CloseReason::InternalError);
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,23 +193,27 @@ pub(crate) struct WsServer {
|
||||
ctx: Arc<WsServerContext>,
|
||||
cancel_token: CancellationToken,
|
||||
lock_file: Arc<LockFile>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
}
|
||||
|
||||
impl WsServer {
|
||||
pub fn new(
|
||||
api_key: Vec<u8>,
|
||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
||||
product_version: &'static str,
|
||||
registry: Arc<SessionRegistry>,
|
||||
dispatcher: Arc<RequestDispatcher>,
|
||||
vpn_state_rx: watch::Receiver<VpnState>,
|
||||
lock_file: Arc<LockFile>,
|
||||
redaction: Arc<Redaction>,
|
||||
) -> Self {
|
||||
let ctx = Arc::new(WsServerContext::new(api_key, ws_req_tx, vpn_state_rx, redaction));
|
||||
let cancel_token = CancellationToken::new();
|
||||
|
||||
Self {
|
||||
ctx,
|
||||
cancel_token,
|
||||
ctx: Arc::new(WsServerContext::new(
|
||||
product_version,
|
||||
registry,
|
||||
dispatcher,
|
||||
&vpn_state_rx,
|
||||
)),
|
||||
cancel_token: CancellationToken::new(),
|
||||
lock_file,
|
||||
vpn_state_rx,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,55 +225,175 @@ impl WsServer {
|
||||
self.cancel_token.clone()
|
||||
}
|
||||
|
||||
pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) {
|
||||
pub async fn start(&self, shutdown_tx: mpsc::Sender<()>, ready_tx: oneshot::Sender<()>) {
|
||||
let listener = match self.start_tcp_server().await {
|
||||
Ok(listener) => listener,
|
||||
Err(err) => {
|
||||
warn!("Failed to start WS server: {}", err);
|
||||
warn!("Failed to start WS server: {err}");
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = ready_tx.send(());
|
||||
|
||||
tokio::select! {
|
||||
_ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => {
|
||||
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
|
||||
info!("VPN state watch task completed");
|
||||
}
|
||||
_ = start_server(listener, self.ctx.clone()) => {
|
||||
info!("WS server stopped");
|
||||
result = axum::serve(listener, routes::routes(Arc::clone(&self.ctx))) => {
|
||||
if let Err(err) = result {
|
||||
warn!("WS server stopped: {err}");
|
||||
}
|
||||
}
|
||||
_ = self.cancel_token.cancelled() => {
|
||||
info!("WS server cancelled");
|
||||
}
|
||||
}
|
||||
|
||||
self.ctx.hip_previews.shutdown().await;
|
||||
let _ = shutdown_tx.send(()).await;
|
||||
}
|
||||
|
||||
async fn start_tcp_server(&self) -> anyhow::Result<TcpListener> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let local_addr = listener.local_addr()?;
|
||||
let port = local_addr.port();
|
||||
|
||||
info!("WS server listening on port: {}", port);
|
||||
|
||||
let port = listener.local_addr()?.port();
|
||||
info!("WS server listening on port: {port}");
|
||||
self.lock_file.lock(&port.to_string())?;
|
||||
|
||||
Ok(listener)
|
||||
}
|
||||
}
|
||||
|
||||
fn build_snapshot(vpn_state: VpnState) -> VpnEnv {
|
||||
VpnEnv {
|
||||
vpn_state,
|
||||
vpnc_script: find_vpnc_script(),
|
||||
auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(),
|
||||
host_info: HostInfo {
|
||||
host_identity: HostIdentity::collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{Arc, atomic::AtomicBool};
|
||||
|
||||
use gpapi::{
|
||||
service::{event::WsEvent, transport::ServerMessage},
|
||||
utils::redact::Redaction,
|
||||
};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn resync_snapshot_is_ordered_with_state_events() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let permit = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
registry,
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let (control, _close_rx) = ConnectionControl::new(Uuid::new_v4(), tx);
|
||||
context.prepare_connection(&permit, control.clone()).await.unwrap();
|
||||
assert!(matches!(
|
||||
rx.recv().await,
|
||||
Some(ConnectionCommand::Send(ServerMessage::Attached { .. }))
|
||||
));
|
||||
|
||||
let (snapshot_result, ()) = tokio::join!(
|
||||
context.send_snapshot(&control),
|
||||
context.send_event(WsEvent::VpnState(VpnState::Disconnected)),
|
||||
);
|
||||
snapshot_result.unwrap();
|
||||
let first = rx.recv().await.unwrap();
|
||||
let second = rx.recv().await.unwrap();
|
||||
match (first, second) {
|
||||
(
|
||||
ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: 0, ..
|
||||
}),
|
||||
ConnectionCommand::Send(ServerMessage::Event { revision: 1, .. }),
|
||||
)
|
||||
| (
|
||||
ConnectionCommand::Send(ServerMessage::Event { revision: 1, .. }),
|
||||
ConnectionCommand::Send(ServerMessage::Snapshot {
|
||||
current_revision: 1, ..
|
||||
}),
|
||||
) => {}
|
||||
_ => panic!("snapshot and event were not atomically ordered"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap();
|
||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
Arc::new(Redaction::new()),
|
||||
true,
|
||||
None,
|
||||
));
|
||||
let (_state_tx, state_rx) = watch::channel(VpnState::Disconnected);
|
||||
let context = Arc::new(WsServerContext::new(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
Arc::clone(®istry),
|
||||
dispatcher,
|
||||
&state_rx,
|
||||
));
|
||||
|
||||
let first = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (first_tx, mut first_rx) = mpsc::channel(4);
|
||||
let (first_control, _first_close) = ConnectionControl::new(Uuid::new_v4(), first_tx);
|
||||
context.prepare_connection(&first, first_control.clone()).await.unwrap();
|
||||
first_rx.recv().await.unwrap();
|
||||
context.commit_connection(&first, &first_control).await.unwrap();
|
||||
|
||||
let reconnect = registry
|
||||
.begin_handshake(
|
||||
credential.service_instance_id(),
|
||||
credential.session_id(),
|
||||
credential.product_version(),
|
||||
)
|
||||
.unwrap();
|
||||
let (candidate_tx, _candidate_rx) = mpsc::channel(1);
|
||||
let (candidate, _candidate_close) = ConnectionControl::new(Uuid::new_v4(), candidate_tx);
|
||||
context.prepare_connection(&reconnect, candidate.clone()).await.unwrap();
|
||||
context.send_event(WsEvent::VpnState(VpnState::Disconnected)).await;
|
||||
|
||||
assert!(context.commit_connection(&reconnect, &candidate).await.is_err());
|
||||
assert!(registry.is_current(credential.session_id(), 1));
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<WsServerContext>) {
|
||||
while vpn_state_rx.changed().await.is_ok() {
|
||||
let vpn_state = vpn_state_rx.borrow().clone();
|
||||
ctx.send_event(WsEvent::VpnState(vpn_state)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_server(listener: TcpListener, ctx: Arc<WsServerContext>) -> anyhow::Result<()> {
|
||||
let routes = routes::routes(ctx);
|
||||
|
||||
axum::serve(listener, routes).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user