mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
fix(desktop): keep GUI in the user authorization session
This commit is contained in:
11 files changed
+438
-281
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
use std::{collections::HashMap, fs, path::PathBuf};
|
use std::{fs, path::PathBuf};
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||||
use std::process::{Command, ExitStatus};
|
use std::process::{Command, ExitStatus};
|
||||||
@@ -11,10 +11,7 @@ use clap::Args;
|
|||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||||
use common::binary_paths;
|
use common::binary_paths;
|
||||||
use directories::ProjectDirs;
|
use directories::ProjectDirs;
|
||||||
use gpapi::{
|
use gpapi::{process::desktop_launcher::DesktopLauncher, utils::endpoint::http_endpoint};
|
||||||
process::service_launcher::ServiceLauncher,
|
|
||||||
utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
|
|
||||||
};
|
|
||||||
use log::info;
|
use log::info;
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
@@ -69,27 +66,13 @@ impl<'a> LaunchGuiHandler<'a> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
shutdown_signal().await;
|
|
||||||
info!("Shutting down...");
|
|
||||||
});
|
|
||||||
|
|
||||||
let log_file = get_log_file()?;
|
let log_file = get_log_file()?;
|
||||||
let log_file_path = log_file.to_string_lossy().to_string();
|
let log_file_path = log_file.to_string_lossy().to_string();
|
||||||
|
|
||||||
info!("Log file: {}", log_file_path);
|
info!("Log file: {}", log_file_path);
|
||||||
|
|
||||||
let mut extra_envs = HashMap::<String, String>::new();
|
let exit_status = DesktopLauncher::new(env!("CARGO_PKG_VERSION"))
|
||||||
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
|
|
||||||
|
|
||||||
// Persist the environment variables to a file
|
|
||||||
let env_file = env_utils::persist_env_vars(Some(extra_envs))?;
|
|
||||||
let env_file = env_file.into_temp_path();
|
|
||||||
let env_file_path = env_file.to_string_lossy().to_string();
|
|
||||||
|
|
||||||
let exit_status = ServiceLauncher::new()
|
|
||||||
.minimized(self.args.minimized)
|
.minimized(self.args.minimized)
|
||||||
.env_file(&env_file_path)
|
|
||||||
.log_file(&log_file_path)
|
.log_file(&log_file_path)
|
||||||
.launch()
|
.launch()
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
+48
-65
@@ -1,11 +1,8 @@
|
|||||||
|
use std::io::Write;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{
|
use std::sync::{Arc, atomic::AtomicBool};
|
||||||
Arc,
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
};
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{collections::HashMap, io::Write};
|
|
||||||
|
|
||||||
use anyhow::{Context, bail};
|
use anyhow::{Context, bail};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
@@ -15,9 +12,8 @@ use gpapi::logger;
|
|||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
use gpapi::utils::lock_file::dev_service_lock_file_path;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
process::gui_launcher::GuiLauncher,
|
|
||||||
service::vpn_state::VpnState,
|
service::vpn_state::VpnState,
|
||||||
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
utils::{lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||||
};
|
};
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
use log::{Log, Metadata, Record};
|
use log::{Log, Metadata, Record};
|
||||||
@@ -64,9 +60,9 @@ impl Log for RedactingMacosLogger {
|
|||||||
#[command(version = VERSION)]
|
#[command(version = VERSION)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[clap(long)]
|
#[clap(long)]
|
||||||
minimized: bool,
|
#[cfg_attr(debug_assertions, clap(conflicts_with = "dev_standalone"))]
|
||||||
#[clap(long)]
|
#[cfg_attr(target_os = "macos", clap(conflicts_with = "macos_brokered"))]
|
||||||
env_file: Option<String>,
|
desktop_credentials: bool,
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
|
||||||
dev_standalone: bool,
|
dev_standalone: bool,
|
||||||
@@ -100,7 +96,29 @@ impl Cli {
|
|||||||
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
let gui_restart_requested = Arc::new(AtomicBool::new(false));
|
||||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
let externally_brokered = self.externally_brokered();
|
let externally_brokered = self.externally_brokered();
|
||||||
let desktop_uid = crate::runtime_user::desktop_uid();
|
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 brokered_scripts_dir = if externally_brokered {
|
||||||
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
|
||||||
let contents_dir = executable
|
let contents_dir = executable
|
||||||
@@ -182,26 +200,28 @@ impl Cli {
|
|||||||
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
|
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 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_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 ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
|
||||||
|
|
||||||
#[cfg(debug_assertions)]
|
let desktop_client_handle = if let Some(channel) = desktop_channel {
|
||||||
let launch_managed_gui = !self.dev_standalone && !externally_brokered;
|
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
let launch_managed_gui = !externally_brokered;
|
|
||||||
|
|
||||||
if launch_managed_gui {
|
|
||||||
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
ws_ready_rx.await.context("WebSocket server failed to start")?;
|
||||||
let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?;
|
let desktop_uid = desktop_uid.context("Desktop user is unavailable")?;
|
||||||
let minimized = self.minimized;
|
Some(tokio::spawn(async move {
|
||||||
tokio::spawn(async move {
|
if let Err(err) = channel
|
||||||
launch_gui(envs, registry, desktop_uid, minimized, gui_restart_requested).await;
|
.serve(registry, desktop_uid, gui_restart_requested, desktop_cancel)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
warn!("Desktop credential channel ended: {err}");
|
||||||
|
}
|
||||||
let _ = shutdown_tx.send(()).await;
|
let _ = shutdown_tx.send(()).await;
|
||||||
});
|
}))
|
||||||
} else {
|
} else {
|
||||||
info!("Running with a separately started debug GUI");
|
info!("Running with an externally launched GUI");
|
||||||
}
|
None
|
||||||
|
};
|
||||||
|
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = shutdown_signal() => {
|
_ = shutdown_signal() => {
|
||||||
@@ -213,7 +233,11 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
vpn_task_cancel_token.cancel();
|
vpn_task_cancel_token.cancel();
|
||||||
|
shutdown_token.cancel();
|
||||||
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
|
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
|
||||||
|
if let Some(handle) = desktop_client_handle {
|
||||||
|
let _ = handle.await;
|
||||||
|
}
|
||||||
|
|
||||||
lock_file.unlock()?;
|
lock_file.unlock()?;
|
||||||
|
|
||||||
@@ -363,47 +387,6 @@ mod signals {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn launch_gui(
|
|
||||||
envs: Option<HashMap<String, String>>,
|
|
||||||
registry: Arc<SessionRegistry>,
|
|
||||||
desktop_uid: Option<u32>,
|
|
||||||
mut minimized: bool,
|
|
||||||
restart_requested: Arc<AtomicBool>,
|
|
||||||
) {
|
|
||||||
loop {
|
|
||||||
let credential = match registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid) {
|
|
||||||
Ok(credential) => credential,
|
|
||||||
Err(err) => {
|
|
||||||
warn!("Failed to issue GUI credential: {err}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let session_id = credential.session_id();
|
|
||||||
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), credential)
|
|
||||||
.envs(envs.clone())
|
|
||||||
.minimized(minimized);
|
|
||||||
|
|
||||||
match gui_launcher.launch().await {
|
|
||||||
Ok(exit_status) => {
|
|
||||||
registry.revoke(session_id);
|
|
||||||
let should_restart = restart_requested.swap(false, Ordering::SeqCst);
|
|
||||||
if !should_restart {
|
|
||||||
info!("GUI exited with code {:?}", exit_status.code());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("GUI restart requested, restarting");
|
|
||||||
minimized = false;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
registry.revoke(session_id);
|
|
||||||
warn!("Failed to launch GUI: {}", err);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run() {
|
pub async fn run() {
|
||||||
let mut cli = Cli::parse();
|
let mut cli = Cli::parse();
|
||||||
|
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
mod cli;
|
mod cli;
|
||||||
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
#[cfg(all(unix, any(target_os = "macos", debug_assertions)))]
|
||||||
mod credential_lease;
|
mod credential_lease;
|
||||||
|
mod desktop_client;
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
mod dev_bootstrap;
|
mod dev_bootstrap;
|
||||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))]
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fs::File,
|
||||||
|
process::{ExitStatus, Stdio},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
|
||||||
|
use anyhow::{Context, ensure};
|
||||||
|
use common::binary_paths;
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
||||||
|
process::Command,
|
||||||
|
};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use super::{CommandExt, gui_launcher::GuiLauncher};
|
||||||
|
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||||
|
|
||||||
|
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
|
||||||
|
pub struct DesktopLauncher<'a> {
|
||||||
|
version: &'a str,
|
||||||
|
minimized: bool,
|
||||||
|
log_file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> DesktopLauncher<'a> {
|
||||||
|
pub fn new(version: &'a str) -> Self {
|
||||||
|
Self {
|
||||||
|
version,
|
||||||
|
minimized: false,
|
||||||
|
log_file: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||||
|
self.minimized = minimized;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||||
|
self.log_file = Some(log_file.to_owned());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||||
|
ensure!(
|
||||||
|
uzers::get_effective_uid() != 0,
|
||||||
|
"The desktop launcher must not run as root"
|
||||||
|
);
|
||||||
|
let mut command = Command::new_pkexec(binary_paths::gpservice());
|
||||||
|
command
|
||||||
|
.arg("--desktop-credentials")
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped());
|
||||||
|
if let Some(path) = &self.log_file {
|
||||||
|
command.stderr(Stdio::from(File::create(path)?));
|
||||||
|
}
|
||||||
|
let mut service = command.spawn().context("Failed to start the privileged service")?;
|
||||||
|
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
|
||||||
|
let mut output = service
|
||||||
|
.stdout
|
||||||
|
.take()
|
||||||
|
.context("Service credential pipe is unavailable")?;
|
||||||
|
let mut received_credential = false;
|
||||||
|
let mut cancelled = false;
|
||||||
|
let result = tokio::select! {
|
||||||
|
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
|
||||||
|
result = async {
|
||||||
|
let mut minimized = self.minimized;
|
||||||
|
loop {
|
||||||
|
let credential = read_credential(&mut output).await?;
|
||||||
|
let Some(credential) = credential else { return Ok(()); };
|
||||||
|
received_credential = true;
|
||||||
|
ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||||
|
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||||
|
if let Some(path) = &self.log_file {
|
||||||
|
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||||
|
}
|
||||||
|
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
|
||||||
|
let mut unexpected = [0];
|
||||||
|
tokio::select! {
|
||||||
|
result = launcher.launch() => { result?; }
|
||||||
|
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
|
||||||
|
result = output.read(&mut unexpected) => {
|
||||||
|
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||||
|
anyhow::bail!("The privileged service closed its credential channel");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input.write_all(&[0]).await?;
|
||||||
|
minimized = false;
|
||||||
|
}
|
||||||
|
} => result,
|
||||||
|
};
|
||||||
|
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
|
||||||
|
drop(input);
|
||||||
|
if cancelled && !received_credential {
|
||||||
|
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
|
||||||
|
if let Err(error) = service.start_kill()
|
||||||
|
&& error.kind() != std::io::ErrorKind::PermissionDenied
|
||||||
|
{
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let status = service.wait().await?;
|
||||||
|
result?;
|
||||||
|
ensure!(
|
||||||
|
cancelled || status.success(),
|
||||||
|
"The privileged service exited with {status}"
|
||||||
|
);
|
||||||
|
Ok(status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
|
||||||
|
let mut header = [0; 2];
|
||||||
|
if reader.read(&mut header[..1]).await? == 0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
reader.read_exact(&mut header[1..]).await?;
|
||||||
|
let length = usize::from(u16::from_be_bytes(header));
|
||||||
|
ensure!(
|
||||||
|
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
|
||||||
|
"Invalid service credential length"
|
||||||
|
);
|
||||||
|
let mut frame = Zeroizing::new(vec![0; length + 2]);
|
||||||
|
frame[..2].copy_from_slice(&header);
|
||||||
|
reader.read_exact(&mut frame[2..]).await?;
|
||||||
|
Ok(Some(SessionCredential::decode_frame(&frame)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
|
||||||
|
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
|
||||||
|
assert!(read_credential(&mut &[0][..]).await.is_err());
|
||||||
|
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
|
||||||
|
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
|
||||||
|
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||||
|
let frame = credential.encode_frame().unwrap();
|
||||||
|
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
|
||||||
|
assert_eq!(decoded.session_id(), credential.session_id());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ use common::binary_paths;
|
|||||||
use log::info;
|
use log::info;
|
||||||
use tokio::{io::AsyncWriteExt, process::Command};
|
use tokio::{io::AsyncWriteExt, process::Command};
|
||||||
|
|
||||||
use crate::{process::command_traits::CommandExt, service::transport::SessionCredential};
|
use crate::service::transport::SessionCredential;
|
||||||
|
|
||||||
pub struct GuiHelperLauncher<'a> {
|
pub struct GuiHelperLauncher<'a> {
|
||||||
program: PathBuf,
|
program: PathBuf,
|
||||||
@@ -49,8 +49,11 @@ impl<'a> GuiHelperLauncher<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
info!("Launching gpgui-helper");
|
info!("Launching gpgui-helper");
|
||||||
let mut non_root_cmd = cmd.into_non_root()?;
|
anyhow::ensure!(
|
||||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
uzers::get_effective_uid() != 0,
|
||||||
|
"The desktop GUI must not be launched by root"
|
||||||
|
);
|
||||||
|
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||||
let mut child = match child {
|
let mut child = match child {
|
||||||
Ok(child) => child,
|
Ok(child) => child,
|
||||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ use tokio::{io::AsyncWriteExt, process::Command};
|
|||||||
|
|
||||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||||
|
|
||||||
use super::command_traits::CommandExt;
|
|
||||||
|
|
||||||
pub struct GuiLauncher<'a> {
|
pub struct GuiLauncher<'a> {
|
||||||
version: &'a str,
|
version: &'a str,
|
||||||
programs: Vec<PathBuf>,
|
programs: Vec<PathBuf>,
|
||||||
@@ -52,6 +50,10 @@ impl<'a> GuiLauncher<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||||
|
anyhow::ensure!(
|
||||||
|
uzers::get_effective_uid() != 0,
|
||||||
|
"The desktop GUI must not be launched by root"
|
||||||
|
);
|
||||||
if let Some(program) = self.find_compatible_program().await {
|
if let Some(program) = self.find_compatible_program().await {
|
||||||
return self.launch_program(&program).await;
|
return self.launch_program(&program).await;
|
||||||
}
|
}
|
||||||
@@ -92,8 +94,7 @@ impl<'a> GuiLauncher<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
info!("Launching gpgui");
|
info!("Launching gpgui");
|
||||||
let mut non_root_cmd = cmd.into_non_root()?;
|
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
|
||||||
let mut child = match child {
|
let mut child = match child {
|
||||||
Ok(child) => child,
|
Ok(child) => child,
|
||||||
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
||||||
@@ -119,7 +120,7 @@ impl<'a> GuiLauncher<'a> {
|
|||||||
cmd.envs(envs);
|
cmd.envs(envs);
|
||||||
}
|
}
|
||||||
cmd.arg("--version");
|
cmd.arg("--version");
|
||||||
let output = cmd.into_non_root()?.output().await?;
|
let output = cmd.output().await?;
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
bail!("Version command exited with {}", output.status);
|
bail!("Version command exited with {}", output.status);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ pub(crate) mod gui_helper_launcher;
|
|||||||
pub use command_traits::CommandExt;
|
pub use command_traits::CommandExt;
|
||||||
|
|
||||||
pub mod auth_launcher;
|
pub mod auth_launcher;
|
||||||
|
pub mod desktop_launcher;
|
||||||
pub mod gui_launcher;
|
pub mod gui_launcher;
|
||||||
pub mod service_launcher;
|
|
||||||
pub mod users;
|
pub mod users;
|
||||||
|
|
||||||
pub mod collection;
|
pub mod collection;
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::File,
|
|
||||||
path::PathBuf,
|
|
||||||
process::{ExitStatus, Stdio},
|
|
||||||
};
|
|
||||||
|
|
||||||
use common::binary_paths;
|
|
||||||
use tokio::process::Command;
|
|
||||||
|
|
||||||
use super::command_traits::CommandExt;
|
|
||||||
|
|
||||||
pub struct ServiceLauncher<'a> {
|
|
||||||
program: PathBuf,
|
|
||||||
minimized: bool,
|
|
||||||
env_file: Option<String>,
|
|
||||||
log_file: Option<String>,
|
|
||||||
verbose: Option<&'a str>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ServiceLauncher<'_> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> ServiceLauncher<'a> {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
program: binary_paths::gpservice(),
|
|
||||||
minimized: false,
|
|
||||||
env_file: None,
|
|
||||||
log_file: None,
|
|
||||||
verbose: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
|
||||||
self.minimized = minimized;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn env_file(mut self, env_file: &str) -> Self {
|
|
||||||
self.env_file = Some(env_file.to_string());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
|
||||||
self.log_file = Some(log_file.to_string());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
|
||||||
self.verbose = verbose;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
|
||||||
let mut cmd = Command::new_pkexec(&self.program);
|
|
||||||
|
|
||||||
if self.minimized {
|
|
||||||
cmd.arg("--minimized");
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(env_file) = &self.env_file {
|
|
||||||
cmd.arg("--env-file").arg(env_file);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(verbose) = self.verbose {
|
|
||||||
cmd.arg(verbose);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(log_file) = &self.log_file {
|
|
||||||
let log_file = File::create(log_file)?;
|
|
||||||
let stdio = Stdio::from(log_file);
|
|
||||||
cmd.stderr(stdio);
|
|
||||||
}
|
|
||||||
|
|
||||||
let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?;
|
|
||||||
|
|
||||||
Ok(exit_status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::io::Write;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use tempfile::NamedTempFile;
|
|
||||||
|
|
||||||
pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> {
|
|
||||||
let mut env_file = NamedTempFile::new()?;
|
|
||||||
let content = env::vars()
|
|
||||||
.map(|(key, value)| format!("{}={}", key, value))
|
|
||||||
.chain(
|
|
||||||
extra
|
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
|
||||||
.map(|(key, value)| format!("{}={}", key, value)),
|
|
||||||
)
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
writeln!(env_file, "{}", content)?;
|
|
||||||
|
|
||||||
Ok(env_file)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> {
|
|
||||||
let content = std::fs::read_to_string(env_file)?;
|
|
||||||
let mut env_vars: HashMap<String, String> = HashMap::new();
|
|
||||||
|
|
||||||
for line in content.lines() {
|
|
||||||
if let Some((key, value)) = line.split_once('=') {
|
|
||||||
env_vars.insert(key.to_string(), value.to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(env_vars)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn patch_gui_runtime_env(hidpi: bool) {
|
pub fn patch_gui_runtime_env(hidpi: bool) {
|
||||||
if is_wayland_session(
|
if is_wayland_session(
|
||||||
|
|||||||
@@ -398,76 +398,10 @@
|
|||||||
#!${pkgs.runtimeShell}
|
#!${pkgs.runtimeShell}
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
gpclient_fhs='${prebuiltCommands.gpclient}/bin/gpclient'
|
export GP_SERVICE_BINARY='@gpservice_public@'
|
||||||
gpservice_public='@gpservice_public@'
|
export GP_AUTH_BINARY='@gpauth_public@'
|
||||||
gpauth_public='@gpauth_public@'
|
export GP_GUI_BINARY='${hostGuiLauncher}'
|
||||||
|
exec '${prebuiltCommands.gpclient}/bin/gpclient' "$@"
|
||||||
if [ "''${1:-}" = "launch-gui" ]; then
|
|
||||||
shift
|
|
||||||
|
|
||||||
minimized=
|
|
||||||
callback=
|
|
||||||
for arg in "$@"; do
|
|
||||||
case "$arg" in
|
|
||||||
--minimized)
|
|
||||||
minimized=--minimized
|
|
||||||
;;
|
|
||||||
globalprotectcallback:*)
|
|
||||||
if [ -n "$callback" ]; then
|
|
||||||
echo "Multiple authentication callback URLs were provided" >&2
|
|
||||||
exit 2
|
|
||||||
fi
|
|
||||||
callback=$arg
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "Unsupported launch-gui argument: $arg" >&2
|
|
||||||
exit 2
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -n "$callback" ]; then
|
|
||||||
if [ -n "$minimized" ]; then
|
|
||||||
echo "An authentication callback cannot be combined with --minimized" >&2
|
|
||||||
exit 2
|
|
||||||
fi
|
|
||||||
exec "$gpauth_public" auth-callback "$callback"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -n "''${XDG_DATA_HOME:-}" ]; then
|
|
||||||
data_home=$XDG_DATA_HOME
|
|
||||||
elif [ -n "''${HOME:-}" ]; then
|
|
||||||
data_home=$HOME/.local/share
|
|
||||||
else
|
|
||||||
data_home=/tmp
|
|
||||||
fi
|
|
||||||
|
|
||||||
log_dir="$data_home/gpclient"
|
|
||||||
mkdir -p "$log_dir"
|
|
||||||
log_file="$log_dir/gpclient.log"
|
|
||||||
env_file=$(mktemp)
|
|
||||||
|
|
||||||
env > "$env_file"
|
|
||||||
printf 'GP_LOG_FILE=%s\n' "$log_file" >> "$env_file"
|
|
||||||
|
|
||||||
pkexec_bin=/run/wrappers/bin/pkexec
|
|
||||||
if [ ! -x "$pkexec_bin" ]; then
|
|
||||||
pkexec_bin=pkexec
|
|
||||||
fi
|
|
||||||
|
|
||||||
set +e
|
|
||||||
if [ -n "$minimized" ]; then
|
|
||||||
"$pkexec_bin" --user root "$gpservice_public" --minimized --env-file "$env_file" 2>"$log_file"
|
|
||||||
else
|
|
||||||
"$pkexec_bin" --user root "$gpservice_public" --env-file "$env_file" 2>"$log_file"
|
|
||||||
fi
|
|
||||||
status=$?
|
|
||||||
set -e
|
|
||||||
rm -f "$env_file"
|
|
||||||
exit "$status"
|
|
||||||
fi
|
|
||||||
|
|
||||||
exec "$gpclient_fhs" "$@"
|
|
||||||
EOF
|
EOF
|
||||||
substituteInPlace $out/bin/gpclient \
|
substituteInPlace $out/bin/gpclient \
|
||||||
--replace-fail '@gpservice_public@' "$out/bin/gpservice" \
|
--replace-fail '@gpservice_public@' "$out/bin/gpservice" \
|
||||||
|
|||||||
Reference in new issue
Block a user