mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -1,4 +1,7 @@
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
fmt,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
@@ -9,6 +12,25 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
|
||||
|
||||
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum AuthWindowTheme {
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl AuthWindowTheme {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Light => "light",
|
||||
Self::Dark => "dark",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SamlAuthData {
|
||||
@@ -25,13 +47,26 @@ pub struct SamlAuthData {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SamlAuthResult {
|
||||
Success(SamlAuthData),
|
||||
Cancelled,
|
||||
Failure(String),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthenticationCancelled;
|
||||
|
||||
impl fmt::Display for AuthenticationCancelled {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Authentication cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AuthenticationCancelled {}
|
||||
|
||||
impl SamlAuthResult {
|
||||
pub fn is_success(&self) -> bool {
|
||||
match self {
|
||||
SamlAuthResult::Success(_) => true,
|
||||
SamlAuthResult::Cancelled => false,
|
||||
SamlAuthResult::Failure(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -39,6 +74,7 @@ impl SamlAuthResult {
|
||||
pub fn host_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
|
||||
SamlAuthResult::Cancelled => None,
|
||||
SamlAuthResult::Failure(_) => None,
|
||||
}
|
||||
}
|
||||
@@ -118,7 +154,6 @@ impl SamlAuthData {
|
||||
|
||||
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| {
|
||||
warn!("Failed to parse token auth data: {}", e);
|
||||
warn!("Auth data: {}", auth_data);
|
||||
AuthDataParseError::Invalid(anyhow::anyhow!(e))
|
||||
})?;
|
||||
|
||||
@@ -127,7 +162,7 @@ impl SamlAuthData {
|
||||
}
|
||||
|
||||
let auth_data = decode_to_string(auth_data).map_err(|e| {
|
||||
warn!("Failed to decode SAML auth data: {}, data: {}", e, data);
|
||||
warn!("Failed to decode SAML auth data: {}", e);
|
||||
AuthDataParseError::Invalid(anyhow::anyhow!(e))
|
||||
})?;
|
||||
let auth_data = Self::from_html(&auth_data)?;
|
||||
@@ -246,4 +281,15 @@ mod tests {
|
||||
let value = serde_json::to_value(result).unwrap();
|
||||
assert!(value["success"].get("hostId").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_result_cancelled_is_structured() {
|
||||
let value = serde_json::to_value(SamlAuthResult::Cancelled).unwrap();
|
||||
|
||||
assert_eq!(value, "cancelled");
|
||||
|
||||
let result: SamlAuthResult = serde_json::from_value(value).unwrap();
|
||||
assert!(!result.is_success());
|
||||
assert_eq!(result.host_id(), None);
|
||||
}
|
||||
}
|
||||
+243
-11
@@ -1,33 +1,139 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
|
||||
use log::Level;
|
||||
|
||||
use crate::error::PortalError;
|
||||
use crate::{
|
||||
error::PortalError,
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
/// How this program renders its logs.
|
||||
///
|
||||
/// Required rather than defaulted: a default would let an implementor drop
|
||||
/// the override and silently report failures as prose to a caller that asked
|
||||
/// for JSON, with nothing — not even a warning — to catch it.
|
||||
fn log_format(&self) -> LogFormat;
|
||||
}
|
||||
|
||||
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
|
||||
eprintln!("\nError: {:?}", err);
|
||||
|
||||
/// Suggestions for re-running the command, for failures that have a known
|
||||
/// workaround. Empty when there is nothing useful to say — including when the
|
||||
/// relevant option is already in use.
|
||||
fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
let Some(err) = err.downcast_ref::<PortalError>() else {
|
||||
return;
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let command_line = || {
|
||||
let argv = std::env::args().collect::<Vec<_>>();
|
||||
let program = argv.first().cloned().unwrap_or_default();
|
||||
let rest = argv.get(1..).map(|rest| rest.join(" ")).unwrap_or_default();
|
||||
|
||||
(program, rest)
|
||||
};
|
||||
|
||||
// The blank line between the sentence and the command is part of the output
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
if err.is_legacy_openssl_error() && !args.fix_openssl() {
|
||||
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--fix-openssl` option to work around this issue, e.g.:\n\n{program} --fix-openssl {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
if err.is_tls_error() && !args.ignore_tls_errors() {
|
||||
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
"Re-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n\n{program} --ignore-tls-errors {rest}"
|
||||
));
|
||||
}
|
||||
|
||||
hints
|
||||
}
|
||||
|
||||
/// Write one message to `w` the way `format` asks for.
|
||||
///
|
||||
/// Text is emitted exactly as it always was, so existing output does not move.
|
||||
/// JSON is written directly rather than through the `log` macros, because these
|
||||
/// are reports rather than log lines: they must survive `--quiet`, which would
|
||||
/// otherwise discard the only explanation of a failed run.
|
||||
///
|
||||
/// The record is rendered into one buffer and written once. `serde_json`'s
|
||||
/// `Display` would otherwise reach the stream in dozens of fragments, and any
|
||||
/// process sharing this stderr — the spawned authenticator, a connect script —
|
||||
/// could land a line inside a half-written record.
|
||||
fn write_message<W: Write>(w: &mut W, format: LogFormat, level: Level, message: &str) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => writeln!(w, "{message}"),
|
||||
LogFormat::Json => {
|
||||
// Callers pass the exact text line, blank-line padding included, so the
|
||||
// text form does not move. A record carries its own separation.
|
||||
let message = message.trim_start_matches('\n');
|
||||
let mut line = Vec::new();
|
||||
|
||||
write_json_record(
|
||||
&mut line,
|
||||
&log::Record::builder()
|
||||
.level(level)
|
||||
.target(module_path!())
|
||||
.args(format_args!("{message}"))
|
||||
.build(),
|
||||
)?;
|
||||
|
||||
w.write_all(&line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Report a user-facing line that is not a log record — a note, a warning, or
|
||||
/// advice about what to try next.
|
||||
///
|
||||
/// Callers used `eprintln!` directly, which in JSON mode drops prose into a
|
||||
/// stream the caller is parsing a line at a time. Routing them here keeps one
|
||||
/// answer to "how does this program emit a user-facing line", and leaves the
|
||||
/// text form byte-for-byte unchanged.
|
||||
pub fn report(format: LogFormat, level: Level, message: &str) {
|
||||
let _ = write_message(&mut io::stderr().lock(), format, level, message);
|
||||
}
|
||||
|
||||
fn write_failure<W: Write>(w: &mut W, format: LogFormat, err: &anyhow::Error, hints: &[String]) -> io::Result<()> {
|
||||
match format {
|
||||
LogFormat::Text => {
|
||||
writeln!(w, "\nError: {err:?}")?;
|
||||
|
||||
for hint in hints {
|
||||
writeln!(w, "\n{hint}\n")?;
|
||||
}
|
||||
}
|
||||
LogFormat::Json => {
|
||||
write_message(w, format, Level::Error, &format!("{err:?}"))?;
|
||||
|
||||
for hint in hints {
|
||||
write_message(w, format, Level::Error, hint)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_error_to<W: Write>(w: &mut W, err: anyhow::Error, args: &impl Args) -> io::Result<()> {
|
||||
let hints = retry_hints(&err, args);
|
||||
|
||||
write_failure(w, args.log_format(), &err, &hints)
|
||||
}
|
||||
|
||||
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
|
||||
// Nothing useful to do if stderr itself is gone.
|
||||
let _ = handle_error_to(&mut io::stderr().lock(), err, args);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -79,3 +185,129 @@ impl ToVerboseArg for Level {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use anyhow::anyhow;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestArgs {
|
||||
fix_openssl: bool,
|
||||
ignore_tls_errors: bool,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl Args for TestArgs {
|
||||
fn fix_openssl(&self) -> bool {
|
||||
self.fix_openssl
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
fn log_format(&self) -> LogFormat {
|
||||
self.log_format
|
||||
}
|
||||
}
|
||||
|
||||
/// The seam that matters: `handle_error` must ask the args which format to
|
||||
/// use. Testing the writer alone would leave a version that always reports as
|
||||
/// prose passing every test.
|
||||
#[test]
|
||||
fn handle_error_honours_the_requested_format() {
|
||||
let args = TestArgs {
|
||||
log_format: LogFormat::Json,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
|
||||
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &args).expect("writing to a Vec cannot fail");
|
||||
|
||||
let out = String::from_utf8(out).expect("output should be UTF-8");
|
||||
for line in out.lines() {
|
||||
serde_json::from_str::<serde_json::Value>(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
}
|
||||
assert!(!out.is_empty(), "the failure must be reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tls_failure_suggests_ignoring_tls_errors() {
|
||||
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
|
||||
|
||||
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
|
||||
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
|
||||
// The command sits on its own line after a blank one, as it always has.
|
||||
assert!(
|
||||
hints[0].contains("e.g.:\n\n"),
|
||||
"blank line before the command: {:?}",
|
||||
hints[0]
|
||||
);
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
/// would be an extra record on every failed run.
|
||||
#[test]
|
||||
fn no_hint_when_the_option_is_already_in_use() {
|
||||
let args = TestArgs {
|
||||
ignore_tls_errors: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
|
||||
}
|
||||
|
||||
/// Most failures have no known workaround; inventing advice for them would
|
||||
/// mislead.
|
||||
#[test]
|
||||
fn no_hints_for_an_unrelated_error() {
|
||||
let hints = retry_hints(&anyhow!("something else went wrong"), &TestArgs::default());
|
||||
|
||||
assert!(hints.is_empty(), "got {hints:?}");
|
||||
}
|
||||
|
||||
fn failure_output(format: LogFormat) -> String {
|
||||
let hints = vec!["Re-run it with the `--ignore-tls-errors` option".to_string()];
|
||||
let mut out = Vec::new();
|
||||
|
||||
write_failure(&mut out, format, &anyhow!(PortalError::TlsError), &hints).expect("writing to a Vec cannot fail");
|
||||
|
||||
String::from_utf8(out).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The failure is the program's final report, so in JSON mode it must be one
|
||||
/// more record on the same stream — and it must not be filtered away, which
|
||||
/// is why it does not go through the log macros. A run that fails silently is
|
||||
/// worse than one that fails noisily.
|
||||
#[test]
|
||||
fn the_failure_is_reported_as_records() {
|
||||
let out = failure_output(LogFormat::Json);
|
||||
let lines: Vec<_> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "expected the error and its hint: {out:?}");
|
||||
|
||||
for line in lines {
|
||||
let v: serde_json::Value = serde_json::from_str(line).unwrap_or_else(|e| panic!("not JSON: {line:?} ({e})"));
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
}
|
||||
}
|
||||
|
||||
/// The format has to be honoured, not merely available: reporting the failure
|
||||
/// as prose to a caller that asked for JSON is the defect this whole flag
|
||||
/// exists to remove.
|
||||
#[test]
|
||||
fn the_format_decides_how_the_failure_is_written() {
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(failure_output(LogFormat::Json).lines().next().unwrap()).is_ok(),
|
||||
"json mode must not emit prose"
|
||||
);
|
||||
|
||||
let text = failure_output(LogFormat::Text);
|
||||
assert!(text.starts_with("\nError: "), "text mode keeps its shape: {text:?}");
|
||||
assert!(
|
||||
serde_json::from_str::<serde_json::Value>(text.trim()).is_err(),
|
||||
"text mode must not emit JSON: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use anyhow::bail;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::auth::{SamlAuthData, SamlAuthResult};
|
||||
use crate::auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -250,6 +250,7 @@ impl TryFrom<SamlAuthResult> for Credential {
|
||||
fn try_from(value: SamlAuthResult) -> anyhow::Result<Self> {
|
||||
match value {
|
||||
SamlAuthResult::Success(auth_data) => Ok(Self::from(auth_data)),
|
||||
SamlAuthResult::Cancelled => bail!(AuthenticationCancelled),
|
||||
SamlAuthResult::Failure(err) => bail!(err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Neutral device-anchor transport model and deterministic derivation.
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "u8", into = "u8")]
|
||||
pub enum AnchorSource {
|
||||
UnixMac,
|
||||
UnixRandom,
|
||||
MacosIokit,
|
||||
}
|
||||
|
||||
impl From<AnchorSource> for u8 {
|
||||
fn from(source: AnchorSource) -> Self {
|
||||
match source {
|
||||
AnchorSource::UnixMac => 1,
|
||||
AnchorSource::UnixRandom => 2,
|
||||
AnchorSource::MacosIokit => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InvalidAnchorSource(u8);
|
||||
|
||||
impl fmt::Display for InvalidAnchorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "unsupported device anchor source {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidAnchorSource {}
|
||||
|
||||
impl TryFrom<u8> for AnchorSource {
|
||||
type Error = InvalidAnchorSource;
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
1 => Ok(Self::UnixMac),
|
||||
2 => Ok(Self::UnixRandom),
|
||||
3 => Ok(Self::MacosIokit),
|
||||
value => Err(InvalidAnchorSource(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DeviceAnchor {
|
||||
pub hardware_id: String,
|
||||
pub source: AnchorSource,
|
||||
}
|
||||
|
||||
impl DeviceAnchor {
|
||||
pub fn validate(&self) -> bool {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(&self.hardware_id)
|
||||
.is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == self.hardware_id)
|
||||
}
|
||||
|
||||
pub fn derive(source: AnchorSource, seed: impl AsRef<[u8]>) -> Self {
|
||||
let domain = match source {
|
||||
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
|
||||
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
|
||||
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
|
||||
};
|
||||
let mut input = domain.to_vec();
|
||||
input.extend_from_slice(seed.as_ref());
|
||||
Self {
|
||||
hardware_id: URL_SAFE_NO_PAD.encode(openssl::sha::sha256(&input)),
|
||||
source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hashes_original_seed_order_with_stable_domain_separation() {
|
||||
let mac = DeviceAnchor::derive(AnchorSource::UnixMac, [0, 17, 34, 51, 68, 85]);
|
||||
assert!(mac.validate());
|
||||
assert_eq!(mac.hardware_id, "UWDOx4AVJEuCAYfJBaPioyGtRfAkJBhMYSi8LuFsE1A");
|
||||
assert_ne!(
|
||||
mac.hardware_id,
|
||||
DeviceAnchor::derive(AnchorSource::UnixMac, [85, 68, 51, 34, 17, 0]).hardware_id
|
||||
);
|
||||
assert_ne!(
|
||||
mac.hardware_id,
|
||||
DeviceAnchor::derive(AnchorSource::UnixRandom, [0, 17, 34, 51, 68, 85]).hardware_id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_uses_stable_numeric_json_codes() {
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
|
||||
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<AnchorSource>("1").unwrap(),
|
||||
AnchorSource::UnixMac
|
||||
);
|
||||
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
|
||||
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
use std::{borrow::Cow, net::UdpSocket};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::Client;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use urlencoding::{decode, encode};
|
||||
use xmltree::Element;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
@@ -12,68 +17,238 @@ use crate::{
|
||||
gateway::GatewayLoginContext,
|
||||
gp_params::GpParams,
|
||||
params::gateway_login::{self, GatewayLoginInput},
|
||||
session::{
|
||||
GatewayAuthentication,
|
||||
network::GatewayBinding,
|
||||
transport::{bound_client, gateway_origin},
|
||||
},
|
||||
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
pub enum GatewayLogin {
|
||||
Cookie(String),
|
||||
Authenticated(GatewayAuthentication),
|
||||
Mfa(String, String),
|
||||
}
|
||||
|
||||
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, false).await
|
||||
/// Protocol failures cannot be repaired by repeating login with different
|
||||
/// credentials. Issued credentials, when identifiable, are cleaned up first.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Gateway login returned invalid session configuration")]
|
||||
pub struct GatewayLoginProtocolError;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GatewayLoginClient {
|
||||
origin: reqwest::Url,
|
||||
client: Client,
|
||||
params: GpParams,
|
||||
binding: Option<GatewayBinding>,
|
||||
login_endpoint: Option<SocketAddr>,
|
||||
login_url: Option<reqwest::Url>,
|
||||
maintenance_client: Option<Client>,
|
||||
}
|
||||
|
||||
pub async fn gateway_login_with_context(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
context: &GatewayLoginContext,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
|
||||
impl GatewayLoginClient {
|
||||
pub fn register_session(
|
||||
&self,
|
||||
gateway: crate::gateway::Gateway,
|
||||
authentication: GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.register(crate::session::GatewaySession {
|
||||
gateway,
|
||||
transport: self.authenticated_transport(authentication),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
pub fn new(gateway: &str, params: GpParams) -> anyhow::Result<Self> {
|
||||
let origin = reqwest::Url::parse(&normalize_server(gateway)?)?;
|
||||
let client = Client::try_from(¶ms)?;
|
||||
Ok(Self {
|
||||
origin,
|
||||
client,
|
||||
params,
|
||||
binding: None,
|
||||
login_endpoint: None,
|
||||
login_url: None,
|
||||
maintenance_client: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only called after an authenticated non-tunnel response and registration in
|
||||
/// the caller's cleanup ledger. Tunnel login never inspects physical routing.
|
||||
pub async fn bind_non_tunnel(
|
||||
&mut self,
|
||||
disable_ipv6: bool,
|
||||
detection: Option<&crate::session::network::InternalHostDetection>,
|
||||
cancellation: &tokio_util::sync::CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
let origin = gateway_origin(self.origin.as_str())?;
|
||||
let response_url = self
|
||||
.login_url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Authenticated response endpoint is unavailable"))?;
|
||||
anyhow::ensure!(
|
||||
response_url.origin() == origin.origin(),
|
||||
"Redirected non-tunnel authentication is unsupported"
|
||||
);
|
||||
let endpoint = self
|
||||
.login_endpoint
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel authentication has no direct peer address"))?;
|
||||
let network = crate::session::network::PhysicalNetwork::capture_controlled(cancellation).await?;
|
||||
let binding = network
|
||||
.bind_authenticated_endpoint(origin.as_str(), endpoint, disable_ipv6, cancellation)
|
||||
.await?;
|
||||
network
|
||||
.validate_internal_binding(&binding, detection, cancellation)
|
||||
.await?;
|
||||
let client = bound_client(origin.as_str(), &self.params, &binding)?;
|
||||
self.binding = Some(binding);
|
||||
self.maintenance_client = Some(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_registered_session(
|
||||
&self,
|
||||
gateway: &crate::gateway::Gateway,
|
||||
authentication: &GatewayAuthentication,
|
||||
sessions: &mut crate::session::GatewaySessions,
|
||||
) {
|
||||
sessions.update(crate::session::GatewaySession {
|
||||
gateway: gateway.clone(),
|
||||
transport: self.authenticated_transport(authentication.clone()),
|
||||
addresses: self
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.addresses())
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn authenticated_transport(
|
||||
&self,
|
||||
authentication: GatewayAuthentication,
|
||||
) -> crate::session::transport::GatewayTransport {
|
||||
crate::session::transport::GatewayTransport::from_authenticated_login(
|
||||
self.maintenance_client.as_ref().unwrap_or(&self.client).clone(),
|
||||
self.origin.clone(),
|
||||
authentication,
|
||||
self.params.os_profile().clone(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn binding(&self) -> Option<&GatewayBinding> {
|
||||
self.binding.as_ref()
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.params.client_identity()
|
||||
}
|
||||
pub(crate) fn request_client(&self) -> &Client {
|
||||
&self.client
|
||||
}
|
||||
pub(crate) fn origin(&self) -> &reqwest::Url {
|
||||
&self.origin
|
||||
}
|
||||
|
||||
pub fn respond_mfa(&mut self, input: &str, otp: &str) {
|
||||
self.params.set_input_str(input);
|
||||
self.params.set_otp(otp);
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
&mut self,
|
||||
cred: &Credential,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
let request = receive_gateway_login(
|
||||
&self.origin,
|
||||
&self.client,
|
||||
cred,
|
||||
&self.params,
|
||||
context,
|
||||
client_ip.as_deref(),
|
||||
false,
|
||||
);
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
response = request => response?,
|
||||
_ = cancellation.cancelled() => return Err(crate::auth::AuthenticationCancelled.into()),
|
||||
};
|
||||
// Once the full response is available, retain issued authentication or finish
|
||||
// cleanup-only logout before the caller observes cancellation.
|
||||
let response = parse_login_response(response, &self.client, &self.origin, &self.params).await?;
|
||||
self.login_endpoint = response.endpoint;
|
||||
self.login_url = Some(response.url);
|
||||
Ok(response.login)
|
||||
}
|
||||
|
||||
pub(crate) async fn extend_lifetime(&self, cred: &Credential) -> anyhow::Result<GatewayLogin> {
|
||||
let response = receive_gateway_login(&self.origin, &self.client, cred, &self.params, None, None, true).await?;
|
||||
Ok(
|
||||
parse_login_response(response, &self.client, &self.origin, &self.params)
|
||||
.await?
|
||||
.login,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn gateway_login_with_extend_lifetime(
|
||||
gateway: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
gateway_login_with_options(gateway, cred, gp_params, None, true).await
|
||||
struct LoginResponse {
|
||||
login: GatewayLogin,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
async fn gateway_login_with_options(
|
||||
gateway: &str,
|
||||
struct ReceivedLogin {
|
||||
body: String,
|
||||
endpoint: Option<SocketAddr>,
|
||||
url: reqwest::Url,
|
||||
}
|
||||
|
||||
fn detect_local_ipv4(host: &str) -> Option<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect((host, 443)).ok()?;
|
||||
let ip = socket.local_addr().ok()?.ip();
|
||||
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
|
||||
}
|
||||
|
||||
async fn receive_gateway_login(
|
||||
origin: &reqwest::Url,
|
||||
client: &Client,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
context: Option<&GatewayLoginContext>,
|
||||
client_ip: Option<&str>,
|
||||
extend_lifetime: bool,
|
||||
) -> anyhow::Result<GatewayLogin> {
|
||||
let url = normalize_server(gateway)?;
|
||||
let gateway = remove_url_scheme(&url);
|
||||
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", url);
|
||||
let client = Client::try_from(gp_params)?;
|
||||
|
||||
let client_ip = context.and_then(|context| {
|
||||
context
|
||||
.client_ip()
|
||||
.map(|ip| ip.to_string())
|
||||
.or_else(|| detect_local_ipv4(context.host()))
|
||||
});
|
||||
) -> anyhow::Result<ReceivedLogin> {
|
||||
let gateway = remove_url_scheme(origin.as_str().trim_end_matches('/'));
|
||||
let login_url = format!("{}/ssl-vpn/login.esp", origin.as_str().trim_end_matches('/'));
|
||||
let request_params = gateway_login::build(&GatewayLoginInput {
|
||||
gp_params,
|
||||
cred,
|
||||
gateway_host: &gateway,
|
||||
context,
|
||||
client_ip: client_ip.as_deref(),
|
||||
client_ip,
|
||||
extend_lifetime,
|
||||
});
|
||||
|
||||
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
|
||||
log_gateway_login_context(context, client_ip.as_deref(), gp_params);
|
||||
log_gateway_login_context(context, client_ip, gp_params);
|
||||
|
||||
let res = client
|
||||
.post(&login_url)
|
||||
.post(login_url)
|
||||
.form(&request_params.body)
|
||||
.send()
|
||||
.await
|
||||
@@ -82,11 +257,32 @@ async fn gateway_login_with_options(
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
let endpoint = res.remote_addr();
|
||||
let url = res.url().clone();
|
||||
let res = parse_gp_response(res).await.map_err(|err| {
|
||||
warn!("{err}");
|
||||
warn!("Gateway login response failed: {}", err.reason);
|
||||
anyhow::anyhow!("Gateway login error: {}", err.reason)
|
||||
})?;
|
||||
|
||||
Ok(ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
async fn parse_login_response(
|
||||
response: ReceivedLogin,
|
||||
client: &Client,
|
||||
origin: &reqwest::Url,
|
||||
gp_params: &GpParams,
|
||||
) -> anyhow::Result<LoginResponse> {
|
||||
let ReceivedLogin {
|
||||
body: res,
|
||||
endpoint,
|
||||
url,
|
||||
} = response;
|
||||
|
||||
// It's possible to get an empty response, log the response headers for debugging
|
||||
if res.trim().is_empty() {
|
||||
info!("Empty gateway login response headers: {:?}", res);
|
||||
@@ -96,27 +292,47 @@ async fn gateway_login_with_options(
|
||||
// MFA detected
|
||||
if res.contains("Challenge") {
|
||||
let Some((message, input_str)) = parse_mfa(&res) else {
|
||||
bail!("Failed to parse MFA challenge: {res}");
|
||||
bail!("Failed to parse MFA challenge");
|
||||
};
|
||||
|
||||
return Ok(GatewayLogin::Mfa(message, input_str));
|
||||
return Ok(LoginResponse {
|
||||
login: GatewayLogin::Mfa(message, input_str),
|
||||
endpoint,
|
||||
url,
|
||||
});
|
||||
}
|
||||
|
||||
debug!("Gateway login response: {}", res);
|
||||
|
||||
let root = Element::parse(res.as_bytes())?;
|
||||
|
||||
let cookie = build_gateway_token(&root, gp_params.computer())?;
|
||||
|
||||
Ok(GatewayLogin::Cookie(cookie))
|
||||
}
|
||||
|
||||
fn detect_local_ipv4(host: &str) -> Option<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect((host, 443)).ok()?;
|
||||
let ip = socket.local_addr().ok()?.ip();
|
||||
|
||||
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
|
||||
let lower = res.to_ascii_lowercase();
|
||||
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
let root = Element::parse(res.as_bytes()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let (cookie, connection_type) =
|
||||
parse_issued_authentication(&root, gp_params.computer()).map_err(|_| GatewayLoginProtocolError)?;
|
||||
let cookie = Zeroizing::new(cookie);
|
||||
let authentication = connection_type.and_then(|mode| GatewayAuthentication::new(cookie.to_string(), mode));
|
||||
let authentication = match authentication {
|
||||
Ok(authentication) => authentication,
|
||||
Err(_) => {
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
crate::session::transport::logout_cookie(client, origin, &cookie, gp_params.os_profile()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => warn!("Cleanup-only gateway logout failed: {error}"),
|
||||
Err(_) => warn!("Cleanup-only gateway logout timed out"),
|
||||
}
|
||||
return Err(GatewayLoginProtocolError.into());
|
||||
}
|
||||
};
|
||||
debug!("Gateway login succeeded, mode: {:?}", authentication.mode());
|
||||
Ok(LoginResponse {
|
||||
login: GatewayLogin::Authenticated(authentication),
|
||||
endpoint,
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>, gp_params: &GpParams) {
|
||||
@@ -136,13 +352,33 @@ fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: O
|
||||
);
|
||||
}
|
||||
|
||||
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
|
||||
let args = element
|
||||
.descendants("argument")
|
||||
fn parse_issued_authentication(element: &Element, computer: &str) -> anyhow::Result<(String, anyhow::Result<String>)> {
|
||||
anyhow::ensure!(element.name == "jnlp", "Gateway login response is not JNLP");
|
||||
anyhow::ensure!(
|
||||
element.attr("status").is_none_or(|status| status == "success"),
|
||||
"Gateway login response rejected authentication"
|
||||
);
|
||||
let application = element
|
||||
.child("application-desc")
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway login response has no application description"))?;
|
||||
let args = application
|
||||
.children("argument")
|
||||
.iter()
|
||||
.map(|e| e.get_text().unwrap_or_default())
|
||||
.collect::<Vec<_>>();
|
||||
let cookie = build_gateway_token(&args, computer)?;
|
||||
let connection_type = read_arg_value(&args, 12)
|
||||
.and_then(|mode| mode.ok_or_else(|| anyhow::anyhow!("Gateway login response has no connection type")));
|
||||
Ok((cookie, connection_type))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn parse_gateway_authentication(element: &Element, computer: &str) -> anyhow::Result<GatewayAuthentication> {
|
||||
let (cookie, mode) = parse_issued_authentication(element, computer)?;
|
||||
GatewayAuthentication::new(cookie, mode?)
|
||||
}
|
||||
|
||||
fn build_gateway_token(args: &[Cow<'_, str>], computer: &str) -> anyhow::Result<String> {
|
||||
let mut params = vec![
|
||||
read_required_arg(&args, 1, "authcookie")?,
|
||||
read_optional_arg(&args, 2, "persistent-cookie")?,
|
||||
@@ -198,11 +434,15 @@ fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<
|
||||
}
|
||||
|
||||
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
|
||||
let value = decode(value)?;
|
||||
if value.is_empty() || value == "(null)" || value == "-1" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some(decode(value)?.into_owned()))
|
||||
anyhow::ensure!(
|
||||
!value.chars().any(char::is_control),
|
||||
"Gateway argument contains control characters"
|
||||
);
|
||||
Ok(Some(value.into_owned()))
|
||||
}
|
||||
|
||||
fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
@@ -223,6 +463,268 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tunnel_response() -> String {
|
||||
let root = login_response(Some("tunnel"), "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
crate::session::transport::tests::response(std::str::from_utf8(&xml).unwrap())
|
||||
}
|
||||
|
||||
fn test_params() -> GpParams {
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_login_cancels_stalled_headers_and_body() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
for partial_response in ["", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n<jnlp>"] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(partial_response.as_bytes()).await.unwrap();
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(1), login)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(result.err().unwrap().is::<crate::auth::AuthenticationCancelled>());
|
||||
release.send(()).unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_during_cleanup_only_logout_awaits_cleanup() {
|
||||
use crate::session::transport::tests::response;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let mut xml = Vec::new();
|
||||
login_response(None, "issued-cookie").write(&mut xml).unwrap();
|
||||
let login_response = response(std::str::from_utf8(&xml).unwrap());
|
||||
let (ready, received) = tokio::sync::oneshot::channel();
|
||||
let (release, released) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buffer = [0; 4096];
|
||||
assert!(socket.read(&mut buffer).await.unwrap() > 0);
|
||||
socket.write_all(login_response.as_bytes()).await.unwrap();
|
||||
drop(socket);
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let read = socket.read(&mut buffer).await.unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&buffer[..read])
|
||||
.unwrap()
|
||||
.contains("/ssl-vpn/logout.esp")
|
||||
);
|
||||
ready.send(()).unwrap();
|
||||
released.await.unwrap();
|
||||
socket
|
||||
.write_all(response("<response status='success'/>").as_bytes())
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let cancellation = CancellationToken::new();
|
||||
let token = cancellation.clone();
|
||||
let mut login = tokio::spawn(async move {
|
||||
let mut client = GatewayLoginClient::new(&origin, test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
client.login(&credential, None, &token).await
|
||||
});
|
||||
received.await.unwrap();
|
||||
cancellation.cancel();
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(20), &mut login)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
release.send(()).unwrap();
|
||||
assert!(login.await.unwrap().err().unwrap().is::<GatewayLoginProtocolError>());
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_follows_redirects_without_physical_binding() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: /redirected-login\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
tunnel_response(),
|
||||
]).await;
|
||||
let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(
|
||||
matches!(client.login(&credential, None, &CancellationToken::new()).await.unwrap(), GatewayLogin::Authenticated(authentication) if authentication.mode() == crate::session::SessionMode::Tunnel)
|
||||
);
|
||||
assert!(client.binding().is_none());
|
||||
assert!(matches!(
|
||||
client.extend_lifetime(&credential).await.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/redirected-login");
|
||||
assert_eq!(requests[3].0, "/redirected-login");
|
||||
assert!(requests[3].1.contains("extend-lifetime=true"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_login_keeps_reqwest_address_fallback() {
|
||||
let (_, origin, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let port = origin.port().unwrap();
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new(&format!("http://gateway.invalid:{port}"), params.clone()).unwrap();
|
||||
// Supply deterministic DNS candidates; all other client behavior is the
|
||||
// ordinary request path. The first address refuses, the second is reachable.
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.no_proxy()
|
||||
.resolve_to_addrs(
|
||||
"gateway.invalid",
|
||||
&[
|
||||
SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, port)),
|
||||
SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
],
|
||||
)
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(server.await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_tunnel_login_can_use_a_proxy_without_local_gateway_resolution() {
|
||||
let (_, proxy, server) = crate::session::transport::tests::login_gateway(vec![tunnel_response()]).await;
|
||||
let params = test_params();
|
||||
let mut client = GatewayLoginClient::new("http://unresolvable.invalid", params.clone()).unwrap();
|
||||
client.client = params
|
||||
.client_builder()
|
||||
.unwrap()
|
||||
.proxy(reqwest::Proxy::all(proxy.as_str()).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
assert!(matches!(
|
||||
client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap(),
|
||||
GatewayLogin::Authenticated(_)
|
||||
));
|
||||
assert!(client.binding().is_none());
|
||||
assert_eq!(
|
||||
server.await.unwrap()[0].0,
|
||||
"http://unresolvable.invalid/ssl-vpn/login.esp"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_mode_logs_out_issued_cookie_before_returning_protocol_error() {
|
||||
use crate::session::transport::tests::{login_gateway, response};
|
||||
let root = login_response(None, "issued-cookie");
|
||||
let mut xml = Vec::new();
|
||||
root.write(&mut xml).unwrap();
|
||||
let (client, origin, server) = login_gateway(vec![
|
||||
response(std::str::from_utf8(&xml).unwrap()),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let params =
|
||||
GpParams::builder(crate::os_profile::OsProfile::builder(crate::os_profile::ClientOs::Linux).build()).build();
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let mut client = GatewayLoginClient {
|
||||
client,
|
||||
..GatewayLoginClient::new(origin.as_str(), params).unwrap()
|
||||
};
|
||||
let error = client
|
||||
.login(&credential, None, &CancellationToken::new())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.is::<GatewayLoginProtocolError>());
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[0].0, "/ssl-vpn/login.esp");
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[1].1).unwrap();
|
||||
assert_eq!(form.get("authcookie").map(String::as_str), Some("issued-cookie"));
|
||||
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_only_parsing_does_not_salvage_server_error_authentication() {
|
||||
let mut root = login_response(None, "issued-cookie");
|
||||
root.attributes.insert("status".into(), "error".into());
|
||||
assert!(parse_issued_authentication(&root, "computer").is_err());
|
||||
for encoded in ["%28null%29", "%2D1", "%00"] {
|
||||
assert!(parse_issued_authentication(&login_response(Some("tunnel"), encoded), "computer").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn login_response(mode: Option<&str>, cookie: &str) -> Element {
|
||||
let mut args = vec![""; 19];
|
||||
args[1] = cookie;
|
||||
args[4] = "alice";
|
||||
if let Some(mode) = mode {
|
||||
args[12] = mode;
|
||||
}
|
||||
let arguments = args
|
||||
.iter()
|
||||
.map(|value| format!("<argument>{value}</argument>"))
|
||||
.collect::<String>();
|
||||
Element::parse(format!("<jnlp><application-desc>{arguments}</application-desc></jnlp>").as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_mode_is_independent_of_network_location() {
|
||||
for (value, mode) in [
|
||||
("tunnel", crate::session::SessionMode::Tunnel),
|
||||
("non-tunnel", crate::session::SessionMode::NonTunnel),
|
||||
("internal", crate::session::SessionMode::NonTunnel),
|
||||
] {
|
||||
let authentication =
|
||||
parse_gateway_authentication(&login_response(Some(value), "test-cookie"), "computer").unwrap();
|
||||
assert_eq!(authentication.mode(), mode);
|
||||
assert_eq!(authentication.connection_type(), value);
|
||||
assert!(!format!("{authentication:?}").contains("test-cookie"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_rejects_missing_mode_or_cookie() {
|
||||
for mode in [None, Some(""), Some("(null)"), Some("-1"), Some(" ")] {
|
||||
assert!(parse_gateway_authentication(&login_response(mode, "test-cookie"), "computer").is_err());
|
||||
}
|
||||
assert!(parse_gateway_authentication(&login_response(Some("tunnel"), ""), "computer").is_err());
|
||||
let response = Element::parse(b"<response status='error'/>".as_slice()).unwrap();
|
||||
assert!(parse_gateway_authentication(&response, "computer").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mfa() {
|
||||
let res = r#"var respStatus = "Challenge";
|
||||
@@ -263,7 +765,9 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
assert_eq!(authentication.mode(), crate::session::SessionMode::Tunnel);
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
@@ -300,7 +804,8 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
|
||||
"#;
|
||||
|
||||
let root = Element::parse(res.as_bytes()).unwrap();
|
||||
let token = build_gateway_token(&root, "metalklesk").unwrap();
|
||||
let authentication = parse_gateway_authentication(&root, "metalklesk").unwrap();
|
||||
let token = authentication.cookie();
|
||||
|
||||
assert_eq!(
|
||||
token,
|
||||
|
||||
@@ -118,7 +118,7 @@ impl GatewayLoginContext {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub(crate) fn kind(&self) -> GatewayKind {
|
||||
pub fn kind(&self) -> GatewayKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
|
||||
@@ -5,15 +5,13 @@ use std::{
|
||||
|
||||
use anyhow::bail;
|
||||
use log::{info, warn};
|
||||
use reqwest::Client;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
credential::Credential,
|
||||
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
|
||||
gp_params::GpParams,
|
||||
gateway::login::{GatewayLogin, GatewayLoginClient},
|
||||
session::SessionRequestArgs,
|
||||
utils::{normalize_server, parse_gp_response, request::create_identity, xml::ElementExt},
|
||||
utils::{parse_gp_response, xml::ElementExt},
|
||||
};
|
||||
|
||||
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
|
||||
@@ -22,12 +20,18 @@ const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
|
||||
#[derive(Clone)]
|
||||
pub struct SessionExtensionAuth {
|
||||
credential: Credential,
|
||||
gp_params: GpParams,
|
||||
client: GatewayLoginClient,
|
||||
}
|
||||
|
||||
impl SessionExtensionAuth {
|
||||
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
|
||||
Self { credential, gp_params }
|
||||
pub fn new(credential: Credential, client: GatewayLoginClient) -> Self {
|
||||
Self { credential, client }
|
||||
}
|
||||
pub fn client_identity(&self) -> Option<&crate::utils::request::ClientIdentity> {
|
||||
self.client.client_identity()
|
||||
}
|
||||
pub fn binding(&self) -> Option<&crate::session::network::GatewayBinding> {
|
||||
self.client.binding()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +39,7 @@ impl std::fmt::Debug for SessionExtensionAuth {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SessionExtensionAuth")
|
||||
.field("username", &self.credential.username())
|
||||
.field("gp_params", &"<redacted>")
|
||||
.field("client", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -83,10 +87,15 @@ impl SessionContext {
|
||||
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
extend_session_lifetime(ctx).await?;
|
||||
|
||||
let base_url = normalize_server(ctx.server())?;
|
||||
let client = build_session_client(ctx.session_args())?;
|
||||
let auth = ctx
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
let client = auth.client.request_client();
|
||||
let url = format!(
|
||||
"{}/ssl-vpn/agentmessage.esp",
|
||||
auth.client.origin().as_str().trim_end_matches('/')
|
||||
);
|
||||
let form = build_extend_session_form(ctx)?;
|
||||
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
|
||||
|
||||
info!("Sending extend-session request");
|
||||
|
||||
@@ -108,33 +117,17 @@ async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
|
||||
.extension_auth()
|
||||
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
|
||||
|
||||
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
|
||||
let login = auth.client.extend_lifetime(&auth.credential).await?;
|
||||
validate_extension_login(login)
|
||||
}
|
||||
|
||||
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
|
||||
match login {
|
||||
GatewayLogin::Cookie(_) => Ok(()),
|
||||
GatewayLogin::Authenticated(_) => Ok(()),
|
||||
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
|
||||
let mut builder = Client::builder();
|
||||
|
||||
if let Some(user_agent) = args.user_agent() {
|
||||
builder = builder.user_agent(user_agent);
|
||||
}
|
||||
|
||||
if let Some(cert) = args.certificate() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(&cert, args.sslkey().as_deref(), args.key_password().as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
|
||||
Ok(serde_urlencoded::from_str(args.cookie())?)
|
||||
}
|
||||
|
||||
+109
-14
@@ -1,11 +1,12 @@
|
||||
use log::info;
|
||||
use reqwest::Client;
|
||||
use reqwest::{Client, ClientBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
utils::request::create_identity,
|
||||
utils::request::{ClientIdentity, create_identity},
|
||||
};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)]
|
||||
@@ -43,6 +44,7 @@ pub struct GpParams {
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
key_password: Option<String>,
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
// Feature
|
||||
csc_mode: CscMode,
|
||||
// Per-request state
|
||||
@@ -135,9 +137,49 @@ impl GpParams {
|
||||
pub(crate) fn otp(&self) -> Option<&str> {
|
||||
self.otp.as_deref()
|
||||
}
|
||||
|
||||
pub fn prepare_client_identity(&mut self) -> anyhow::Result<()> {
|
||||
if self.prepared_identity.is_none() {
|
||||
if let Some(certificate) = self.certificate.as_deref() {
|
||||
self.prepared_identity = Some(ClientIdentity::load(
|
||||
certificate,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
if let Some(mut passphrase) = self.key_password.take() {
|
||||
passphrase.zeroize();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn client_identity(&self) -> Option<&ClientIdentity> {
|
||||
self.prepared_identity.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
if let Some(identity) = &self.prepared_identity {
|
||||
builder = builder.identity(identity.request_identity());
|
||||
} else if let Some(cert) = self.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
builder = builder.identity(create_identity(
|
||||
cert,
|
||||
self.sslkey.as_deref(),
|
||||
self.key_password.as_deref(),
|
||||
)?);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GpParamsBuilder {
|
||||
prepared_identity: Option<ClientIdentity>,
|
||||
is_gateway: bool,
|
||||
os_profile: OsProfile,
|
||||
csc_mode: CscMode,
|
||||
@@ -150,6 +192,7 @@ pub struct GpParamsBuilder {
|
||||
impl GpParamsBuilder {
|
||||
pub fn new(os_profile: OsProfile) -> Self {
|
||||
Self {
|
||||
prepared_identity: None,
|
||||
is_gateway: false,
|
||||
os_profile,
|
||||
csc_mode: Default::default(),
|
||||
@@ -176,22 +219,34 @@ impl GpParamsBuilder {
|
||||
}
|
||||
|
||||
pub fn certificate<T: Into<Option<String>>>(&mut self, certificate: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.certificate = certificate.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn sslkey<T: Into<Option<String>>>(&mut self, sslkey: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.sslkey = sslkey.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn key_password<T: Into<Option<String>>>(&mut self, password: T) -> &mut Self {
|
||||
self.prepared_identity = None;
|
||||
self.key_password = password.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_identity(&mut self, identity: Option<ClientIdentity>) -> &mut Self {
|
||||
self.prepared_identity = identity;
|
||||
self.certificate = None;
|
||||
self.sslkey = None;
|
||||
self.key_password = None;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(&self) -> GpParams {
|
||||
GpParams {
|
||||
prepared_identity: self.prepared_identity.clone(),
|
||||
os_profile: self.os_profile.clone(),
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
certificate: self.certificate.clone(),
|
||||
@@ -209,24 +264,64 @@ impl TryFrom<&GpParams> for Client {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &GpParams) -> Result<Self, Self::Error> {
|
||||
let mut builder = Client::builder()
|
||||
.danger_accept_invalid_certs(value.ignore_tls_errors)
|
||||
.user_agent(value.user_agent());
|
||||
|
||||
if let Some(cert) = value.certificate.as_deref() {
|
||||
info!("Using client certificate authentication...");
|
||||
let identity = create_identity(cert, value.sslkey.as_deref(), value.key_password.as_deref())?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
|
||||
let client = builder.build()?;
|
||||
Ok(client)
|
||||
Ok(value.client_builder()?.build()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn path_identity_settings_replace_a_prepared_snapshot() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let setters: [fn(&mut GpParamsBuilder); 3] = [
|
||||
|builder| {
|
||||
builder.certificate(Some("missing-replacement-certificate.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.sslkey(Some("replacement-key.pem".into()));
|
||||
},
|
||||
|builder| {
|
||||
builder.key_password(Some("replacement-password".into()));
|
||||
},
|
||||
];
|
||||
for setter in setters {
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder.client_identity(Some(identity.clone()));
|
||||
setter(&mut builder);
|
||||
let params = builder.build();
|
||||
assert!(
|
||||
params.client_identity().is_none(),
|
||||
"Path settings must not silently use the previous identity"
|
||||
);
|
||||
if params.certificate.is_some() {
|
||||
assert!(
|
||||
Client::try_from(¶ms).is_err(),
|
||||
"The replacement certificate path must actually be loaded"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_identity_replaces_paths_and_can_be_explicitly_disabled() {
|
||||
let identity = ClientIdentity::load("tests/files/badssl.com-client.pem", None, Some("badssl.com")).unwrap();
|
||||
let mut builder = GpParams::builder(profile(ClientOs::Linux));
|
||||
builder
|
||||
.certificate(Some("missing-certificate.pem".into()))
|
||||
.sslkey(Some("missing-key.pem".into()))
|
||||
.key_password(Some("unused-password".into()))
|
||||
.client_identity(Some(identity));
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_some());
|
||||
assert!(params.certificate.is_none() && params.sslkey.is_none() && params.key_password.is_none());
|
||||
assert!(Client::try_from(¶ms).is_ok());
|
||||
builder.certificate(None);
|
||||
let params = builder.build();
|
||||
assert!(params.client_identity().is_none());
|
||||
assert!(params.certificate.is_none());
|
||||
}
|
||||
use crate::os_profile::runtime_client_os;
|
||||
|
||||
fn profile(client_os: ClientOs) -> OsProfile {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// The GUI's choice of HIP report source. gpservice resolves execution details.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, Type, PartialEq, Eq)]
|
||||
#[serde(tag = "source", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum HipSource {
|
||||
#[default]
|
||||
Disabled,
|
||||
Generated,
|
||||
Edited {
|
||||
report_id: String,
|
||||
},
|
||||
UserScript {
|
||||
path: String,
|
||||
},
|
||||
ApprovedRootScript {
|
||||
approval_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Type, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HipApprovalStatus {
|
||||
Valid,
|
||||
Revoked,
|
||||
Corrupt,
|
||||
OtherUser,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn source_round_trips_without_execution_uid_or_wrapper() {
|
||||
let source = HipSource::ApprovedRootScript {
|
||||
approval_id: "approved-1".into(),
|
||||
};
|
||||
let json = serde_json::to_value(&source).unwrap();
|
||||
assert_eq!(
|
||||
json,
|
||||
serde_json::json!({ "source": "approvedRootScript", "approvalId": "approved-1" })
|
||||
);
|
||||
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
pub mod auth;
|
||||
pub mod cookie_store;
|
||||
pub mod credential;
|
||||
pub mod device_anchor;
|
||||
pub mod error;
|
||||
pub mod gateway;
|
||||
pub mod gp_params;
|
||||
pub mod hip;
|
||||
pub mod log_format;
|
||||
pub mod os_profile;
|
||||
pub mod params;
|
||||
pub mod portal;
|
||||
@@ -17,6 +20,3 @@ pub mod logger;
|
||||
|
||||
#[cfg(feature = "clap")]
|
||||
pub mod clap;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub const GP_API_KEY: &[u8; 32] = &[0; 32];
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Machine-readable log output.
|
||||
//!
|
||||
//! The default human format is fine at a terminal, but tools that drive
|
||||
//! gpclient headless have to parse it — and end up matching on prose, including
|
||||
//! text that comes from dependencies rather than from this project. JSON lines
|
||||
//! give those callers fields instead.
|
||||
//!
|
||||
//! This module deliberately depends only on `log` and `serde_json`, so every
|
||||
//! binary can use it without pulling in a logging backend, and so the rendering
|
||||
//! can be tested without installing a global logger.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
/// How log records are rendered.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
|
||||
pub enum LogFormat {
|
||||
/// The human-readable default.
|
||||
#[default]
|
||||
Text,
|
||||
/// One JSON object per line.
|
||||
Json,
|
||||
}
|
||||
|
||||
impl LogFormat {
|
||||
/// The name this format is known by on a command line.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Json => "json",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a [`log::Record`] to `w` as one JSON line, newline included.
|
||||
///
|
||||
/// This is the form a logging backend needs, and it writes into the buffer the
|
||||
/// backend already handed us rather than allocating a line to be copied. It
|
||||
/// takes a `Record` and a `Write` rather than any backend's own types, so `log`
|
||||
/// stays the only logging dependency here — with `env_logger`, this function
|
||||
/// *is* the format callback:
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Not compiled as a doctest: env_logger is an optional dependency of this
|
||||
/// // crate, so it is not linked when the docs are built.
|
||||
/// env_logger::builder().format(write_json_record).init();
|
||||
/// ```
|
||||
pub fn write_json_record<W: Write>(w: &mut W, record: &log::Record) -> io::Result<()> {
|
||||
writeln!(
|
||||
w,
|
||||
"{}",
|
||||
json!({
|
||||
"timestamp": Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),
|
||||
"level": record.level().as_str(),
|
||||
"target": record.target(),
|
||||
"message": record.args().to_string(),
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{DateTime, SubsecRound};
|
||||
use log::Level;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse(line: &str) -> serde_json::Value {
|
||||
serde_json::from_str(line).expect("each line must be valid JSON")
|
||||
}
|
||||
|
||||
fn write_record(record: &log::Record) -> String {
|
||||
let mut buf = Vec::new();
|
||||
write_json_record(&mut buf, record).expect("writing to a Vec cannot fail");
|
||||
String::from_utf8(buf).expect("output should be UTF-8")
|
||||
}
|
||||
|
||||
/// The fields a consumer is promised, taken off a `Record` as a backend
|
||||
/// hands it over.
|
||||
#[test]
|
||||
fn record_renders_the_expected_fields() {
|
||||
// Built inline: `format_args!` borrows its arguments for the statement it
|
||||
// appears in, so a `Record` held in a `let` would outlive them.
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Error)
|
||||
.target("gpclient::connect")
|
||||
.args(format_args!("portal {} unreachable", "vpn.example.com"))
|
||||
.build(),
|
||||
));
|
||||
|
||||
assert_eq!(v["level"], "ERROR");
|
||||
assert_eq!(v["target"], "gpclient::connect");
|
||||
assert_eq!(v["message"], "portal vpn.example.com unreachable");
|
||||
}
|
||||
|
||||
/// Without a timestamp the JSON output would be strictly less informative
|
||||
/// than the text format it replaces, and a consumer could not order or
|
||||
/// correlate events.
|
||||
#[test]
|
||||
fn records_carry_a_utc_timestamp() {
|
||||
let before = Utc::now();
|
||||
let v = parse(&write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("connected"))
|
||||
.build(),
|
||||
));
|
||||
let after = Utc::now();
|
||||
|
||||
let ts = v["timestamp"].as_str().expect("timestamp must be a string");
|
||||
let parsed = DateTime::parse_from_rfc3339(ts)
|
||||
.unwrap_or_else(|e| panic!("timestamp must be RFC 3339: {ts:?} ({e})"))
|
||||
.with_timezone(&Utc);
|
||||
|
||||
assert!(ts.ends_with('Z'), "timestamp must be UTC, got {ts:?}");
|
||||
assert!(
|
||||
parsed >= before.trunc_subsecs(3) && parsed <= after,
|
||||
"timestamp {parsed} should be between {before} and {after}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The backend appends records to one stream, so each has to terminate its
|
||||
/// own line — exactly one, or the next record joins this one. A message
|
||||
/// containing a newline must be escaped into the JSON string rather than
|
||||
/// splitting the record in two.
|
||||
#[test]
|
||||
fn record_ends_with_a_single_newline() {
|
||||
let out = write_record(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("t")
|
||||
.args(format_args!("first\nsecond"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
assert!(out.ends_with('\n'), "record must terminate its line: {out:?}");
|
||||
assert_eq!(out.matches('\n').count(), 1, "record must be one line: {out:?}");
|
||||
assert_eq!(parse(&out)["message"], "first\nsecond", "the newline must survive");
|
||||
}
|
||||
|
||||
/// `as_str` is what gets passed to a child process on the command line, and
|
||||
/// clap parses that with the names from its own `ValueEnum` derive. If the
|
||||
/// two ever disagree, gpclient hands gpauth a value gpauth rejects.
|
||||
#[cfg(feature = "clap")]
|
||||
#[test]
|
||||
fn as_str_agrees_with_the_names_clap_parses() {
|
||||
use clap::ValueEnum;
|
||||
|
||||
for format in [LogFormat::Text, LogFormat::Json] {
|
||||
let clap_name = format
|
||||
.to_possible_value()
|
||||
.expect("every variant is selectable")
|
||||
.get_name()
|
||||
.to_owned();
|
||||
|
||||
assert_eq!(format.as_str(), clap_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
+132
-11
@@ -1,21 +1,44 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::bail;
|
||||
use env_logger::Logger;
|
||||
use log::{Level, warn};
|
||||
use log::{Level, Log, warn};
|
||||
use log_reload::{ReloadHandle, ReloadLog};
|
||||
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
|
||||
use crate::log_format::{LogFormat, write_json_record};
|
||||
|
||||
pub fn init(level: Level) {
|
||||
// Initialize the env_logger and global max level to trace, the logs will be
|
||||
// filtered by the outer logger
|
||||
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
|
||||
init_with_logger(level, logger);
|
||||
pub const LOG_BACKEND_ENV: &str = "GP_LOG_BACKEND";
|
||||
pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
|
||||
|
||||
type BoxedLogger = Box<dyn Log + Send + Sync>;
|
||||
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
|
||||
|
||||
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if log_format == LogFormat::Text && macos_unified_log_enabled() {
|
||||
init_with_logger(level, MacosLogger::new(subsystem, category));
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (subsystem, category);
|
||||
|
||||
init_with_logger(level, build_env_logger(log_format).build());
|
||||
}
|
||||
|
||||
pub fn init_with_logger(level: Level, logger: Logger) {
|
||||
if let Some(_) = LOG_HANDLE.get() {
|
||||
fn build_env_logger(log_format: LogFormat) -> env_logger::Builder {
|
||||
let mut builder = env_logger::builder();
|
||||
// The outer reloadable logger owns filtering.
|
||||
builder.filter_level(log::LevelFilter::Trace);
|
||||
|
||||
if log_format == LogFormat::Json {
|
||||
builder.format(write_json_record);
|
||||
}
|
||||
|
||||
builder
|
||||
}
|
||||
|
||||
pub fn init_with_logger(level: Level, logger: impl Log + Send + Sync + 'static) {
|
||||
if LOG_HANDLE.get().is_some() {
|
||||
warn!("Logger already initialized");
|
||||
return;
|
||||
}
|
||||
@@ -23,7 +46,7 @@ pub fn init_with_logger(level: Level, logger: Logger) {
|
||||
log::set_max_level(log::LevelFilter::Trace);
|
||||
|
||||
// Create a new logger that will filter the logs based on the max level
|
||||
let level_filter_logger = log_reload::LevelFilter::new(level, logger);
|
||||
let level_filter_logger = log_reload::LevelFilter::new(level, Box::new(logger) as BoxedLogger);
|
||||
|
||||
let reload_log = ReloadLog::new(level_filter_logger);
|
||||
let handle = reload_log.handle();
|
||||
@@ -42,3 +65,101 @@ pub fn set_max_level(level: Level) -> anyhow::Result<()> {
|
||||
.modify(|logger| logger.set_level(level))
|
||||
.map_err(|e| anyhow::anyhow!(e))
|
||||
}
|
||||
|
||||
pub fn macos_unified_log_enabled() -> bool {
|
||||
cfg!(target_os = "macos") && std::env::var(LOG_BACKEND_ENV).as_deref() == Ok(MACOS_UNIFIED_LOG_BACKEND)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub struct MacosLogger {
|
||||
inner: oslog::OsLog,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl MacosLogger {
|
||||
pub fn new(subsystem: &str, category: &str) -> Self {
|
||||
Self {
|
||||
inner: oslog::OsLog::new(subsystem, category),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self, level: Level, target: &str, message: &str) {
|
||||
self
|
||||
.inner
|
||||
.with_level(macos_log_level(level), &format!("[{target}] {message}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Log for MacosLogger {
|
||||
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
|
||||
self.inner.level_is_enabled(macos_log_level(metadata.level()))
|
||||
}
|
||||
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if self.enabled(record.metadata()) {
|
||||
self.write(record.level(), record.target(), &record.args().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_log_level(level: Level) -> oslog::Level {
|
||||
match level {
|
||||
Level::Trace | Level::Debug => oslog::Level::Debug,
|
||||
Level::Info => oslog::Level::Default,
|
||||
Level::Warn | Level::Error => oslog::Level::Error,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Write for Captured {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_format_configures_the_env_logger() {
|
||||
let captured = Captured::default();
|
||||
let logger = build_env_logger(LogFormat::Json)
|
||||
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
|
||||
.build();
|
||||
|
||||
logger.log(
|
||||
&log::Record::builder()
|
||||
.level(Level::Info)
|
||||
.target("gpauth")
|
||||
.args(format_args!("authenticating"))
|
||||
.build(),
|
||||
);
|
||||
|
||||
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
|
||||
assert_eq!(value["message"], "authenticating");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn info_logs_use_the_persistent_macos_level() {
|
||||
assert_eq!(macos_log_level(Level::Info) as u8, oslog::Level::Default as u8);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -20,8 +23,39 @@ impl HostIdentity {
|
||||
Self::collect_with_host_id(None)
|
||||
}
|
||||
|
||||
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
|
||||
Self::collect_with_host_id_and_control(None, control)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
|
||||
RuntimeNativeHostIdentity::collect(host_id).into_host_identity()
|
||||
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
|
||||
Ok(identity) => identity,
|
||||
Err(error) => {
|
||||
log::warn!("Host identity collection was unavailable: {error}");
|
||||
Self::default_with_host_id(host_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort convenience callers retain the established derived identity
|
||||
/// when native collection is unavailable. Controlled HIP callers get errors.
|
||||
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
|
||||
Self::from_parts(
|
||||
fallback_hostname(),
|
||||
resolve_host_id(host_id, fallback_host_id),
|
||||
String::new(),
|
||||
primary_mac_colon().unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn collect_with_host_id_and_control(
|
||||
host_id: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<Self> {
|
||||
control.check()?;
|
||||
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -29,7 +63,8 @@ impl HostIdentity {
|
||||
Self::from_parts(computer, host_id, serialno, mac_addr)
|
||||
}
|
||||
|
||||
pub(crate) fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
/// Construct a host identity from an already collected or negotiated snapshot.
|
||||
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
|
||||
let host_id = non_empty(host_id, fallback_host_id());
|
||||
let computer = non_empty(computer, fallback_hostname());
|
||||
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
|
||||
@@ -163,12 +198,12 @@ fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
use std::process::Command;
|
||||
|
||||
use super::{
|
||||
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
|
||||
primary_mac_colon, resolve_host_id,
|
||||
};
|
||||
use crate::process::collection::{CollectionControl, CollectorCommands};
|
||||
use std::io;
|
||||
|
||||
pub(super) struct RuntimeNativeHostIdentity;
|
||||
|
||||
@@ -177,74 +212,80 @@ mod platform {
|
||||
ClientOs::Mac
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let native_mac = macos_builtin_mac().or_else(primary_mac_colon);
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn CollectionControl,
|
||||
) -> io::Result<NativeHostIdentitySnapshot> {
|
||||
let commands = CollectorCommands::new(control);
|
||||
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
|
||||
control.check()?;
|
||||
let host_id = resolve_host_id(host_id_override, || {
|
||||
native_mac
|
||||
.clone()
|
||||
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
|
||||
});
|
||||
NativeHostIdentitySnapshot {
|
||||
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
|
||||
let serial_number = collect_macos_serial_number(&commands)?;
|
||||
control.check()?;
|
||||
Ok(NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
computer: macos_computer_name().unwrap_or_else(fallback_hostname),
|
||||
serial_number: collect_macos_serial_number(),
|
||||
computer,
|
||||
serial_number,
|
||||
mac_address: native_mac,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn macos_computer_name() -> Option<String> {
|
||||
["ComputerName", "LocalHostName"].into_iter().find_map(|name| {
|
||||
let output = Command::new("scutil").args(["--get", name]).output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
|
||||
Ok(
|
||||
commands
|
||||
.run(program, args)?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok()),
|
||||
)
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
for name in ["ComputerName", "LocalHostName"] {
|
||||
if let Some(value) = output(commands, "scutil", &["--get", name])?
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_builtin_mac() -> Option<String> {
|
||||
macos_networksetup_mac("Wi-Fi")
|
||||
.or_else(|| macos_networksetup_mac("AirPort"))
|
||||
.or_else(macos_system_profiler_wifi_mac)
|
||||
}
|
||||
|
||||
fn macos_networksetup_mac(port_name: &str) -> Option<String> {
|
||||
let output = Command::new("networksetup")
|
||||
.arg("-listallhardwareports")
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
{
|
||||
return Ok(Some(value));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
|
||||
for name in ["Wi-Fi", "AirPort"] {
|
||||
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
|
||||
return Ok(Some(mac));
|
||||
}
|
||||
}
|
||||
}
|
||||
macos_system_profiler_wifi_mac(commands)
|
||||
}
|
||||
|
||||
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
|
||||
let mut in_port = false;
|
||||
for line in stdout.lines() {
|
||||
if let Some(port) = line.strip_prefix("Hardware Port: ") {
|
||||
in_port = port == port_name;
|
||||
in_port = port == name;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn macos_system_profiler_wifi_mac() -> Option<String> {
|
||||
let output = Command::new("system_profiler").arg("SPNetworkDataType").output().ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut in_wifi = false;
|
||||
for line in stdout.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -252,29 +293,24 @@ mod platform {
|
||||
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
|
||||
return normalize_mac_colon(mac);
|
||||
return Ok(normalize_mac_colon(mac));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn collect_macos_serial_number() -> Option<String> {
|
||||
let output = Command::new("ioreg")
|
||||
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let stdout = String::from_utf8(output.stdout).ok()?;
|
||||
|
||||
stdout.lines().find_map(|line| {
|
||||
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
|
||||
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(stdout.lines().find_map(|line| {
|
||||
line
|
||||
.split_once("IOPlatformSerialNumber")
|
||||
.and_then(|(_, value)| value.split_once('='))
|
||||
.map(|(_, value)| value.trim().trim_matches('"').to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +327,17 @@ mod platform {
|
||||
ClientOs::Windows
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
let host_id = resolve_host_id(host_id_override, Self::host_id);
|
||||
NativeHostIdentitySnapshot {
|
||||
host_id,
|
||||
@@ -362,6 +408,7 @@ mod platform {
|
||||
mod platform {
|
||||
use super::{
|
||||
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
|
||||
serial_number,
|
||||
};
|
||||
use log::debug;
|
||||
|
||||
@@ -372,7 +419,17 @@ mod platform {
|
||||
ClientOs::Linux
|
||||
}
|
||||
|
||||
pub(super) fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
pub(super) fn collect_with_control(
|
||||
host_id_override: Option<&str>,
|
||||
control: &dyn super::CollectionControl,
|
||||
) -> super::io::Result<NativeHostIdentitySnapshot> {
|
||||
control.check()?;
|
||||
let identity = Self::collect(host_id_override);
|
||||
control.check()?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
|
||||
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
|
||||
debug!("Runtime host-id source: explicit override ({})", host_id);
|
||||
}
|
||||
@@ -429,9 +486,17 @@ mod platform {
|
||||
}
|
||||
|
||||
fn collect_linux_serial_number() -> Option<String> {
|
||||
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
|
||||
.iter()
|
||||
.find_map(|path| read_linux_identity_file(path))
|
||||
resolve_linux_serial_number(
|
||||
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
|
||||
collect_linux_product_uuid,
|
||||
)
|
||||
}
|
||||
|
||||
fn resolve_linux_serial_number(
|
||||
product_serial: Option<String>,
|
||||
product_uuid: impl FnOnce() -> Option<String>,
|
||||
) -> Option<String> {
|
||||
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -446,6 +511,20 @@ mod platform {
|
||||
);
|
||||
assert_eq!(normalize_uuid("not-a-uuid"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
|
||||
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
|
||||
|
||||
assert_eq!(
|
||||
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
|
||||
Some("product-serial".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_linux_serial_number(None, || uuid),
|
||||
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +532,15 @@ mod platform {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_identity_collection_propagates_cancellation() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = HostIdentity::collect_with_control(&control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_produces_non_empty_identity() {
|
||||
let identity = HostIdentity::collect();
|
||||
@@ -505,7 +593,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn native_snapshot_uses_host_id_as_derivation_seed() {
|
||||
let native = RuntimeNativeHostIdentity::collect(None);
|
||||
let native =
|
||||
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
|
||||
|
||||
assert!(!native.host_id.is_empty());
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ mod serial_number;
|
||||
|
||||
pub use host_identity::HostIdentity;
|
||||
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl};
|
||||
use std::{io, time::Duration};
|
||||
|
||||
use common::constants::{GP_CLIENT_VERSION_LINUX, GP_CLIENT_VERSION_MACOS, GP_CLIENT_VERSION_WINDOWS, GP_USER_AGENT};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -366,6 +369,7 @@ impl OsProfile {
|
||||
pub struct OsProfileBuilder {
|
||||
client_os: ClientOs,
|
||||
client_version: Option<String>,
|
||||
os_version_override: Option<String>,
|
||||
computer_name_override: Option<String>,
|
||||
host_id_override: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
@@ -377,6 +381,7 @@ impl OsProfileBuilder {
|
||||
Self {
|
||||
client_os,
|
||||
client_version: None,
|
||||
os_version_override: None,
|
||||
computer_name_override: None,
|
||||
host_id_override: None,
|
||||
host_identity: None,
|
||||
@@ -394,6 +399,13 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Preserve an explicitly negotiated operating system version.
|
||||
pub fn os_version(mut self, version: impl Into<String>) -> Self {
|
||||
let version = version.into();
|
||||
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
|
||||
self
|
||||
}
|
||||
|
||||
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
|
||||
self.host_identity = Some(identity);
|
||||
self
|
||||
@@ -411,31 +423,67 @@ impl OsProfileBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Build a best-effort profile with a bounded native collection budget.
|
||||
/// Use `build_with_control` when interruption or timeout must be reported.
|
||||
pub fn build(self) -> OsProfile {
|
||||
match self
|
||||
.clone()
|
||||
.build_with_control(&CollectionBudget::new(Duration::from_secs(60)))
|
||||
{
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
log::warn!("OS profile collection was unavailable: {error}");
|
||||
let identity = self
|
||||
.host_identity
|
||||
.clone()
|
||||
.unwrap_or_else(|| HostIdentity::default_with_host_id(self.host_id_override.as_deref()));
|
||||
let (os_version, software_version) = match self.client_os {
|
||||
ClientOs::Mac => (
|
||||
format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
|
||||
DEFAULT_MACOS_VERSION.into(),
|
||||
),
|
||||
os => (target::os_version(os), target::software_version(os)),
|
||||
};
|
||||
self.finish(identity, os_version, software_version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_with_control(self, control: &dyn CollectionControl) -> io::Result<OsProfile> {
|
||||
control.check()?;
|
||||
let host_identity = match (&self.host_identity, &self.host_id_override) {
|
||||
(Some(identity), _) => identity.clone(),
|
||||
(None, host_id) => HostIdentity::collect_with_host_id_and_control(host_id.as_deref(), control)?,
|
||||
};
|
||||
let (os_version, software_version) = if self.client_os == ClientOs::Mac {
|
||||
let version = macos_version_with_control(control)?;
|
||||
(format!("Apple Mac OS X {version}"), version)
|
||||
} else {
|
||||
(
|
||||
target::os_version(self.client_os),
|
||||
target::software_version(self.client_os),
|
||||
)
|
||||
};
|
||||
control.check()?;
|
||||
Ok(self.finish(host_identity, os_version, software_version))
|
||||
}
|
||||
|
||||
fn finish(self, host_identity: HostIdentity, default_os_version: String, software_version: String) -> OsProfile {
|
||||
let client_version = self
|
||||
.client_version
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().to_string());
|
||||
|
||||
let host_identity = match (self.host_identity, self.host_id_override) {
|
||||
(Some(identity), _) => identity,
|
||||
(None, host_id) => HostIdentity::collect_with_host_id(host_id.as_deref()),
|
||||
};
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
.unwrap_or_else(|| self.client_os.default_client_version().into());
|
||||
let profile_identity =
|
||||
ProfileHostIdentity::for_client_os(self.client_os, &host_identity, self.computer_name_override);
|
||||
let os_version = target::os_version(self.client_os);
|
||||
let software_version = target::software_version(self.client_os);
|
||||
let os_vendor = target::os_vendor(self.client_os);
|
||||
|
||||
let os_version = self.os_version_override.unwrap_or(default_os_version);
|
||||
let user_agent = self
|
||||
.user_agent
|
||||
.unwrap_or_else(|| format!("{}/{} ({})", GP_USER_AGENT, client_version, os_version));
|
||||
|
||||
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
|
||||
OsProfile {
|
||||
client_os: self.client_os,
|
||||
os_version,
|
||||
software_version,
|
||||
os_vendor,
|
||||
os_vendor: target::os_vendor(self.client_os),
|
||||
client_version,
|
||||
host_identity,
|
||||
profile_identity,
|
||||
@@ -500,14 +548,28 @@ fn runtime_distro_or(fallback: &str) -> String {
|
||||
}
|
||||
|
||||
fn macos_version() -> String {
|
||||
if runtime_client_os() == ClientOs::Mac {
|
||||
match os_info::get().version() {
|
||||
os_info::Version::Unknown => DEFAULT_MACOS_VERSION.to_string(),
|
||||
v => v.to_string(),
|
||||
}
|
||||
} else {
|
||||
DEFAULT_MACOS_VERSION.to_string()
|
||||
macos_version_with_control(&CollectionBudget::new(Duration::from_secs(60))).unwrap_or_else(|error| {
|
||||
log::warn!("Operating system version collection was unavailable: {error}");
|
||||
DEFAULT_MACOS_VERSION.into()
|
||||
})
|
||||
}
|
||||
|
||||
fn macos_version_with_control(control: &dyn CollectionControl) -> io::Result<String> {
|
||||
control.check()?;
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let commands = crate::process::collection::CollectorCommands::new(control);
|
||||
let version = commands
|
||||
.run("sw_vers", &["-productVersion"])?
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||
.map(|version| version.trim().to_string())
|
||||
.filter(|version| !version.is_empty());
|
||||
control.check()?;
|
||||
Ok(version.unwrap_or_else(|| DEFAULT_MACOS_VERSION.into()))
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
Ok(DEFAULT_MACOS_VERSION.into())
|
||||
}
|
||||
|
||||
fn macos_os_string() -> String {
|
||||
@@ -691,6 +753,37 @@ mod target_identity {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
|
||||
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.build_with_control(&cancelled)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
let expired = CollectionBudget::new(Duration::ZERO);
|
||||
let error = OsProfileBuilder::new(ClientOs::Linux)
|
||||
.build_with_control(&expired)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
|
||||
let identity = HostIdentity::from_parts(
|
||||
"device".into(),
|
||||
"host".into(),
|
||||
"serial".into(),
|
||||
"00:11:22:33:44:55".into(),
|
||||
);
|
||||
let profile = OsProfileBuilder::new(ClientOs::Mac)
|
||||
.host_identity(identity)
|
||||
.client_version("6.3.3")
|
||||
.os_version("negotiated-system-version")
|
||||
.build();
|
||||
assert_eq!(profile.os_version(), "negotiated-system-version");
|
||||
assert!(profile.user_agent().contains("negotiated-system-version"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csc_support_defaults_match_official_profiles() {
|
||||
assert!(!ClientOs::Linux.default_csc_support());
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::bail;
|
||||
use dns_lookup::lookup_addr;
|
||||
use log::{debug, info, warn};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{
|
||||
@@ -14,6 +14,7 @@ use crate::{
|
||||
gateway::{Gateway, parse_gateways},
|
||||
gp_params::GpParams,
|
||||
params,
|
||||
session::{InternalSessionPolicy, network::InternalHostDetection},
|
||||
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt},
|
||||
};
|
||||
|
||||
@@ -35,6 +36,7 @@ pub struct PortalConfig {
|
||||
* - Some(true): Internal host detection is supported and the user is connected to the internal network
|
||||
*/
|
||||
internal_host_detection: Option<bool>,
|
||||
internal_detection: Option<InternalHostDetection>,
|
||||
/**
|
||||
* The version returned by the portal config, if any
|
||||
*/
|
||||
@@ -47,6 +49,7 @@ pub struct PortalConfig {
|
||||
* Whether the portal policy enables default-browser authentication.
|
||||
*/
|
||||
default_browser: Option<bool>,
|
||||
internal_session_policy: Option<InternalSessionPolicy>,
|
||||
}
|
||||
|
||||
impl PortalConfig {
|
||||
@@ -70,6 +73,10 @@ impl PortalConfig {
|
||||
self.internal_host_detection
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
|
||||
pub fn connect_method(&self) -> Option<&str> {
|
||||
self.connect_method.as_deref()
|
||||
}
|
||||
@@ -86,6 +93,10 @@ impl PortalConfig {
|
||||
self.default_browser
|
||||
}
|
||||
|
||||
pub fn internal_session_policy(&self) -> Option<InternalSessionPolicy> {
|
||||
self.internal_session_policy
|
||||
}
|
||||
|
||||
/// In-place sort the gateways by region
|
||||
pub fn sort_gateways(&mut self, region: &str) {
|
||||
let preferred_gateway = self.find_preferred_gateway(region);
|
||||
@@ -129,7 +140,14 @@ impl PortalConfig {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<PortalConfig> {
|
||||
/// Cancellation is handled inside the request so a running native detection
|
||||
/// helper is always cancelled and joined. Do not drop this future on disconnect.
|
||||
pub async fn retrieve_config(
|
||||
portal: &str,
|
||||
cred: &Credential,
|
||||
gp_params: &GpParams,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let portal = normalize_server(portal)?;
|
||||
let server = remove_url_scheme(&portal);
|
||||
|
||||
@@ -146,29 +164,35 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
|
||||
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
|
||||
info!("Portal config request params: {}", redact_form_params(&body_pairs));
|
||||
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
let res_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = async {
|
||||
let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| {
|
||||
warn!("Network error: {:?}", e);
|
||||
anyhow::anyhow!(PortalError::NetworkError(e))
|
||||
})?;
|
||||
|
||||
let res_xml = parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
parse_gp_response(res).await.or_else(|err| {
|
||||
if err.status == StatusCode::NOT_FOUND {
|
||||
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
|
||||
}
|
||||
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
if err.is_status_error() {
|
||||
warn!("{err}");
|
||||
bail!("Portal config error: {}", err.reason);
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})?;
|
||||
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
|
||||
})
|
||||
} => result?,
|
||||
};
|
||||
|
||||
if res_xml.is_empty() {
|
||||
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
|
||||
}
|
||||
|
||||
debug!("Portal config response: {}", res_xml);
|
||||
debug!("Portal config response received: {} bytes", res_xml.len());
|
||||
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
|
||||
if csc::is_config_criteria(&root) {
|
||||
@@ -178,14 +202,18 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
|
||||
"Portal returned CSC criteria but CSC support is disabled".to_string()
|
||||
));
|
||||
}
|
||||
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
|
||||
debug!("Portal CSC config response: {}", csc_xml);
|
||||
let csc_xml = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
|
||||
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
|
||||
};
|
||||
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
|
||||
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
|
||||
return parse_portal_config(&server, cred, root);
|
||||
return parse_portal_config(&server, cred, root, cancellation).await;
|
||||
}
|
||||
|
||||
info!("Portal did not return CSC criteria");
|
||||
parse_portal_config(&server, cred, root)
|
||||
parse_portal_config(&server, cred, root, cancellation).await
|
||||
}
|
||||
|
||||
async fn retrieve_csc_config(
|
||||
@@ -245,12 +273,31 @@ fn present(value: Option<&str>) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
|
||||
let mut ihd_enabled = false;
|
||||
let mut prefer_internal = false;
|
||||
if let Some(ihd_node) = root.descendant("internal-host-detection") {
|
||||
ihd_enabled = true;
|
||||
prefer_internal = internal_host_detect(ihd_node)
|
||||
async fn parse_portal_config(
|
||||
server: &str,
|
||||
cred: &Credential,
|
||||
root: Element,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<PortalConfig> {
|
||||
let internal_detection = root
|
||||
.descendant("internal-host-detection")
|
||||
.map(parse_internal_detection)
|
||||
.transpose()
|
||||
.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection policy is unavailable: {error}");
|
||||
None
|
||||
})
|
||||
.flatten();
|
||||
let prefer_internal = match &internal_detection {
|
||||
Some(detection) => detection.detect(cancellation).await.unwrap_or_else(|error| {
|
||||
warn!("Internal host detection failed: {error}");
|
||||
false
|
||||
}),
|
||||
None => false,
|
||||
};
|
||||
|
||||
if cancellation.is_cancelled() {
|
||||
bail!("Portal configuration cancelled");
|
||||
}
|
||||
|
||||
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
|
||||
@@ -275,6 +322,7 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
|
||||
info!("Detected portal version: {:?}", version);
|
||||
let allow_extend_session = parse_allow_extend_session(&root);
|
||||
let default_browser = parse_default_browser(&root);
|
||||
let internal_session_policy = parse_internal_session_policy(&root).ok();
|
||||
|
||||
Ok(PortalConfig {
|
||||
portal: server.to_string(),
|
||||
@@ -283,13 +331,42 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
|
||||
gateways,
|
||||
connect_method,
|
||||
config_digest: config_digest.map(|s| s.to_string()),
|
||||
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
|
||||
internal_host_detection: internal_detection.as_ref().map(|_| prefer_internal),
|
||||
internal_detection,
|
||||
version,
|
||||
allow_extend_session,
|
||||
default_browser,
|
||||
internal_session_policy,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_internal_session_policy(root: &Element) -> anyhow::Result<InternalSessionPolicy> {
|
||||
let hip = root.descendant("hip-collection");
|
||||
let interval = hip
|
||||
.and_then(|hip| hip.child("hip-report-interval"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let collect = hip
|
||||
.and_then(|hip| hip.child("collect-hip-data"))
|
||||
.map(|element| element.get_text().unwrap_or_default().into_owned());
|
||||
let interval = parse_policy_number(interval, 3600, "hip-report-interval")?;
|
||||
let collect = match collect.as_deref().map(str::trim) {
|
||||
None | Some("yes") => true,
|
||||
Some("no") => false,
|
||||
Some(_) => bail!("Invalid portal collect-hip-data policy"),
|
||||
};
|
||||
InternalSessionPolicy::new(interval, collect)
|
||||
}
|
||||
|
||||
fn parse_policy_number(value: Option<String>, default: u32, field: &str) -> anyhow::Result<u32> {
|
||||
match value {
|
||||
Some(value) => value
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("Invalid portal {field} policy")),
|
||||
None => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_default_browser(root: &Element) -> Option<bool> {
|
||||
match root.descendant_text("default-browser")?.trim() {
|
||||
"yes" => Some(true),
|
||||
@@ -313,49 +390,94 @@ fn parse_connect_method(root: &Element) -> Option<String> {
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
// Perform DNS lookup and compare the result with the expected hostname
|
||||
fn internal_host_detect(element: &Element) -> bool {
|
||||
fn parse_internal_detection(element: &Element) -> anyhow::Result<Option<InternalHostDetection>> {
|
||||
let ip_info = [
|
||||
(element.child_text("ip-address"), element.child_text("host")),
|
||||
(element.child_text("ipv6-address"), element.child_text("ipv6-host")),
|
||||
];
|
||||
|
||||
info!("Found internal-host-detection, performing DNS lookup");
|
||||
|
||||
let mut targets = Vec::new();
|
||||
for (ip_address, host) in ip_info.iter() {
|
||||
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref())
|
||||
&& !ip_address.is_empty()
|
||||
&& !host.is_empty()
|
||||
{
|
||||
match ip_address.parse::<std::net::IpAddr>() {
|
||||
Ok(ip) => match lookup_addr(&ip) {
|
||||
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
|
||||
return true;
|
||||
}
|
||||
Ok(host_lookup) => {
|
||||
info!(
|
||||
"rDNS lookup for {} returned {}, expected {}",
|
||||
ip_address, host_lookup, host
|
||||
);
|
||||
}
|
||||
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
|
||||
},
|
||||
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
|
||||
}
|
||||
let address = ip_address.as_deref().filter(|value| !value.is_empty());
|
||||
let host = host.as_deref().filter(|value| !value.is_empty());
|
||||
match (address, host) {
|
||||
(None, None) => {}
|
||||
(Some(address), Some(host)) => targets.push((address.parse()?, host.to_owned())),
|
||||
_ => bail!("Incomplete internal host detection policy"),
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
if targets.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(InternalHostDetection::new(targets)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_non_tunnel_policy_does_not_reject_tunnel_candidates() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>invalid</hip-report-interval></hip-collection><internal-host-detection><ip-address>invalid</ip-address><host>internal.example</host></internal-host-detection><gateways><external><list><entry name='vpn.example'/></list></external></gateways></policy>",
|
||||
);
|
||||
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
|
||||
let config = parse_portal_config("portal.example", &credential, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(config.internal_session_policy().is_none());
|
||||
assert_eq!(config.gateways()[0].server(), "vpn.example");
|
||||
assert_eq!(config.gateways()[0].kind(), crate::gateway::GatewayKind::External);
|
||||
}
|
||||
|
||||
fn parse_xml(xml: &str) -> Element {
|
||||
Element::parse(xml.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_internal_maintenance_policy_with_explicit_units() {
|
||||
let root = parse_xml(
|
||||
"<policy><hip-collection><hip-report-interval>60</hip-report-interval><collect-hip-data>no</collect-hip-data></hip-collection><max-internal-gateway-connection-attempts>3</max-internal-gateway-connection-attempts></policy>",
|
||||
);
|
||||
let policy = parse_internal_session_policy(&root).unwrap();
|
||||
assert_eq!(policy.hip_interval(), std::time::Duration::from_secs(60));
|
||||
assert!(!policy.collect_hip_data());
|
||||
assert_eq!(
|
||||
parse_internal_session_policy(&parse_xml("<policy/>")).unwrap(),
|
||||
InternalSessionPolicy::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_supplied_internal_policy() {
|
||||
for interval in ["0", "-1", "", "4294967295", "not-a-number"] {
|
||||
let root = parse_xml(&format!(
|
||||
"<policy><hip-collection><hip-report-interval>{interval}</hip-report-interval></hip-collection></policy>"
|
||||
));
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
let root = parse_xml("<policy><hip-collection><collect-hip-data>true</collect-hip-data></hip-collection></policy>");
|
||||
assert!(parse_internal_session_policy(&root).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepts_existing_full_portal_fixture() {
|
||||
let root = parse_xml(include_str!("../../tests/files/portal_config.xml"));
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new(
|
||||
"fixture-user",
|
||||
"fixture-password",
|
||||
));
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config.internal_session_policy().unwrap().hip_interval(),
|
||||
std::time::Duration::from_secs(3600)
|
||||
);
|
||||
assert!(!config.gateways().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_allow_extend_session_yes() {
|
||||
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
|
||||
@@ -412,8 +534,8 @@ mod tests {
|
||||
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_csc_policy_response_as_portal_config() {
|
||||
#[tokio::test]
|
||||
async fn parses_csc_policy_response_as_portal_config() {
|
||||
let root = parse_xml(
|
||||
r#"<policy>
|
||||
<portal-userauthcookie>user-cookie</portal-userauthcookie>
|
||||
@@ -431,7 +553,9 @@ mod tests {
|
||||
);
|
||||
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
|
||||
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
|
||||
let config = parse_portal_config("vpn.example.com", &cred, root, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
|
||||
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
use std::{path::PathBuf, process::Stdio};
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
|
||||
#[cfg(feature = "webview-auth")]
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
use super::{command_runner::run_controlled, command_traits::CommandExt};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
auth_executable: Option<&'a str>,
|
||||
gateway: bool,
|
||||
@@ -27,13 +36,20 @@ pub struct SamlAuthLauncher<'a> {
|
||||
clean: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: bool,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: Option<&'a str>,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: Option<AuthWindowTheme>,
|
||||
browser: Option<&'a str>,
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
pub fn new(server: &'a str) -> Self {
|
||||
Self {
|
||||
cancellation: CancellationToken::new(),
|
||||
server,
|
||||
auth_executable: None,
|
||||
gateway: false,
|
||||
@@ -52,8 +68,14 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
clean: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
default_browser: false,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_title: None,
|
||||
#[cfg(feature = "webview-auth")]
|
||||
window_theme: None,
|
||||
browser: None,
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,23 +144,54 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_title(mut self, window_title: &'a str) -> Self {
|
||||
self.window_title = Some(window_title);
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
|
||||
self.window_theme = Some(window_theme);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser(mut self, browser: Option<&'a str>) -> Self {
|
||||
self.browser = browser;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn browser_listen(mut self, browser_listen: Option<IpAddr>) -> Self {
|
||||
self.browser_listen = browser_listen;
|
||||
self
|
||||
}
|
||||
|
||||
/// Render the child's logs the same way as ours.
|
||||
///
|
||||
/// gpauth inherits this process's stderr, so both processes must use the same
|
||||
/// format to keep the stream consistent.
|
||||
pub fn log_format(mut self, log_format: LogFormat) -> Self {
|
||||
self.log_format = log_format;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let mut auth_cmd = Command::new(&program);
|
||||
pub fn cancellation(mut self, cancellation: &CancellationToken) -> Self {
|
||||
self.cancellation = cancellation.clone();
|
||||
self
|
||||
}
|
||||
|
||||
/// The command line this launcher will run.
|
||||
///
|
||||
/// Split out from `launch` so a test can observe the argv the child actually
|
||||
/// receives: asserting on the builder's own fields would not catch an
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -194,28 +247,65 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if self.default_browser {
|
||||
auth_cmd.arg("--default-browser");
|
||||
}
|
||||
|
||||
if let Some(window_title) = self.window_title {
|
||||
auth_cmd.arg("--window-title").arg(window_title);
|
||||
}
|
||||
|
||||
if let Some(window_theme) = self.window_theme {
|
||||
auth_cmd.arg("--window-theme").arg(window_theme.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(browser) = self.browser {
|
||||
auth_cmd.arg("--browser").arg(browser);
|
||||
}
|
||||
|
||||
if let Some(browser_listen) = self.browser_listen {
|
||||
auth_cmd.arg("--browser-listen").arg(browser_listen.to_string());
|
||||
}
|
||||
|
||||
auth_cmd.arg("--log-format").arg(self.log_format.as_str());
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
auth_cmd.arg(verbose);
|
||||
}
|
||||
|
||||
let mut non_root_cmd = auth_cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
auth_cmd
|
||||
}
|
||||
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => {
|
||||
bail!("Failed to spawn {}: {}", program.display(), err);
|
||||
/// Launch the authenticator binary as the current user or SUDO_USER if available.
|
||||
pub async fn launch(self) -> anyhow::Result<Credential> {
|
||||
let program = self
|
||||
.auth_executable
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let command = auth_cmd.into_non_root()?.into_std();
|
||||
let cancellation = self.cancellation;
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
|
||||
})
|
||||
.await?;
|
||||
let output = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
@@ -256,6 +346,45 @@ mod tests {
|
||||
assert_eq!(launcher.client_version, Some("6.0.0"));
|
||||
}
|
||||
|
||||
fn child_args(launcher: SamlAuthLauncher) -> Vec<String> {
|
||||
launcher
|
||||
.build_command(Path::new("gpauth"))
|
||||
.as_std()
|
||||
.get_args()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
#[test]
|
||||
fn json_is_forwarded_to_the_child() {
|
||||
let args = child_args(SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Json));
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "json"]),
|
||||
"expected --log-format json in {args:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The launcher always passes the selected format so the parent and child
|
||||
/// cannot silently drift onto different output formats.
|
||||
#[test]
|
||||
fn text_is_forwarded_to_the_child() {
|
||||
for launcher in [
|
||||
SamlAuthLauncher::new("portal.example.com").log_format(LogFormat::Text),
|
||||
SamlAuthLauncher::new("portal.example.com"),
|
||||
] {
|
||||
let args = child_args(launcher);
|
||||
|
||||
assert!(
|
||||
args.windows(2).any(|pair| pair == ["--log-format", "text"]),
|
||||
"expected --log-format text in {args:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_certificate_options_are_stored() {
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com")
|
||||
@@ -267,4 +396,12 @@ mod tests {
|
||||
assert_eq!(launcher.sslkey, Some("/tmp/client.key"));
|
||||
assert_eq!(launcher.key_password, Some("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_listen_address_is_stored() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let launcher = SamlAuthLauncher::new("portal.example.com").browser_listen(Some(listen_ip));
|
||||
|
||||
assert_eq!(launcher.browser_listen, Some(listen_ip));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use super::command_runner::run_controlled;
|
||||
|
||||
/// Invocation control borrowed by collection; interruption must never be treated
|
||||
/// as an unavailable optional product.
|
||||
pub trait CollectionControl {
|
||||
fn check(&self) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl<F: Fn() -> io::Result<()>> CollectionControl for F {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
self()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CollectionBudget {
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionBudget {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
deadline: Instant::now() + timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CollectionControl for CollectionBudget {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Device information collection timed out",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: usize = 256 * 1024;
|
||||
const TOOL_DIRECTORIES: &[&str] = &[
|
||||
"/usr/bin",
|
||||
"/usr/sbin",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/usr/local/bin",
|
||||
"/usr/local/sbin",
|
||||
#[cfg(target_os = "linux")]
|
||||
"/run/current-system/sw/bin",
|
||||
];
|
||||
|
||||
fn tool_directories() -> Vec<PathBuf> {
|
||||
let configured = std::env::var_os("GP_COMMAND_PATH").unwrap_or_default();
|
||||
let mut directories: Vec<_> = std::env::split_paths(&configured)
|
||||
.filter(|path| path.is_absolute())
|
||||
.collect();
|
||||
directories.extend(TOOL_DIRECTORIES.iter().map(PathBuf::from));
|
||||
directories
|
||||
}
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
resolve_in_directories(name, &tool_directories(), uzers::get_effective_uid() == 0)
|
||||
}
|
||||
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = self.resolve(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
/// Run an installed helper with the same trust checks as system collectors.
|
||||
/// Root only executes helpers protected from unprivileged modification.
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let Some(path) = resolve_executable(path, uzers::get_effective_uid() == 0) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.run_path(&path, args)
|
||||
}
|
||||
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let home = if uzers::get_effective_uid() == 0 {
|
||||
if cfg!(target_os = "macos") {
|
||||
"/var/root"
|
||||
} else {
|
||||
"/root"
|
||||
}
|
||||
} else {
|
||||
"/"
|
||||
};
|
||||
let mut command = Command::new(path);
|
||||
command
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.env("PATH", command_path(uzers::get_effective_uid() == 0)?)
|
||||
.env("LC_ALL", "C")
|
||||
.env("HOME", home)
|
||||
.current_dir("/")
|
||||
.stderr(Stdio::null());
|
||||
match run_controlled(command, self.control, COMMAND_OUTPUT_LIMIT) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_in_directories(name: &str, directories: &[PathBuf], require_root: bool) -> Option<PathBuf> {
|
||||
directories.iter().find_map(|directory| {
|
||||
let directory = fs::canonicalize(directory).ok()?;
|
||||
if require_root && !root_owned_path(&directory) {
|
||||
return None;
|
||||
}
|
||||
resolve_executable(&directory.join(name), require_root)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_executable(path: &Path, require_root: bool) -> Option<PathBuf> {
|
||||
let resolved = fs::canonicalize(path).ok()?;
|
||||
let metadata = fs::metadata(&resolved).ok()?;
|
||||
if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Known command directories, canonicalized and restricted to trusted root
|
||||
/// ownership when used for privileged execution.
|
||||
pub fn command_path(require_root: bool) -> io::Result<std::ffi::OsString> {
|
||||
let configured = tool_directories();
|
||||
let directories = configured.iter().filter_map(|directory| {
|
||||
let resolved = fs::canonicalize(directory).ok()?;
|
||||
if resolved.is_dir() && (!require_root || root_owned_path(&resolved)) {
|
||||
Some(resolved)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
std::env::join_paths(directories).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))
|
||||
}
|
||||
|
||||
fn root_owned_path(path: &Path) -> bool {
|
||||
path.ancestors().all(|part| {
|
||||
fs::symlink_metadata(part).is_ok_and(|metadata| {
|
||||
let mode = metadata.permissions().mode();
|
||||
let writable = mode & 0o022 != 0;
|
||||
// A root-owned sticky directory protects each root-owned descendant
|
||||
// from replacement, including entries in the Nix store.
|
||||
let protected_ancestor = part != path && metadata.is_dir() && mode & 0o1000 != 0;
|
||||
metadata.uid() == 0 && (!writable || protected_ancestor) && !metadata.file_type().is_symlink()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
|
||||
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
|
||||
if uzers::get_effective_uid() != 0 {
|
||||
return;
|
||||
}
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let tool = directory.path().join("collector");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert_eq!(resolve_executable(&tool, true), Some(fs::canonicalize(&tool).unwrap()));
|
||||
// A PATH directory must itself reject unprivileged additions, even with the sticky bit.
|
||||
assert!(!root_owned_path(directory.path()));
|
||||
assert!(resolve_in_directories("collector", &[directory.path().to_owned()], true).is_none());
|
||||
let bin = directory.path().join("bin");
|
||||
fs::create_dir(&bin).unwrap();
|
||||
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::copy(&tool, bin.join("collector")).unwrap();
|
||||
assert!(resolve_in_directories("collector", &[bin], true).is_some());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_some());
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o1775)).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::os::unix::fs::chown(&tool, Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
std::os::unix::fs::chown(&tool, Some(0), None).unwrap();
|
||||
std::os::unix::fs::chown(directory.path(), Some(1), None).unwrap();
|
||||
assert!(resolve_executable(&tool, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_directories_resolve_tools_without_using_the_process_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tool = dir.path().join("configured-tool");
|
||||
fs::write(&tool, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(
|
||||
resolve_in_directories("configured-tool", &[dir.path().to_owned()], false),
|
||||
Some(fs::canonicalize(&tool).unwrap())
|
||||
);
|
||||
fs::set_permissions(&tool, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(resolve_in_directories("configured-tool", &[dir.path().to_owned()], true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_command_path_contains_only_trusted_canonical_directories() {
|
||||
let path = command_path(true).unwrap();
|
||||
let directories: Vec<_> = std::env::split_paths(&path).collect();
|
||||
assert!(!directories.is_empty());
|
||||
for directory in directories {
|
||||
assert!(directory.is_dir());
|
||||
assert!(root_owned_path(&directory));
|
||||
assert_eq!(directory, fs::canonicalize(&directory).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_resolution_returns_target_not_mutable_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let link = dir.path().join("tool");
|
||||
std::os::unix::fs::symlink("/bin/sh", &link).unwrap();
|
||||
let resolved = resolve_executable(&link, false).unwrap();
|
||||
fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/echo", &link).unwrap();
|
||||
assert_eq!(resolved, fs::canonicalize("/bin/sh").unwrap());
|
||||
assert_ne!(resolved, fs::canonicalize(&link).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_running_collector() {
|
||||
let started = Instant::now();
|
||||
let control = || {
|
||||
if started.elapsed() >= Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = CollectorCommands::new(&control)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30 & wait"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_has_private_environment_and_cwd() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let output = CollectorCommands::new(&budget)
|
||||
.run_path(
|
||||
Path::new("/bin/sh"),
|
||||
&[
|
||||
"-c",
|
||||
"printf '%s|%s|%s' \"$LC_ALL\" \"$PWD\" \"${SENTINEL_OUTPUT_JSON-unset}\"",
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8(output.stdout).unwrap(), "C|/|unset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deadline_stops_collector_instead_of_hanging() {
|
||||
let budget = CollectionBudget::new(Duration::from_millis(100));
|
||||
let started = Instant::now();
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "sleep 30"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_output_is_bounded() {
|
||||
let budget = CollectionBudget::new(Duration::from_secs(2));
|
||||
let error = CollectorCommands::new(&budget)
|
||||
.run_path(Path::new("/bin/sh"), &["-c", "yes x"])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_not_an_optional_missing_product() {
|
||||
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
let error = CollectorCommands::new(&control).run("not-installed", &[]).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::{
|
||||
io::{self, Read},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
|
||||
use super::collection::CollectionControl;
|
||||
|
||||
/// Execute an already configured command. Environment, identity and executable
|
||||
/// trust belong to its caller. This worker owns the process group until reaped;
|
||||
/// its asynchronous caller must cancel and await it instead of dropping it.
|
||||
pub(crate) fn run_controlled(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: usize,
|
||||
) -> io::Result<Output> {
|
||||
control.check()?;
|
||||
let child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
let mut child = ControlledChild(child);
|
||||
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
|
||||
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
&stdout,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut eof = false;
|
||||
let mut status = None;
|
||||
loop {
|
||||
control.check()?;
|
||||
if !eof {
|
||||
match stdout.read(&mut buffer) {
|
||||
Ok(0) => eof = true,
|
||||
Ok(length) => {
|
||||
if length > output_limit.saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
continue;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none() {
|
||||
status = child.0.try_wait()?;
|
||||
}
|
||||
if eof && let Some(status) = status {
|
||||
return Ok(Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
// Reap the direct child and stop helpers retaining stdout after it exits.
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{File, OpenOptions},
|
||||
path::Path,
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use common::binary_paths;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
||||
process::Command,
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{CommandExt, gui_launcher::GuiLauncher};
|
||||
use crate::service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential};
|
||||
|
||||
/// Owns the desktop GUI and its privileged service without leaving the desktop session.
|
||||
pub struct DesktopLauncher<'a> {
|
||||
version: &'a str,
|
||||
minimized: bool,
|
||||
log_file: Option<String>,
|
||||
}
|
||||
|
||||
impl<'a> DesktopLauncher<'a> {
|
||||
pub fn new(version: &'a str) -> Self {
|
||||
Self {
|
||||
version,
|
||||
minimized: false,
|
||||
log_file: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||
self.minimized = minimized;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||
self.log_file = Some(log_file.to_owned());
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop launcher must not run as root"
|
||||
);
|
||||
let mut command = Command::new_pkexec(binary_paths::gpservice());
|
||||
command
|
||||
.arg("--desktop-credentials")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped());
|
||||
if let Some(path) = &self.log_file {
|
||||
command.stderr(Stdio::from(create_log_file(Path::new(path))?));
|
||||
}
|
||||
let mut service = command.spawn().context("Failed to start the privileged service")?;
|
||||
let mut input = service.stdin.take().context("Service input pipe is unavailable")?;
|
||||
let mut output = service
|
||||
.stdout
|
||||
.take()
|
||||
.context("Service credential pipe is unavailable")?;
|
||||
let mut received_credential = false;
|
||||
let mut cancelled = false;
|
||||
let result = tokio::select! {
|
||||
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
|
||||
result = async {
|
||||
let mut minimized = self.minimized;
|
||||
loop {
|
||||
let credential = read_credential(&mut output).await?;
|
||||
let Some(credential) = credential else { return Ok(()); };
|
||||
received_credential = true;
|
||||
ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||
if let Some(path) = &self.log_file {
|
||||
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||
}
|
||||
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
|
||||
let mut unexpected = [0];
|
||||
tokio::select! {
|
||||
result = launcher.launch() => { result?; }
|
||||
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
|
||||
result = output.read(&mut unexpected) => {
|
||||
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||
anyhow::bail!("The privileged service closed its credential channel");
|
||||
}
|
||||
}
|
||||
input.write_all(&[0]).await?;
|
||||
minimized = false;
|
||||
}
|
||||
} => result,
|
||||
};
|
||||
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
|
||||
drop(input);
|
||||
if cancelled && !received_credential {
|
||||
// pkexec is still user-owned during authorization. After elevation, EOF owns shutdown.
|
||||
if let Err(error) = service.start_kill()
|
||||
&& error.kind() != std::io::ErrorKind::PermissionDenied
|
||||
{
|
||||
return Err(error.into());
|
||||
}
|
||||
}
|
||||
let status = service.wait().await?;
|
||||
result?;
|
||||
ensure!(
|
||||
cancelled || status.success(),
|
||||
"The privileged service exited with {status}"
|
||||
);
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
|
||||
fn create_log_file(path: &Path) -> std::io::Result<File> {
|
||||
// Start a fresh desktop session, then let both processes append without overwriting each other.
|
||||
File::create(path)?;
|
||||
OpenOptions::new().append(true).open(path)
|
||||
}
|
||||
|
||||
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
|
||||
let mut header = [0; 2];
|
||||
if reader.read(&mut header[..1]).await? == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
reader.read_exact(&mut header[1..]).await?;
|
||||
let length = usize::from(u16::from_be_bytes(header));
|
||||
ensure!(
|
||||
length != 0 && length + 2 <= MAX_CREDENTIAL_FRAME,
|
||||
"Invalid service credential length"
|
||||
);
|
||||
let mut frame = Zeroizing::new(vec![0; length + 2]);
|
||||
frame[..2].copy_from_slice(&header);
|
||||
reader.read_exact(&mut frame[2..]).await?;
|
||||
Ok(Some(SessionCredential::decode_frame(&frame)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_log_starts_fresh_and_service_writes_preserve_gui_logs() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let path = dir.path().join("desktop.log");
|
||||
std::fs::write(&path, "previous session\n").unwrap();
|
||||
let mut service = create_log_file(&path).unwrap();
|
||||
writeln!(service, "[gpservice] started").unwrap();
|
||||
let mut gui = OpenOptions::new().append(true).open(&path).unwrap();
|
||||
writeln!(gui, "[gpgui] initialized").unwrap();
|
||||
writeln!(service, "[gpservice] connected").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpservice] connected\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_channel_distinguishes_clean_close_from_truncated_or_oversized_frames() {
|
||||
assert!(read_credential(&mut &[][..]).await.unwrap().is_none());
|
||||
assert!(read_credential(&mut &[0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[0, 0][..]).await.is_err());
|
||||
assert!(read_credential(&mut &[255, 255][..]).await.is_err());
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = read_credential(&mut frame.as_slice()).await.unwrap().unwrap();
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
}
|
||||
}
|
||||
@@ -5,21 +5,21 @@ use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::command_traits::CommandExt, utils};
|
||||
use crate::service::transport::SessionCredential;
|
||||
|
||||
pub struct GuiHelperLauncher<'a> {
|
||||
program: PathBuf,
|
||||
envs: Option<&'a HashMap<String, String>>,
|
||||
api_key: &'a [u8],
|
||||
credential: &'a SessionCredential,
|
||||
gui_version: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> GuiHelperLauncher<'a> {
|
||||
pub fn new(api_key: &'a [u8]) -> Self {
|
||||
pub fn new(credential: &'a SessionCredential) -> Self {
|
||||
Self {
|
||||
program: binary_paths::gpgui_helper(),
|
||||
envs: None,
|
||||
api_key,
|
||||
credential,
|
||||
gui_version: None,
|
||||
}
|
||||
}
|
||||
@@ -42,15 +42,18 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if let Some(gui_version) = self.gui_version {
|
||||
cmd.arg("--gui-version").arg(gui_version);
|
||||
}
|
||||
|
||||
info!("Launching gpgui-helper");
|
||||
let mut non_root_cmd = cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||
@@ -60,13 +63,11 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = utils::base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
info!("gpgui-helper exited with: {}", exit_status);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,32 +1,40 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::PathBuf,
|
||||
fs::OpenOptions,
|
||||
path::{Path, PathBuf},
|
||||
process::{ExitStatus, Stdio},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64};
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||
|
||||
pub struct GuiLauncher<'a> {
|
||||
version: &'a str,
|
||||
program: PathBuf,
|
||||
api_key: &'a [u8],
|
||||
programs: Vec<PathBuf>,
|
||||
credential: Arc<SessionCredential>,
|
||||
minimized: bool,
|
||||
envs: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
impl<'a> GuiLauncher<'a> {
|
||||
pub fn new(version: &'a str, api_key: &'a [u8]) -> Self {
|
||||
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
|
||||
let primary = binary_paths::gpgui();
|
||||
let update_target = binary_paths::gpgui_update_target();
|
||||
let programs = if primary == update_target {
|
||||
vec![primary]
|
||||
} else {
|
||||
vec![primary, update_target]
|
||||
};
|
||||
|
||||
Self {
|
||||
version,
|
||||
program: binary_paths::gpgui(),
|
||||
api_key,
|
||||
programs,
|
||||
credential,
|
||||
minimized: false,
|
||||
envs: None,
|
||||
}
|
||||
@@ -43,56 +51,93 @@ impl<'a> GuiLauncher<'a> {
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
// Check if the program's version
|
||||
if let Err(err) = self.check_version().await {
|
||||
info!("Check version failed: {}", err);
|
||||
// Download the program and replace the current one
|
||||
self.download_program().await?;
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
if let Some(program) = self.find_compatible_program().await {
|
||||
return self.launch_program(&program).await;
|
||||
}
|
||||
|
||||
self.launch_program().await
|
||||
self.download_program().await?;
|
||||
|
||||
let program = binary_paths::gpgui_update_target();
|
||||
self.check_version(&program).await?;
|
||||
self.launch_program(&program).await
|
||||
}
|
||||
|
||||
async fn launch_program(&self) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(&self.program);
|
||||
async fn find_compatible_program(&self) -> Option<PathBuf> {
|
||||
for program in &self.programs {
|
||||
match self.check_version(program).await {
|
||||
Ok(()) => return Some(program.clone()),
|
||||
Err(err) => info!(
|
||||
"GUI candidate {} is unavailable or incompatible: {err}",
|
||||
program.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(program);
|
||||
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
|
||||
cmd.arg("--api-key-on-stdin");
|
||||
let log_file = match &self.envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
};
|
||||
if let Some(path) = log_file {
|
||||
let file = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?;
|
||||
cmd.stderr(Stdio::from(file));
|
||||
}
|
||||
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
info!("Launching gpgui");
|
||||
let mut non_root_cmd = cmd.into_non_root()?;
|
||||
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let api_key = base64::encode(self.api_key);
|
||||
tokio::spawn(async move {
|
||||
stdin.write_all(api_key.as_bytes()).await.unwrap();
|
||||
drop(stdin);
|
||||
});
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
|
||||
async fn check_version(&self) -> anyhow::Result<()> {
|
||||
let cmd = Command::new(&self.program).arg("--version").output().await?;
|
||||
let output = String::from_utf8_lossy(&cmd.stdout);
|
||||
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
|
||||
let mut cmd = Command::new(program);
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
cmd.arg("--version");
|
||||
let output = cmd.output().await?;
|
||||
if !output.status.success() {
|
||||
bail!("Version command exited with {}", output.status);
|
||||
}
|
||||
let output = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
// Version string: "gpgui 2.0.0 (2024-02-05)"
|
||||
let Some(version) = output.split_whitespace().nth(1) else {
|
||||
@@ -109,17 +154,96 @@ impl<'a> GuiLauncher<'a> {
|
||||
}
|
||||
|
||||
async fn download_program(&self) -> anyhow::Result<()> {
|
||||
let gui_helper = GuiHelperLauncher::new(self.api_key);
|
||||
let gui_helper = GuiHelperLauncher::new(&self.credential);
|
||||
|
||||
gui_helper
|
||||
.envs(self.envs.as_ref())
|
||||
.gui_version(Some(self.version))
|
||||
.launch()
|
||||
.await?;
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
// Check the version again
|
||||
self.check_version().await?;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
Ok(())
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
|
||||
const VERSION: &str = "test-version";
|
||||
|
||||
fn executable(dir: &TempDir, name: &str, output: &str, exit_code: i32) -> PathBuf {
|
||||
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let path = dir.path().join(name);
|
||||
fs::write(
|
||||
&path,
|
||||
format!("#!/bin/sh\nprintf '%s\\n' '{output}'\nexit {exit_code}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
|
||||
GuiLauncher {
|
||||
version,
|
||||
programs,
|
||||
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
|
||||
minimized: false,
|
||||
envs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn captures_gui_logs_in_the_desktop_log_file_across_restarts() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let log_file = dir.path().join("desktop.log");
|
||||
fs::write(&log_file, "[gpservice] started\n").unwrap();
|
||||
let program = dir.path().join("gui");
|
||||
fs::write(&program, "#!/bin/sh\nprintf '[gpgui] initialized\\n' >&2\n").unwrap();
|
||||
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let launcher = launcher(VERSION, vec![]).envs(HashMap::from([(
|
||||
"GP_LOG_FILE".to_owned(),
|
||||
log_file.to_str().unwrap().to_owned(),
|
||||
)]));
|
||||
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(log_file).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prefers_the_first_compatible_program() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let packaged = executable(&dir, "packaged", "gpgui test-version", 0);
|
||||
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
|
||||
let launcher = launcher(VERSION, vec![packaged.clone(), downloaded]);
|
||||
|
||||
assert_eq!(launcher.find_compatible_program().await, Some(packaged));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_when_the_first_program_is_incompatible() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let packaged = executable(&dir, "packaged", "gpgui other-version", 0);
|
||||
let downloaded = executable(&dir, "downloaded", "gpgui test-version", 0);
|
||||
let launcher = launcher(VERSION, vec![packaged, downloaded.clone()]);
|
||||
|
||||
assert_eq!(launcher.find_compatible_program().await, Some(downloaded));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_an_unsuccessful_version_command() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let program = executable(&dir, "broken", "gpgui test-version", 1);
|
||||
let launcher = launcher(VERSION, vec![program]);
|
||||
|
||||
assert_eq!(launcher.find_compatible_program().await, None);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use std::process::Stdio;
|
||||
|
||||
use anyhow::bail;
|
||||
use tokio::process::Command;
|
||||
|
||||
pub struct HipLauncher<'a> {
|
||||
program: &'a str,
|
||||
cookie: Option<&'a str>,
|
||||
client_ip: Option<&'a str>,
|
||||
md5: Option<&'a str>,
|
||||
client_os: Option<&'a str>,
|
||||
client_version: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> HipLauncher<'a> {
|
||||
pub fn new(program: &'a str) -> Self {
|
||||
Self {
|
||||
program,
|
||||
cookie: None,
|
||||
client_ip: None,
|
||||
md5: None,
|
||||
client_os: None,
|
||||
client_version: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie(mut self, cookie: &'a str) -> Self {
|
||||
self.cookie = Some(cookie);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_ip(mut self, client_ip: &'a str) -> Self {
|
||||
self.client_ip = Some(client_ip);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn md5(mut self, md5: &'a str) -> Self {
|
||||
self.md5 = Some(md5);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_os(mut self, client_os: &'a str) -> Self {
|
||||
self.client_os = Some(client_os);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn client_version(mut self, client_version: Option<&'a str>) -> Self {
|
||||
self.client_version = client_version;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<String> {
|
||||
let mut cmd = Command::new(self.program);
|
||||
|
||||
if let Some(cookie) = self.cookie {
|
||||
cmd.arg("--cookie").arg(cookie);
|
||||
}
|
||||
|
||||
if let Some(client_ip) = self.client_ip {
|
||||
cmd.arg("--client-ip").arg(client_ip);
|
||||
}
|
||||
|
||||
if let Some(md5) = self.md5 {
|
||||
cmd.arg("--md5").arg(md5);
|
||||
}
|
||||
|
||||
if let Some(client_os) = self.client_os {
|
||||
cmd.arg("--client-os").arg(client_os);
|
||||
}
|
||||
|
||||
if let Some(client_version) = self.client_version {
|
||||
cmd.env("APP_VERSION", client_version);
|
||||
}
|
||||
|
||||
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
|
||||
|
||||
let child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program, err),
|
||||
};
|
||||
|
||||
let output = child.wait_with_output().await?;
|
||||
|
||||
if let Some(exit_status) = output.status.code() {
|
||||
if exit_status != 0 {
|
||||
bail!("HIP report generation failed with exit code {}", exit_status);
|
||||
}
|
||||
|
||||
let report = String::from_utf8(output.stdout)?;
|
||||
|
||||
Ok(report)
|
||||
} else {
|
||||
bail!("HIP report generation failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
pub(crate) mod command_traits;
|
||||
mod command_runner;
|
||||
mod command_traits;
|
||||
mod desktop_session_env;
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
pub mod desktop_launcher;
|
||||
pub mod gui_launcher;
|
||||
pub mod hip_launcher;
|
||||
pub mod service_launcher;
|
||||
pub mod users;
|
||||
|
||||
pub mod collection;
|
||||
@@ -1,82 +0,0 @@
|
||||
use std::{
|
||||
fs::File,
|
||||
path::PathBuf,
|
||||
process::{ExitStatus, Stdio},
|
||||
};
|
||||
|
||||
use common::binary_paths;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::command_traits::CommandExt;
|
||||
|
||||
pub struct ServiceLauncher<'a> {
|
||||
program: PathBuf,
|
||||
minimized: bool,
|
||||
env_file: Option<String>,
|
||||
log_file: Option<String>,
|
||||
verbose: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl Default for ServiceLauncher<'_> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ServiceLauncher<'a> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
program: binary_paths::gpservice(),
|
||||
minimized: false,
|
||||
env_file: None,
|
||||
log_file: None,
|
||||
verbose: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn minimized(mut self, minimized: bool) -> Self {
|
||||
self.minimized = minimized;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn env_file(mut self, env_file: &str) -> Self {
|
||||
self.env_file = Some(env_file.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn log_file(mut self, log_file: &str) -> Self {
|
||||
self.log_file = Some(log_file.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
|
||||
self.verbose = verbose;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new_pkexec(&self.program);
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
if let Some(env_file) = &self.env_file {
|
||||
cmd.arg("--env-file").arg(env_file);
|
||||
}
|
||||
|
||||
if let Some(verbose) = self.verbose {
|
||||
cmd.arg(verbose);
|
||||
}
|
||||
|
||||
if let Some(log_file) = &self.log_file {
|
||||
let log_file = File::create(log_file)?;
|
||||
let stdio = Stdio::from(log_file);
|
||||
cmd.stderr(stdio);
|
||||
}
|
||||
|
||||
let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?;
|
||||
|
||||
Ok(exit_status)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
pub mod event;
|
||||
pub mod request;
|
||||
pub mod transport;
|
||||
pub mod vpn_env;
|
||||
pub mod vpn_state;
|
||||
pub mod vpnc_script;
|
||||
@@ -1,15 +1,41 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, fmt};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
hip::HipSource,
|
||||
os_profile::{ClientOs, HostIdentity, OsProfile},
|
||||
session::ConnectionPlan,
|
||||
};
|
||||
|
||||
use super::vpn_state::ConnectInfo;
|
||||
|
||||
pub const MAX_CLIENT_IDENTITY_DATA: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct StoreEditedHipReportChunkRequest {
|
||||
pub upload_id: Option<String>,
|
||||
pub offset: usize,
|
||||
pub xml: String,
|
||||
pub complete: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct PreviewHipReportRequest {
|
||||
pub source: HipSource,
|
||||
pub client_os: ClientOs,
|
||||
pub client_version: String,
|
||||
pub host_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ReadHipPreviewChunkRequest {
|
||||
pub preview_id: String,
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct LaunchGuiRequest {
|
||||
user: String,
|
||||
@@ -30,10 +56,11 @@ impl LaunchGuiRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
#[derive(Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectArgs {
|
||||
cookie: String,
|
||||
vpnc_script: Option<String>,
|
||||
host_identity: Option<HostIdentity>,
|
||||
ignore_tls_errors: bool,
|
||||
|
||||
user_agent: Option<String>,
|
||||
os: Option<ClientOs>,
|
||||
@@ -43,11 +70,11 @@ pub struct ConnectArgs {
|
||||
|
||||
certificate: Option<String>,
|
||||
sslkey: Option<String>,
|
||||
certificate_data: Option<String>,
|
||||
sslkey_data: Option<String>,
|
||||
key_password: Option<String>,
|
||||
|
||||
hip: bool,
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<String>,
|
||||
hip_source: HipSource,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -61,10 +88,11 @@ pub struct ConnectArgs {
|
||||
}
|
||||
|
||||
impl ConnectArgs {
|
||||
pub fn new(cookie: String) -> Self {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
cookie,
|
||||
vpnc_script: None,
|
||||
host_identity: None,
|
||||
ignore_tls_errors: false,
|
||||
user_agent: None,
|
||||
os: None,
|
||||
os_version: None,
|
||||
@@ -72,10 +100,10 @@ impl ConnectArgs {
|
||||
host_id: None,
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
certificate_data: None,
|
||||
sslkey_data: None,
|
||||
key_password: None,
|
||||
hip: false,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: HipSource::Disabled,
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
@@ -87,8 +115,12 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cookie(&self) -> &str {
|
||||
&self.cookie
|
||||
pub fn host_identity(&self) -> Option<&HostIdentity> {
|
||||
self.host_identity.as_ref()
|
||||
}
|
||||
|
||||
pub fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
|
||||
pub fn vpnc_script(&self) -> Option<String> {
|
||||
@@ -127,20 +159,28 @@ impl ConnectArgs {
|
||||
self.sslkey.clone()
|
||||
}
|
||||
|
||||
pub fn certificate_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.certificate_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn sslkey_data(&self) -> anyhow::Result<Option<Vec<u8>>> {
|
||||
self
|
||||
.sslkey_data
|
||||
.as_deref()
|
||||
.map(crate::utils::base64::decode_to_vec)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn key_password(&self) -> Option<String> {
|
||||
self.key_password.clone()
|
||||
}
|
||||
|
||||
pub fn hip(&self) -> bool {
|
||||
self.hip
|
||||
}
|
||||
|
||||
pub fn csd_uid(&self) -> u32 {
|
||||
self.csd_uid
|
||||
}
|
||||
|
||||
pub fn csd_wrapper(&self) -> Option<String> {
|
||||
self.csd_wrapper.clone()
|
||||
pub fn hip_source(&self) -> &HipSource {
|
||||
&self.hip_source
|
||||
}
|
||||
|
||||
pub fn reconnect_timeout(&self) -> u32 {
|
||||
@@ -176,17 +216,49 @@ impl ConnectArgs {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ConnectArgs {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ConnectArgs")
|
||||
.field("vpnc_script", &self.vpnc_script)
|
||||
.field(
|
||||
"client_auth_path",
|
||||
&(self.certificate.is_some() || self.sslkey.is_some()),
|
||||
)
|
||||
.field(
|
||||
"client_auth_data",
|
||||
&(self.certificate_data.is_some() || self.sslkey_data.is_some()),
|
||||
)
|
||||
.field("hip_source", &self.hip_source)
|
||||
.field("reconnect_timeout", &self.reconnect_timeout)
|
||||
.field("mtu", &self.mtu)
|
||||
.field("disable_ipv6", &self.disable_ipv6)
|
||||
.field("no_dtls", &self.no_dtls)
|
||||
.field("allow_extend_session", &self.allow_extend_session)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectArgs {
|
||||
fn drop(&mut self) {
|
||||
self.key_password.zeroize();
|
||||
self.certificate_data.zeroize();
|
||||
self.sslkey_data.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectRequest {
|
||||
info: ConnectInfo,
|
||||
plan: ConnectionPlan,
|
||||
args: ConnectArgs,
|
||||
}
|
||||
|
||||
impl ConnectRequest {
|
||||
pub fn new(info: ConnectInfo, cookie: String) -> Self {
|
||||
pub fn new(info: ConnectInfo, plan: ConnectionPlan) -> Self {
|
||||
Self {
|
||||
info,
|
||||
args: ConnectArgs::new(cookie),
|
||||
plan,
|
||||
args: ConnectArgs::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,22 +267,13 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_hip(mut self, hip: bool) -> Self {
|
||||
self.args.hip = hip;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_csd_uid(mut self, csd_uid: u32) -> Self {
|
||||
self.args.csd_uid = csd_uid;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
|
||||
self.args.csd_wrapper = csd_wrapper.into();
|
||||
pub fn with_hip_source(mut self, hip_source: HipSource) -> Self {
|
||||
self.args.hip_source = hip_source;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_os_profile(mut self, profile: &OsProfile) -> Self {
|
||||
self.args.host_identity = Some(profile.host_identity().clone());
|
||||
self.args.os = Some(profile.client_os());
|
||||
self.args.os_version = Some(profile.os_version().to_string());
|
||||
self.args.client_version = Some(profile.client_version().to_string());
|
||||
@@ -219,6 +282,11 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
|
||||
self.args.ignore_tls_errors = ignore_tls_errors;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
|
||||
self.args.certificate = certificate.into();
|
||||
self
|
||||
@@ -229,6 +297,16 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_certificate_data(mut self, certificate: Option<Vec<u8>>) -> Self {
|
||||
self.args.certificate_data = certificate.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_sslkey_data(mut self, sslkey: Option<Vec<u8>>) -> Self {
|
||||
self.args.sslkey_data = sslkey.map(encode_secret);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
|
||||
self.args.key_password = key_password.into();
|
||||
self
|
||||
@@ -274,8 +352,8 @@ impl ConnectRequest {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn gateway(&self) -> &Gateway {
|
||||
self.info.gateway()
|
||||
pub fn plan(&self) -> &ConnectionPlan {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
@@ -287,6 +365,12 @@ impl ConnectRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_secret(mut data: Vec<u8>) -> String {
|
||||
let encoded = crate::utils::base64::encode(&data);
|
||||
data.zeroize();
|
||||
encoded
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
pub struct DisconnectRequest;
|
||||
|
||||
@@ -298,10 +382,19 @@ pub struct UpdateLogLevelRequest(pub String);
|
||||
pub enum WsRequest {
|
||||
Connect(Box<ConnectRequest>),
|
||||
Disconnect(DisconnectRequest),
|
||||
StopNonTunnelAttachment { connection_id: uuid::Uuid },
|
||||
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
|
||||
PreviewHipReport(PreviewHipReportRequest),
|
||||
GetHipApprovalStatus { approval_id: String },
|
||||
ReadHipPreviewChunk(ReadHipPreviewChunkRequest),
|
||||
GetLastSubmittedHipReport,
|
||||
UpdateLogLevel(UpdateLogLevelRequest),
|
||||
RestartGui,
|
||||
UpdateGui(UpdateGuiRequest),
|
||||
GetVpncScriptMetadata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct UpdateGuiRequest {
|
||||
pub path: String,
|
||||
pub checksum: String,
|
||||
@@ -313,17 +406,52 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::os_profile::OsProfileBuilder;
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{AuthenticatedGateway, GatewayAuthentication, InternalSessionPolicy},
|
||||
};
|
||||
|
||||
fn test_request(info: ConnectInfo) -> ConnectRequest {
|
||||
let plan = ConnectionPlan::new(
|
||||
vec![AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: GatewayAuthentication::new("authcookie=secret-cookie&user=user".into(), "tunnel".into())
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
ConnectRequest::new(info, plan)
|
||||
}
|
||||
|
||||
fn test_connect_info() -> ConnectInfo {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_round_trips_a_validated_plan_and_rejects_cookie_only_wire_input() {
|
||||
let request = test_request(test_connect_info());
|
||||
let mut value = serde_json::to_value(&request).unwrap();
|
||||
assert!(value["args"].get("cookie").is_none());
|
||||
let decoded: ConnectRequest = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(decoded.plan().members().len(), 1);
|
||||
assert_eq!(decoded.plan().members()[0].authentication.connection_type(), "tunnel");
|
||||
value["plan"]["members"] = json!([]);
|
||||
assert!(serde_json::from_value::<ConnectRequest>(value).is_err());
|
||||
let mut legacy = serde_json::to_value(&request).unwrap();
|
||||
legacy.as_object_mut().unwrap().remove("plan");
|
||||
legacy["args"]["cookie"] = json!("authcookie=secret-cookie&user=user");
|
||||
assert!(serde_json::from_value::<ConnectRequest>(legacy).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connect_request_serializes_allow_extend_session() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
|
||||
let req = test_request(info).with_allow_extend_session(true);
|
||||
let value = serde_json::to_value(req).unwrap();
|
||||
|
||||
assert_eq!(value["args"]["allowExtendSession"], json!(true));
|
||||
@@ -333,7 +461,7 @@ mod tests {
|
||||
fn with_os_profile_sets_user_agent_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(req.args().user_agent(), Some(profile.user_agent().to_string()));
|
||||
}
|
||||
@@ -342,11 +470,26 @@ mod tests {
|
||||
fn with_os_profile_sets_host_id_from_profile_runtime_identity() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux).build();
|
||||
|
||||
let req = ConnectRequest::new(test_connect_info(), "cookie".to_string()).with_os_profile(&profile);
|
||||
let req = test_request(test_connect_info()).with_os_profile(&profile);
|
||||
|
||||
assert_eq!(
|
||||
req.args().host_id(),
|
||||
Some(profile.host_identity().host_id().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_data_round_trips_without_debug_disclosure() {
|
||||
let req = test_request(test_connect_info())
|
||||
.with_certificate_data(Some(b"certificate".to_vec()))
|
||||
.with_sslkey_data(Some(b"private-key".to_vec()));
|
||||
let encoded = serde_json::to_vec(&req).unwrap();
|
||||
let decoded: ConnectRequest = serde_json::from_slice(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded.args().certificate_data().unwrap().unwrap(), b"certificate");
|
||||
assert_eq!(decoded.args().sslkey_data().unwrap().unwrap(), b"private-key");
|
||||
let debug = format!("{decoded:?}");
|
||||
assert!(!debug.contains("secret-cookie"));
|
||||
assert!(!debug.contains("private-key"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::fmt;
|
||||
|
||||
use ::base64::{Engine, engine::general_purpose};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::device_anchor::DeviceAnchor;
|
||||
use crate::utils::base64;
|
||||
|
||||
use super::{MAX_CREDENTIAL_FRAME, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
pub struct SessionCredential {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<[u8; 32]>,
|
||||
product_version: String,
|
||||
device_anchor: Option<DeviceAnchor>,
|
||||
}
|
||||
|
||||
impl SessionCredential {
|
||||
pub fn generate(service_instance_id: Uuid, product_version: &str) -> Result<Self, TransportError> {
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
getrandom::fill(secret.as_mut()).map_err(|_| TransportError::InvalidState)?;
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id: Uuid::new_v4(),
|
||||
secret,
|
||||
product_version: product_version.to_owned(),
|
||||
device_anchor: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn service_instance_id(&self) -> Uuid {
|
||||
self.service_instance_id
|
||||
}
|
||||
|
||||
pub fn session_id(&self) -> Uuid {
|
||||
self.session_id
|
||||
}
|
||||
|
||||
pub fn secret(&self) -> &[u8; 32] {
|
||||
&self.secret
|
||||
}
|
||||
|
||||
pub fn product_version(&self) -> &str {
|
||||
&self.product_version
|
||||
}
|
||||
|
||||
pub fn with_device_anchor(mut self, anchor: DeviceAnchor) -> Result<Self, TransportError> {
|
||||
if !anchor.validate() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
self.device_anchor = Some(anchor);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn device_anchor(&self) -> Option<&DeviceAnchor> {
|
||||
self.device_anchor.as_ref()
|
||||
}
|
||||
|
||||
pub fn encode_frame(&self) -> Result<Zeroizing<Vec<u8>>, TransportError> {
|
||||
let encoded_secret = Zeroizing::new(base64::encode(self.secret()));
|
||||
let dto = CredentialDtoRef {
|
||||
service_instance_id: self.service_instance_id,
|
||||
session_id: self.session_id,
|
||||
secret: encoded_secret.as_str(),
|
||||
product_version: &self.product_version,
|
||||
device_anchor: self.device_anchor.as_ref(),
|
||||
};
|
||||
let payload = Zeroizing::new(serde_json::to_vec(&dto)?);
|
||||
|
||||
if payload.len() + 2 > MAX_CREDENTIAL_FRAME || payload.len() > u16::MAX as usize {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
|
||||
let mut frame = Zeroizing::new(Vec::with_capacity(payload.len() + 2));
|
||||
frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
|
||||
frame.extend_from_slice(&payload);
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn decode_frame(frame: &[u8]) -> Result<Self, TransportError> {
|
||||
if frame.len() < 2 || frame.len() > MAX_CREDENTIAL_FRAME {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let payload_len = u16::from_be_bytes([frame[0], frame[1]]) as usize;
|
||||
if payload_len == 0 || payload_len + 2 != frame.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let dto: CredentialDto = serde_json::from_slice(&frame[2..]).map_err(|_| TransportError::InvalidCredential)?;
|
||||
let CredentialDto {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
device_anchor,
|
||||
} = dto;
|
||||
let encoded_secret = secret;
|
||||
if device_anchor.as_ref().is_some_and(|anchor| !anchor.validate()) {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
let mut secret = Zeroizing::new([0_u8; 32]);
|
||||
let decoded_len = general_purpose::STANDARD
|
||||
.decode_slice(encoded_secret.as_bytes(), secret.as_mut())
|
||||
.map_err(|_| TransportError::InvalidCredential)?;
|
||||
if decoded_len != secret.len() {
|
||||
return Err(TransportError::InvalidCredential);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
service_instance_id,
|
||||
session_id,
|
||||
secret,
|
||||
product_version,
|
||||
device_anchor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SessionCredential {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SessionCredential")
|
||||
.field("service_instance_id", &self.service_instance_id)
|
||||
.field("session_id", &self.session_id)
|
||||
.field("secret", &"[REDACTED]")
|
||||
.field("product_version", &self.product_version)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDtoRef<'a> {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: &'a str,
|
||||
product_version: &'a str,
|
||||
device_anchor: Option<&'a DeviceAnchor>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CredentialDto {
|
||||
service_instance_id: Uuid,
|
||||
session_id: Uuid,
|
||||
secret: Zeroizing<String>,
|
||||
product_version: String,
|
||||
device_anchor: Option<DeviceAnchor>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_without_debugging_secret() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.4").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
|
||||
assert_eq!(decoded.service_instance_id(), credential.service_instance_id());
|
||||
assert_eq!(decoded.session_id(), credential.session_id());
|
||||
assert_eq!(decoded.secret(), credential.secret());
|
||||
assert_eq!(decoded.product_version(), credential.product_version());
|
||||
assert!(!format!("{credential:?}").contains(&base64::encode(credential.secret())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_rejects_malformed_lengths() {
|
||||
assert!(SessionCredential::decode_frame(&[]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 0]).is_err());
|
||||
assert!(SessionCredential::decode_frame(&[0, 2, b'{']).is_err());
|
||||
assert!(SessionCredential::decode_frame(&vec![0; MAX_CREDENTIAL_FRAME + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_round_trips_a_validated_device_anchor() {
|
||||
let anchor = DeviceAnchor {
|
||||
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
|
||||
source: crate::device_anchor::AnchorSource::UnixMac,
|
||||
};
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
|
||||
.unwrap()
|
||||
.with_device_anchor(anchor.clone())
|
||||
.unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
assert_eq!(payload["device_anchor"]["source"], 1);
|
||||
let decoded = SessionCredential::decode_frame(&frame).unwrap();
|
||||
assert_eq!(decoded.device_anchor(), Some(&anchor));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_rejects_reserved_and_unknown_anchor_sources() {
|
||||
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5").unwrap();
|
||||
let frame = credential.encode_frame().unwrap();
|
||||
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
|
||||
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
|
||||
|
||||
for source in [0, 4] {
|
||||
payload["device_anchor"] = serde_json::json!({
|
||||
"hardware_id": hardware_id,
|
||||
"source": source
|
||||
});
|
||||
let bytes = serde_json::to_vec(&payload).unwrap();
|
||||
let mut invalid_frame = (bytes.len() as u16).to_be_bytes().to_vec();
|
||||
invalid_frame.extend_from_slice(&bytes);
|
||||
assert!(SessionCredential::decode_frame(&invalid_frame).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransportError {
|
||||
#[error("invalid credential frame")]
|
||||
InvalidCredential,
|
||||
#[error("invalid transport state")]
|
||||
InvalidState,
|
||||
#[error("message exceeds transport limit")]
|
||||
MessageTooLarge,
|
||||
#[error("malformed transport message")]
|
||||
MalformedMessage,
|
||||
#[error("Noise operation failed")]
|
||||
Noise(#[from] snow::Error),
|
||||
#[error("transport serialization failed")]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum HandshakeRejection {
|
||||
VersionMismatch { client: String, service: String },
|
||||
HipProtocolMismatch { client: u16, service: u16 },
|
||||
ServiceRestarted { service_instance_id: Uuid },
|
||||
ReconnectSuperseded,
|
||||
Unauthorized,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ServiceErrorCode {
|
||||
InvalidRequest,
|
||||
Busy,
|
||||
ChecksumFailed,
|
||||
InstallFailed,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CloseReason {
|
||||
VersionMismatch,
|
||||
Unauthorized,
|
||||
SessionReplaced,
|
||||
HandshakeFailed,
|
||||
MalformedMessage,
|
||||
MessageTooLarge,
|
||||
AuthenticationFailed,
|
||||
HandshakeTimeout,
|
||||
ReconnectSuperseded,
|
||||
InternalError,
|
||||
ServiceRestarted,
|
||||
HeartbeatTimeout,
|
||||
}
|
||||
|
||||
impl CloseReason {
|
||||
pub const fn code(self) -> u16 {
|
||||
match self {
|
||||
Self::VersionMismatch => 4001,
|
||||
Self::Unauthorized => 4002,
|
||||
Self::SessionReplaced => 4003,
|
||||
Self::HandshakeFailed => 4004,
|
||||
Self::MalformedMessage => 4005,
|
||||
Self::MessageTooLarge => 4006,
|
||||
Self::AuthenticationFailed => 4007,
|
||||
Self::HandshakeTimeout => 4008,
|
||||
Self::ReconnectSuperseded => 4009,
|
||||
Self::InternalError => 4010,
|
||||
Self::ServiceRestarted => 4011,
|
||||
Self::HeartbeatTimeout => 4012,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn reason(self) -> &'static str {
|
||||
match self {
|
||||
Self::VersionMismatch => "VersionMismatch",
|
||||
Self::Unauthorized => "Unauthorized",
|
||||
Self::SessionReplaced => "SessionReplaced",
|
||||
Self::HandshakeFailed => "HandshakeFailed",
|
||||
Self::MalformedMessage => "MalformedMessage",
|
||||
Self::MessageTooLarge => "MessageTooLarge",
|
||||
Self::AuthenticationFailed => "AuthenticationFailed",
|
||||
Self::HandshakeTimeout => "HandshakeTimeout",
|
||||
Self::ReconnectSuperseded => "ReconnectSuperseded",
|
||||
Self::InternalError => "InternalError",
|
||||
Self::ServiceRestarted => "ServiceRestarted",
|
||||
Self::HeartbeatTimeout => "HeartbeatTimeout",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn close_codes_are_unique_application_codes() {
|
||||
let reasons = [
|
||||
CloseReason::VersionMismatch,
|
||||
CloseReason::Unauthorized,
|
||||
CloseReason::SessionReplaced,
|
||||
CloseReason::HandshakeFailed,
|
||||
CloseReason::MalformedMessage,
|
||||
CloseReason::MessageTooLarge,
|
||||
CloseReason::AuthenticationFailed,
|
||||
CloseReason::HandshakeTimeout,
|
||||
CloseReason::ReconnectSuperseded,
|
||||
CloseReason::InternalError,
|
||||
CloseReason::ServiceRestarted,
|
||||
CloseReason::HeartbeatTimeout,
|
||||
];
|
||||
let codes: HashSet<_> = reasons.iter().map(|reason| reason.code()).collect();
|
||||
assert_eq!(codes.len(), reasons.len());
|
||||
assert!(codes.iter().all(|code| (4000..5000).contains(code)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{HandshakeRejection, MAX_PRELUDE, MAX_PRODUCT_VERSION, TransportError};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ClientPrelude {
|
||||
pub product_version: String,
|
||||
#[serde(default)]
|
||||
pub hip_protocol_version: u16,
|
||||
pub service_instance_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
}
|
||||
|
||||
impl ClientPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
if self.product_version.is_empty() || self.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let prelude: Self = serde_json::from_slice(encoded)?;
|
||||
if prelude.product_version.is_empty() || prelude.product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MalformedMessage);
|
||||
}
|
||||
Ok(prelude)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerPrelude {
|
||||
Ready,
|
||||
Rejected(HandshakeRejection),
|
||||
}
|
||||
|
||||
impl ServerPrelude {
|
||||
pub fn encode(&self) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(self)?;
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub fn decode(encoded: &[u8]) -> Result<Self, TransportError> {
|
||||
if encoded.len() > MAX_PRELUDE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preludes_reject_unknown_fields_and_invalid_versions() {
|
||||
let instance = Uuid::new_v4();
|
||||
let session = Uuid::new_v4();
|
||||
let unknown = format!(
|
||||
r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}","extra":true}}"#
|
||||
);
|
||||
assert!(ClientPrelude::decode(unknown.as_bytes()).is_err());
|
||||
let legacy =
|
||||
format!(r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}"}}"#);
|
||||
assert_eq!(
|
||||
ClientPrelude::decode(legacy.as_bytes()).unwrap().hip_protocol_version,
|
||||
0
|
||||
);
|
||||
assert!(
|
||||
ClientPrelude {
|
||||
product_version: String::new(),
|
||||
hip_protocol_version: super::super::HIP_PROTOCOL_VERSION,
|
||||
service_instance_id: instance,
|
||||
session_id: session,
|
||||
}
|
||||
.encode()
|
||||
.is_err()
|
||||
);
|
||||
assert!(ClientPrelude::decode(&vec![b'x'; MAX_PRELUDE + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::hip::HipApprovalStatus;
|
||||
use crate::service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpnc_script::VpncScriptMetadata};
|
||||
|
||||
use super::{MAX_PLAINTEXT, MAX_SERVICE_MESSAGE, ServiceErrorCode, TransportError};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ClientMessage {
|
||||
Attach { last_event_revision: Option<u64> },
|
||||
Request { id: Uuid, request: WsRequest },
|
||||
Resync { last_event_revision: u64 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServerMessage {
|
||||
Attached {
|
||||
connection_id: Uuid,
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
Reply {
|
||||
id: Uuid,
|
||||
result: ServiceResult,
|
||||
},
|
||||
Event {
|
||||
revision: u64,
|
||||
event: WsEvent,
|
||||
},
|
||||
Snapshot {
|
||||
current_revision: u64,
|
||||
snapshot: VpnEnv,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum ServiceResult {
|
||||
Accepted,
|
||||
StoredHipReport {
|
||||
report_id: String,
|
||||
},
|
||||
HipUploadProgress {
|
||||
upload_id: String,
|
||||
},
|
||||
HipPreviewChunk {
|
||||
preview_id: String,
|
||||
offset: usize,
|
||||
xml: String,
|
||||
complete: bool,
|
||||
},
|
||||
HipApprovalStatus(HipApprovalStatus),
|
||||
NoSubmittedHipReport,
|
||||
VpncScriptMetadata(Option<VpncScriptMetadata>),
|
||||
Rejected(ServiceRejection),
|
||||
}
|
||||
|
||||
impl ServiceResult {
|
||||
pub fn rejected(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
Self::Rejected(ServiceRejection::new(code, message))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "ServiceRejectionDto")]
|
||||
pub struct ServiceRejection {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ServiceRejection {
|
||||
fn new(code: ServiceErrorCode, message: impl Into<String>) -> Self {
|
||||
let mut message = message.into();
|
||||
if message.len() > MAX_SERVICE_MESSAGE {
|
||||
let mut boundary = MAX_SERVICE_MESSAGE;
|
||||
while !message.is_char_boundary(boundary) {
|
||||
boundary -= 1;
|
||||
}
|
||||
message.truncate(boundary);
|
||||
}
|
||||
Self { code, message }
|
||||
}
|
||||
|
||||
pub fn code(&self) -> ServiceErrorCode {
|
||||
self.code
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ServiceRejectionDto {
|
||||
code: ServiceErrorCode,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl TryFrom<ServiceRejectionDto> for ServiceRejection {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: ServiceRejectionDto) -> Result<Self, Self::Error> {
|
||||
if value.message.len() > MAX_SERVICE_MESSAGE {
|
||||
return Err("service rejection message is too long");
|
||||
}
|
||||
Ok(Self {
|
||||
code: value.code,
|
||||
message: value.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn encode<T: Serialize>(message: &T) -> Result<Vec<u8>, TransportError> {
|
||||
let encoded = serde_json::to_vec(message)?;
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
pub(crate) fn decode<T: for<'de> Deserialize<'de>>(encoded: &[u8]) -> Result<T, TransportError> {
|
||||
if encoded.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
Ok(serde_json::from_slice(encoded)?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
service::{
|
||||
request::{ConnectRequest, MAX_CLIENT_IDENTITY_DATA, WsRequest},
|
||||
vpn_state::ConnectInfo,
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_messages() {
|
||||
assert!(encode(&"x".repeat(MAX_PLAINTEXT)).is_err());
|
||||
assert!(decode::<String>(&vec![b'x'; MAX_PLAINTEXT + 1]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejection_messages_are_utf8_safely_bounded() {
|
||||
let ServiceResult::Rejected(rejection) = ServiceResult::rejected(ServiceErrorCode::Internal, "界".repeat(100))
|
||||
else {
|
||||
panic!("expected rejection");
|
||||
};
|
||||
assert!(rejection.message().len() <= MAX_SERVICE_MESSAGE);
|
||||
|
||||
let oversized = format!(
|
||||
r#"{{"type":"rejected","data":{{"code":"internal","message":"{}"}}}}"#,
|
||||
"x".repeat(MAX_SERVICE_MESSAGE + 1)
|
||||
);
|
||||
assert!(serde_json::from_str::<ServiceResult>(&oversized).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_client_identity_fits_one_transport_message() {
|
||||
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
|
||||
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
|
||||
let certificate_size = MAX_CLIENT_IDENTITY_DATA / 2;
|
||||
let plan = crate::session::ConnectionPlan::new(
|
||||
vec![crate::session::AuthenticatedGateway {
|
||||
gateway: info.gateway().clone(),
|
||||
binding: Some(crate::session::network::test_binding()),
|
||||
authentication: crate::session::GatewayAuthentication::new(
|
||||
"authcookie=token&user=user".into(),
|
||||
"tunnel".into(),
|
||||
)
|
||||
.unwrap(),
|
||||
}],
|
||||
vec![],
|
||||
crate::session::InternalSessionPolicy::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let request = ConnectRequest::new(info, plan)
|
||||
.with_certificate_data(Some(vec![b'c'; certificate_size]))
|
||||
.with_sslkey_data(Some(vec![b'k'; MAX_CLIENT_IDENTITY_DATA - certificate_size]));
|
||||
let message = ClientMessage::Request {
|
||||
id: Uuid::new_v4(),
|
||||
request: WsRequest::Connect(Box::new(request)),
|
||||
};
|
||||
|
||||
let encoded = encode(&message).unwrap();
|
||||
assert!(encoded.len() <= MAX_PLAINTEXT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
mod credential;
|
||||
mod error;
|
||||
mod handshake;
|
||||
mod message;
|
||||
mod noise;
|
||||
|
||||
pub use credential::SessionCredential;
|
||||
pub use error::{CloseReason, HandshakeRejection, ServiceErrorCode, TransportError};
|
||||
pub use handshake::{ClientPrelude, ServerPrelude};
|
||||
pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult};
|
||||
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
|
||||
|
||||
pub const MAX_CREDENTIAL_FRAME: usize = 512;
|
||||
pub const MAX_PRELUDE: usize = 256;
|
||||
pub const MAX_PRODUCT_VERSION: usize = 64;
|
||||
pub const HIP_PROTOCOL_VERSION: u16 = 1;
|
||||
pub const MAX_PLAINTEXT: usize = 60 * 1024;
|
||||
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
|
||||
pub const MAX_SERVICE_MESSAGE: usize = 256;
|
||||
@@ -0,0 +1,231 @@
|
||||
use snow::{Builder, HandshakeState, TransportState, params::NoiseParams};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{MAX_PLAINTEXT, MAX_PRODUCT_VERSION, MAX_WS_MESSAGE, TransportError};
|
||||
|
||||
const NOISE_PATTERN: &str = "Noise_NNpsk0_25519_ChaChaPoly_SHA256";
|
||||
const NOISE_TAG_SIZE: usize = 16;
|
||||
|
||||
pub struct NoiseInitiator {
|
||||
state: Option<HandshakeState>,
|
||||
}
|
||||
|
||||
impl NoiseInitiator {
|
||||
pub fn new(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
psk: &[u8; 32],
|
||||
) -> Result<Self, TransportError> {
|
||||
let params = noise_params()?;
|
||||
let prologue = prologue(product_version, service_instance_id, session_id)?;
|
||||
Ok(Self {
|
||||
state: Some(
|
||||
Builder::new(params)
|
||||
.prologue(&prologue)?
|
||||
.psk(0, psk)?
|
||||
.build_initiator()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_first(&mut self) -> Result<Vec<u8>, TransportError> {
|
||||
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
let len = state.write_message(&[], &mut output)?;
|
||||
output.truncate(len);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn read_response(mut self, message: &[u8]) -> Result<NoiseTransport, TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
state.read_message(message, &mut output)?;
|
||||
Ok(NoiseTransport::new(state.into_transport_mode()?))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseResponder {
|
||||
state: Option<HandshakeState>,
|
||||
}
|
||||
|
||||
impl NoiseResponder {
|
||||
pub fn new(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
psk: &[u8; 32],
|
||||
) -> Result<Self, TransportError> {
|
||||
let params = noise_params()?;
|
||||
let prologue = prologue(product_version, service_instance_id, session_id)?;
|
||||
Ok(Self {
|
||||
state: Some(
|
||||
Builder::new(params)
|
||||
.prologue(&prologue)?
|
||||
.psk(0, psk)?
|
||||
.build_responder()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read_first(&mut self, message: &[u8]) -> Result<(), TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let state = self.state.as_mut().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
state.read_message(message, &mut output)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write_response(mut self) -> Result<(Vec<u8>, NoiseTransport), TransportError> {
|
||||
let mut state = self.state.take().ok_or(TransportError::InvalidState)?;
|
||||
let mut output = vec![0_u8; 128];
|
||||
let len = state.write_message(&[], &mut output)?;
|
||||
output.truncate(len);
|
||||
let transport = NoiseTransport::new(state.into_transport_mode()?);
|
||||
Ok((output, transport))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseTransport {
|
||||
state: TransportState,
|
||||
}
|
||||
|
||||
impl NoiseTransport {
|
||||
fn new(state: TransportState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub fn encrypt<T: serde::Serialize>(&mut self, message: &T) -> Result<Vec<u8>, TransportError> {
|
||||
let plaintext = Zeroizing::new(super::message::encode(message)?);
|
||||
let mut output = vec![0_u8; plaintext.len() + NOISE_TAG_SIZE];
|
||||
let len = self.state.write_message(&plaintext, &mut output)?;
|
||||
output.truncate(len);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn decrypt<T: for<'de> serde::Deserialize<'de>>(&mut self, message: &[u8]) -> Result<T, TransportError> {
|
||||
if message.len() > MAX_WS_MESSAGE || message.len() < NOISE_TAG_SIZE {
|
||||
return Err(if message.len() > MAX_WS_MESSAGE {
|
||||
TransportError::MessageTooLarge
|
||||
} else {
|
||||
TransportError::MalformedMessage
|
||||
});
|
||||
}
|
||||
let mut plaintext = Zeroizing::new(vec![0_u8; message.len()]);
|
||||
let len = self.state.read_message(message, &mut plaintext)?;
|
||||
plaintext.truncate(len);
|
||||
if plaintext.len() > MAX_PLAINTEXT {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
super::message::decode(&plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
fn noise_params() -> Result<NoiseParams, TransportError> {
|
||||
NOISE_PATTERN.parse().map_err(|_| TransportError::InvalidState)
|
||||
}
|
||||
|
||||
fn prologue(
|
||||
product_version: &str,
|
||||
service_instance_id: uuid::Uuid,
|
||||
session_id: uuid::Uuid,
|
||||
) -> Result<Vec<u8>, TransportError> {
|
||||
if product_version.is_empty() || product_version.len() > MAX_PRODUCT_VERSION {
|
||||
return Err(TransportError::MessageTooLarge);
|
||||
}
|
||||
let mut value = Vec::with_capacity(5 + 2 + product_version.len() + 32);
|
||||
value.extend_from_slice(b"GPWS\0");
|
||||
value.extend_from_slice(&(product_version.len() as u16).to_be_bytes());
|
||||
value.extend_from_slice(product_version.as_bytes());
|
||||
value.extend_from_slice(service_instance_id.as_bytes());
|
||||
value.extend_from_slice(session_id.as_bytes());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
struct Payload(String);
|
||||
|
||||
#[test]
|
||||
fn peers_exchange_directional_messages() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [7_u8; 32];
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
|
||||
let first = initiator.write_first().unwrap();
|
||||
responder.read_first(&first).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
|
||||
let encrypted = client.encrypt(&Payload("hello".into())).unwrap();
|
||||
assert_eq!(server.decrypt::<Payload>(&encrypted).unwrap(), Payload("hello".into()));
|
||||
assert!(server.decrypt::<Payload>(&encrypted).is_err());
|
||||
|
||||
let response = server.encrypt(&Payload("world".into())).unwrap();
|
||||
assert_eq!(client.decrypt::<Payload>(&response).unwrap(), Payload("world".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_psk_fails_handshake() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &[1; 32]).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &[2; 32]).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
assert!(responder.read_first(&first).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transcript_identity_mismatch_fails_handshake() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [3_u8; 32];
|
||||
for mut responder in [
|
||||
NoiseResponder::new("2.6.5", instance, session, &psk).unwrap(),
|
||||
NoiseResponder::new("2.6.4", uuid::Uuid::new_v4(), session, &psk).unwrap(),
|
||||
NoiseResponder::new("2.6.4", instance, uuid::Uuid::new_v4(), &psk).unwrap(),
|
||||
] {
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
assert!(responder.read_first(&first).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_rejects_tampering_truncation_and_reordering() {
|
||||
let instance = uuid::Uuid::new_v4();
|
||||
let session = uuid::Uuid::new_v4();
|
||||
let psk = [9_u8; 32];
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let first = initiator.write_first().unwrap();
|
||||
responder.read_first(&first).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
|
||||
let first = client.encrypt(&Payload("first".into())).unwrap();
|
||||
let second = client.encrypt(&Payload("second".into())).unwrap();
|
||||
assert!(server.decrypt::<Payload>(&second).is_err());
|
||||
|
||||
let mut initiator = NoiseInitiator::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let mut responder = NoiseResponder::new("2.6.4", instance, session, &psk).unwrap();
|
||||
let handshake = initiator.write_first().unwrap();
|
||||
responder.read_first(&handshake).unwrap();
|
||||
let (response, mut server) = responder.write_response().unwrap();
|
||||
let mut client = initiator.read_response(&response).unwrap();
|
||||
let mut tampered = client.encrypt(&Payload("value".into())).unwrap();
|
||||
tampered[0] ^= 1;
|
||||
assert!(server.decrypt::<Payload>(&tampered).is_err());
|
||||
assert!(server.decrypt::<Payload>(&first[..NOISE_TAG_SIZE - 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,6 @@ pub struct VpnEnv {
|
||||
/// The default VPN script path
|
||||
pub vpnc_script: Option<String>,
|
||||
|
||||
/// The default CSD wrapper script path
|
||||
pub csd_wrapper: Option<String>,
|
||||
|
||||
/// The gpauth executable path
|
||||
/// Used by the client to launch gpauth for authentication
|
||||
pub auth_executable: String,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::{gateway::Gateway, session::SessionInfo};
|
||||
use crate::{
|
||||
gateway::Gateway,
|
||||
session::{GatewayFailureSummary, GatewaySessionSummary, SessionInfo},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
|
||||
pub struct ConnectInfo {
|
||||
@@ -15,6 +20,9 @@ pub struct ConnectInfo {
|
||||
pub struct ConnectedInfo {
|
||||
info: Box<ConnectInfo>,
|
||||
session_info: Option<SessionInfo>,
|
||||
connected_at: u32,
|
||||
members: Vec<GatewaySessionSummary>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
}
|
||||
|
||||
impl ConnectedInfo {
|
||||
@@ -22,9 +30,26 @@ impl ConnectedInfo {
|
||||
Self {
|
||||
info: Box::new(info),
|
||||
session_info,
|
||||
connected_at: unix_timestamp(),
|
||||
members: vec![],
|
||||
failures: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_members(mut self, members: Vec<GatewaySessionSummary>, failures: Vec<GatewayFailureSummary>) -> Self {
|
||||
self.members = members;
|
||||
self.failures = failures;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn members(&self) -> &[GatewaySessionSummary] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> &[GatewayFailureSummary] {
|
||||
&self.failures
|
||||
}
|
||||
|
||||
pub fn info(&self) -> &ConnectInfo {
|
||||
&self.info
|
||||
}
|
||||
@@ -32,6 +57,17 @@ impl ConnectedInfo {
|
||||
pub fn session_info(&self) -> Option<&SessionInfo> {
|
||||
self.session_info.as_ref()
|
||||
}
|
||||
|
||||
pub fn connected_at(&self) -> u32 {
|
||||
self.connected_at
|
||||
}
|
||||
}
|
||||
|
||||
fn unix_timestamp() -> u32 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as u32
|
||||
}
|
||||
|
||||
impl ConnectInfo {
|
||||
@@ -52,6 +88,7 @@ impl ConnectInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VpnState {
|
||||
Disconnected,
|
||||
Failed(String),
|
||||
Connecting(Box<ConnectInfo>),
|
||||
Connected(Box<ConnectedInfo>),
|
||||
Disconnecting,
|
||||
@@ -79,5 +116,6 @@ mod tests {
|
||||
|
||||
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
|
||||
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
|
||||
assert!(value["connected"]["connectedAt"].as_u64().is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use anyhow::bail;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::utils::base64;
|
||||
|
||||
pub const MAX_VPNC_SCRIPT_SOURCE_VALUE: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VpncScriptSource {
|
||||
File,
|
||||
Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VpncScriptMetadata {
|
||||
pub source: VpncScriptSource,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl VpncScriptMetadata {
|
||||
pub fn new(source: VpncScriptSource, value: String) -> anyhow::Result<Self> {
|
||||
if value.trim().is_empty() {
|
||||
bail!("VPNC script source is empty");
|
||||
}
|
||||
if value.contains('\0') {
|
||||
bail!("VPNC script source contains a null character");
|
||||
}
|
||||
if value.len() > MAX_VPNC_SCRIPT_SOURCE_VALUE {
|
||||
bail!(
|
||||
"VPNC script source exceeds the {} byte limit",
|
||||
MAX_VPNC_SCRIPT_SOURCE_VALUE
|
||||
);
|
||||
}
|
||||
Ok(Self { source, value })
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> anyhow::Result<()> {
|
||||
Self::new(self.source, self.value.clone()).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct InstallVpncScriptRequest {
|
||||
pub metadata: VpncScriptMetadata,
|
||||
contents: String,
|
||||
}
|
||||
|
||||
impl InstallVpncScriptRequest {
|
||||
pub fn new(metadata: VpncScriptMetadata, contents: &[u8]) -> Self {
|
||||
Self {
|
||||
metadata,
|
||||
contents: base64::encode(contents),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contents(&self) -> anyhow::Result<Vec<u8>> {
|
||||
base64::decode_to_vec(&self.contents)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn install_request_round_trips_binary_contents() {
|
||||
let metadata = VpncScriptMetadata::new(VpncScriptSource::File, "/tmp/vpnc-script".to_owned()).unwrap();
|
||||
let request = InstallVpncScriptRequest::new(metadata, b"#!/bin/sh\n");
|
||||
let encoded = serde_json::to_vec(&request).unwrap();
|
||||
let decoded: InstallVpncScriptRequest = serde_json::from_slice(&encoded).unwrap();
|
||||
|
||||
assert_eq!(decoded.contents().unwrap(), b"#!/bin/sh\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_rejects_invalid_source_value() {
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, String::new()).is_err());
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "echo\0value".to_owned()).is_err());
|
||||
assert!(VpncScriptMetadata::new(VpncScriptSource::Command, "x".repeat(MAX_VPNC_SCRIPT_SOURCE_VALUE + 1)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,14 @@ use chrono::{Local, TimeZone};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
mod connection;
|
||||
mod gateway_sessions;
|
||||
pub mod network;
|
||||
pub mod non_tunnel;
|
||||
pub mod transport;
|
||||
pub use connection::*;
|
||||
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct SessionWarning {
|
||||
pub prior_secs: u32,
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
use std::{fmt, time::Duration};
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::gateway::Gateway;
|
||||
|
||||
/// Network location and session mode are independent: an internal gateway can
|
||||
/// still require a tunnel.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionMode {
|
||||
Tunnel,
|
||||
NonTunnel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MaintenanceState {
|
||||
Authenticated,
|
||||
Healthy,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GatewaySessionSummary {
|
||||
pub gateway: Gateway,
|
||||
pub mode: SessionMode,
|
||||
pub client_ip: Option<String>,
|
||||
pub client_ipv6: Option<String>,
|
||||
pub maintenance: MaintenanceState,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SessionEndReason {
|
||||
InvalidCookie,
|
||||
NetworkChanged,
|
||||
AllMembersFailed,
|
||||
AuthorizationRevoked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "GatewayAuthenticationFields")]
|
||||
pub struct GatewayAuthentication {
|
||||
cookie: String,
|
||||
connection_type: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GatewayAuthenticationFields {
|
||||
cookie: String,
|
||||
connection_type: String,
|
||||
}
|
||||
|
||||
impl TryFrom<GatewayAuthenticationFields> for GatewayAuthentication {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: GatewayAuthenticationFields) -> Result<Self, Self::Error> {
|
||||
Self::new(fields.cookie, fields.connection_type)
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayAuthentication {
|
||||
pub fn new(cookie: String, connection_type: String) -> anyhow::Result<Self> {
|
||||
let authentication = Self {
|
||||
cookie,
|
||||
connection_type,
|
||||
};
|
||||
ensure!(
|
||||
!authentication.cookie.is_empty() && authentication.cookie.len() <= 64 * 1024,
|
||||
"Gateway authentication cookie is missing or too large"
|
||||
);
|
||||
let params = url::form_urlencoded::parse(authentication.cookie.as_bytes()).collect::<Vec<_>>();
|
||||
for key in ["authcookie", "user"] {
|
||||
let mut values = params.iter().filter(|(name, _)| name == key).map(|(_, value)| value);
|
||||
ensure!(
|
||||
values.next().is_some_and(|value| !value.is_empty()) && values.next().is_none(),
|
||||
"Gateway authentication requires one nonempty {key}"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!authentication.connection_type.trim().is_empty()
|
||||
&& authentication.connection_type != "(null)"
|
||||
&& authentication.connection_type != "-1",
|
||||
"Gateway connection type is missing"
|
||||
);
|
||||
Ok(authentication)
|
||||
}
|
||||
|
||||
pub fn cookie(&self) -> &str {
|
||||
&self.cookie
|
||||
}
|
||||
|
||||
pub fn connection_type(&self) -> &str {
|
||||
&self.connection_type
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> SessionMode {
|
||||
if self.connection_type == "tunnel" {
|
||||
SessionMode::Tunnel
|
||||
} else {
|
||||
SessionMode::NonTunnel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for GatewayAuthentication {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("GatewayAuthentication")
|
||||
.field("cookie", &"<redacted>")
|
||||
.field("mode", &self.mode())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for GatewayAuthentication {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", try_from = "InternalSessionPolicyFields")]
|
||||
pub struct InternalSessionPolicy {
|
||||
hip_interval_secs: u32,
|
||||
collect_hip_data: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct InternalSessionPolicyFields {
|
||||
hip_interval_secs: u32,
|
||||
collect_hip_data: bool,
|
||||
}
|
||||
|
||||
impl TryFrom<InternalSessionPolicyFields> for InternalSessionPolicy {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: InternalSessionPolicyFields) -> Result<Self, Self::Error> {
|
||||
Self::new(fields.hip_interval_secs, fields.collect_hip_data)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct AuthenticatedGateway {
|
||||
pub gateway: Gateway,
|
||||
pub authentication: GatewayAuthentication,
|
||||
pub binding: Option<super::network::GatewayBinding>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GatewayFailure {
|
||||
AuthenticationRejected,
|
||||
Unreachable,
|
||||
TunnelFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
pub struct GatewayFailureSummary {
|
||||
pub gateway: Gateway,
|
||||
pub failure: GatewayFailure,
|
||||
}
|
||||
|
||||
/// Credentials remain in the interactive authentication owner; only issued
|
||||
/// gateway cookies cross the runtime/service boundary.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "ConnectionPlanFields")]
|
||||
pub struct ConnectionPlan {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConnectionPlanFields {
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
internal_detection: Option<super::network::InternalHostDetection>,
|
||||
}
|
||||
|
||||
impl TryFrom<ConnectionPlanFields> for ConnectionPlan {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: ConnectionPlanFields) -> Result<Self, Self::Error> {
|
||||
Ok(Self::new(fields.members, fields.failures, fields.policy)?.with_internal_detection(fields.internal_detection))
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionPlan {
|
||||
pub fn new(
|
||||
members: Vec<AuthenticatedGateway>,
|
||||
failures: Vec<GatewayFailureSummary>,
|
||||
policy: InternalSessionPolicy,
|
||||
) -> anyhow::Result<Self> {
|
||||
ensure!(!members.is_empty(), "Connection plan has no authenticated gateways");
|
||||
ensure!(
|
||||
members.len() <= 64 && failures.len() <= 64,
|
||||
"Connection plan exceeds its gateway limit"
|
||||
);
|
||||
let mode = members[0].authentication.mode();
|
||||
ensure!(
|
||||
members.iter().all(|member| member.authentication.mode() == mode),
|
||||
"Mixed tunnel and non-tunnel sessions are unsupported"
|
||||
);
|
||||
ensure!(
|
||||
mode != SessionMode::NonTunnel
|
||||
|| members
|
||||
.iter()
|
||||
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
|
||||
"Non-tunnel sessions require freshly discovered internal gateways"
|
||||
);
|
||||
ensure!(
|
||||
members.len() == 1
|
||||
|| members
|
||||
.iter()
|
||||
.all(|member| member.gateway.kind() == crate::gateway::GatewayKind::Internal),
|
||||
"Multiple authenticated gateways require an internal connection"
|
||||
);
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for member in &members {
|
||||
if mode == SessionMode::NonTunnel {
|
||||
let binding = member
|
||||
.binding
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Non-tunnel session has no physical binding"))?;
|
||||
binding.validate_server(member.gateway.server())?;
|
||||
}
|
||||
let host = crate::utils::normalize_server(member.gateway.server())?;
|
||||
ensure!(hosts.insert(host), "Connection plan has duplicate gateways");
|
||||
}
|
||||
Ok(Self {
|
||||
members,
|
||||
failures,
|
||||
policy,
|
||||
internal_detection: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn members(&self) -> &[AuthenticatedGateway] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> &[GatewayFailureSummary] {
|
||||
&self.failures
|
||||
}
|
||||
|
||||
pub fn policy(&self) -> InternalSessionPolicy {
|
||||
self.policy
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> SessionMode {
|
||||
self.members[0].authentication.mode()
|
||||
}
|
||||
|
||||
pub fn with_internal_detection(mut self, detection: Option<super::network::InternalHostDetection>) -> Self {
|
||||
self.internal_detection = detection;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn internal_detection(&self) -> Option<&super::network::InternalHostDetection> {
|
||||
self.internal_detection.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for InternalSessionPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hip_interval_secs: 3600,
|
||||
collect_hip_data: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalSessionPolicy {
|
||||
pub fn new(hip_interval_secs: u32, collect_hip_data: bool) -> anyhow::Result<Self> {
|
||||
ensure!(hip_interval_secs > 0, "HIP report interval must be positive");
|
||||
ensure!(
|
||||
hip_interval_secs.checked_mul(1000).is_some(),
|
||||
"HIP report interval exceeds the supported range"
|
||||
);
|
||||
Ok(Self {
|
||||
hip_interval_secs,
|
||||
collect_hip_data,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn hip_interval(&self) -> Duration {
|
||||
Duration::from_secs(u64::from(self.hip_interval_secs))
|
||||
}
|
||||
|
||||
pub fn collect_hip_data(&self) -> bool {
|
||||
self.collect_hip_data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deserialization_enforces_authentication_invariants() {
|
||||
for (cookie, mode) in [
|
||||
("", "tunnel"),
|
||||
("not-a-cookie", "tunnel"),
|
||||
("user=alice", "tunnel"),
|
||||
("authcookie=token", "tunnel"),
|
||||
("authcookie=token&user=alice&user=bob", "tunnel"),
|
||||
("authcookie=token&user=alice", ""),
|
||||
] {
|
||||
let serialized = serde_json::json!({"cookie":cookie, "connection_type":mode});
|
||||
assert!(serde_json::from_value::<GatewayAuthentication>(serialized).is_err());
|
||||
}
|
||||
let auth = GatewayAuthentication::new("authcookie=token&user=alice".into(), "non-tunnel".into()).unwrap();
|
||||
let decoded: GatewayAuthentication = serde_json::from_str(&serde_json::to_string(&auth).unwrap()).unwrap();
|
||||
assert_eq!(decoded.mode(), SessionMode::NonTunnel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialization_enforces_schedule_invariants() {
|
||||
for interval in [0, u32::MAX] {
|
||||
let serialized = serde_json::json!({"hipIntervalSecs":interval,"collectHipData":false});
|
||||
assert!(serde_json::from_value::<InternalSessionPolicy>(serialized).is_err());
|
||||
}
|
||||
let serialized = serde_json::to_string(&InternalSessionPolicy::default()).unwrap();
|
||||
let decoded: InternalSessionPolicy = serde_json::from_str(&serialized).unwrap();
|
||||
assert_eq!(decoded.hip_interval(), Duration::from_secs(3600));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::{
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::gateway::Gateway;
|
||||
|
||||
use super::transport::GatewayTransport;
|
||||
|
||||
const LOGOUT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
pub struct ClientAddresses {
|
||||
pub ipv4: Option<Ipv4Addr>,
|
||||
pub ipv6: Option<Ipv6Addr>,
|
||||
}
|
||||
|
||||
/// One issued gateway authentication and its original request context. Session
|
||||
/// mode governs execution, while every mode has the same cleanup owner.
|
||||
pub struct GatewaySession {
|
||||
pub gateway: Gateway,
|
||||
pub transport: GatewayTransport,
|
||||
pub addresses: ClientAddresses,
|
||||
}
|
||||
|
||||
/// Owns issued gateway sessions independently of tunnel or HIP setup. Workers
|
||||
/// borrow members; their owner joins them before consuming this ledger in logout.
|
||||
/// This owner is deliberately not Clone: transfer or drain it exactly once.
|
||||
#[derive(Default)]
|
||||
pub struct GatewaySessions {
|
||||
members: Vec<Arc<GatewaySession>>,
|
||||
}
|
||||
|
||||
impl GatewaySessions {
|
||||
pub fn new(members: Vec<GatewaySession>) -> Self {
|
||||
Self {
|
||||
members: members.into_iter().map(Arc::new).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, session: GatewaySession) {
|
||||
self.members.push(Arc::new(session));
|
||||
}
|
||||
|
||||
pub(crate) fn update(&mut self, session: GatewaySession) {
|
||||
if let Some(member) = self
|
||||
.members
|
||||
.iter_mut()
|
||||
.find(|member| member.gateway.server() == session.gateway.server())
|
||||
{
|
||||
*member = Arc::new(session);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.members.is_empty()
|
||||
}
|
||||
|
||||
/// Consume the local cleanup copies only after another owner has proved it
|
||||
/// acquired responsibility for these issued sessions.
|
||||
pub fn relinquish(self) {}
|
||||
|
||||
pub fn members(&self) -> &[Arc<GatewaySession>] {
|
||||
&self.members
|
||||
}
|
||||
|
||||
/// Transfer a selected tunnel login to OpenConnect immediately before its
|
||||
/// native worker starts. OpenConnect owns the live reconnect cookie and logout.
|
||||
pub fn relinquish_gateway(&mut self, server: &str) {
|
||||
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
|
||||
self.members.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// Call only after this member's worker has joined. Removing ownership before
|
||||
/// awaiting logout prevents routine final cleanup from repeating the request.
|
||||
pub async fn logout_gateway(&mut self, server: &str) {
|
||||
if let Some(index) = self.members.iter().position(|member| member.gateway.server() == server) {
|
||||
logout(self.members.remove(index)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn logout(self) {
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for session in self.members {
|
||||
workers.spawn(logout(session));
|
||||
}
|
||||
while let Some(result) = workers.join_next().await {
|
||||
if let Err(error) = result {
|
||||
log::warn!("Gateway cleanup worker failed: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn logout(session: Arc<GatewaySession>) {
|
||||
match tokio::time::timeout(LOGOUT_TIMEOUT, session.transport.logout()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => log::warn!("Gateway logout failed: {error}"),
|
||||
Err(_) => log::warn!("Gateway logout timed out"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::super::ClientAddresses;
|
||||
|
||||
/// Physical network context bound to the authenticated non-tunnel endpoint. Wire input is validated;
|
||||
/// runtime transports use this context without performing another DNS lookup.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "BindingFields", rename_all = "camelCase")]
|
||||
pub struct GatewayBinding {
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct BindingFields {
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
impl TryFrom<BindingFields> for GatewayBinding {
|
||||
type Error = anyhow::Error;
|
||||
fn try_from(fields: BindingFields) -> Result<Self, Self::Error> {
|
||||
Self::new(
|
||||
fields.endpoint,
|
||||
fields.source,
|
||||
fields.interface,
|
||||
fields.interface_index,
|
||||
fields.addresses,
|
||||
fields.network_fingerprint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayBinding {
|
||||
pub fn new(
|
||||
endpoint: SocketAddr,
|
||||
source: SocketAddr,
|
||||
interface: String,
|
||||
interface_index: u32,
|
||||
addresses: ClientAddresses,
|
||||
network_fingerprint: impl Into<Option<String>>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let network_fingerprint = network_fingerprint.into();
|
||||
ensure!(
|
||||
network_fingerprint
|
||||
.as_ref()
|
||||
.is_none_or(|value| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())),
|
||||
"Physical network fingerprint is invalid"
|
||||
);
|
||||
ensure!(
|
||||
endpoint.port() != 0 && !endpoint.ip().is_unspecified() && !endpoint.ip().is_multicast(),
|
||||
"Gateway endpoint is invalid"
|
||||
);
|
||||
ensure!(
|
||||
source.port() == 0 && !source.ip().is_unspecified() && !source.ip().is_multicast(),
|
||||
"Gateway source is invalid"
|
||||
);
|
||||
ensure!(
|
||||
endpoint.is_ipv4() == source.is_ipv4(),
|
||||
"Gateway address families differ"
|
||||
);
|
||||
ensure!(
|
||||
!interface.is_empty() && interface.len() < 64 && !interface.contains('\0') && interface_index != 0,
|
||||
"Gateway interface is invalid"
|
||||
);
|
||||
for address in [endpoint, source] {
|
||||
if let SocketAddr::V6(address) = address {
|
||||
ensure!(address.flowinfo() == 0, "Gateway IPv6 flow information is invalid");
|
||||
ensure!(
|
||||
address.scope_id() == 0 || address.scope_id() == interface_index,
|
||||
"Gateway IPv6 scope differs from its interface"
|
||||
);
|
||||
ensure!(
|
||||
!address.ip().is_unicast_link_local() || address.scope_id() == interface_index,
|
||||
"Gateway IPv6 scope is missing"
|
||||
);
|
||||
}
|
||||
}
|
||||
match source.ip() {
|
||||
IpAddr::V4(ip) => ensure!(
|
||||
addresses.ipv4 == Some(ip),
|
||||
"Gateway IPv4 source differs from its identity"
|
||||
),
|
||||
IpAddr::V6(ip) => ensure!(
|
||||
addresses.ipv6 == Some(ip),
|
||||
"Gateway IPv6 source differs from its identity"
|
||||
),
|
||||
}
|
||||
Ok(Self {
|
||||
endpoint,
|
||||
source,
|
||||
interface,
|
||||
interface_index,
|
||||
addresses,
|
||||
network_fingerprint,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn endpoint(&self) -> SocketAddr {
|
||||
self.endpoint
|
||||
}
|
||||
pub fn source(&self) -> SocketAddr {
|
||||
self.source
|
||||
}
|
||||
pub fn interface(&self) -> &str {
|
||||
&self.interface
|
||||
}
|
||||
pub fn interface_index(&self) -> u32 {
|
||||
self.interface_index
|
||||
}
|
||||
pub fn addresses(&self) -> ClientAddresses {
|
||||
self.addresses
|
||||
}
|
||||
|
||||
pub fn network_fingerprint(&self) -> Option<&str> {
|
||||
self.network_fingerprint.as_deref()
|
||||
}
|
||||
|
||||
pub fn validate_server(&self, server: &str) -> anyhow::Result<()> {
|
||||
let origin = super::super::transport::gateway_origin(server)?;
|
||||
ensure!(
|
||||
origin.port_or_known_default() == Some(self.endpoint.port()),
|
||||
"Gateway endpoint port differs"
|
||||
);
|
||||
let literal = match origin.host() {
|
||||
Some(url::Host::Ipv4(ip)) => Some(IpAddr::V4(ip)),
|
||||
Some(url::Host::Ipv6(ip)) => Some(IpAddr::V6(ip)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(ip) = literal {
|
||||
ensure!(self.endpoint.ip() == ip, "Literal gateway endpoint differs");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ipv4_binding() -> GatewayBinding {
|
||||
GatewayBinding::new(
|
||||
"192.0.2.10:443".parse().unwrap(),
|
||||
"192.0.2.5:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
7,
|
||||
ClientAddresses {
|
||||
ipv4: Some("192.0.2.5".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
"a".repeat(64),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_input_rejects_inconsistent_network_identity() {
|
||||
let original = serde_json::to_value(ipv4_binding()).unwrap();
|
||||
for (field, value) in [
|
||||
("source", serde_json::json!("192.0.2.6:0")),
|
||||
("source", serde_json::json!("192.0.2.5:1234")),
|
||||
("endpoint", serde_json::json!("[2001:db8::10]:443")),
|
||||
("interfaceIndex", serde_json::json!(0)),
|
||||
("networkFingerprint", serde_json::json!("not-a-fingerprint")),
|
||||
] {
|
||||
let mut invalid = original.clone();
|
||||
invalid[field] = value;
|
||||
assert!(
|
||||
serde_json::from_value::<GatewayBinding>(invalid).is_err(),
|
||||
"accepted {field}"
|
||||
);
|
||||
}
|
||||
assert!(serde_json::from_value::<GatewayBinding>(original).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_local_scope_survives_wire_round_trip_and_must_match_interface() {
|
||||
let addresses = ClientAddresses {
|
||||
ipv4: None,
|
||||
ipv6: Some("fe80::5".parse().unwrap()),
|
||||
};
|
||||
let binding = GatewayBinding::new(
|
||||
"[fe80::10%7]:443".parse().unwrap(),
|
||||
"[fe80::5%7]:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
7,
|
||||
addresses,
|
||||
"a".repeat(64),
|
||||
)
|
||||
.unwrap();
|
||||
let value = serde_json::to_value(&binding).unwrap();
|
||||
let restored: GatewayBinding = serde_json::from_value(value.clone()).unwrap();
|
||||
assert_eq!(restored.source(), binding.source());
|
||||
assert_eq!(restored.endpoint(), binding.endpoint());
|
||||
for source in ["[fe80::5]:0", "[fe80::5%8]:0"] {
|
||||
let mut invalid = value.clone();
|
||||
invalid["source"] = serde_json::json!(source);
|
||||
assert!(serde_json::from_value::<GatewayBinding>(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_origin_must_match_endpoint_port_and_literal_address() {
|
||||
let binding = ipv4_binding();
|
||||
assert!(binding.validate_server("gateway.example.com").is_ok());
|
||||
assert!(binding.validate_server("192.0.2.10").is_ok());
|
||||
assert!(binding.validate_server("192.0.2.11").is_err());
|
||||
assert!(binding.validate_server("gateway.example.com:444").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
pub(super) use super::bsd_routes::routes;
|
||||
use super::*;
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
_socket: &tokio::net::UdpSocket,
|
||||
_interface: &Interface,
|
||||
_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
// resolv.conf has no per-interface resolver contexts. IPv6 zones are carried
|
||||
// in the destination address instead.
|
||||
anyhow::bail!("Interface-scoped resolver contexts are unsupported on BSD")
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
resolv_conf(control)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos"))]
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut routes = Vec::new();
|
||||
for family in ["inet", "inet6"] {
|
||||
routes.extend(parse_routes(&command("netstat", &["-rn", "-f", family], control)?)?);
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut interface_column = None;
|
||||
let mut routes = Vec::new();
|
||||
for line in contents.lines() {
|
||||
let fields = line.split_whitespace().collect::<Vec<_>>();
|
||||
if fields.first() == Some(&"Destination") {
|
||||
interface_column = Some(
|
||||
fields
|
||||
.iter()
|
||||
.position(|field| matches!(*field, "Netif" | "Iface"))
|
||||
.context("Route table has no interface column")?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let Some(column) = interface_column else {
|
||||
continue;
|
||||
};
|
||||
if fields.len() <= column {
|
||||
continue;
|
||||
}
|
||||
// L/W entries are neighbor-cache or cloned host routes. Their presence,
|
||||
// gateway MAC and expiry depend on traffic and must not cause rediscovery.
|
||||
if fields[2].contains('L') || fields[2].contains('W') {
|
||||
continue;
|
||||
}
|
||||
routes.push(RouteContext {
|
||||
destination: fields[0].into(),
|
||||
gateway: fields[1].into(),
|
||||
interface: fields[column].into(),
|
||||
table: String::new(),
|
||||
metric: String::new(),
|
||||
});
|
||||
}
|
||||
ensure!(interface_column.is_some(), "Route table header is missing");
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn ignores_route_use_expiry_and_platform_column_positions() {
|
||||
let darwin = parse_routes("Routing tables\nInternet:\nDestination Gateway Flags Netif Expire\ndefault 192.0.2.1 UGScg en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHLWI en0 123").unwrap();
|
||||
let bsd = parse_routes("Destination Gateway Flags Refs Use Mtu Netif Expire\ndefault 192.0.2.1 UGS 4 22 1500 en0\n192.0.2.5 aa:bb:cc:dd:ee:ff UHL 0 33 1500 en0 99").unwrap();
|
||||
assert_eq!(darwin, bsd);
|
||||
assert_eq!(darwin.len(), 1);
|
||||
assert!(parse_routes("unrecognized table").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
use anyhow::ensure;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(try_from = "DetectionFields")]
|
||||
pub struct InternalHostDetection {
|
||||
targets: Vec<DetectionTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
struct DetectionTarget {
|
||||
address: IpAddr,
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DetectionFields {
|
||||
targets: Vec<DetectionTarget>,
|
||||
}
|
||||
|
||||
impl TryFrom<DetectionFields> for InternalHostDetection {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(fields: DetectionFields) -> anyhow::Result<Self> {
|
||||
Self::new(
|
||||
fields
|
||||
.targets
|
||||
.into_iter()
|
||||
.map(|target| (target.address, target.hostname))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalHostDetection {
|
||||
pub fn new(targets: Vec<(IpAddr, String)>) -> anyhow::Result<Self> {
|
||||
ensure!(
|
||||
!targets.is_empty() && targets.len() <= 2,
|
||||
"Invalid internal detection target count"
|
||||
);
|
||||
let targets = targets
|
||||
.into_iter()
|
||||
.map(|(address, hostname)| {
|
||||
validate_target(address, &hostname)?;
|
||||
Ok(DetectionTarget { address, hostname })
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
Ok(Self { targets })
|
||||
}
|
||||
|
||||
pub async fn detect(&self, cancellation: &CancellationToken) -> anyhow::Result<bool> {
|
||||
for target in &self.targets {
|
||||
if super::native::detect(target.address, &target.hostname, cancellation).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_target(address: IpAddr, hostname: &str) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!address.is_unspecified() && !address.is_loopback() && !address.is_multicast(),
|
||||
"Invalid internal detection address"
|
||||
);
|
||||
ensure!(
|
||||
!hostname.is_empty()
|
||||
&& hostname.len() <= 253
|
||||
&& hostname.is_ascii()
|
||||
&& hostname
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')),
|
||||
"Invalid internal detection hostname"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detection_inputs_are_retained_and_validated_on_deserialization() {
|
||||
let detection = InternalHostDetection::new(vec![("192.0.2.10".parse().unwrap(), "host.example".into())]).unwrap();
|
||||
let value = serde_json::to_value(&detection).unwrap();
|
||||
assert!(serde_json::from_value::<InternalHostDetection>(value).is_ok());
|
||||
assert!(InternalHostDetection::new(vec![]).is_err());
|
||||
assert!(InternalHostDetection::new(vec![("127.0.0.1".parse().unwrap(), "host.example".into())]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
socket2::SockRef::from(socket).bind_device(Some(interface.name.as_bytes()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let mut routes = Vec::new();
|
||||
for family in ["-4", "-6"] {
|
||||
routes.extend(parse_routes(&command(
|
||||
"ip",
|
||||
&[family, "-j", "route", "show", "table", "all"],
|
||||
control,
|
||||
)?)?);
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
fn parse_routes(contents: &str) -> anyhow::Result<Vec<RouteContext>> {
|
||||
let value: Vec<serde_json::Value> = serde_json::from_str(contents)?;
|
||||
let mut routes = Vec::new();
|
||||
for route in value {
|
||||
// Kernel cache and neighbor lifetimes are traffic, not network changes.
|
||||
if route.get("cache").is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(interface) = route["dev"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
let field = |name| {
|
||||
route
|
||||
.get(name)
|
||||
.map(|value| value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
routes.push(RouteContext {
|
||||
destination: field("dst"),
|
||||
gateway: field("gateway"),
|
||||
interface: interface.into(),
|
||||
table: field("table"),
|
||||
metric: field("metric"),
|
||||
});
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let path = std::fs::canonicalize("/etc/resolv.conf")?;
|
||||
if path.starts_with("/run/systemd/resolve") {
|
||||
let dns = command("resolvectl", &["dns"], control)?;
|
||||
let domains = command("resolvectl", &["domain"], control)?;
|
||||
return parse_resolved(&dns, &domains);
|
||||
}
|
||||
resolv_conf(control)
|
||||
}
|
||||
|
||||
fn parse_resolved(dns: &str, domains: &str) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let mut resolvers = std::collections::BTreeMap::<Option<String>, ResolverContext>::new();
|
||||
for (contents, is_dns) in [(dns, true), (domains, false)] {
|
||||
for line in contents.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let (label, values) = line.split_once(':').context("Invalid systemd resolver output")?;
|
||||
let interface = if label == "Global" {
|
||||
None
|
||||
} else {
|
||||
let (_, name) = label.split_once('(').context("Invalid systemd resolver interface")?;
|
||||
Some(
|
||||
name
|
||||
.strip_suffix(')')
|
||||
.context("Invalid systemd resolver interface")?
|
||||
.to_owned(),
|
||||
)
|
||||
};
|
||||
let resolver = resolvers.entry(interface.clone()).or_insert_with(|| ResolverContext {
|
||||
interface,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
});
|
||||
if is_dns {
|
||||
for server in values.split_whitespace() {
|
||||
server
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid systemd resolver address")?;
|
||||
resolver.servers.push(server.to_owned());
|
||||
}
|
||||
} else {
|
||||
resolver
|
||||
.domains
|
||||
.extend(values.split_whitespace().map(|domain| domain.to_ascii_lowercase()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(resolvers.into_values().collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn route_identity_retains_ipv6_and_ignores_cache() {
|
||||
let routes = parse_routes(r#"[{"dst":"default","gateway":"2001:db8::1","dev":"eth0","metric":600,"table":"main"},{"dst":"2001:db8::5","dev":"eth0","cache":[]}]"#).unwrap();
|
||||
assert_eq!(routes.len(), 1);
|
||||
assert_eq!(routes[0].gateway, "2001:db8::1");
|
||||
assert_eq!(routes[0].metric, "600");
|
||||
}
|
||||
#[test]
|
||||
fn resolved_preserves_interface_domains_and_empty_global_context() {
|
||||
let resolvers = parse_resolved(
|
||||
"Global:\nLink 2 (eth0): 192.0.2.53\n\nLink 3 (tun0): 198.51.100.53\n",
|
||||
"Global:\nLink 2 (eth0): CORP.EXAMPLE\nLink 3 (tun0): ~.\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(resolvers.len(), 3);
|
||||
assert!(
|
||||
resolvers
|
||||
.iter()
|
||||
.any(|resolver| resolver.interface.as_deref() == Some("eth0")
|
||||
&& resolver.domains.iter().any(|domain| domain == "corp.example"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
pub(super) use super::bsd_routes::routes;
|
||||
use super::*;
|
||||
|
||||
pub(super) fn scope_resolver_socket(
|
||||
socket: &tokio::net::UdpSocket,
|
||||
interface: &Interface,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
let index = std::num::NonZeroU32::new(interface.index).context("Resolver interface index is missing")?;
|
||||
let socket = socket2::SockRef::from(socket);
|
||||
if endpoint.is_ipv4() {
|
||||
socket.bind_device_by_index_v4(Some(index))?;
|
||||
} else {
|
||||
socket.bind_device_by_index_v6(Some(index))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
parse_resolvers(&command("scutil", &["--dns"], control)?)
|
||||
}
|
||||
|
||||
fn parse_resolvers(contents: &str) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
let mut resolvers = Vec::new();
|
||||
let mut current: Option<ResolverContext> = None;
|
||||
for line in contents.lines().map(str::trim) {
|
||||
if line.starts_with("resolver #") {
|
||||
if let Some(resolver) = current.take() {
|
||||
resolvers.push(resolver);
|
||||
}
|
||||
current = Some(ResolverContext {
|
||||
interface: None,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(resolver) = &mut current else {
|
||||
continue;
|
||||
};
|
||||
let Some((field, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let field = field.trim();
|
||||
let value = value.trim();
|
||||
if field.starts_with("nameserver[") {
|
||||
value
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid macOS resolver address")?;
|
||||
resolver.servers.push(value.to_owned());
|
||||
} else if field == "domain" || field.starts_with("search domain[") {
|
||||
resolver.domains.push(value.to_ascii_lowercase());
|
||||
} else if field == "if_index" {
|
||||
if let Some((_, name)) = value.split_once('(') {
|
||||
resolver.interface = Some(
|
||||
name
|
||||
.strip_suffix(')')
|
||||
.context("Invalid macOS resolver interface")?
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(resolver) = current {
|
||||
resolvers.push(resolver);
|
||||
}
|
||||
Ok(resolvers)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn resolver_identity_is_scoped_and_ignores_reachability_counters() {
|
||||
let a = parse_resolvers(
|
||||
"resolver #1\n nameserver[0] : 192.0.2.53\n if_index : 4 (en0)\n search domain[0] : CORP.EXAMPLE\n reach : 2",
|
||||
)
|
||||
.unwrap();
|
||||
let b = parse_resolvers(
|
||||
"resolver #9\n search domain[0] : corp.example\n if_index : 4 (en0)\n nameserver[0] : 192.0.2.53\n reach : 3",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a[0].interface.as_deref(), Some("en0"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io,
|
||||
net::{IpAddr, SocketAddr},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use netdev::Interface;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::ClientAddresses;
|
||||
use crate::process::collection::{CollectionBudget, CollectionControl, CollectorCommands};
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
mod bsd;
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "macos", test))]
|
||||
mod bsd_routes;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
use bsd as platform;
|
||||
#[cfg(target_os = "linux")]
|
||||
use linux as platform;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos as platform;
|
||||
|
||||
mod binding;
|
||||
mod detection;
|
||||
pub mod native;
|
||||
pub use binding::GatewayBinding;
|
||||
pub use detection::InternalHostDetection;
|
||||
|
||||
const INSPECTION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(5);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct InterfaceIdentity {
|
||||
index: u32,
|
||||
name: String,
|
||||
mac: Option<String>,
|
||||
flags: u32,
|
||||
addresses: BTreeSet<(String, u32)>,
|
||||
}
|
||||
|
||||
impl From<&Interface> for InterfaceIdentity {
|
||||
fn from(interface: &Interface) -> Self {
|
||||
let mut addresses = interface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|ip| (ip.to_string(), 0))
|
||||
.collect::<BTreeSet<_>>();
|
||||
addresses.extend(interface.ipv6.iter().enumerate().map(|(index, ip)| {
|
||||
(
|
||||
ip.to_string(),
|
||||
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
|
||||
)
|
||||
}));
|
||||
Self {
|
||||
index: interface.index,
|
||||
name: interface.name.clone(),
|
||||
mac: interface.mac_addr.map(|mac| mac.to_string()),
|
||||
flags: interface.flags,
|
||||
addresses,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct RouteContext {
|
||||
destination: String,
|
||||
gateway: String,
|
||||
interface: String,
|
||||
table: String,
|
||||
metric: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
struct ResolverContext {
|
||||
interface: Option<String>,
|
||||
servers: Vec<String>,
|
||||
domains: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
struct NetworkSnapshot {
|
||||
interfaces: BTreeSet<InterfaceIdentity>,
|
||||
routes: BTreeSet<RouteContext>,
|
||||
resolvers: Vec<ResolverContext>,
|
||||
}
|
||||
|
||||
/// Captured before this attempt installs a tunnel. Interface counters and
|
||||
/// timestamps do not participate in identity; routes and resolver context do.
|
||||
#[derive(Clone)]
|
||||
pub struct PhysicalNetwork {
|
||||
snapshot: NetworkSnapshot,
|
||||
interfaces: Vec<Interface>,
|
||||
}
|
||||
|
||||
impl PhysicalNetwork {
|
||||
pub async fn bind_authenticated_endpoint(
|
||||
&self,
|
||||
server: &str,
|
||||
endpoint: SocketAddr,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<GatewayBinding> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
let binding = resolve_binding(
|
||||
&self.interfaces,
|
||||
Some(self.fingerprint()?),
|
||||
server,
|
||||
disable_ipv6,
|
||||
cancellation,
|
||||
endpoint,
|
||||
)
|
||||
.await?;
|
||||
self.ensure_current(cancellation).await?;
|
||||
Ok(binding)
|
||||
}
|
||||
pub async fn validate_internal_binding(
|
||||
&self,
|
||||
binding: &GatewayBinding,
|
||||
detection: Option<&InternalHostDetection>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.validate_binding(binding, cancellation).await?;
|
||||
physical_interface_for_source(&self.interfaces, binding.source(), binding.endpoint())?;
|
||||
self.validate_internal(detection, cancellation).await
|
||||
}
|
||||
|
||||
pub async fn validate_internal(
|
||||
&self,
|
||||
detection: Option<&InternalHostDetection>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
let mut resolver_count = 0;
|
||||
for resolver in &self.snapshot.resolvers {
|
||||
if resolver.servers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for server in &resolver.servers {
|
||||
let endpoint = resolver_endpoint(server, resolver.interface.as_deref(), &self.interfaces)?;
|
||||
ensure!(
|
||||
!endpoint.ip().is_loopback() && !endpoint.ip().is_unspecified(),
|
||||
"Unattributed local DNS stub is unsupported"
|
||||
);
|
||||
let socket = tokio::net::UdpSocket::bind(if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" }).await?;
|
||||
if let Some(name) = &resolver.interface {
|
||||
let interface = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.name == *name)
|
||||
.context("Configured resolver interface is missing")?;
|
||||
platform::scope_resolver_socket(&socket, interface, endpoint)?;
|
||||
}
|
||||
socket.connect(endpoint).await?;
|
||||
let interface = physical_interface_for_source(&self.interfaces, socket.local_addr()?, endpoint)?;
|
||||
ensure!(
|
||||
resolver.interface.as_deref().is_none_or(|name| name == interface.name),
|
||||
"Resolver route differs from its configured interface"
|
||||
);
|
||||
resolver_count += 1;
|
||||
}
|
||||
}
|
||||
ensure!(resolver_count > 0, "Physical resolver context is unavailable");
|
||||
if let Some(detection) = detection {
|
||||
ensure!(
|
||||
detection.detect(cancellation).await?,
|
||||
"Internal host detection no longer matches"
|
||||
);
|
||||
}
|
||||
self.ensure_current(cancellation).await
|
||||
}
|
||||
pub async fn capture_controlled(cancellation: &CancellationToken) -> anyhow::Result<Self> {
|
||||
let cancellation = cancellation.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "Network capture cancelled"));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
Self::capture(&check)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub async fn validate_binding(
|
||||
&self,
|
||||
binding: &GatewayBinding,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<()> {
|
||||
self.ensure_current(cancellation).await?;
|
||||
ensure!(
|
||||
binding.network_fingerprint() == Some(self.fingerprint()?.as_str()),
|
||||
"Physical network changed since authentication"
|
||||
);
|
||||
let interface = self
|
||||
.interfaces
|
||||
.iter()
|
||||
.find(|interface| interface.index == binding.interface_index() && interface.name == binding.interface())
|
||||
.context("Authenticated gateway interface is no longer present")?;
|
||||
let addresses = binding.addresses();
|
||||
ensure!(
|
||||
addresses
|
||||
.ipv4
|
||||
.is_none_or(|ip| interface.ipv4.iter().any(|address| address.addr() == ip)),
|
||||
"Authenticated IPv4 address changed"
|
||||
);
|
||||
ensure!(
|
||||
addresses
|
||||
.ipv6
|
||||
.is_none_or(|ip| interface.ipv6.iter().any(|address| address.addr() == ip)),
|
||||
"Authenticated IPv6 address changed"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fingerprint(&self) -> anyhow::Result<String> {
|
||||
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
|
||||
}
|
||||
|
||||
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
|
||||
control.check()?;
|
||||
let mut interfaces = netdev::get_interfaces();
|
||||
for interface in &mut interfaces {
|
||||
interface.ipv4.sort();
|
||||
// The address and its zone must move together when native enumeration
|
||||
// order changes between captures.
|
||||
let mut ipv6 = interface
|
||||
.ipv6
|
||||
.iter()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(index, address)| {
|
||||
(
|
||||
address,
|
||||
interface.ipv6_scope_ids.get(index).copied().unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
ipv6.sort();
|
||||
interface.ipv6 = ipv6.iter().map(|(address, _)| *address).collect();
|
||||
interface.ipv6_scope_ids = ipv6.into_iter().map(|(_, scope)| scope).collect();
|
||||
}
|
||||
let snapshot = snapshot(&interfaces, control)?;
|
||||
control.check()?;
|
||||
Ok(Self { snapshot, interfaces })
|
||||
}
|
||||
|
||||
/// Validate endpoint selection against the captured network. The inspection
|
||||
/// is joined even when cancellation occurs, so native collectors cannot outlive
|
||||
/// the connection attempt.
|
||||
pub async fn ensure_current(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let current = inspect(cancellation.clone()).await?;
|
||||
ensure!(
|
||||
current == self.snapshot,
|
||||
"Physical network changed during gateway setup"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The owner must cancel and await this monitor, including its blocking
|
||||
/// inspection. Dropping a selected future would detach the native collector.
|
||||
pub async fn wait_for_change(
|
||||
&self,
|
||||
detection: Option<InternalHostDetection>,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<bool> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Ok(false),
|
||||
_ = tokio::time::sleep(POLL_INTERVAL) => {},
|
||||
}
|
||||
let current = self.validate_internal(detection.as_ref(), &cancellation).await;
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(false);
|
||||
}
|
||||
if current.is_err() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_binding(
|
||||
interfaces: &[Interface],
|
||||
fingerprint: Option<String>,
|
||||
server: &str,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
authenticated_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<GatewayBinding> {
|
||||
let origin = super::transport::gateway_origin(server)?;
|
||||
let host = origin.host_str().context("Gateway host is missing")?;
|
||||
let port = origin.port_or_known_default().context("Gateway port is missing")?;
|
||||
let literal = literal_gateway_address(&origin)?;
|
||||
let endpoints = if let Some(ip) = literal {
|
||||
vec![SocketAddr::new(ip, port)]
|
||||
} else {
|
||||
native::resolve(host, port, disable_ipv6, cancellation).await?
|
||||
};
|
||||
ensure!(
|
||||
endpoints.contains(&authenticated_endpoint),
|
||||
"Authenticated peer differs from the gateway's current DNS addresses; check for a proxy or changed DNS answer"
|
||||
);
|
||||
let endpoint = authenticated_endpoint;
|
||||
ensure!(
|
||||
!(disable_ipv6 && endpoint.is_ipv6()),
|
||||
"Authenticated gateway uses disabled IPv6"
|
||||
);
|
||||
let bind = if endpoint.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
|
||||
let socket = tokio::net::UdpSocket::bind(bind).await?;
|
||||
socket.connect(endpoint).await?;
|
||||
let mut source_address = socket.local_addr()?;
|
||||
source_address.set_port(0);
|
||||
let source = source_address.ip();
|
||||
let interface = physical_interface_for_source(interfaces, source_address, endpoint)?;
|
||||
let ipv4 = match source {
|
||||
IpAddr::V4(ip) => Some(ip),
|
||||
_ => interface
|
||||
.ipv4
|
||||
.iter()
|
||||
.map(|ip| ip.addr())
|
||||
.find(|ip| !ip.is_loopback() && !ip.is_unspecified()),
|
||||
};
|
||||
let ipv6 = if disable_ipv6 {
|
||||
None
|
||||
} else {
|
||||
match source {
|
||||
IpAddr::V6(ip) => Some(ip),
|
||||
_ => interface
|
||||
.ipv6
|
||||
.iter()
|
||||
.map(|ip| ip.addr())
|
||||
.find(|ip| !ip.is_loopback() && !ip.is_unspecified() && !ip.is_unicast_link_local()),
|
||||
}
|
||||
};
|
||||
if let std::net::SocketAddr::V6(address) = &mut source_address {
|
||||
if address.ip().is_unicast_link_local() && address.scope_id() == 0 {
|
||||
address.set_scope_id(interface.index);
|
||||
}
|
||||
}
|
||||
GatewayBinding::new(
|
||||
endpoint,
|
||||
source_address,
|
||||
interface.name.clone(),
|
||||
interface.index,
|
||||
ClientAddresses { ipv4, ipv6 },
|
||||
fingerprint.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
// Default-route inventories include scoped, backup, and unrelated address-family
|
||||
// routes. Attribute each actual destination by its selected source instead.
|
||||
fn physical_interface_for_source(
|
||||
interfaces: &[Interface],
|
||||
source: SocketAddr,
|
||||
endpoint: SocketAddr,
|
||||
) -> anyhow::Result<&Interface> {
|
||||
let mut scope = None;
|
||||
for address in [source, endpoint] {
|
||||
if let SocketAddr::V6(address) = address {
|
||||
if address.scope_id() != 0 {
|
||||
ensure!(
|
||||
scope.is_none_or(|scope| scope == address.scope_id()),
|
||||
"Network source and destination have different interface scopes"
|
||||
);
|
||||
scope = Some(address.scope_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
let source = source.ip();
|
||||
ensure!(
|
||||
!source.is_unspecified() && !source.is_loopback(),
|
||||
"Network route has no physical source address"
|
||||
);
|
||||
let mut matches = interfaces.iter().filter(|interface| {
|
||||
scope.is_none_or(|scope| scope == interface.index)
|
||||
&& (interface.ipv4.iter().any(|ip| IpAddr::V4(ip.addr()) == source)
|
||||
|| interface.ipv6.iter().any(|ip| IpAddr::V6(ip.addr()) == source))
|
||||
});
|
||||
let interface = matches
|
||||
.next()
|
||||
.context("Network route has no matching physical interface")?;
|
||||
ensure!(
|
||||
matches.next().is_none(),
|
||||
"Network route has ambiguous physical interfaces"
|
||||
);
|
||||
ensure!(
|
||||
matches!(
|
||||
interface.if_type,
|
||||
netdev::prelude::InterfaceType::Ethernet
|
||||
| netdev::prelude::InterfaceType::Wireless80211
|
||||
| netdev::prelude::InterfaceType::FastEthernetT
|
||||
| netdev::prelude::InterfaceType::FastEthernetFx
|
||||
| netdev::prelude::InterfaceType::GigabitEthernet
|
||||
),
|
||||
"Network route uses an unsupported physical interface: {}",
|
||||
interface.name
|
||||
);
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
fn resolver_endpoint(server: &str, interface: Option<&str>, interfaces: &[Interface]) -> anyhow::Result<SocketAddr> {
|
||||
let (address, zone) = server
|
||||
.split_once('%')
|
||||
.map_or((server, None), |(ip, zone)| (ip, Some(zone)));
|
||||
let ip: IpAddr = address.parse().context("Invalid resolver address")?;
|
||||
let mut endpoint = SocketAddr::new(ip, 53);
|
||||
if let SocketAddr::V6(address) = &mut endpoint {
|
||||
let zone = if zone.is_none() && address.ip().is_unicast_link_local() {
|
||||
interface
|
||||
} else {
|
||||
zone
|
||||
};
|
||||
if let Some(zone) = zone {
|
||||
let index = interfaces
|
||||
.iter()
|
||||
.find(|candidate| candidate.name == zone || candidate.index.to_string() == zone)
|
||||
.context("Resolver IPv6 zone has no matching interface")?
|
||||
.index;
|
||||
address.set_scope_id(index);
|
||||
}
|
||||
ensure!(
|
||||
!address.ip().is_unicast_link_local() || address.scope_id() != 0,
|
||||
"Link-local resolver has no interface scope"
|
||||
);
|
||||
} else {
|
||||
ensure!(zone.is_none(), "IPv4 resolver cannot have an interface scope");
|
||||
}
|
||||
Ok(endpoint)
|
||||
}
|
||||
|
||||
async fn inspect(cancellation: CancellationToken) -> anyhow::Result<NetworkSnapshot> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Network inspection cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
let result = snapshot(&netdev::get_interfaces(), &check)?;
|
||||
check()?;
|
||||
Ok(result)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn literal_gateway_address(origin: &url::Url) -> anyhow::Result<Option<IpAddr>> {
|
||||
Ok(match origin.host().context("Gateway host is missing")? {
|
||||
url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
|
||||
url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
|
||||
url::Host::Domain(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow::Result<NetworkSnapshot> {
|
||||
control.check()?;
|
||||
Ok(NetworkSnapshot {
|
||||
interfaces: interfaces.iter().map(InterfaceIdentity::from).collect(),
|
||||
routes: platform::routes(control)?.into_iter().collect(),
|
||||
resolvers: platform::resolvers(control)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let output = CollectorCommands::new(control)
|
||||
.run(name, args)?
|
||||
.with_context(|| format!("Required network tool {name} is unavailable"))?;
|
||||
ensure!(output.status.success(), "Network tool {name} failed");
|
||||
String::from_utf8(output.stdout).context("Network tool output is not UTF-8")
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn resolv_conf(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
|
||||
control.check()?;
|
||||
let file = std::fs::File::open("/etc/resolv.conf")?;
|
||||
use std::io::Read;
|
||||
let mut contents = String::new();
|
||||
file.take(64 * 1024 + 1).read_to_string(&mut contents)?;
|
||||
ensure!(contents.len() <= 64 * 1024, "Resolver configuration is too large");
|
||||
control.check()?;
|
||||
Ok(vec![parse_resolv_conf(&contents)?])
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn parse_resolv_conf(contents: &str) -> anyhow::Result<ResolverContext> {
|
||||
let mut resolver = ResolverContext {
|
||||
interface: None,
|
||||
servers: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
};
|
||||
for line in contents.lines() {
|
||||
let line = line.split(['#', ';']).next().unwrap_or_default();
|
||||
let mut fields = line.split_whitespace();
|
||||
match fields.next() {
|
||||
Some("nameserver") => {
|
||||
if let Some(server) = fields.next() {
|
||||
// IPv6 zone identifiers are retained for scoped physical resolvers.
|
||||
server
|
||||
.split('%')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.parse::<IpAddr>()
|
||||
.context("Invalid resolver address")?;
|
||||
resolver.servers.push(server.to_owned());
|
||||
}
|
||||
}
|
||||
Some("search" | "domain") => resolver
|
||||
.domains
|
||||
.extend(fields.map(|domain| domain.to_ascii_lowercase())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(resolver)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ethernet(name: &str, index: u32, address: &str) -> Interface {
|
||||
let mut interface = Interface::dummy();
|
||||
interface.name = name.into();
|
||||
interface.index = index;
|
||||
interface.if_type = netdev::prelude::InterfaceType::Ethernet;
|
||||
interface.ipv4 = vec![address.parse().unwrap()];
|
||||
interface.ipv6 = vec!["fe80::1/64".parse().unwrap()];
|
||||
interface
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_each_destination_without_requiring_a_single_uplink() {
|
||||
let ethernet = ethernet("en0", 7, "192.0.2.10/24");
|
||||
let mut wifi = ethernet.clone();
|
||||
wifi.name = "en1".into();
|
||||
wifi.index = 8;
|
||||
wifi.if_type = netdev::prelude::InterfaceType::Wireless80211;
|
||||
wifi.ipv4 = vec!["198.51.100.10/24".parse().unwrap()];
|
||||
let mut tunnel = Interface::dummy();
|
||||
tunnel.name = "utun0".into();
|
||||
tunnel.index = 9;
|
||||
tunnel.ipv4 = vec!["10.0.0.1/24".parse().unwrap()];
|
||||
let interfaces = [ethernet, wifi, tunnel];
|
||||
for (source, endpoint, expected) in [
|
||||
("192.0.2.10:0", "203.0.113.1:443", "en0"),
|
||||
("198.51.100.10:0", "198.51.100.53:53", "en1"),
|
||||
("[fe80::1%8]:0", "[fe80::53%8]:53", "en1"),
|
||||
] {
|
||||
assert_eq!(
|
||||
physical_interface_for_source(&interfaces, source.parse().unwrap(), endpoint.parse().unwrap())
|
||||
.unwrap()
|
||||
.name,
|
||||
expected
|
||||
);
|
||||
}
|
||||
// Virtual interfaces may coexist, but must never supply the selected source.
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"10.0.0.1:0".parse().unwrap(),
|
||||
"10.0.0.53:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
// Identical link-local addresses without scope are ambiguous.
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"[fe80::1]:0".parse().unwrap(),
|
||||
"[fe80::53]:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
physical_interface_for_source(
|
||||
&interfaces,
|
||||
"[fe80::1%7]:0".parse().unwrap(),
|
||||
"[fe80::53%8]:53".parse().unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ambiguous_or_unattributed_sources() {
|
||||
let interfaces = [ethernet("en0", 7, "192.0.2.10/24"), ethernet("en1", 8, "192.0.2.10/24")];
|
||||
for source in ["192.0.2.10:0", "192.0.2.11:0", "127.0.0.1:0", "0.0.0.0:0"] {
|
||||
assert!(
|
||||
physical_interface_for_source(&interfaces, source.parse().unwrap(), "192.0.2.53:53".parse().unwrap()).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_zones_support_native_names_and_numeric_indices() {
|
||||
let interfaces = [ethernet("en0", 7, "192.0.2.10/24")];
|
||||
let expected: SocketAddr = "[fe80::53%7]:53".parse().unwrap();
|
||||
assert_eq!(resolver_endpoint("fe80::53%en0", None, &interfaces).unwrap(), expected);
|
||||
assert_eq!(resolver_endpoint("fe80::53%7", None, &interfaces).unwrap(), expected);
|
||||
assert_eq!(
|
||||
resolver_endpoint("fe80::53", Some("en0"), &interfaces).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
resolver_endpoint("192.0.2.53", Some("en0"), &interfaces).unwrap(),
|
||||
"192.0.2.53:53".parse().unwrap()
|
||||
);
|
||||
for server in ["fe80::53", "fe80::53%missing", "fe80::53%8", "192.0.2.53%en0"] {
|
||||
assert!(
|
||||
resolver_endpoint(server, None, &interfaces).is_err(),
|
||||
"accepted {server}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_ipv6_gateway_is_a_literal_endpoint() {
|
||||
let origin = super::super::transport::gateway_origin("https://[2001:db8::1]:444").unwrap();
|
||||
assert_eq!(
|
||||
literal_gateway_address(&origin).unwrap(),
|
||||
Some("2001:db8::1".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_order_comments_and_case_do_not_change_network_identity() {
|
||||
assert_eq!(
|
||||
parse_resolv_conf("nameserver 192.0.2.53\nsearch CORP.EXAMPLE\n# comment").unwrap(),
|
||||
parse_resolv_conf("search corp.example\nnameserver 192.0.2.53 # DHCP\n").unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
parse_resolv_conf("nameserver 192.0.2.53").unwrap(),
|
||||
parse_resolv_conf("nameserver 192.0.2.54").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_identity_ignores_counters_and_address_enumeration_order() {
|
||||
let mut interface = Interface::dummy();
|
||||
interface.index = 7;
|
||||
interface.name = "bridge0".into();
|
||||
interface.ipv4 = vec!["192.0.2.10/24".parse().unwrap(), "192.0.2.11/24".parse().unwrap()];
|
||||
let original = InterfaceIdentity::from(&interface);
|
||||
interface.ipv4.reverse();
|
||||
interface.mtu = Some(1200);
|
||||
interface.default = !interface.default;
|
||||
assert_eq!(original, InterfaceIdentity::from(&interface));
|
||||
interface.index = 8;
|
||||
assert_ne!(original, InterfaceIdentity::from(&interface));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_binding() -> GatewayBinding {
|
||||
GatewayBinding::new(
|
||||
"192.0.2.10:443".parse().unwrap(),
|
||||
"192.0.2.5:0".parse().unwrap(),
|
||||
"fixture".into(),
|
||||
1,
|
||||
ClientAddresses {
|
||||
ipv4: Some("192.0.2.5".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
"0".repeat(64),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, ensure};
|
||||
use dns_lookup::{AddrFamily, AddrInfoHints, SockType, getaddrinfo};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::*;
|
||||
|
||||
const MAX_ADDRESSES: usize = 64;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn detect_in_helper(address: std::net::IpAddr, hostname: &str) -> anyhow::Result<bool> {
|
||||
super::detection::validate_target(address, hostname)?;
|
||||
Ok(dns_lookup::lookup_addr(&address).is_ok_and(|name| name.eq_ignore_ascii_case(hostname)))
|
||||
}
|
||||
|
||||
pub(super) async fn detect(
|
||||
address: std::net::IpAddr,
|
||||
hostname: &str,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<bool> {
|
||||
super::detection::validate_target(address, hostname)?;
|
||||
let args = vec![
|
||||
"detect-internal-host".into(),
|
||||
"--address".into(),
|
||||
address.to_string(),
|
||||
"--hostname".into(),
|
||||
hostname.into(),
|
||||
];
|
||||
let output = run_helper(common::binary_paths::gpclient(), args, cancellation.clone()).await?;
|
||||
serde_json::from_slice(&output).context("Invalid internal detection helper response")
|
||||
}
|
||||
|
||||
/// Entry point for gpclient's isolated native resolver helper. This blocking
|
||||
/// function must run in the child process, never a connection runtime thread.
|
||||
#[doc(hidden)]
|
||||
pub fn lookup_in_helper(host: &str, port: u16, disable_ipv6: bool) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
validate_host(host, port)?;
|
||||
let hints = AddrInfoHints {
|
||||
address: if disable_ipv6 { AddrFamily::Inet.into() } else { 0 },
|
||||
socktype: SockType::Stream.into(),
|
||||
..AddrInfoHints::default()
|
||||
};
|
||||
let service = port.to_string();
|
||||
let mut addresses = Vec::new();
|
||||
for result in getaddrinfo(Some(host), Some(&service), Some(hints)).map_err(io::Error::from)? {
|
||||
let address = result?.sockaddr;
|
||||
if !addresses.contains(&address) {
|
||||
ensure!(
|
||||
addresses.len() < MAX_ADDRESSES,
|
||||
"Native resolver returned too many gateway addresses"
|
||||
);
|
||||
addresses.push(address);
|
||||
}
|
||||
}
|
||||
validate_addresses(&addresses, port, disable_ipv6)?;
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve(
|
||||
host: &str,
|
||||
port: u16,
|
||||
disable_ipv6: bool,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
validate_host(host, port)?;
|
||||
let mut args = vec!["resolve-gateway".into(), host.into(), "--port".into(), port.to_string()];
|
||||
if disable_ipv6 {
|
||||
args.push("--disable-ipv6".into());
|
||||
}
|
||||
run_resolver(
|
||||
common::binary_paths::gpclient(),
|
||||
args,
|
||||
port,
|
||||
disable_ipv6,
|
||||
cancellation.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_resolver(
|
||||
executable: PathBuf,
|
||||
args: Vec<String>,
|
||||
port: u16,
|
||||
disable_ipv6: bool,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
let output = run_helper(executable, args, cancellation).await?;
|
||||
let addresses: Vec<SocketAddr> = serde_json::from_slice(&output).context("Invalid resolver helper response")?;
|
||||
validate_addresses(&addresses, port, disable_ipv6)?;
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
async fn run_helper(
|
||||
executable: PathBuf,
|
||||
args: Vec<String>,
|
||||
cancellation: CancellationToken,
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
// Await the owned worker even on cancellation. CollectorCommands kills and
|
||||
// waits for the helper process and any descendants before returning.
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let budget = CollectionBudget::new(INSPECTION_TIMEOUT);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Gateway resolution cancelled",
|
||||
));
|
||||
}
|
||||
budget.check()
|
||||
};
|
||||
let args = args.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let output = CollectorCommands::new(&check)
|
||||
.run_executable(&executable, &args)?
|
||||
.context("Native resolver helper is unavailable")?;
|
||||
check()?;
|
||||
ensure!(output.status.success(), "Native gateway resolution failed");
|
||||
Ok(output.stdout)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn validate_host(host: &str, port: u16) -> anyhow::Result<()> {
|
||||
ensure!(port != 0, "Gateway port is zero");
|
||||
ensure!(
|
||||
!host.is_empty() && host.len() <= 253 && !host.contains('\0') && !host.contains(['/', ':']),
|
||||
"Invalid gateway hostname"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_addresses(addresses: &[SocketAddr], port: u16, disable_ipv6: bool) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
!addresses.is_empty() && addresses.len() <= MAX_ADDRESSES,
|
||||
"Invalid gateway address count"
|
||||
);
|
||||
ensure!(
|
||||
addresses.iter().all(|address| {
|
||||
address.port() == port && !address.ip().is_unspecified() && (!disable_ipv6 || address.is_ipv4())
|
||||
}),
|
||||
"Invalid gateway address from resolver helper"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_helper_output_is_validated_before_admission() {
|
||||
let addresses = run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), "printf '[\"192.0.2.1:443\"]'".into()],
|
||||
443,
|
||||
true,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(addresses, vec!["192.0.2.1:443".parse::<SocketAddr>().unwrap()]);
|
||||
assert!(
|
||||
run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), "printf '[\"192.0.2.1:444\"]'".into()],
|
||||
443,
|
||||
true,
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_kills_and_joins_the_running_resolver_process() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
let path = file.path().to_owned();
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker = tokio::spawn(run_resolver(
|
||||
"/bin/sh".into(),
|
||||
vec![
|
||||
"-c".into(),
|
||||
"printf '%s' \"$$\" > \"$1\"; sleep 30 & wait".into(),
|
||||
"resolver-test".into(),
|
||||
path.to_string_lossy().into_owned(),
|
||||
],
|
||||
443,
|
||||
false,
|
||||
cancellation.clone(),
|
||||
));
|
||||
let pid = tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
if let Ok(pid) = std::fs::read_to_string(&path).unwrap().parse::<i32>() {
|
||||
break pid;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
cancellation.cancel();
|
||||
let error = tokio::time::timeout(Duration::from_secs(1), worker)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
assert_eq!(
|
||||
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
|
||||
Err(nix::errno::Errno::ESRCH)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_lookup_preserves_port_and_ipv4_policy() {
|
||||
let addresses = lookup_in_helper("localhost", 444, true).unwrap();
|
||||
assert!(
|
||||
addresses
|
||||
.iter()
|
||||
.all(|address| address.is_ipv4() && address.ip().is_loopback() && address.port() == 444)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_response_validation_retains_ipv6_scope_and_rejects_wrong_port() {
|
||||
let addresses = vec!["[fe80::1%7]:443".parse().unwrap(), "192.0.2.1:443".parse().unwrap()];
|
||||
validate_addresses(&addresses, 443, false).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Vec<SocketAddr>>(&serde_json::to_string(&addresses).unwrap()).unwrap(),
|
||||
addresses
|
||||
);
|
||||
assert!(validate_addresses(&addresses, 444, false).is_err());
|
||||
assert!(validate_addresses(&addresses, 443, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_helper_requests_before_lookup() {
|
||||
assert!(lookup_in_helper("gateway.example/path", 443, false).is_err());
|
||||
assert!(lookup_in_helper("gateway.example", 0, false).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::{gateway::Gateway, process::collection::CollectionControl};
|
||||
|
||||
use super::{
|
||||
GatewaySession, GatewaySessionSummary, GatewaySessions, InternalSessionPolicy, MaintenanceState, SessionEndReason,
|
||||
SessionMode, transport::GatewayRequestError,
|
||||
};
|
||||
|
||||
const COLLECTION_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// This request is deliberately independent of OpenConnect's callback/FFI types.
|
||||
#[derive(Clone)]
|
||||
pub struct SessionHipRequest {
|
||||
pub gateway: Gateway,
|
||||
pub cookie: String,
|
||||
pub client_ip: Option<String>,
|
||||
pub client_ipv6: Option<String>,
|
||||
pub md5: String,
|
||||
pub collect_posture: bool,
|
||||
}
|
||||
|
||||
impl Drop for SessionHipRequest {
|
||||
fn drop(&mut self) {
|
||||
self.cookie.zeroize();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SessionCollectionControl {
|
||||
cancellation: CancellationToken,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl CollectionControl for SessionCollectionControl {
|
||||
fn check(&self) -> io::Result<()> {
|
||||
if self.cancellation.is_cancelled() {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "HIP collection cancelled"))
|
||||
} else if Instant::now() >= self.deadline {
|
||||
Err(io::Error::new(io::ErrorKind::TimedOut, "HIP collection timed out"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type SessionReportProducer =
|
||||
dyn Fn(&SessionHipRequest, &SessionCollectionControl) -> io::Result<String> + Send + Sync;
|
||||
pub type SessionReportObserver = dyn Fn(&SessionHipRequest, &str) + Send + Sync;
|
||||
pub type SessionStatusObserver = dyn Fn(GatewaySessionSummary) + Send + Sync;
|
||||
pub type SessionNetworkValidator =
|
||||
dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SessionCallbacks {
|
||||
pub produce_report: Arc<SessionReportProducer>,
|
||||
pub report_submitted: Arc<SessionReportObserver>,
|
||||
pub status_changed: Arc<SessionStatusObserver>,
|
||||
pub validate_network: Arc<SessionNetworkValidator>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionExit {
|
||||
Disconnected,
|
||||
Failed(SessionEndReason),
|
||||
}
|
||||
|
||||
/// Owns maintenance workers until they have stopped. The session owner retains
|
||||
/// its ledger and logs out after joining every worker. Interactive authentication
|
||||
/// also belongs to that owner. Cancel and await this future, never abort/drop it:
|
||||
/// blocking collectors must finish before cleanup releases their resources.
|
||||
pub async fn maintain_non_tunnel_sessions(
|
||||
sessions: &mut GatewaySessions,
|
||||
policy: InternalSessionPolicy,
|
||||
mut callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
network_change: impl Future<Output = SessionEndReason>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
anyhow::ensure!(!sessions.is_empty(), "Non-tunnel session set is empty");
|
||||
anyhow::ensure!(
|
||||
sessions
|
||||
.members()
|
||||
.iter()
|
||||
.all(|session| session.transport.authentication().mode() == SessionMode::NonTunnel),
|
||||
"Tunnel member supplied to non-tunnel runtime"
|
||||
);
|
||||
let workers_cancel = cancellation.child_token();
|
||||
let observer = callbacks.status_changed.clone();
|
||||
let status_gate = Arc::new(Mutex::new(()));
|
||||
let gate = status_gate.clone();
|
||||
let cancelled = workers_cancel.clone();
|
||||
let worker_observer = observer.clone();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
let _guard = gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if !cancelled.is_cancelled() {
|
||||
worker_observer(summary);
|
||||
}
|
||||
});
|
||||
let mut workers = JoinSet::new();
|
||||
for session in sessions.members() {
|
||||
let session = session.clone();
|
||||
let callbacks = callbacks.clone();
|
||||
let cancellation = workers_cancel.clone();
|
||||
workers.spawn(async move {
|
||||
let server = session.gateway.server().to_owned();
|
||||
(server, maintain_member(session, policy, callbacks, cancellation).await)
|
||||
});
|
||||
}
|
||||
tokio::pin!(network_change);
|
||||
let mut worker_failure = None;
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => break SessionExit::Disconnected,
|
||||
reason = &mut network_change => break SessionExit::Failed(reason),
|
||||
result = workers.join_next() => match result {
|
||||
Some(Ok((_, MemberExit::Terminal(reason)))) => break SessionExit::Failed(reason),
|
||||
Some(Ok((server, MemberExit::Rejected))) => {
|
||||
sessions.logout_gateway(&server).await;
|
||||
if workers.is_empty() { break SessionExit::Failed(SessionEndReason::AllMembersFailed); }
|
||||
},
|
||||
Some(Ok((_, MemberExit::Cancelled))) => {},
|
||||
Some(Err(error)) => { worker_failure = Some(error); break SessionExit::Disconnected; },
|
||||
None => break SessionExit::Failed(SessionEndReason::AllMembersFailed),
|
||||
},
|
||||
}
|
||||
};
|
||||
workers_cancel.cancel();
|
||||
if matches!(outcome, SessionExit::Failed(_)) || worker_failure.is_some() {
|
||||
// Invalidate advertised health before waiting for collectors or remote
|
||||
// cleanup. Cancellation prevents workers from publishing Healthy afterwards.
|
||||
let _guard = status_gate.lock().unwrap_or_else(|error| error.into_inner());
|
||||
for session in sessions.members() {
|
||||
observer(GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: SessionMode::NonTunnel,
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
maintenance: MaintenanceState::Rejected,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Do not abort workers: a blocking collector must observe cancellation and be
|
||||
// joined before approval/identity resources can be released by the caller.
|
||||
while let Some(result) = workers.join_next().await {
|
||||
if let Err(error) = result {
|
||||
worker_failure.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
if let Some(error) = worker_failure {
|
||||
return Err(error.into());
|
||||
}
|
||||
// Deliberate disconnect wins even when it arrives during coordinated cleanup.
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
Ok(outcome)
|
||||
}
|
||||
}
|
||||
|
||||
async fn maintain_member(
|
||||
session: Arc<GatewaySession>,
|
||||
policy: InternalSessionPolicy,
|
||||
callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
) -> MemberExit {
|
||||
let request = SessionHipRequest {
|
||||
gateway: session.gateway.clone(),
|
||||
cookie: session.transport.authentication().cookie().into(),
|
||||
client_ip: session.addresses.ipv4.map(|ip| ip.to_string()),
|
||||
client_ipv6: session.addresses.ipv6.map(|ip| ip.to_string()),
|
||||
md5: session.transport.hip_token(),
|
||||
collect_posture: policy.collect_hip_data(),
|
||||
};
|
||||
let status = |maintenance| {
|
||||
if !cancellation.is_cancelled() {
|
||||
(callbacks.status_changed)(GatewaySessionSummary {
|
||||
gateway: session.gateway.clone(),
|
||||
mode: SessionMode::NonTunnel,
|
||||
client_ip: request.client_ip.clone(),
|
||||
client_ipv6: request.client_ipv6.clone(),
|
||||
maintenance,
|
||||
});
|
||||
}
|
||||
};
|
||||
status(MaintenanceState::Authenticated);
|
||||
loop {
|
||||
if (callbacks.validate_network)(cancellation.clone()).await.is_err() {
|
||||
return MemberExit::Terminal(SessionEndReason::NetworkChanged);
|
||||
}
|
||||
let sent_at = tokio::time::Instant::now();
|
||||
let check = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return MemberExit::Cancelled,
|
||||
result = session.transport.check_hip(session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result,
|
||||
};
|
||||
let (result, delay) = match check {
|
||||
Ok(check) => {
|
||||
let result = if check.report_needed {
|
||||
collect_and_submit(&session, &request, &callbacks, &cancellation).await
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
(result, check.delay)
|
||||
}
|
||||
Err(error) => (Err(MemberError::Gateway(error)), Duration::ZERO),
|
||||
};
|
||||
let next_check = match result {
|
||||
Ok(()) => {
|
||||
if cancellation.is_cancelled() {
|
||||
return MemberExit::Cancelled;
|
||||
}
|
||||
status(MaintenanceState::Healthy);
|
||||
let Some(next_check) = sent_at
|
||||
.checked_add(policy.hip_interval())
|
||||
.and_then(|time| time.checked_add(delay))
|
||||
else {
|
||||
status(MaintenanceState::Rejected);
|
||||
return MemberExit::Rejected;
|
||||
};
|
||||
next_check
|
||||
}
|
||||
Err(MemberError::Gateway(GatewayRequestError::InvalidCookie)) => {
|
||||
status(MaintenanceState::Rejected);
|
||||
return MemberExit::Terminal(SessionEndReason::InvalidCookie);
|
||||
}
|
||||
Err(MemberError::Network) => return MemberExit::Terminal(SessionEndReason::NetworkChanged),
|
||||
Err(MemberError::Authorization) => return MemberExit::Terminal(SessionEndReason::AuthorizationRevoked),
|
||||
Err(error) => {
|
||||
if cancellation.is_cancelled() {
|
||||
return MemberExit::Cancelled;
|
||||
}
|
||||
status(MaintenanceState::Rejected);
|
||||
log::warn!("Gateway maintenance failed: {error}");
|
||||
return MemberExit::Rejected;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return MemberExit::Cancelled,
|
||||
_ = tokio::time::sleep_until(next_check) => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum MemberExit {
|
||||
Cancelled,
|
||||
Rejected,
|
||||
Terminal(SessionEndReason),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum MemberError {
|
||||
#[error("{0}")]
|
||||
Gateway(#[from] GatewayRequestError),
|
||||
// Collector/script errors can contain user-provided text. Do not log payloads.
|
||||
#[error("HIP report collection failed")]
|
||||
Collection,
|
||||
#[error("Physical network validation failed")]
|
||||
Network,
|
||||
#[error("HIP report authorization was revoked")]
|
||||
Authorization,
|
||||
}
|
||||
|
||||
async fn collect_and_submit(
|
||||
session: &GatewaySession,
|
||||
request: &SessionHipRequest,
|
||||
callbacks: &SessionCallbacks,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<(), MemberError> {
|
||||
let producer = callbacks.produce_report.clone();
|
||||
let input = request.clone();
|
||||
let control = SessionCollectionControl {
|
||||
cancellation: cancellation.clone(),
|
||||
deadline: Instant::now() + COLLECTION_TIMEOUT,
|
||||
};
|
||||
let report = tokio::task::spawn_blocking(move || {
|
||||
control.check()?;
|
||||
let report = Zeroizing::new(producer(&input, &control)?);
|
||||
control.check()?;
|
||||
Ok::<_, io::Error>(report)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| MemberError::Collection)?
|
||||
.map_err(|error| {
|
||||
if error.kind() == io::ErrorKind::PermissionDenied {
|
||||
MemberError::Authorization
|
||||
} else {
|
||||
MemberError::Collection
|
||||
}
|
||||
})?;
|
||||
(callbacks.validate_network)(cancellation.clone())
|
||||
.await
|
||||
.map_err(|_| MemberError::Network)?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Err(MemberError::Collection),
|
||||
result = session.transport.submit_hip(&report, session.addresses.ipv4.map(Into::into), session.addresses.ipv6.map(Into::into)) => result?,
|
||||
}
|
||||
if !cancellation.is_cancelled() {
|
||||
(callbacks.report_submitted)(request, &report);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,415 @@
|
||||
use std::{
|
||||
future::pending,
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::*;
|
||||
use crate::session::transport::GatewayTransport;
|
||||
use crate::session::{
|
||||
ClientAddresses, GatewaySessions,
|
||||
transport::tests::{gateway, response},
|
||||
};
|
||||
|
||||
async fn run_owned_sessions(
|
||||
members: Vec<GatewaySession>,
|
||||
policy: InternalSessionPolicy,
|
||||
callbacks: SessionCallbacks,
|
||||
cancellation: CancellationToken,
|
||||
network_change: impl Future<Output = SessionEndReason>,
|
||||
) -> anyhow::Result<SessionExit> {
|
||||
let mut sessions = GatewaySessions::new(members);
|
||||
let result =
|
||||
maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation.clone(), network_change).await;
|
||||
sessions.logout().await;
|
||||
if cancellation.is_cancelled() {
|
||||
Ok(SessionExit::Disconnected)
|
||||
} else {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn member(name: &str, transport: GatewayTransport) -> GatewaySession {
|
||||
GatewaySession {
|
||||
gateway: Gateway::new(name.into(), format!("{name}.example")),
|
||||
transport,
|
||||
addresses: ClientAddresses {
|
||||
ipv4: Some("192.0.2.7".parse().unwrap()),
|
||||
ipv6: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn callbacks() -> SessionCallbacks {
|
||||
SessionCallbacks {
|
||||
produce_report: Arc::new(|_, _| Ok("<hip-report/>".into())),
|
||||
report_submitted: Arc::new(|_, _| {}),
|
||||
status_changed: Arc::new(|_| {}),
|
||||
validate_network: Arc::new(|_| Box::pin(async { Ok(()) })),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn network_uncertainty_prevents_hip_and_healthy_status() {
|
||||
let (transport, server) = gateway(vec![response("<response status='success'/>")]).await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.validate_network = Arc::new(|_| Box::pin(async { anyhow::bail!("Network changed") }));
|
||||
callbacks.status_changed = Arc::new(|summary| assert_ne!(summary.maintenance, MaintenanceState::Healthy));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
|
||||
assert_eq!(server.await.unwrap()[0].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoked_report_authorization_terminates_the_attempt() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.produce_report = Arc::new(|_, _| Err(io::ErrorKind::PermissionDenied.into()));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AuthorizationRevoked));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_cookie_terminates_only_after_logout() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks(),
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(requests[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejection_preserves_healthy_members_and_cleanup_owns_all_members() {
|
||||
let (rejected, rejected_server) = gateway(vec![
|
||||
response("<response status='error'><error>Denied</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let (healthy, healthy_server) = gateway(vec![
|
||||
response("<response><hip-report-needed>no</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let ready = Arc::new(Notify::new());
|
||||
let states = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut callbacks = callbacks();
|
||||
let states_copy = states.clone();
|
||||
let ready_copy = ready.clone();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
if summary.maintenance != MaintenanceState::Authenticated {
|
||||
let mut states = states_copy.lock().unwrap();
|
||||
states.push((summary.gateway.name().to_owned(), summary.maintenance));
|
||||
if states.len() == 2 {
|
||||
ready_copy.notify_one();
|
||||
}
|
||||
}
|
||||
});
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("rejected", rejected), member("healthy", healthy)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
async {
|
||||
ready.notified().await;
|
||||
SessionEndReason::NetworkChanged
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::NetworkChanged));
|
||||
let states = states.lock().unwrap();
|
||||
assert!(states.contains(&("rejected".into(), MaintenanceState::Rejected)));
|
||||
assert!(states.contains(&("healthy".into(), MaintenanceState::Healthy)));
|
||||
assert_eq!(rejected_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observes_reports_only_after_successful_submission() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let submitted = Arc::new(AtomicUsize::new(0));
|
||||
let observed = submitted.clone();
|
||||
let stop = cancellation.clone();
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.report_submitted = Arc::new(move |request, report| {
|
||||
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.7"));
|
||||
assert_eq!(report, "<hip-report/>");
|
||||
observed.fetch_add(1, Ordering::SeqCst);
|
||||
stop.cancel();
|
||||
});
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Disconnected);
|
||||
assert_eq!(submitted.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(server.await.unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_collection_is_joined_before_runtime_returns() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let entered = Arc::new(Notify::new());
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let mut callbacks = callbacks();
|
||||
let entered_copy = entered.clone();
|
||||
let stopped_copy = stopped.clone();
|
||||
callbacks.produce_report = Arc::new(move |_, control| {
|
||||
entered_copy.notify_one();
|
||||
loop {
|
||||
if let Err(error) = control.check() {
|
||||
stopped_copy.store(true, Ordering::SeqCst);
|
||||
return Err(error);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
});
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Cancelled report must not be observed"));
|
||||
let stop = cancellation.clone();
|
||||
let exit = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
async {
|
||||
entered.notified().await;
|
||||
stop.cancel();
|
||||
pending().await
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Disconnected);
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_rejected_members_are_logged_out_before_terminal_failure() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Denied</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.produce_report = Arc::new(|_, _| panic!("Rejected member cannot collect a report"));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("rejected", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
|
||||
assert_eq!(server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_member_cookie_cancels_and_joins_another_members_collector() {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let release = Arc::new(Notify::new());
|
||||
let collecting = Arc::new(Notify::new());
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let (expired, expired_server) = crate::session::transport::tests::gateway_with_first_response_gate(
|
||||
vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
response("<response status='success'/>"),
|
||||
],
|
||||
arrived.clone(),
|
||||
release.clone(),
|
||||
)
|
||||
.await;
|
||||
let (healthy, healthy_server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
let collecting_copy = collecting.clone();
|
||||
let stopped_copy = stopped.clone();
|
||||
callbacks.produce_report = Arc::new(move |request, control| {
|
||||
assert_eq!(request.gateway.name(), "collecting");
|
||||
collecting_copy.notify_one();
|
||||
loop {
|
||||
if let Err(error) = control.check() {
|
||||
stopped_copy.store(true, Ordering::SeqCst);
|
||||
return Err(error);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
});
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Interrupted collection must not submit"));
|
||||
let exit = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
run_owned_sessions(
|
||||
vec![member("expired", expired), member("collecting", healthy)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
async {
|
||||
arrived.notified().await;
|
||||
collecting.notified().await;
|
||||
release.notify_one();
|
||||
pending().await
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::InvalidCookie));
|
||||
assert!(stopped.load(Ordering::SeqCst));
|
||||
assert_eq!(expired_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
assert_eq!(healthy_server.await.unwrap()[1].0, "/ssl-vpn/logout.esp");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_submission_is_terminal_without_retry_or_observation() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed></response>"),
|
||||
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.report_submitted = Arc::new(|_, _| panic!("Failed report must not be retained"));
|
||||
let exit = run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::default(),
|
||||
callbacks,
|
||||
CancellationToken::new(),
|
||||
pending(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(exit, SessionExit::Failed(SessionEndReason::AllMembersFailed));
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(
|
||||
requests.iter().map(|request| request.0.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"/ssl-vpn/hipreportcheck.esp",
|
||||
"/ssl-vpn/hipreport.esp",
|
||||
"/ssl-vpn/logout.esp"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn schedules_from_send_time_plus_interval_and_server_delay() {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let release = Arc::new(Notify::new());
|
||||
let (transport, server) = crate::session::transport::tests::gateway_with_first_response_gate(
|
||||
vec![
|
||||
response("<response><hip-report-needed>no</hip-report-needed><delay>7</delay></response>"),
|
||||
response("<response><hip-report-needed>no</hip-report-needed></response>"),
|
||||
response("<response status='success'/>"),
|
||||
],
|
||||
arrived.clone(),
|
||||
release.clone(),
|
||||
)
|
||||
.await;
|
||||
let cancellation = CancellationToken::new();
|
||||
let stop = cancellation.clone();
|
||||
let (sent, mut received) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut callbacks = callbacks();
|
||||
callbacks.status_changed = Arc::new(move |summary| {
|
||||
if summary.maintenance == MaintenanceState::Healthy {
|
||||
sent.send(tokio::time::Instant::now()).unwrap();
|
||||
}
|
||||
});
|
||||
let runtime = tokio::spawn(run_owned_sessions(
|
||||
vec![member("internal", transport)],
|
||||
InternalSessionPolicy::new(10, false).unwrap(),
|
||||
callbacks,
|
||||
cancellation,
|
||||
pending(),
|
||||
));
|
||||
arrived.notified().await;
|
||||
// Simulate three seconds spent waiting for the first response. The interval
|
||||
// must be anchored before that latency, rather than after completion.
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(3)).await;
|
||||
tokio::time::resume();
|
||||
release.notify_one();
|
||||
let first = received.recv().await.unwrap();
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(13)).await;
|
||||
tokio::time::resume();
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(received.try_recv().is_err(), "Server delay must extend the interval");
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::time::resume();
|
||||
let second = tokio::time::timeout(Duration::from_millis(500), received.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let elapsed = second.duration_since(first);
|
||||
assert!(
|
||||
elapsed >= Duration::from_millis(13_900) && elapsed < Duration::from_millis(14_500),
|
||||
"Unexpected anchored interval: {elapsed:?}"
|
||||
);
|
||||
stop.cancel();
|
||||
assert_eq!(runtime.await.unwrap().unwrap(), SessionExit::Disconnected);
|
||||
assert_eq!(server.await.unwrap().len(), 3);
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
use std::{net::IpAddr, time::Duration};
|
||||
|
||||
use reqwest::{Client, StatusCode, Url, redirect::Policy};
|
||||
use xmltree::Element;
|
||||
|
||||
use crate::{gp_params::GpParams, os_profile::OsProfile, utils::xml::ElementExt};
|
||||
|
||||
use super::{GatewayAuthentication, network::GatewayBinding};
|
||||
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub(crate) const MAX_GATEWAY_RESPONSE_BYTES: usize = 1024 * 1024;
|
||||
pub const MAX_HIP_REPORT_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GatewayRequestError {
|
||||
#[error("Gateway authentication cookie expired")]
|
||||
InvalidCookie,
|
||||
#[error("Gateway request failed: {0}")]
|
||||
Transport(#[from] reqwest::Error),
|
||||
#[error("Gateway returned HTTP {0}")]
|
||||
Http(StatusCode),
|
||||
#[error("Gateway rejected the request")]
|
||||
Rejected,
|
||||
#[error("Gateway returned a malformed response")]
|
||||
MalformedResponse,
|
||||
#[error("Gateway response exceeds its size limit")]
|
||||
ResponseTooLarge,
|
||||
#[error("HIP report is empty, contains NUL, or exceeds its size limit")]
|
||||
InvalidReport,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct HipCheck {
|
||||
pub report_needed: bool,
|
||||
pub delay: Duration,
|
||||
}
|
||||
|
||||
/// Authenticated HTTP requests retain the login identity. Non-tunnel maintenance
|
||||
/// uses a validated physical binding; pre-tunnel cleanup uses ordinary HTTP.
|
||||
pub struct GatewayTransport {
|
||||
client: Client,
|
||||
origin: Url,
|
||||
authentication: GatewayAuthentication,
|
||||
profile: OsProfile,
|
||||
}
|
||||
|
||||
impl GatewayTransport {
|
||||
pub fn new(
|
||||
server: &str,
|
||||
authentication: GatewayAuthentication,
|
||||
params: &GpParams,
|
||||
binding: Option<&GatewayBinding>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let origin = Url::parse(&crate::utils::normalize_server(server)?)?;
|
||||
let client = match binding {
|
||||
Some(binding) => bound_client(server, params, binding)?,
|
||||
None => Client::try_from(params)?,
|
||||
};
|
||||
Ok(Self {
|
||||
client,
|
||||
origin,
|
||||
authentication,
|
||||
profile: params.os_profile().clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The login client already validated and built this transport before issuing
|
||||
/// authentication. Registering its cleanup context cannot fail afterwards.
|
||||
pub(crate) fn from_authenticated_login(
|
||||
client: Client,
|
||||
origin: Url,
|
||||
authentication: GatewayAuthentication,
|
||||
profile: OsProfile,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
origin,
|
||||
authentication,
|
||||
profile,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn authentication(&self) -> &GatewayAuthentication {
|
||||
&self.authentication
|
||||
}
|
||||
|
||||
pub fn hip_token(&self) -> String {
|
||||
hip_token(self.authentication.cookie())
|
||||
}
|
||||
|
||||
pub async fn check_hip(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Result<HipCheck, GatewayRequestError> {
|
||||
let mut form = self.hip_form(ipv4, ipv6);
|
||||
form.push(("md5".into(), self.hip_token()));
|
||||
parse_hip_check(&self.post("hipreportcheck.esp", &form).await?)
|
||||
}
|
||||
|
||||
pub async fn submit_hip(
|
||||
&self,
|
||||
report: &str,
|
||||
ipv4: Option<IpAddr>,
|
||||
ipv6: Option<IpAddr>,
|
||||
) -> Result<(), GatewayRequestError> {
|
||||
if report.is_empty() || report.len() > MAX_HIP_REPORT_BYTES || report.contains('\0') {
|
||||
return Err(GatewayRequestError::InvalidReport);
|
||||
}
|
||||
let mut form = self.hip_form(ipv4, ipv6);
|
||||
form.push(("report".into(), report.into()));
|
||||
self.post("hipreport.esp", &form).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn logout(&self) -> Result<(), GatewayRequestError> {
|
||||
logout_cookie(&self.client, &self.origin, self.authentication.cookie(), &self.profile).await
|
||||
}
|
||||
|
||||
fn cookie_form(&self) -> Vec<(String, String)> {
|
||||
url::form_urlencoded::parse(self.authentication.cookie().as_bytes())
|
||||
.into_owned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hip_form(&self, ipv4: Option<IpAddr>, ipv6: Option<IpAddr>) -> Vec<(String, String)> {
|
||||
let mut form = self.cookie_form();
|
||||
set_form(&mut form, "client-role", "global-protect-full");
|
||||
set_form(&mut form, "computer", self.profile.computer());
|
||||
set_form(&mut form, "host-id", self.profile.host_id());
|
||||
set_form(&mut form, "serialno", self.profile.serialno());
|
||||
if let Some(ip) = ipv4 {
|
||||
set_form(&mut form, "client-ip", &ip.to_string());
|
||||
}
|
||||
if let Some(ip) = ipv6 {
|
||||
set_form(&mut form, "client-ipv6", &ip.to_string());
|
||||
}
|
||||
form
|
||||
}
|
||||
|
||||
async fn post(&self, endpoint: &str, form: &[(String, String)]) -> Result<Element, GatewayRequestError> {
|
||||
post(&self.client, &self.origin, endpoint, form).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleanup uses trustworthy issued cookie fields even when execution mode is
|
||||
/// invalid. It never creates a runnable authentication with a fabricated mode.
|
||||
pub(crate) async fn logout_cookie(
|
||||
client: &Client,
|
||||
origin: &Url,
|
||||
cookie: &str,
|
||||
profile: &OsProfile,
|
||||
) -> Result<(), GatewayRequestError> {
|
||||
let mut form = url::form_urlencoded::parse(cookie.as_bytes()).into_owned().collect();
|
||||
set_form(&mut form, "computer", profile.computer());
|
||||
set_form(&mut form, "clientos", profile.client_os().as_str());
|
||||
set_form(&mut form, "os-version", profile.os_version());
|
||||
post(client, origin, "logout.esp", &form).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn post(
|
||||
client: &Client,
|
||||
origin: &Url,
|
||||
endpoint: &str,
|
||||
form: &[(String, String)],
|
||||
) -> Result<Element, GatewayRequestError> {
|
||||
let mut url = origin.clone();
|
||||
url.set_path(&format!("/ssl-vpn/{endpoint}"));
|
||||
let response = client.post(url).form(form).send().await?;
|
||||
let status = response.status();
|
||||
let invalid_cookie = status.as_u16() == 512
|
||||
|| response
|
||||
.headers()
|
||||
.get("x-private-pan-globalprotect")
|
||||
.is_some_and(|value| value == "Invalid authentication cookie");
|
||||
if invalid_cookie {
|
||||
return Err(GatewayRequestError::InvalidCookie);
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(GatewayRequestError::Http(status));
|
||||
}
|
||||
let body = crate::utils::request::read_bounded_response(response, MAX_GATEWAY_RESPONSE_BYTES)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
|
||||
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
|
||||
})?;
|
||||
parse_response(&body)
|
||||
}
|
||||
|
||||
pub(crate) fn bound_client(server: &str, params: &GpParams, binding: &GatewayBinding) -> anyhow::Result<Client> {
|
||||
binding.validate_server(server)?;
|
||||
let origin = gateway_origin(server)?;
|
||||
let host = origin
|
||||
.host_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Gateway host is missing"))?;
|
||||
let builder = params
|
||||
.client_builder()?
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.local_address(binding.source().ip())
|
||||
.resolve(host, binding.endpoint())
|
||||
.timeout(REQUEST_TIMEOUT);
|
||||
let builder = bind_interface(builder, binding)?;
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
Ok(builder.interface(binding.interface()))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
|
||||
if let std::net::SocketAddr::V6(source) = binding.source() {
|
||||
anyhow::ensure!(
|
||||
source.scope_id() == 0,
|
||||
"Scoped IPv6 source requires a native socket connector"
|
||||
);
|
||||
}
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_origin(server: &str) -> anyhow::Result<Url> {
|
||||
let server = if server.starts_with("https://") {
|
||||
server.to_owned()
|
||||
} else {
|
||||
format!("https://{server}")
|
||||
};
|
||||
let origin = Url::parse(&server)?;
|
||||
anyhow::ensure!(
|
||||
origin.scheme() == "https"
|
||||
&& origin.username().is_empty()
|
||||
&& origin.password().is_none()
|
||||
&& origin.path() == "/"
|
||||
&& origin.query().is_none()
|
||||
&& origin.fragment().is_none(),
|
||||
"Gateway endpoint must be an HTTPS origin"
|
||||
);
|
||||
Ok(origin)
|
||||
}
|
||||
|
||||
fn set_form(form: &mut Vec<(String, String)>, key: &str, value: &str) {
|
||||
form.retain(|(name, _)| name != key);
|
||||
form.push((key.into(), value.into()));
|
||||
}
|
||||
|
||||
/// Match gpst.c::build_csd_token without decoding or reordering cookie fields.
|
||||
pub fn hip_token(cookie: &str) -> String {
|
||||
let stable = cookie
|
||||
.split('&')
|
||||
.filter(|field| {
|
||||
let key = field.split('=').next().unwrap_or_default();
|
||||
!matches!(key, "authcookie" | "preferred-ip" | "preferred-ipv6")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{:x}", md5::compute(stable.as_bytes()))
|
||||
}
|
||||
|
||||
fn parse_response(body: &[u8]) -> Result<Element, GatewayRequestError> {
|
||||
let text = std::str::from_utf8(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
|
||||
let lower = text.to_ascii_lowercase();
|
||||
if lower.contains("<!doctype") || lower.contains("<!entity") {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
if let Some(error) = javascript_error(text) {
|
||||
return Err(error);
|
||||
}
|
||||
let root = Element::parse(body).map_err(|_| GatewayRequestError::MalformedResponse)?;
|
||||
if root.name == "html" {
|
||||
return Err(
|
||||
root
|
||||
.descendant_text("body")
|
||||
.as_deref()
|
||||
.and_then(javascript_error)
|
||||
.unwrap_or(GatewayRequestError::MalformedResponse),
|
||||
);
|
||||
}
|
||||
if root.name == "prelogin-response" && root.child_text("status").as_deref() == Some("Error") {
|
||||
return Err(message_error(root.child_text("msg").as_deref()));
|
||||
}
|
||||
if root.name != "response" {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
match root.attr("status") {
|
||||
Some("error") => Err(message_error(root.child_text("error").as_deref())),
|
||||
None | Some("success") => Ok(root),
|
||||
_ => Err(GatewayRequestError::Rejected),
|
||||
}
|
||||
}
|
||||
|
||||
fn message_error(message: Option<&str>) -> GatewayRequestError {
|
||||
if message == Some("Invalid authentication cookie") {
|
||||
GatewayRequestError::InvalidCookie
|
||||
} else {
|
||||
GatewayRequestError::Rejected
|
||||
}
|
||||
}
|
||||
|
||||
fn javascript_error(text: &str) -> Option<GatewayRequestError> {
|
||||
static ERROR: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
|
||||
let regex = ERROR.get_or_init(|| {
|
||||
regex::Regex::new(r#"(?s)^\s*var\s+respStatus\s*=\s*"Error"\s*;\s*var\s+respMsg\s*=\s*("(?:\\.|[^"\\])*")"#)
|
||||
.expect("valid GlobalProtect error pattern")
|
||||
});
|
||||
let captures = regex.captures(text)?;
|
||||
match serde_json::from_str::<String>(&captures[1]) {
|
||||
Ok(message) => Some(message_error(Some(&message))),
|
||||
Err(_) => Some(GatewayRequestError::MalformedResponse),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
|
||||
let report_needed = match root.child_text("hip-report-needed").as_deref() {
|
||||
Some("yes") => true,
|
||||
Some("no") => false,
|
||||
_ => return Err(GatewayRequestError::MalformedResponse),
|
||||
};
|
||||
let delay = match root.child_text("delay") {
|
||||
Some(value) => value
|
||||
.parse::<u32>()
|
||||
.map_err(|_| GatewayRequestError::MalformedResponse)?,
|
||||
None => 0,
|
||||
};
|
||||
// Limit this client's supported response delay to one hour. The official
|
||||
// registry scheduling cap is not evidence of a wire-protocol maximum.
|
||||
if delay > 3600 {
|
||||
return Err(GatewayRequestError::MalformedResponse);
|
||||
}
|
||||
Ok(HipCheck {
|
||||
report_needed,
|
||||
delay: Duration::from_secs(u64::from(delay)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,246 @@
|
||||
use super::*;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpListener,
|
||||
task::JoinHandle,
|
||||
};
|
||||
|
||||
pub(crate) async fn gateway(responses: Vec<String>) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
gateway_fixture(responses, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn login_gateway(responses: Vec<String>) -> (Client, Url, JoinHandle<Vec<(String, String)>>) {
|
||||
let (transport, server) = gateway(responses).await;
|
||||
(transport.client, transport.origin, server)
|
||||
}
|
||||
|
||||
pub(crate) async fn gateway_with_first_response_gate(
|
||||
responses: Vec<String>,
|
||||
arrived: std::sync::Arc<tokio::sync::Notify>,
|
||||
release: std::sync::Arc<tokio::sync::Notify>,
|
||||
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
gateway_fixture(responses, Some((arrived, release))).await
|
||||
}
|
||||
|
||||
async fn gateway_fixture(
|
||||
responses: Vec<String>,
|
||||
gate: Option<(std::sync::Arc<tokio::sync::Notify>, std::sync::Arc<tokio::sync::Notify>)>,
|
||||
) -> (GatewayTransport, JoinHandle<Vec<(String, String)>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut requests = Vec::new();
|
||||
for (index, response) in responses.into_iter().enumerate() {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
let (headers_end, length) = loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
if let Some(position) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
|
||||
let headers = std::str::from_utf8(&bytes[..position]).unwrap();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
key
|
||||
.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
break (position + 4, length);
|
||||
}
|
||||
};
|
||||
while bytes.len() < headers_end + length {
|
||||
let mut chunk = [0; 1024];
|
||||
let count = stream.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(count, 0);
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
let path = std::str::from_utf8(&bytes[..headers_end])
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = String::from_utf8(bytes[headers_end..headers_end + length].to_vec()).unwrap();
|
||||
requests.push((path, body));
|
||||
if index == 0
|
||||
&& let Some((arrived, release)) = &gate
|
||||
{
|
||||
arrived.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
stream.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
requests
|
||||
});
|
||||
let transport = GatewayTransport {
|
||||
client: Client::builder()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.build()
|
||||
.unwrap(),
|
||||
origin,
|
||||
authentication: GatewayAuthentication::new(
|
||||
"authcookie=test-cookie&portal=portal&user=alice&domain=example&computer=test".into(),
|
||||
"non-tunnel".into(),
|
||||
)
|
||||
.unwrap(),
|
||||
profile: OsProfile::builder(crate::os_profile::ClientOs::Linux)
|
||||
.computer_name_override("test")
|
||||
.build(),
|
||||
};
|
||||
(transport, server)
|
||||
}
|
||||
|
||||
pub(crate) fn response(body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_matches_c_protocol_golden_fixture() {
|
||||
for volatile in [
|
||||
"authcookie=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1",
|
||||
"authcookie=refreshed&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2",
|
||||
] {
|
||||
let cookie =
|
||||
format!("user=test&{volatile}&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&computer=test");
|
||||
assert_eq!(hip_token(&cookie), "20f30054f721fd212925866b5778447d");
|
||||
}
|
||||
assert_ne!(hip_token("user=alice%20bob"), hip_token("user=alice+bob"));
|
||||
assert_ne!(hip_token("user=alice&portal=a"), hip_token("portal=a&user=alice"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maintenance_uses_only_hip_and_logout_with_physical_identity() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response><hip-report-needed>yes</hip-report-needed><delay>7</delay></response>"),
|
||||
response("<response status='success'/>"),
|
||||
response("<response status='success'/>"),
|
||||
])
|
||||
.await;
|
||||
let ipv4 = Some("192.0.2.7".parse().unwrap());
|
||||
let ipv6 = Some("2001:db8::7".parse().unwrap());
|
||||
let check = transport.check_hip(ipv4, ipv6).await.unwrap();
|
||||
assert_eq!(
|
||||
check,
|
||||
HipCheck {
|
||||
report_needed: true,
|
||||
delay: Duration::from_secs(7)
|
||||
}
|
||||
);
|
||||
transport.submit_hip("<hip-report/>", ipv4, ipv6).await.unwrap();
|
||||
transport.logout().await.unwrap();
|
||||
let requests = server.await.unwrap();
|
||||
assert_eq!(
|
||||
requests.iter().map(|(path, _)| path.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"/ssl-vpn/hipreportcheck.esp",
|
||||
"/ssl-vpn/hipreport.esp",
|
||||
"/ssl-vpn/logout.esp"
|
||||
]
|
||||
);
|
||||
let form: std::collections::HashMap<String, String> = serde_urlencoded::from_str(&requests[0].1).unwrap();
|
||||
assert_eq!(form["authcookie"], "test-cookie");
|
||||
assert_eq!(form["client-ip"], "192.0.2.7");
|
||||
assert_eq!(form["client-ipv6"], "2001:db8::7");
|
||||
assert_eq!(form["md5"], transport.hip_token());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_redirects_without_forwarding_authentication() {
|
||||
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (transport, server) = gateway(vec![format!(
|
||||
"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{}/stolen\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
destination.local_addr().unwrap()
|
||||
)])
|
||||
.await;
|
||||
assert!(
|
||||
matches!(transport.check_hip(None, None).await, Err(GatewayRequestError::Http(status)) if status.as_u16() == 307)
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(100), destination.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(server.await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_expired_cookie_from_transport_and_protocol_errors() {
|
||||
let (transport, server) = gateway(vec![
|
||||
response("<response status='error'><error>Invalid authentication cookie</error></response>"),
|
||||
"HTTP/1.1 512 Invalid Cookie\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
|
||||
response("<response><hip-report-needed>maybe</hip-report-needed></response>"),
|
||||
response("<response status='error'><error>server-private-payload</error></response>"),
|
||||
])
|
||||
.await;
|
||||
for _ in 0..2 {
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::InvalidCookie)
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await.unwrap_err(),
|
||||
GatewayRequestError::Http(StatusCode::SERVICE_UNAVAILABLE)
|
||||
));
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::MalformedResponse)
|
||||
));
|
||||
let error = transport.check_hip(None, None).await.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains("server-private-payload"));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounds_response_size_before_reading_body() {
|
||||
let (transport, server) = gateway(vec![format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
MAX_GATEWAY_RESPONSE_BYTES + 1
|
||||
)])
|
||||
.await;
|
||||
assert!(matches!(
|
||||
transport.check_hip(None, None).await,
|
||||
Err(GatewayRequestError::ResponseTooLarge)
|
||||
));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_delays_and_unsafe_response_xml() {
|
||||
for delay in ["-1", "3601", "4294967296", "invalid"] {
|
||||
let root = parse_response(
|
||||
format!("<response><hip-report-needed>no</hip-report-needed><delay>{delay}</delay></response>").as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(parse_hip_check(&root).is_err());
|
||||
}
|
||||
assert!(parse_response(b"<!DOCTYPE response><response/>").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_cookie_expiry_in_official_error_formats() {
|
||||
for body in [
|
||||
r#"var respStatus = "Error"; var respMsg = "Invalid authentication\u0020cookie"; thisForm.inputStr.value = "";"#,
|
||||
r#"<html><head/><body>var respStatus = "Error"; var respMsg = "Invalid authentication cookie";</body></html>"#,
|
||||
"<prelogin-response><status>Error</status><msg>Invalid authentication cookie</msg></prelogin-response>",
|
||||
] {
|
||||
assert!(matches!(
|
||||
parse_response(body.as_bytes()),
|
||||
Err(GatewayRequestError::InvalidCookie)
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
parse_response(b"<response status='error'><error>Denied</error></response>"),
|
||||
Err(GatewayRequestError::Rejected)
|
||||
));
|
||||
}
|
||||
@@ -1,19 +1,38 @@
|
||||
use super::lock_file::gpservice_lock_info;
|
||||
use std::path::Path;
|
||||
|
||||
async fn read_port() -> anyhow::Result<String> {
|
||||
let lock_info = gpservice_lock_info().await?;
|
||||
|
||||
Ok(lock_info.port.to_string())
|
||||
}
|
||||
use super::lock_file::{gpservice_lock_info, gpservice_lock_info_at};
|
||||
|
||||
pub async fn http_endpoint() -> anyhow::Result<String> {
|
||||
let port = read_port().await?;
|
||||
let port = gpservice_lock_info().await?.port;
|
||||
|
||||
Ok(format!("http://127.0.0.1:{}", port))
|
||||
}
|
||||
|
||||
pub async fn ws_endpoint() -> anyhow::Result<String> {
|
||||
let port = read_port().await?;
|
||||
let port = gpservice_lock_info().await?.port;
|
||||
|
||||
Ok(format!("ws://127.0.0.1:{}/ws", port))
|
||||
}
|
||||
|
||||
pub async fn ws_endpoint_from_lock_file(path: impl AsRef<Path>) -> anyhow::Result<String> {
|
||||
let port = gpservice_lock_info_at(path).await?.port;
|
||||
|
||||
Ok(format!("ws://127.0.0.1:{}/ws", port))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_endpoint_uses_the_selected_lock_file() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let lock_file = temp.path().join("gpservice.lock");
|
||||
std::fs::write(&lock_file, "123:4242").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
ws_endpoint_from_lock_file(lock_file).await.unwrap(),
|
||||
"ws://127.0.0.1:4242/ws"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,14 @@
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use log::info;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> {
|
||||
let mut env_file = NamedTempFile::new()?;
|
||||
let content = env::vars()
|
||||
.map(|(key, value)| format!("{}={}", key, value))
|
||||
.chain(
|
||||
extra
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(key, value)| format!("{}={}", key, value)),
|
||||
)
|
||||
.collect::<Vec<String>>()
|
||||
.join("\n");
|
||||
|
||||
writeln!(env_file, "{}", content)?;
|
||||
|
||||
Ok(env_file)
|
||||
}
|
||||
|
||||
pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> {
|
||||
let content = std::fs::read_to_string(env_file)?;
|
||||
let mut env_vars: HashMap<String, String> = HashMap::new();
|
||||
|
||||
for line in content.lines() {
|
||||
if let Some((key, value)) = line.split_once('=') {
|
||||
env_vars.insert(key.to_string(), value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(env_vars)
|
||||
}
|
||||
|
||||
pub fn patch_gui_runtime_env(hidpi: bool) {
|
||||
// This is to avoid blank screen on some systems
|
||||
unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") };
|
||||
|
||||
if is_wayland_session(
|
||||
env::var_os("WAYLAND_DISPLAY").as_deref(),
|
||||
env::var("XDG_SESSION_TYPE").ok().as_deref(),
|
||||
) {
|
||||
info!("Wayland session detected, enabling Linux WebKit rendering fallbacks");
|
||||
set_env_if_missing("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
info!("Wayland session detected, enabling software GL");
|
||||
set_env_if_missing("LIBGL_ALWAYS_SOFTWARE", "1");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use common::constants::GP_SERVICE_LOCK_FILE;
|
||||
use thiserror::Error;
|
||||
@@ -9,6 +9,10 @@ pub struct LockFile {
|
||||
pid: u32,
|
||||
}
|
||||
|
||||
pub fn dev_service_lock_file_path(bootstrap_socket: impl AsRef<Path>) -> PathBuf {
|
||||
bootstrap_socket.as_ref().with_file_name("gpservice.lock")
|
||||
}
|
||||
|
||||
impl LockFile {
|
||||
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
|
||||
Self { path: path.into(), pid }
|
||||
@@ -25,8 +29,15 @@ impl LockFile {
|
||||
}
|
||||
|
||||
pub fn unlock(&self) -> anyhow::Result<()> {
|
||||
std::fs::remove_file(&self.path)?;
|
||||
Ok(())
|
||||
match std::fs::read_to_string(&self.path) {
|
||||
Ok(content) if LockInfo::parse(&content).is_ok_and(|info| info.pid == self.pid) => {
|
||||
std::fs::remove_file(&self.path)?;
|
||||
Ok(())
|
||||
}
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check_health(&self) -> bool {
|
||||
@@ -95,7 +106,11 @@ impl LockInfo {
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
|
||||
LockInfo::from_file(GP_SERVICE_LOCK_FILE).await
|
||||
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
|
||||
}
|
||||
|
||||
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
|
||||
LockInfo::from_file(path).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -126,4 +141,50 @@ mod tests {
|
||||
Err(LockFileError::InvalidPort(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_service_lock_file_is_next_to_the_bootstrap_socket() {
|
||||
assert_eq!(
|
||||
dev_service_lock_file_path("/var/run/gpservice-dev-123/dev-bootstrap.sock"),
|
||||
PathBuf::from("/var/run/gpservice-dev-123/gpservice.lock")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlock_removes_lock_owned_by_process() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("gpservice.lock");
|
||||
let lock = LockFile::new(&path, 1234);
|
||||
lock.lock("8080").unwrap();
|
||||
|
||||
lock.unlock().unwrap();
|
||||
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlock_preserves_lock_owned_by_another_process() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("gpservice.lock");
|
||||
let owner = LockFile::new(&path, 1234);
|
||||
let other = LockFile::new(&path, 5678);
|
||||
owner.lock("8080").unwrap();
|
||||
|
||||
other.unlock().unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "1234:8080");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlock_ignores_missing_or_malformed_lock() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("gpservice.lock");
|
||||
let lock = LockFile::new(&path, 1234);
|
||||
|
||||
lock.unlock().unwrap();
|
||||
std::fs::write(&path, "not-a-lock").unwrap();
|
||||
lock.unlock().unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "not-a-lock");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
use std::{borrow::Cow, fs};
|
||||
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use log::warn;
|
||||
use openssl::pkey::PKey;
|
||||
use pem::parse_many;
|
||||
use anyhow::{Context, ensure};
|
||||
use openssl::{pkey::PKey, x509::X509};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
@@ -16,103 +15,453 @@ pub enum RequestIdentityError {
|
||||
DecryptError(&'static str),
|
||||
}
|
||||
|
||||
/// Create an identity object from a certificate and key
|
||||
/// The file is expected to be the PKCS#8 PEM or PKCS#12 format
|
||||
/// When using a PKCS#12 file, the key is NOT required, but a passphrase is required
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
if cert.ends_with(".p12") || cert.ends_with(".pfx") {
|
||||
create_identity_from_pkcs12(cert, passphrase)
|
||||
} else {
|
||||
create_identity_from_pem(cert, key, passphrase)
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
/// retains its original bytes and passphrase so each native backend imports the
|
||||
/// same identity and chain. Debug never exposes retained material.
|
||||
#[derive(Clone)]
|
||||
pub struct ClientIdentity {
|
||||
material: Arc<IdentityMaterial>,
|
||||
identity: Identity,
|
||||
}
|
||||
|
||||
struct IdentityMaterial {
|
||||
certificate: Zeroizing<Vec<u8>>,
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<Zeroizing<String>>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientIdentity {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ClientIdentity")
|
||||
.field("material", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn create_identity_from_pem(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
let cert_pem = fs::read(cert).map_err(|err| anyhow::anyhow!("Failed to read certificate file: {}", err))?;
|
||||
impl ClientIdentity {
|
||||
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
|
||||
let certificate_bytes = read_identity_file(certificate)?;
|
||||
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
return Self::from_data(certificate_bytes, None, Some(passphrase));
|
||||
}
|
||||
let key_bytes = match key {
|
||||
Some(path) => read_identity_file(path)?,
|
||||
None => certificate_bytes.clone(),
|
||||
};
|
||||
// Keep the previous first-private-key rule: unrelated later blocks must not
|
||||
// change which key is selected or whether the caller is prompted.
|
||||
let key = pem::parse_many(&*key_bytes)?
|
||||
.into_iter()
|
||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
let key_pem = Zeroizing::new(pem::encode(&key));
|
||||
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
|
||||
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
|
||||
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
|
||||
} else {
|
||||
Zeroizing::new(key_pem.as_bytes().to_vec())
|
||||
};
|
||||
// Strip private-key blocks before importing the certificate chain: macOS
|
||||
// otherwise imports the same key twice for combined PEM files.
|
||||
let mut certificate = Zeroizing::new(Vec::new());
|
||||
for cert in X509::stack_from_pem(&certificate_bytes)? {
|
||||
certificate.extend(cert.to_pem()?);
|
||||
}
|
||||
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
|
||||
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key: Some(key),
|
||||
passphrase: None,
|
||||
}),
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
// Use the certificate as the key if no key is provided
|
||||
let key_pem_file = match key {
|
||||
Some(key) => Cow::Owned(fs::read(key).map_err(|err| anyhow::anyhow!("Failed to read key file: {}", err))?),
|
||||
None => Cow::Borrowed(&cert_pem),
|
||||
};
|
||||
/// A separate key denotes decrypted PEM; no separate key denotes original
|
||||
/// PKCS#12 bytes. Input-size limits belong to the service transport boundary.
|
||||
pub fn from_data(
|
||||
certificate: Zeroizing<Vec<u8>>,
|
||||
key: Option<Zeroizing<Vec<u8>>>,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
|
||||
None => {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
|
||||
(
|
||||
Identity::from_pkcs12_der(&certificate, passphrase)?,
|
||||
Some(Zeroizing::new(passphrase.to_owned())),
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
material: Arc::new(IdentityMaterial {
|
||||
certificate,
|
||||
key,
|
||||
passphrase,
|
||||
}),
|
||||
identity,
|
||||
})
|
||||
}
|
||||
|
||||
// Find the private key in the pem file
|
||||
let key_pem = parse_many(key_pem_file.as_ref())?
|
||||
.into_iter()
|
||||
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
|
||||
.ok_or(RequestIdentityError::NoKey)?;
|
||||
pub fn certificate_data(&self) -> &[u8] {
|
||||
&self.material.certificate
|
||||
}
|
||||
pub fn key_data(&self) -> Option<&[u8]> {
|
||||
self.material.key.as_ref().map(|key| key.as_slice())
|
||||
}
|
||||
pub fn key_password(&self) -> Option<&str> {
|
||||
self.material.passphrase.as_ref().map(|value| value.as_str())
|
||||
}
|
||||
pub(crate) fn request_identity(&self) -> Identity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
// The key pem could be encrypted, so we need to decrypt it
|
||||
let decrypted_key_pem = if key_pem.tag().ends_with("ENCRYPTED PRIVATE KEY") {
|
||||
let passphrase = passphrase.ok_or_else(|| {
|
||||
warn!("Key is encrypted but no passphrase provided");
|
||||
RequestIdentityError::NoPassphrase("PEM")
|
||||
})?;
|
||||
let pem_content = pem::encode(&key_pem);
|
||||
let key = PKey::private_key_from_pem_passphrase(pem_content.as_bytes(), passphrase.as_bytes()).map_err(|err| {
|
||||
warn!("Failed to decrypt key: {}", err);
|
||||
RequestIdentityError::DecryptError("PEM")
|
||||
})?;
|
||||
|
||||
key.private_key_to_pem_pkcs8()?
|
||||
} else {
|
||||
pem::encode(&key_pem).into()
|
||||
};
|
||||
|
||||
let identity = Identity::from_pkcs8_pem(&cert_pem, &decrypted_key_pem)?;
|
||||
Ok(identity)
|
||||
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
|
||||
let suffix = if self.material.key.is_some() { ".pem" } else { ".p12" };
|
||||
let certificate = write_identity_file(self.certificate_data(), directory, suffix)?;
|
||||
let key = self
|
||||
.key_data()
|
||||
.map(|key| write_identity_file(key, directory, ".pem"))
|
||||
.transpose()?;
|
||||
Ok(ClientIdentityFiles { certificate, key })
|
||||
}
|
||||
}
|
||||
|
||||
fn create_identity_from_pkcs12(pkcs12: &str, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
let pkcs12 = fs::read(pkcs12)?;
|
||||
/// Named files are private and remain owned until native workers and logout
|
||||
/// finish. The original configured files are never reopened by these workers.
|
||||
pub struct ClientIdentityFiles {
|
||||
certificate: tempfile::NamedTempFile,
|
||||
key: Option<tempfile::NamedTempFile>,
|
||||
}
|
||||
|
||||
let Some(passphrase) = passphrase else {
|
||||
bail!(RequestIdentityError::NoPassphrase("PKCS#12"));
|
||||
impl ClientIdentityFiles {
|
||||
pub fn certificate(&self) -> &str {
|
||||
self.certificate.path().to_str().expect("identity path is UTF-8")
|
||||
}
|
||||
pub fn key(&self) -> Option<&str> {
|
||||
self
|
||||
.key
|
||||
.as_ref()
|
||||
.map(|key| key.path().to_str().expect("identity path is UTF-8"))
|
||||
}
|
||||
}
|
||||
|
||||
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
|
||||
Ok(Zeroizing::new(
|
||||
fs::read(path).context("Failed to read client identity")?,
|
||||
))
|
||||
}
|
||||
|
||||
fn write_identity_file(
|
||||
bytes: &[u8],
|
||||
directory: Option<&Path>,
|
||||
suffix: &str,
|
||||
) -> anyhow::Result<tempfile::NamedTempFile> {
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix("gp-identity-").suffix(suffix);
|
||||
let mut file = match directory {
|
||||
Some(directory) => builder.tempfile_in(directory)?,
|
||||
None => builder.tempfile()?,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
file.as_file().set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
ensure!(file.path().to_str().is_some(), "Client identity path is not UTF-8");
|
||||
file.write_all(bytes)?;
|
||||
file.flush()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
let identity = Identity::from_pkcs12_der(&pkcs12, passphrase)?;
|
||||
Ok(identity)
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
|
||||
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut name = X509NameBuilder::new().unwrap();
|
||||
name.append_entry_by_text("CN", "identity-fixture").unwrap();
|
||||
let name = name.build();
|
||||
let mut certificate = X509::builder().unwrap();
|
||||
certificate.set_version(2).unwrap();
|
||||
certificate.set_subject_name(&name).unwrap();
|
||||
certificate.set_issuer_name(&name).unwrap();
|
||||
certificate.set_pubkey(&key).unwrap();
|
||||
certificate
|
||||
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
||||
.unwrap();
|
||||
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
certificate.sign(&key, MessageDigest::sha256()).unwrap();
|
||||
(
|
||||
certificate.build().to_pem().unwrap(),
|
||||
key.private_key_to_pem_pkcs8().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
|
||||
.unwrap();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(&encrypted).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_without_key_reports_missing_key_even_with_passphrase() {
|
||||
let (certificate, _) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
for passphrase in [None, Some("unused")] {
|
||||
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoKey)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_identity_loading_is_not_limited_by_service_message_size() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(&certificate).unwrap();
|
||||
source.write_all(&key).unwrap();
|
||||
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
|
||||
cert_file.write_all(&certificate).unwrap();
|
||||
let mut key_file = tempfile::NamedTempFile::new().unwrap();
|
||||
let encrypted = PKey::private_key_from_pem(&key)
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
|
||||
.unwrap();
|
||||
key_file.write_all(&encrypted).unwrap();
|
||||
let cert = cert_file.path().to_str().unwrap();
|
||||
let key_path = Some(key_file.path().to_str().unwrap());
|
||||
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
|
||||
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>().unwrap() {
|
||||
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
|
||||
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
|
||||
other => panic!("Unexpected identity error: {other}"),
|
||||
}
|
||||
}
|
||||
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
|
||||
assert_eq!(loaded.key_data().unwrap(), key);
|
||||
fs::write(key_file.path(), &key).unwrap();
|
||||
for passphrase in [None, Some("ignored for unencrypted key")] {
|
||||
assert_eq!(
|
||||
ClientIdentity::load(cert, key_path, passphrase)
|
||||
.unwrap()
|
||||
.key_data()
|
||||
.unwrap(),
|
||||
key
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (certificate, key) = generated_identity();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
let mut combined = certificate.clone();
|
||||
combined.extend(&key);
|
||||
fs::write(&source, &combined).unwrap();
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
|
||||
fs::write(&source, "changed after authentication").unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
assert_eq!(identity.key_data().unwrap(), key);
|
||||
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
|
||||
let files = identity.write_files(Some(directory.path())).unwrap();
|
||||
let certificate_path = files.certificate().to_owned();
|
||||
let key_path = files.key().unwrap().to_owned();
|
||||
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
|
||||
assert_eq!(fs::read(&key_path).unwrap(), key);
|
||||
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&certificate_path).exists());
|
||||
assert!(!Path::new(&key_path).exists());
|
||||
// The request identity remains valid after its original files disappear.
|
||||
fs::remove_file(&source).unwrap();
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
|
||||
let (certificate, key) = generated_identity();
|
||||
let certificate = X509::from_pem(&certificate).unwrap();
|
||||
let key = PKey::private_key_from_pem(&key).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("identity-fixture").pkey(&key).cert(&certificate);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
for suffix in [".p12", ".pfx"] {
|
||||
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let path = source.path().to_str().unwrap();
|
||||
assert!(ClientIdentity::load(path, None, None).is_err());
|
||||
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
|
||||
// PKCS#12 has always ignored a separately configured key path.
|
||||
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
|
||||
fs::write(source.path(), b"replaced after login").unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
assert_eq!(identity.key_password(), Some("fixture-password"));
|
||||
assert!(!format!("{identity:?}").contains("fixture-password"));
|
||||
let files = identity.write_files(None).unwrap();
|
||||
assert!(files.certificate().ends_with(".p12"));
|
||||
assert!(files.key().is_none());
|
||||
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
|
||||
let owned_path = files.certificate().to_owned();
|
||||
drop(files);
|
||||
assert!(!Path::new(&owned_path).exists());
|
||||
}
|
||||
let empty_password = builder.build2("").unwrap().to_der().unwrap();
|
||||
// Empty-password support varies by native backend and PKCS#12 algorithms.
|
||||
// Match the previous native import instead of introducing another parser.
|
||||
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
|
||||
previously_accepted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
|
||||
use openssl::{
|
||||
asn1::Asn1Time,
|
||||
hash::MessageDigest,
|
||||
rsa::Rsa,
|
||||
stack::Stack,
|
||||
x509::{X509NameBuilder, extension::BasicConstraints},
|
||||
};
|
||||
fn certificate(
|
||||
name: &str,
|
||||
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
|
||||
ca: bool,
|
||||
) -> (X509, PKey<openssl::pkey::Private>) {
|
||||
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
|
||||
let mut subject = X509NameBuilder::new().unwrap();
|
||||
subject.append_entry_by_text("CN", name).unwrap();
|
||||
let subject = subject.build();
|
||||
let mut cert = X509::builder().unwrap();
|
||||
cert.set_version(2).unwrap();
|
||||
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
|
||||
.unwrap()
|
||||
.to_asn1_integer()
|
||||
.unwrap();
|
||||
cert.set_serial_number(&serial).unwrap();
|
||||
cert.set_subject_name(&subject).unwrap();
|
||||
cert
|
||||
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
|
||||
.unwrap();
|
||||
cert.set_pubkey(&key).unwrap();
|
||||
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
|
||||
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
|
||||
if ca {
|
||||
cert
|
||||
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
cert
|
||||
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
|
||||
.unwrap();
|
||||
(cert.build(), key)
|
||||
}
|
||||
let (root, root_key) = certificate("root", None, true);
|
||||
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
|
||||
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
|
||||
// This is the reverse CA stack consumed by the previous native-tls path.
|
||||
let mut ca = Stack::new().unwrap();
|
||||
ca.push(root.clone()).unwrap();
|
||||
ca.push(intermediate.clone()).unwrap();
|
||||
let mut builder = Pkcs12::builder();
|
||||
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
|
||||
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
|
||||
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
|
||||
source.write_all(&encoded).unwrap();
|
||||
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
assert_eq!(identity.certificate_data(), encoded);
|
||||
assert!(identity.key_data().is_none());
|
||||
ClientIdentity::from_data(
|
||||
Zeroizing::new(identity.certificate_data().to_vec()),
|
||||
None,
|
||||
identity.key_password(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_from_pem_requires_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let identity = create_identity_from_pem(cert, None, None);
|
||||
let identity = create_identity(cert, None, None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_with_passphrase() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity_from_pem(cert, None, Some(passphrase));
|
||||
let identity = create_identity(cert, None, Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_unencrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
let identity = create_identity_from_pem(cert, None, None);
|
||||
let identity = create_identity(cert, None, None);
|
||||
println!("{:?}", identity);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_cert_and_encrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
let passphrase = "badssl.com";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), Some(passphrase));
|
||||
let identity = create_identity(cert, Some(key), Some(passphrase));
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
@@ -122,19 +471,45 @@ mod tests {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client.pem";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), None);
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_err());
|
||||
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn create_identity_from_pem_cert_and_unencrypted_key() {
|
||||
let cert = "tests/files/badssl.com-client.pem";
|
||||
let key = "tests/files/badssl.com-client-unencrypted.pem";
|
||||
|
||||
let identity = create_identity_from_pem(cert, Some(key), None);
|
||||
let identity = create_identity(cert, Some(key), None);
|
||||
|
||||
assert!(identity.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum ResponseBodyError {
|
||||
#[error("Response read failed: {0}")]
|
||||
Transport(#[from] reqwest::Error),
|
||||
#[error("Response exceeds its size limit")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
pub(crate) async fn read_bounded_response(
|
||||
mut response: reqwest::Response,
|
||||
limit: usize,
|
||||
) -> Result<Vec<u8>, ResponseBodyError> {
|
||||
if response.content_length().is_some_and(|length| length > limit as u64) {
|
||||
return Err(ResponseBodyError::TooLarge);
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
if chunk.len() > limit.saturating_sub(body.len()) {
|
||||
return Err(ResponseBodyError::TooLarge);
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
@@ -1,11 +1,65 @@
|
||||
use tauri::WebviewWindow;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum WindowTypeHint {
|
||||
Dialog,
|
||||
Utility,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn is_screen_composited() -> bool {
|
||||
gtk::gdk::Screen::default().is_some_and(|screen| screen.is_composited())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn set_window_type_hint(window: &WebviewWindow, hint: WindowTypeHint) -> anyhow::Result<()> {
|
||||
use gtk::{gdk, traits::GtkWindowExt};
|
||||
|
||||
let hint = match hint {
|
||||
WindowTypeHint::Dialog => gdk::WindowTypeHint::Dialog,
|
||||
WindowTypeHint::Utility => gdk::WindowTypeHint::Utility,
|
||||
};
|
||||
|
||||
window.gtk_window()?.set_type_hint(hint);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the frame-to-content height difference for a standard titled macOS window.
|
||||
/// This is nonzero only on macOS.
|
||||
pub fn get_title_bar_height() -> f64 {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos_title_bar_height(os_info::get().version())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_title_bar_height(version: &os_info::Version) -> f64 {
|
||||
if version.ge(&os_info::Version::from_string("26.0.0")) {
|
||||
32.0
|
||||
} else {
|
||||
28.0
|
||||
}
|
||||
}
|
||||
|
||||
pub trait WindowExt {
|
||||
fn raise(&self) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
impl WindowExt for WebviewWindow {
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn raise(&self) -> anyhow::Result<()> {
|
||||
self.show()?;
|
||||
self.set_focus()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn raise(&self) -> anyhow::Result<()> {
|
||||
self.show()?;
|
||||
Ok(())
|
||||
@@ -17,6 +71,24 @@ impl WindowExt for WebviewWindow {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn uses_the_current_macos_title_bar_height() {
|
||||
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("25.9.0")), 28.0);
|
||||
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("26.0.0")), 32.0);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn native_title_bar_height_is_zero_without_a_native_macos_title_bar() {
|
||||
assert_eq!(get_title_bar_height(), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
mod unix {
|
||||
use std::{process::ExitStatus, time::Duration};
|
||||
|
||||
Reference in new issue
Block a user