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, pub session_id: uuid::Uuid, pub generation: u64, } pub(crate) enum PendingDispatch { Connect { preparation: ConnectionPreparation, request: Box, desktop_uid: Option, edited_report: Option>, }, Drain(Option), Other(WsRequest), } pub(crate) struct ConnectionPreparation { authority: SessionAuthority, non_tunnel: bool, reservation: Option, } 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, edited_report: Option>, ) -> 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, redaction: Arc, install_lock: Mutex<()>, gui_management_enabled: bool, externally_brokered: bool, } impl RequestDispatcher { pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver { self.lifecycle.subscribe_tunnel() } pub fn new( lifecycle: crate::vpn_task::LifecycleHandle, gui_restart_requested: Arc, redaction: Arc, gui_management_enabled: bool, externally_brokered: bool, ) -> Self { Self { lifecycle, gui_restart_requested, redaction, install_lock: Mutex::new(()), gui_management_enabled, externally_brokered, } } pub fn dispatch_lifecycle( &self, request: WsRequest, desktop_uid: Option, edited_report: Option>, authority: Option, ) -> Result { match request { WsRequest::Connect(request) => { if let Err(message) = self.validate_connect_request(&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::>(); 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(request.restart_of().map(|attempt| (attempt, authority.session_id))) })?; 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.externally_brokered, 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 | WsRequest::SetTunnelStatisticsEnabled { .. } => { unreachable!("session-bound request was already dispatched") } } } fn validate_connect_request(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> { if !self.externally_brokered { return Ok(()); } if request.args().vpnc_script().is_some() { return Err("macOS does not support custom VPN scripts"); } 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 { 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(archive: &mut Archive, dir: &Path) -> Result { 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 { 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 = gpapi::utils::checksum::file_sha256(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, true, ); 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_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_rejects_script_overrides() { let dispatcher = RequestDispatcher::new( crate::vpn_task::LifecycleHandle::for_tests(), Arc::new(AtomicBool::new(false)), Arc::new(Redaction::new()), false, true, ); 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 embedded = test_request(info.clone()); assert_eq!(dispatcher.validate_connect_request(&embedded), Ok(())); for script in [ "/app/Contents/Resources/Scripts/vpnc-script", "/tmp/custom-vpnc-script", "echo untrusted", "", ] { let custom = test_request(info.clone()).with_vpnc_script(Some(script.to_string())); assert_eq!( dispatcher.validate_connect_request(&custom), Err("macOS does not support custom VPN scripts") ); } let custom = test_request(info).with_hip_source(gpapi::hip::HipSource::UserScript { path: "/tmp/hip.sh".into(), }); assert_eq!( dispatcher.validate_connect_request(&custom), Err("macOS does not support custom HIP scripts") ); } #[test] #[ignore = "requires GP_TEST_GUI_BINARY pointing to a built gpgui"] fn installs_single_gui_binary_for_fresh_and_upgrade_downloads() { let binary = std::fs::read(std::env::var("GP_TEST_GUI_BINARY").expect("GP_TEST_GUI_BINARY")).unwrap(); let archive = compressed_gui_archive(&binary); let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap(); let temporary = tempfile::tempdir().unwrap(); let output = std::env::var_os("GP_TEST_GUI_INSTALL_DIR") .map(std::path::PathBuf::from) .unwrap_or_else(|| temporary.path().to_owned()); std::fs::create_dir_all(&output).unwrap(); std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755)).unwrap(); let target = output.join("gpclient/gpgui"); for upgrade in [false, true] { if upgrade { std::fs::write(&target, b"old GUI").unwrap(); } install_gui_at(archive.path(), &checksum, &target).unwrap(); assert_eq!(std::fs::read_dir(target.parent().unwrap()).unwrap().count(), 1); assert_eq!(std::fs::read(&target).unwrap(), binary); let result = std::process::Command::new(&target).arg("--version").output().unwrap(); assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); assert!(String::from_utf8_lossy(&result.stdout).contains(env!("CARGO_PKG_VERSION"))); } } }