mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-21 15:26:13 -05:00
feat: add device anchor persistence and serialize vpn lifecycle
- Implement Unix device anchor discovery, root-owned persistence under /var/lib/gp, and credential delivery in gpapi and gpservice. - Introduce LifecycleHandle to serialize VPN connect/disconnect lifecycles and ensure cancellation cannot be superseded by late connect events.
This commit is contained in:
13 files changed
+866
-217
No files matched your search
Generated
+26
-2
@@ -1850,6 +1850,7 @@ dependencies = [
|
|||||||
"humantime",
|
"humantime",
|
||||||
"log",
|
"log",
|
||||||
"log-reload",
|
"log-reload",
|
||||||
|
"mac_address",
|
||||||
"md5",
|
"md5",
|
||||||
"netdev",
|
"netdev",
|
||||||
"openssl",
|
"openssl",
|
||||||
@@ -1963,7 +1964,7 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"gpapi",
|
"gpapi",
|
||||||
"log",
|
"log",
|
||||||
"nix",
|
"nix 0.31.3",
|
||||||
"openconnect",
|
"openconnect",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -2770,6 +2771,16 @@ version = "0.3.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f"
|
checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mac_address"
|
||||||
|
version = "1.1.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303"
|
||||||
|
dependencies = [
|
||||||
|
"nix 0.29.0",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "markup5ever"
|
name = "markup5ever"
|
||||||
version = "0.38.0"
|
version = "0.38.0"
|
||||||
@@ -2964,6 +2975,19 @@ version = "1.0.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
|
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nix"
|
||||||
|
version = "0.29.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.0",
|
||||||
|
"cfg-if",
|
||||||
|
"cfg_aliases",
|
||||||
|
"libc",
|
||||||
|
"memoffset",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nix"
|
name = "nix"
|
||||||
version = "0.31.3"
|
version = "0.31.3"
|
||||||
@@ -3365,7 +3389,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"android_system_properties",
|
"android_system_properties",
|
||||||
"log",
|
"log",
|
||||||
"nix",
|
"nix 0.31.3",
|
||||||
"objc2",
|
"objc2",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"objc2-ui-kit",
|
"objc2-ui-kit",
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ use gpapi::logger;
|
|||||||
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,
|
process::gui_launcher::GuiLauncher,
|
||||||
service::{request::WsRequest, vpn_state::VpnState},
|
service::vpn_state::VpnState,
|
||||||
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
|
||||||
};
|
};
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
@@ -95,9 +95,7 @@ impl Cli {
|
|||||||
bail!("Another instance of the service is already running");
|
bail!("Another instance of the service is already running");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Channel for sending requests to the VPN task
|
// Channel for receiving VPN state from the lifecycle actor
|
||||||
let (ws_req_tx, ws_req_rx) = mpsc::channel::<WsRequest>(32);
|
|
||||||
// Channel for receiving the VPN state from the VPN task
|
|
||||||
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
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()));
|
||||||
@@ -113,15 +111,14 @@ impl Cli {
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, trusted_csd_uid);
|
||||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||||
ws_req_tx.clone(),
|
lifecycle.clone(),
|
||||||
Arc::clone(&gui_restart_requested),
|
Arc::clone(&gui_restart_requested),
|
||||||
Arc::clone(&redaction),
|
Arc::clone(&redaction),
|
||||||
!externally_brokered,
|
!externally_brokered,
|
||||||
brokered_scripts_dir,
|
brokered_scripts_dir,
|
||||||
));
|
));
|
||||||
|
|
||||||
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx, externally_brokered, trusted_csd_uid);
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
let idle_vpn_state_rx = vpn_state_rx.clone();
|
let idle_vpn_state_rx = vpn_state_rx.clone();
|
||||||
let ws_server = WsServer::new(
|
let ws_server = WsServer::new(
|
||||||
@@ -179,10 +176,10 @@ impl Cli {
|
|||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
let vpn_ctx = vpn_task.context();
|
let lifecycle = lifecycle.clone();
|
||||||
let ws_ctx = ws_server.context();
|
let ws_ctx = ws_server.context();
|
||||||
|
|
||||||
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
|
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
|
||||||
}
|
}
|
||||||
|
|
||||||
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 });
|
||||||
@@ -324,12 +321,12 @@ mod signals {
|
|||||||
|
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use crate::vpn_task::VpnTaskContext;
|
use crate::vpn_task::LifecycleHandle;
|
||||||
use crate::ws_server::WsServerContext;
|
use crate::ws_server::WsServerContext;
|
||||||
|
|
||||||
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
|
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 gpapi::service::event::WsEvent;
|
||||||
use tokio::signal::unix::{Signal, SignalKind, signal};
|
use tokio::signal::unix::{Signal, SignalKind, signal};
|
||||||
|
|
||||||
@@ -349,7 +346,7 @@ mod signals {
|
|||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = user_sig1.recv() => {
|
_ = user_sig1.recv() => {
|
||||||
info!("Received SIGUSR1 signal");
|
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
|
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
//! 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, gpapi::device_anchor::collect_unix)
|
||||||
|
.context("cannot resolve persistent GUI device anchor")
|
||||||
|
}
|
||||||
|
|
||||||
|
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::LinuxMac | AnchorSource::LinuxRandom),
|
||||||
|
"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::LinuxMac | AnchorSource::LinuxRandom),
|
||||||
|
"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::LinuxMac,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ mod cli;
|
|||||||
mod credential_lease;
|
mod credential_lease;
|
||||||
#[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)))]
|
||||||
|
mod device_anchor;
|
||||||
mod handlers;
|
mod handlers;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
mod macos_broker;
|
mod macos_broker;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use std::{
|
|||||||
use common::binary_paths;
|
use common::binary_paths;
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
service::{
|
service::{
|
||||||
request::{UpdateGuiRequest, WsRequest},
|
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||||
transport::{ServiceErrorCode, ServiceResult},
|
transport::{ServiceErrorCode, ServiceResult},
|
||||||
},
|
},
|
||||||
utils::{checksum::verify_checksum, redact::Redaction},
|
utils::{checksum::verify_checksum, redact::Redaction},
|
||||||
@@ -17,7 +17,7 @@ use gpapi::{
|
|||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use tar::Archive;
|
use tar::Archive;
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
use tokio::sync::{Mutex, mpsc};
|
use tokio::sync::Mutex;
|
||||||
use xz2::read::XzDecoder;
|
use xz2::read::XzDecoder;
|
||||||
|
|
||||||
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
const MAX_GUI_ARCHIVE_SIZE: u64 = 256 * 1024 * 1024;
|
||||||
@@ -25,7 +25,7 @@ const MAX_GUI_ARCHIVE_CONTENT_SIZE: u64 = 512 * 1024 * 1024;
|
|||||||
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
const MAX_GUI_BINARY_SIZE: u64 = 256 * 1024 * 1024;
|
||||||
|
|
||||||
pub struct RequestDispatcher {
|
pub struct RequestDispatcher {
|
||||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
gui_restart_requested: Arc<AtomicBool>,
|
||||||
redaction: Arc<Redaction>,
|
redaction: Arc<Redaction>,
|
||||||
install_lock: Mutex<()>,
|
install_lock: Mutex<()>,
|
||||||
@@ -35,14 +35,14 @@ pub struct RequestDispatcher {
|
|||||||
|
|
||||||
impl RequestDispatcher {
|
impl RequestDispatcher {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
ws_req_tx: mpsc::Sender<WsRequest>,
|
lifecycle: crate::vpn_task::LifecycleHandle,
|
||||||
gui_restart_requested: Arc<AtomicBool>,
|
gui_restart_requested: Arc<AtomicBool>,
|
||||||
redaction: Arc<Redaction>,
|
redaction: Arc<Redaction>,
|
||||||
gui_management_enabled: bool,
|
gui_management_enabled: bool,
|
||||||
brokered_scripts_dir: Option<std::path::PathBuf>,
|
brokered_scripts_dir: Option<std::path::PathBuf>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
ws_req_tx,
|
lifecycle,
|
||||||
gui_restart_requested,
|
gui_restart_requested,
|
||||||
redaction,
|
redaction,
|
||||||
install_lock: Mutex::new(()),
|
install_lock: Mutex::new(()),
|
||||||
@@ -51,7 +51,35 @@ impl RequestDispatcher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn dispatch_lifecycle(&self, request: WsRequest) -> Result<WsRequest, ServiceResult> {
|
||||||
|
match request {
|
||||||
|
WsRequest::Connect(request) => {
|
||||||
|
if let Err(message) = self.validate_connect_paths(&request) {
|
||||||
|
return Err(ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message));
|
||||||
|
}
|
||||||
|
if let Err(err) = self
|
||||||
|
.redaction
|
||||||
|
.add_values(&[request.gateway().server(), request.args().cookie()])
|
||||||
|
{
|
||||||
|
warn!("Failed to update log redaction: {err}");
|
||||||
|
return Err(ServiceResult::rejected(
|
||||||
|
ServiceErrorCode::Internal,
|
||||||
|
"Request could not be accepted",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(self.lifecycle.submit_connect(*request))
|
||||||
|
}
|
||||||
|
WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()),
|
||||||
|
request => Ok(request),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
pub async fn dispatch(&self, request: WsRequest) -> ServiceResult {
|
||||||
|
let request = match self.dispatch_lifecycle(request) {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(result) => return result,
|
||||||
|
};
|
||||||
|
|
||||||
match request {
|
match request {
|
||||||
WsRequest::RestartGui => {
|
WsRequest::RestartGui => {
|
||||||
if !self.gui_management_enabled {
|
if !self.gui_management_enabled {
|
||||||
@@ -85,30 +113,15 @@ impl RequestDispatcher {
|
|||||||
ServiceResult::VpncScriptMetadata(None)
|
ServiceResult::VpncScriptMetadata(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
request => {
|
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
|
||||||
if let WsRequest::Connect(ref connect) = request {
|
let level = level.parse().unwrap_or(log::Level::Info);
|
||||||
if let Err(message) = self.validate_connect_paths(connect) {
|
info!("Updating log level to: {level}");
|
||||||
return ServiceResult::rejected(ServiceErrorCode::InvalidRequest, message);
|
if let Err(err) = gpapi::logger::set_max_level(level) {
|
||||||
}
|
warn!("Failed to update log level: {err}");
|
||||||
if let Err(err) = self
|
|
||||||
.redaction
|
|
||||||
.add_values(&[connect.gateway().server(), connect.args().cookie()])
|
|
||||||
{
|
|
||||||
warn!("Failed to update log redaction: {err}");
|
|
||||||
return ServiceResult::rejected(ServiceErrorCode::Internal, "Request could not be accepted");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match self.ws_req_tx.try_send(request) {
|
|
||||||
Ok(()) => ServiceResult::Accepted,
|
|
||||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::Busy, "Service request queue is full")
|
|
||||||
}
|
|
||||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
|
||||||
ServiceResult::rejected(ServiceErrorCode::Internal, "VPN task is unavailable")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
ServiceResult::Accepted
|
||||||
}
|
}
|
||||||
|
WsRequest::Connect(_) | WsRequest::Disconnect(_) => unreachable!("lifecycle request was already dispatched"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,9 +392,8 @@ mod tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
async fn brokered_mode_rejects_gui_management_and_root_readable_identity_paths() {
|
||||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
|
||||||
let dispatcher = RequestDispatcher::new(
|
let dispatcher = RequestDispatcher::new(
|
||||||
request_tx,
|
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||||
Arc::new(AtomicBool::new(false)),
|
Arc::new(AtomicBool::new(false)),
|
||||||
Arc::new(Redaction::new()),
|
Arc::new(Redaction::new()),
|
||||||
false,
|
false,
|
||||||
@@ -406,9 +418,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn brokered_mode_accepts_only_resource_script_paths() {
|
fn brokered_mode_accepts_only_resource_script_paths() {
|
||||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
|
||||||
let dispatcher = RequestDispatcher::new(
|
let dispatcher = RequestDispatcher::new(
|
||||||
request_tx,
|
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||||
Arc::new(AtomicBool::new(false)),
|
Arc::new(AtomicBool::new(false)),
|
||||||
Arc::new(Redaction::new()),
|
Arc::new(Redaction::new()),
|
||||||
false,
|
false,
|
||||||
|
|||||||
@@ -90,9 +90,19 @@ impl SessionRegistry {
|
|||||||
return Err(SessionError::TooManyPending);
|
return Err(SessionError::TooManyPending);
|
||||||
}
|
}
|
||||||
|
|
||||||
let credential = Arc::new(
|
let credential =
|
||||||
SessionCredential::generate(self.service_instance_id, product_version).map_err(|_| SessionError::Unavailable)?,
|
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(
|
sessions.insert(
|
||||||
credential.session_id(),
|
credential.session_id(),
|
||||||
SessionRecord {
|
SessionRecord {
|
||||||
|
|||||||
+514
-161
@@ -1,65 +1,330 @@
|
|||||||
use std::{io::Write, os::unix::fs::PermissionsExt, sync::Arc, thread};
|
use std::{
|
||||||
|
io::Write,
|
||||||
|
os::unix::fs::PermissionsExt,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
},
|
||||||
|
thread,
|
||||||
|
};
|
||||||
|
|
||||||
use gpapi::{
|
use gpapi::{
|
||||||
logger,
|
|
||||||
service::{
|
service::{
|
||||||
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, UpdateLogLevelRequest, WsRequest},
|
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA},
|
||||||
vpn_state::{ConnectedInfo, VpnState},
|
transport::{ServiceErrorCode, ServiceResult},
|
||||||
|
vpn_state::{ConnectInfo, ConnectedInfo, VpnState},
|
||||||
},
|
},
|
||||||
session::{SessionInfo, SessionWarning},
|
session::{SessionInfo, SessionWarning},
|
||||||
};
|
};
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
use openconnect::Vpn;
|
use openconnect::{Vpn, VpnSessionInfo};
|
||||||
use tokio::sync::{RwLock, mpsc, oneshot, watch};
|
use tokio::sync::{Notify, mpsc, watch};
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
pub(crate) struct VpnTaskContext {
|
#[derive(Clone)]
|
||||||
vpn_handle: Arc<RwLock<Option<Vpn>>>,
|
pub(crate) struct LifecycleHandle {
|
||||||
vpn_state_tx: Arc<watch::Sender<VpnState>>,
|
events: mpsc::Sender<LifecycleEvent>,
|
||||||
disconnect_rx: RwLock<Option<oneshot::Receiver<()>>>,
|
admissions: Arc<Mutex<Admissions>>,
|
||||||
brokered_macos: bool,
|
|
||||||
trusted_csd_uid: Option<u32>,
|
|
||||||
identity_files: Arc<RwLock<Vec<tempfile::NamedTempFile>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VpnTaskContext {
|
impl LifecycleHandle {
|
||||||
pub fn new(vpn_state_tx: watch::Sender<VpnState>, brokered_macos: bool, trusted_csd_uid: Option<u32>) -> Self {
|
pub fn submit_connect(&self, request: ConnectRequest) -> ServiceResult {
|
||||||
Self {
|
let attempt = {
|
||||||
vpn_handle: Default::default(),
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
vpn_state_tx: Arc::new(vpn_state_tx),
|
if admissions.current.is_some() {
|
||||||
disconnect_rx: Default::default(),
|
return ServiceResult::rejected(ServiceErrorCode::Busy, "A VPN connection is already in progress");
|
||||||
brokered_macos,
|
}
|
||||||
trusted_csd_uid,
|
let attempt = admissions.next_attempt;
|
||||||
identity_files: Default::default(),
|
admissions.next_attempt += 1;
|
||||||
|
admissions.current = Some(Admission {
|
||||||
|
attempt,
|
||||||
|
phase: AdmissionPhase::Pending,
|
||||||
|
stop_requested: false,
|
||||||
|
completion: Arc::new(AttemptCompletion::default()),
|
||||||
|
});
|
||||||
|
attempt
|
||||||
|
};
|
||||||
|
|
||||||
|
match self.events.try_send(LifecycleEvent::Start { attempt, request }) {
|
||||||
|
Ok(()) => ServiceResult::Accepted,
|
||||||
|
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||||
|
self.clear_attempt(attempt);
|
||||||
|
ServiceResult::rejected(ServiceErrorCode::Busy, "VPN lifecycle queue is full")
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||||
|
self.clear_attempt(attempt);
|
||||||
|
ServiceResult::rejected(ServiceErrorCode::Internal, "VPN task is unavailable")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn connect(&self, req: ConnectRequest) {
|
pub fn request_disconnect(&self) -> ServiceResult {
|
||||||
let vpn_state = self.vpn_state_tx.borrow().clone();
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
if !matches!(vpn_state, VpnState::Disconnected) {
|
let Some(admission) = admissions.current.as_mut() else {
|
||||||
info!("VPN is not disconnected, ignore the request");
|
return ServiceResult::Accepted;
|
||||||
|
};
|
||||||
|
if admission.stop_requested {
|
||||||
|
return ServiceResult::Accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.events.try_send(LifecycleEvent::Stop {
|
||||||
|
attempt: admission.attempt,
|
||||||
|
}) {
|
||||||
|
Ok(()) => {
|
||||||
|
admission.stop_requested = true;
|
||||||
|
admission.phase = AdmissionPhase::Stopping;
|
||||||
|
ServiceResult::Accepted
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||||
|
ServiceResult::rejected(ServiceErrorCode::Busy, "VPN lifecycle queue is full")
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||||
|
ServiceResult::rejected(ServiceErrorCode::Internal, "VPN task is unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn disconnect_and_wait(&self) -> bool {
|
||||||
|
let completion = {
|
||||||
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
|
let Some(admission) = admissions.current.as_mut() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if !admission.stop_requested {
|
||||||
|
if self
|
||||||
|
.events
|
||||||
|
.try_send(LifecycleEvent::Stop {
|
||||||
|
attempt: admission.attempt,
|
||||||
|
})
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
admission.stop_requested = true;
|
||||||
|
admission.phase = AdmissionPhase::Stopping;
|
||||||
|
}
|
||||||
|
Arc::clone(&admission.completion)
|
||||||
|
};
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let notified = completion.notify.notified();
|
||||||
|
if completion.completed.load(Ordering::Acquire) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
notified.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn has_attempt(&self, attempt: u64) -> bool {
|
||||||
|
self
|
||||||
|
.admissions
|
||||||
|
.lock()
|
||||||
|
.expect("VPN lifecycle admissions mutex poisoned")
|
||||||
|
.current
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|admission| admission.attempt == attempt)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_stop_requested(&self, attempt: u64) -> bool {
|
||||||
|
self
|
||||||
|
.admissions
|
||||||
|
.lock()
|
||||||
|
.expect("VPN lifecycle admissions mutex poisoned")
|
||||||
|
.current
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|admission| admission.attempt == attempt && admission.stop_requested)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn activate_attempt(&self, attempt: u64) -> bool {
|
||||||
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
|
let Some(admission) = admissions.current.as_mut() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if admission.attempt != attempt || admission.stop_requested || admission.phase != AdmissionPhase::Pending {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
admission.phase = AdmissionPhase::Active;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_attempt(&self, attempt: u64) {
|
||||||
|
let completion = {
|
||||||
|
let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned");
|
||||||
|
let Some(admission) = admissions.current.as_ref() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if admission.attempt != attempt {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let completion = Arc::clone(&admission.completion);
|
||||||
|
admissions.current = None;
|
||||||
|
completion
|
||||||
|
};
|
||||||
|
completion.completed.store(true, Ordering::Release);
|
||||||
|
completion.notify.notify_waiters();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn for_tests() -> Self {
|
||||||
|
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
lifecycle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Admissions {
|
||||||
|
next_attempt: u64,
|
||||||
|
current: Option<Admission>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Admission {
|
||||||
|
attempt: u64,
|
||||||
|
phase: AdmissionPhase,
|
||||||
|
stop_requested: bool,
|
||||||
|
completion: Arc<AttemptCompletion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct AttemptCompletion {
|
||||||
|
completed: AtomicBool,
|
||||||
|
notify: Notify,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||||
|
enum AdmissionPhase {
|
||||||
|
Pending,
|
||||||
|
Active,
|
||||||
|
Stopping,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum LifecycleEvent {
|
||||||
|
Start { attempt: u64, request: ConnectRequest },
|
||||||
|
Stop { attempt: u64 },
|
||||||
|
Established { attempt: u64, session: VpnSessionInfo },
|
||||||
|
Ended { attempt: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ActiveAttempt {
|
||||||
|
attempt: u64,
|
||||||
|
vpn: Arc<Vpn>,
|
||||||
|
info: ConnectInfo,
|
||||||
|
allow_extend_session: bool,
|
||||||
|
_identity_files: Vec<tempfile::NamedTempFile>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct VpnTask {
|
||||||
|
events: mpsc::Receiver<LifecycleEvent>,
|
||||||
|
lifecycle: LifecycleHandle,
|
||||||
|
vpn_state_tx: watch::Sender<VpnState>,
|
||||||
|
brokered_macos: bool,
|
||||||
|
trusted_csd_uid: Option<u32>,
|
||||||
|
active: Option<ActiveAttempt>,
|
||||||
|
cancel_token: CancellationToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VpnTask {
|
||||||
|
pub fn new(
|
||||||
|
vpn_state_tx: watch::Sender<VpnState>,
|
||||||
|
brokered_macos: bool,
|
||||||
|
trusted_csd_uid: Option<u32>,
|
||||||
|
) -> (Self, LifecycleHandle) {
|
||||||
|
let (events_tx, events) = mpsc::channel(4);
|
||||||
|
let lifecycle = LifecycleHandle {
|
||||||
|
events: events_tx,
|
||||||
|
admissions: Arc::new(Mutex::new(Admissions::default())),
|
||||||
|
};
|
||||||
|
let task = Self {
|
||||||
|
events,
|
||||||
|
lifecycle: lifecycle.clone(),
|
||||||
|
vpn_state_tx,
|
||||||
|
brokered_macos,
|
||||||
|
trusted_csd_uid,
|
||||||
|
active: None,
|
||||||
|
cancel_token: CancellationToken::new(),
|
||||||
|
};
|
||||||
|
(task, lifecycle)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cancel_token(&self) -> CancellationToken {
|
||||||
|
self.cancel_token.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start(&mut self, server_cancel_token: CancellationToken) {
|
||||||
|
let cancel_token = self.cancel_token.clone();
|
||||||
|
let mut shutting_down = false;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if shutting_down {
|
||||||
|
if self.active.is_none() && !self.has_admission() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Some(event) = self.events.recv().await else { break };
|
||||||
|
self.handle_event(event);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
event = self.events.recv() => {
|
||||||
|
let Some(event) = event else { break };
|
||||||
|
self.handle_event(event);
|
||||||
|
}
|
||||||
|
_ = cancel_token.cancelled() => {
|
||||||
|
info!("VPN task cancelled");
|
||||||
|
shutting_down = true;
|
||||||
|
self.lifecycle.request_disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server_cancel_token.cancel();
|
||||||
|
info!("VPN task stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_admission(&self) -> bool {
|
||||||
|
self
|
||||||
|
.lifecycle
|
||||||
|
.admissions
|
||||||
|
.lock()
|
||||||
|
.expect("VPN lifecycle admissions mutex poisoned")
|
||||||
|
.current
|
||||||
|
.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_event(&mut self, event: LifecycleEvent) {
|
||||||
|
match event {
|
||||||
|
LifecycleEvent::Start { attempt, request } => self.start_attempt(attempt, request),
|
||||||
|
LifecycleEvent::Stop { attempt } => self.stop_attempt(attempt),
|
||||||
|
LifecycleEvent::Established { attempt, session } => self.establish_attempt(attempt, session),
|
||||||
|
LifecycleEvent::Ended { attempt } => self.end_attempt(attempt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_attempt(&mut self, attempt: u64, request: ConnectRequest) {
|
||||||
|
if !self.lifecycle.activate_attempt(attempt) {
|
||||||
|
self.finish_attempt(attempt);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let vpn_state_tx = self.vpn_state_tx.clone();
|
let info = request.info().clone();
|
||||||
let info = req.info().clone();
|
let args = request.args();
|
||||||
let vpn_handle = Arc::clone(&self.vpn_handle);
|
|
||||||
let args = req.args();
|
|
||||||
let identity = match prepare_identity(args, self.brokered_macos) {
|
let identity = match prepare_identity(args, self.brokered_macos) {
|
||||||
Ok(identity) => identity,
|
Ok(identity) => identity,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Failed to prepare client identity: {err}");
|
warn!("Failed to prepare client identity: {err}");
|
||||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
self.finish_attempt(attempt);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let allow_extend_session = args.allow_extend_session();
|
let allow_extend_session = args.allow_extend_session();
|
||||||
let vpn_builder = match crate::vpn_script::builder(req.gateway().server(), args.cookie(), args) {
|
let vpn_builder = match crate::vpn_script::builder(request.gateway().server(), args.cookie(), args) {
|
||||||
Ok(builder) => builder,
|
Ok(builder) => builder,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Failed to select the VPNC script: {err}");
|
warn!("Failed to select the VPNC script: {err}");
|
||||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
self.finish_attempt(attempt);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -67,7 +332,7 @@ impl VpnTaskContext {
|
|||||||
Ok(uid) => uid,
|
Ok(uid) => uid,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Failed to select the HIP script user: {err}");
|
warn!("Failed to select the HIP script user: {err}");
|
||||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
self.finish_attempt(attempt);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -92,128 +357,120 @@ impl VpnTaskContext {
|
|||||||
.no_xmlpost(args.no_xmlpost())
|
.no_xmlpost(args.no_xmlpost())
|
||||||
.build()
|
.build()
|
||||||
{
|
{
|
||||||
Ok(vpn) => vpn,
|
Ok(vpn) => Arc::new(vpn),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
warn!("Failed to create VPN: {}", err);
|
warn!("Failed to create VPN: {err}");
|
||||||
vpn_state_tx.send(VpnState::Disconnected).ok();
|
self.finish_attempt(attempt);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Save the VPN handle
|
if self.lifecycle.is_stop_requested(attempt) {
|
||||||
vpn_handle.write().await.replace(vpn);
|
self.finish_attempt(attempt);
|
||||||
*self.identity_files.write().await = identity.files;
|
return;
|
||||||
let connect_info = Box::new(info.clone());
|
}
|
||||||
vpn_state_tx.send(VpnState::Connecting(connect_info)).ok();
|
|
||||||
|
|
||||||
let (disconnect_tx, disconnect_rx) = oneshot::channel::<()>();
|
let events = self.lifecycle.events.clone();
|
||||||
self.disconnect_rx.write().await.replace(disconnect_rx);
|
let started = {
|
||||||
let identity_files = Arc::clone(&self.identity_files);
|
let admissions = self
|
||||||
|
.lifecycle
|
||||||
// Spawn a new thread to process the VPN connection, cannot use tokio::spawn here.
|
.admissions
|
||||||
// Otherwise, it will block the tokio runtime and cannot send the VPN state to the channel
|
.lock()
|
||||||
thread::spawn(move || {
|
.expect("VPN lifecycle admissions mutex poisoned");
|
||||||
let vpn_state_tx_clone = vpn_state_tx.clone();
|
let can_start = admissions.current.as_ref().is_some_and(|admission| {
|
||||||
|
admission.attempt == attempt && admission.phase == AdmissionPhase::Active && !admission.stop_requested
|
||||||
vpn_handle.blocking_read().as_ref().map(|vpn| {
|
|
||||||
vpn.connect(move |vpn_session_info| {
|
|
||||||
let session_info = SessionInfo::from_vpn_session_fields(
|
|
||||||
vpn_session_info.lifetime_secs,
|
|
||||||
vpn_session_info.user_expires,
|
|
||||||
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
|
|
||||||
prior_secs: warning.prior_secs,
|
|
||||||
message: warning.message,
|
|
||||||
}),
|
|
||||||
allow_extend_session,
|
|
||||||
);
|
|
||||||
info!("VPN session info: {}", session_info.log_summary());
|
|
||||||
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
|
|
||||||
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
|
if !can_start {
|
||||||
// Notify the VPN is disconnected
|
false
|
||||||
vpn_state_tx_clone.send(VpnState::Disconnected).ok();
|
} else {
|
||||||
// Remove the VPN handle
|
self.active = Some(ActiveAttempt {
|
||||||
vpn_handle.blocking_write().take();
|
attempt,
|
||||||
identity_files.blocking_write().clear();
|
vpn: Arc::clone(&vpn),
|
||||||
|
info: info.clone(),
|
||||||
disconnect_tx.send(()).ok();
|
allow_extend_session,
|
||||||
});
|
_identity_files: identity.files,
|
||||||
}
|
});
|
||||||
|
self.send_state(VpnState::Connecting(Box::new(info)));
|
||||||
pub async fn disconnect(&self) -> bool {
|
thread::spawn(move || {
|
||||||
if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() {
|
let established_events = events.clone();
|
||||||
info!("Disconnecting VPN...");
|
vpn.connect(move |vpn_session_info| {
|
||||||
if let Some(vpn) = self.vpn_handle.read().await.as_ref() {
|
let _ = established_events.blocking_send(LifecycleEvent::Established {
|
||||||
info!("VPN is connected, start disconnecting...");
|
attempt,
|
||||||
self.vpn_state_tx.send(VpnState::Disconnecting).ok();
|
session: vpn_session_info,
|
||||||
vpn.disconnect()
|
});
|
||||||
|
});
|
||||||
|
let _ = events.blocking_send(LifecycleEvent::Ended { attempt });
|
||||||
|
});
|
||||||
|
true
|
||||||
}
|
}
|
||||||
// Wait for the VPN to be disconnected
|
};
|
||||||
disconnect_rx.await.ok();
|
if !started {
|
||||||
info!("VPN disconnected");
|
self.finish_attempt(attempt);
|
||||||
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
info!("VPN is not connected, skip disconnect");
|
|
||||||
self.vpn_state_tx.send(VpnState::Disconnected).ok();
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct VpnTask {
|
|
||||||
ws_req_rx: mpsc::Receiver<WsRequest>,
|
|
||||||
ctx: Arc<VpnTaskContext>,
|
|
||||||
cancel_token: CancellationToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VpnTask {
|
|
||||||
pub fn new(
|
|
||||||
ws_req_rx: mpsc::Receiver<WsRequest>,
|
|
||||||
vpn_state_tx: watch::Sender<VpnState>,
|
|
||||||
brokered_macos: bool,
|
|
||||||
trusted_csd_uid: Option<u32>,
|
|
||||||
) -> Self {
|
|
||||||
let ctx = Arc::new(VpnTaskContext::new(vpn_state_tx, brokered_macos, trusted_csd_uid));
|
|
||||||
let cancel_token = CancellationToken::new();
|
|
||||||
|
|
||||||
Self {
|
|
||||||
ws_req_rx,
|
|
||||||
ctx,
|
|
||||||
cancel_token,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cancel_token(&self) -> CancellationToken {
|
fn stop_attempt(&mut self, attempt: u64) {
|
||||||
self.cancel_token.clone()
|
let Some(active) = self.active.as_ref() else {
|
||||||
}
|
return;
|
||||||
|
};
|
||||||
pub async fn start(&mut self, server_cancel_token: CancellationToken) {
|
if active.attempt != attempt || !self.lifecycle.is_stop_requested(attempt) {
|
||||||
let cancel_token = self.cancel_token.clone();
|
return;
|
||||||
|
|
||||||
tokio::select! {
|
|
||||||
_ = self.recv() => {
|
|
||||||
info!("VPN task stopped");
|
|
||||||
}
|
|
||||||
_ = cancel_token.cancelled() => {
|
|
||||||
info!("VPN task cancelled");
|
|
||||||
self.ctx.disconnect().await;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
server_cancel_token.cancel();
|
info!("Disconnecting VPN...");
|
||||||
|
self.send_state(VpnState::Disconnecting);
|
||||||
|
active.vpn.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn context(&self) -> Arc<VpnTaskContext> {
|
fn establish_attempt(&mut self, attempt: u64, vpn_session_info: VpnSessionInfo) {
|
||||||
Arc::clone(&self.ctx)
|
let Some(active) = self.active.as_ref() else {
|
||||||
}
|
return;
|
||||||
|
};
|
||||||
async fn recv(&mut self) {
|
if active.attempt != attempt {
|
||||||
while let Some(req) = self.ws_req_rx.recv().await {
|
return;
|
||||||
tokio::spawn(process_ws_req(req, self.ctx.clone()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let session_info = SessionInfo::from_vpn_session_fields(
|
||||||
|
vpn_session_info.lifetime_secs,
|
||||||
|
vpn_session_info.user_expires,
|
||||||
|
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
|
||||||
|
prior_secs: warning.prior_secs,
|
||||||
|
message: warning.message,
|
||||||
|
}),
|
||||||
|
active.allow_extend_session,
|
||||||
|
);
|
||||||
|
self.publish_connected(attempt, active.info.clone(), session_info);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_connected(&self, attempt: u64, info: ConnectInfo, session_info: SessionInfo) {
|
||||||
|
let connected = VpnState::Connected(Box::new(ConnectedInfo::new(info, Some(session_info))));
|
||||||
|
let admissions = self
|
||||||
|
.lifecycle
|
||||||
|
.admissions
|
||||||
|
.lock()
|
||||||
|
.expect("VPN lifecycle admissions mutex poisoned");
|
||||||
|
if admissions.current.as_ref().is_some_and(|admission| {
|
||||||
|
admission.attempt == attempt && admission.phase == AdmissionPhase::Active && !admission.stop_requested
|
||||||
|
}) {
|
||||||
|
self.send_state(connected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end_attempt(&mut self, attempt: u64) {
|
||||||
|
if self.active.as_ref().is_none_or(|active| active.attempt != attempt) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.active = None;
|
||||||
|
self.finish_attempt(attempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_attempt(&self, attempt: u64) {
|
||||||
|
self.send_state(VpnState::Disconnected);
|
||||||
|
self.lifecycle.clear_attempt(attempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_state(&self, state: VpnState) {
|
||||||
|
let _ = self.vpn_state_tx.send(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,31 +531,127 @@ fn write_identity_file(
|
|||||||
Ok(Some(path))
|
Ok(Some(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
|
|
||||||
match req {
|
|
||||||
WsRequest::Connect(req) => {
|
|
||||||
ctx.connect(*req).await;
|
|
||||||
}
|
|
||||||
WsRequest::Disconnect(_) => {
|
|
||||||
ctx.disconnect().await;
|
|
||||||
}
|
|
||||||
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
|
|
||||||
let level = level.parse().unwrap_or(log::Level::Info);
|
|
||||||
info!("Updating log level to: {}", level);
|
|
||||||
if let Err(err) = logger::set_max_level(level) {
|
|
||||||
warn!("Failed to update log level: {}", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WsRequest::RestartGui | WsRequest::UpdateGui(_) | WsRequest::GetVpncScriptMetadata => {
|
|
||||||
warn!("Non-VPN request reached the VPN task");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disconnect_before_start_discards_the_pending_attempt() {
|
||||||
|
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
let request = ConnectRequest::new(
|
||||||
|
ConnectInfo::new(
|
||||||
|
"portal.example.com".to_string(),
|
||||||
|
gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()),
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
"cookie".to_string(),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted));
|
||||||
|
assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted));
|
||||||
|
let start = task.events.try_recv().unwrap();
|
||||||
|
task.handle_event(start);
|
||||||
|
|
||||||
|
assert!(!lifecycle.has_attempt(0));
|
||||||
|
assert!(task.active.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn late_established_event_is_ignored_after_disconnect_is_accepted() {
|
||||||
|
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let state_rx = vpn_state_rx.clone();
|
||||||
|
let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
let info = ConnectInfo::new(
|
||||||
|
"portal.example.com".to_string(),
|
||||||
|
gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()),
|
||||||
|
vec![],
|
||||||
|
);
|
||||||
|
let request = ConnectRequest::new(info.clone(), "cookie".to_string());
|
||||||
|
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted));
|
||||||
|
assert!(lifecycle.activate_attempt(0));
|
||||||
|
assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted));
|
||||||
|
task.publish_connected(0, info, SessionInfo::default());
|
||||||
|
|
||||||
|
assert!(matches!(*state_rx.borrow(), VpnState::Disconnected));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disconnect_waiter_completes_for_its_attempt_before_a_later_connect() {
|
||||||
|
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
let request = || {
|
||||||
|
ConnectRequest::new(
|
||||||
|
ConnectInfo::new(
|
||||||
|
"portal.example.com".to_string(),
|
||||||
|
gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()),
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
"cookie".to_string(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted));
|
||||||
|
let waiter_lifecycle = lifecycle.clone();
|
||||||
|
let waiter = tokio::spawn(async move { waiter_lifecycle.disconnect_and_wait().await });
|
||||||
|
while !lifecycle.is_stop_requested(0) {
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
task.finish_attempt(0);
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted));
|
||||||
|
assert!(
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(1), waiter)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_disconnects_enqueue_one_stop_for_an_attempt() {
|
||||||
|
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
let request = ConnectRequest::new(
|
||||||
|
ConnectInfo::new(
|
||||||
|
"portal.example.com".to_string(),
|
||||||
|
gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()),
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
"cookie".to_string(),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted));
|
||||||
|
assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted));
|
||||||
|
assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted));
|
||||||
|
assert!(matches!(task.events.try_recv(), Ok(LifecycleEvent::Start { .. })));
|
||||||
|
assert!(matches!(task.events.try_recv(), Ok(LifecycleEvent::Stop { .. })));
|
||||||
|
assert!(matches!(task.events.try_recv(), Err(mpsc::error::TryRecvError::Empty)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn second_connect_is_rejected_while_an_attempt_is_admitted() {
|
||||||
|
let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected);
|
||||||
|
let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, None);
|
||||||
|
let request = || {
|
||||||
|
ConnectRequest::new(
|
||||||
|
ConnectInfo::new(
|
||||||
|
"portal.example.com".to_string(),
|
||||||
|
gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()),
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
"cookie".to_string(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted));
|
||||||
|
assert!(matches!(
|
||||||
|
lifecycle.submit_connect(request()),
|
||||||
|
ServiceResult::Rejected(rejection) if rejection.code() == ServiceErrorCode::Busy
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn trusted_csd_uid_overrides_request_uid() {
|
fn trusted_csd_uid_overrides_request_uid() {
|
||||||
assert_eq!(resolve_csd_uid(Some(1000), 0, true).unwrap(), 1000);
|
assert_eq!(resolve_csd_uid(Some(1000), 0, true).unwrap(), 1000);
|
||||||
|
|||||||
@@ -324,6 +324,16 @@ async fn handle_client_message(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let dispatcher = ctx.dispatcher();
|
let dispatcher = ctx.dispatcher();
|
||||||
|
let request = match dispatcher.dispatch_lifecycle(request) {
|
||||||
|
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();
|
let control = control.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let result = dispatcher.dispatch(request).await;
|
let result = dispatcher.dispatch(request).await;
|
||||||
@@ -396,7 +406,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
utils::redact::Redaction,
|
utils::redact::Redaction,
|
||||||
};
|
};
|
||||||
use tokio::sync::{mpsc, watch};
|
use tokio::sync::watch;
|
||||||
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientFrame};
|
use tokio_tungstenite::{connect_async, tungstenite::Message as ClientFrame};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -408,9 +418,8 @@ mod tests {
|
|||||||
async fn authenticates_attaches_and_replies_to_a_request() {
|
async fn authenticates_attaches_and_replies_to_a_request() {
|
||||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||||
let (request_tx, mut request_rx) = mpsc::channel(4);
|
|
||||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||||
request_tx,
|
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||||
Arc::new(AtomicBool::new(false)),
|
Arc::new(AtomicBool::new(false)),
|
||||||
Arc::new(Redaction::new()),
|
Arc::new(Redaction::new()),
|
||||||
true,
|
true,
|
||||||
@@ -475,7 +484,6 @@ mod tests {
|
|||||||
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
.send(ClientFrame::Binary(noise.encrypt(&request).unwrap().into()))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(matches!(request_rx.recv().await, Some(WsRequest::UpdateLogLevel(_))));
|
|
||||||
let reply = noise
|
let reply = noise
|
||||||
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
.decrypt::<ServerMessage>(&receive_client_binary(&mut socket).await)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -290,9 +290,8 @@ mod tests {
|
|||||||
credential.product_version(),
|
credential.product_version(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
|
||||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||||
request_tx,
|
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||||
Arc::new(AtomicBool::new(false)),
|
Arc::new(AtomicBool::new(false)),
|
||||||
Arc::new(Redaction::new()),
|
Arc::new(Redaction::new()),
|
||||||
true,
|
true,
|
||||||
@@ -341,9 +340,8 @@ mod tests {
|
|||||||
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
async fn removed_prepared_candidate_cannot_commit_takeover() {
|
||||||
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
|
||||||
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap();
|
||||||
let (request_tx, _request_rx) = mpsc::channel(1);
|
|
||||||
let dispatcher = Arc::new(RequestDispatcher::new(
|
let dispatcher = Arc::new(RequestDispatcher::new(
|
||||||
request_tx,
|
crate::vpn_task::LifecycleHandle::for_tests(),
|
||||||
Arc::new(AtomicBool::new(false)),
|
Arc::new(AtomicBool::new(false)),
|
||||||
Arc::new(Redaction::new()),
|
Arc::new(Redaction::new()),
|
||||||
true,
|
true,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ license = "MIT"
|
|||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
base64.workspace = true
|
base64.workspace = true
|
||||||
|
mac_address = "1"
|
||||||
dns-lookup.workspace = true
|
dns-lookup.workspace = true
|
||||||
log.workspace = true
|
log.workspace = true
|
||||||
reqwest.workspace = true
|
reqwest.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
//! Neutral device-anchor transport model and Linux collection.
|
||||||
|
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum AnchorSource {
|
||||||
|
LinuxMac,
|
||||||
|
LinuxRandom,
|
||||||
|
MacosIokit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct DeviceAnchor {
|
||||||
|
pub hardware_id: String,
|
||||||
|
pub source: AnchorSource,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceAnchor {
|
||||||
|
pub fn validate(&self) -> bool {
|
||||||
|
URL_SAFE_NO_PAD
|
||||||
|
.decode(&self.hardware_id)
|
||||||
|
.is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == self.hardware_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
|
||||||
|
let domain = match source {
|
||||||
|
AnchorSource::LinuxMac => b"gp-device-anchor:v1:linux-mac:".as_slice(),
|
||||||
|
AnchorSource::LinuxRandom => b"gp-device-anchor:v1:linux-random:".as_slice(),
|
||||||
|
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||||
|
};
|
||||||
|
let mut input = domain.to_vec();
|
||||||
|
input.extend_from_slice(seed.as_ref());
|
||||||
|
Self {
|
||||||
|
hardware_id: URL_SAFE_NO_PAD.encode(openssl::sha::sha256(&input)),
|
||||||
|
source,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub fn collect_unix() -> anyhow::Result<DeviceAnchor> {
|
||||||
|
if let Some(mac) = mac_address::get_mac_address()? {
|
||||||
|
let bytes = mac.bytes();
|
||||||
|
if bytes != [0; 6] && bytes[0] & 1 == 0 {
|
||||||
|
return Ok(DeviceAnchor::derive(AnchorSource::LinuxMac, bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut random = [0_u8; 32];
|
||||||
|
getrandom::fill(&mut random).map_err(|_| anyhow::anyhow!("cannot initialize device anchor"))?;
|
||||||
|
Ok(DeviceAnchor::derive(AnchorSource::LinuxRandom, random))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hashes_are_domain_separated_and_canonical() {
|
||||||
|
let mac = DeviceAnchor::derive(AnchorSource::LinuxMac, [0, 17, 34, 51, 68, 85]);
|
||||||
|
assert!(mac.validate());
|
||||||
|
assert_ne!(
|
||||||
|
mac.hardware_id,
|
||||||
|
DeviceAnchor::derive(AnchorSource::LinuxRandom, [0, 17, 34, 51, 68, 85]).hardware_id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod cookie_store;
|
pub mod cookie_store;
|
||||||
pub mod credential;
|
pub mod credential;
|
||||||
|
pub mod device_anchor;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod gateway;
|
pub mod gateway;
|
||||||
pub mod gp_params;
|
pub mod gp_params;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use zeroize::Zeroizing;
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use crate::device_anchor::DeviceAnchor;
|
||||||
use crate::utils::base64;
|
use crate::utils::base64;
|
||||||
|
|
||||||
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
|
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
|
||||||
@@ -14,6 +15,7 @@ pub struct SessionCredential {
|
|||||||
session_id: Uuid,
|
session_id: Uuid,
|
||||||
secret: Zeroizing<[u8; 32]>,
|
secret: Zeroizing<[u8; 32]>,
|
||||||
product_version: String,
|
product_version: String,
|
||||||
|
device_anchor: Option<DeviceAnchor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionCredential {
|
impl SessionCredential {
|
||||||
@@ -30,6 +32,7 @@ impl SessionCredential {
|
|||||||
session_id: Uuid::new_v4(),
|
session_id: Uuid::new_v4(),
|
||||||
secret,
|
secret,
|
||||||
product_version: product_version.to_owned(),
|
product_version: product_version.to_owned(),
|
||||||
|
device_anchor: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,6 +52,18 @@ impl SessionCredential {
|
|||||||
&self.product_version
|
&self.product_version
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_device_anchor(mut self, anchor: DeviceAnchor) -> Result<Self, TransportError> {
|
||||||
|
if !anchor.validate() {
|
||||||
|
return Err(TransportError::InvalidCredential);
|
||||||
|
}
|
||||||
|
self.device_anchor = Some(anchor);
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn device_anchor(&self) -> Option<&DeviceAnchor> {
|
||||||
|
self.device_anchor.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
|
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
|
||||||
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
|
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
|
||||||
let dto = CredentialDtoRef {
|
let dto = CredentialDtoRef {
|
||||||
@@ -56,6 +71,7 @@ impl SessionCredential {
|
|||||||
session_id: self.session_id,
|
session_id: self.session_id,
|
||||||
secret: encoded_secret.as_str(),
|
secret: encoded_secret.as_str(),
|
||||||
product_version: &self.product_version,
|
product_version: &self.product_version,
|
||||||
|
device_anchor: self.device_anchor.as_ref(),
|
||||||
};
|
};
|
||||||
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
|
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
|
||||||
|
|
||||||
@@ -85,8 +101,12 @@ impl SessionCredential {
|
|||||||
session_id,
|
session_id,
|
||||||
secret,
|
secret,
|
||||||
product_version,
|
product_version,
|
||||||
|
device_anchor,
|
||||||
} = dto;
|
} = dto;
|
||||||
let encoded_secret = secret;
|
let encoded_secret = secret;
|
||||||
|
if device_anchor.as_ref().is_some_and(|anchor| !anchor.validate()) {
|
||||||
|
return Err(TransportError::InvalidCredential);
|
||||||
|
}
|
||||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||||
return Err(TransportError::InvalidCredential);
|
return Err(TransportError::InvalidCredential);
|
||||||
}
|
}
|
||||||
@@ -104,6 +124,7 @@ impl SessionCredential {
|
|||||||
session_id,
|
session_id,
|
||||||
secret,
|
secret,
|
||||||
product_version,
|
product_version,
|
||||||
|
device_anchor,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,6 +147,7 @@ struct CredentialDtoRef<'a> {
|
|||||||
session_id: Uuid,
|
session_id: Uuid,
|
||||||
secret: &'a str,
|
secret: &'a str,
|
||||||
product_version: &'a str,
|
product_version: &'a str,
|
||||||
|
device_anchor: Option<&'a DeviceAnchor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -135,6 +157,7 @@ struct CredentialDto {
|
|||||||
session_id: Uuid,
|
session_id: Uuid,
|
||||||
secret: Zeroizing<String>,
|
secret: Zeroizing<String>,
|
||||||
product_version: String,
|
product_version: String,
|
||||||
|
device_anchor: Option<DeviceAnchor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -161,4 +184,18 @@ mod tests {
|
|||||||
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
|
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
|
||||||
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
|
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn credential_round_trips_a_validated_device_anchor() {
|
||||||
|
let anchor = DeviceAnchor {
|
||||||
|
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
|
||||||
|
source: crate::device_anchor::AnchorSource::LinuxMac,
|
||||||
|
};
|
||||||
|
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
|
||||||
|
.unwrap()
|
||||||
|
.with_device_anchor(anchor.clone())
|
||||||
|
.unwrap();
|
||||||
|
let decoded = SessionCredential::decode_frame(&credential.encode_frame().unwrap()).unwrap();
|
||||||
|
assert_eq!(decoded.device_anchor(), Some(&anchor));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user