mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-17 13:46:27 -05:00
fix: recover desktop session env for browser auth
This commit is contained in:
7 files changed
+269
-8
No files matched your search
@@ -44,7 +44,12 @@ impl ConnectHandler<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
|
||||
pub(super) async fn obtain_credential(
|
||||
&self,
|
||||
prelogin: &Prelogin,
|
||||
server: &str,
|
||||
portal_default_browser_enabled: bool,
|
||||
) -> anyhow::Result<Credential> {
|
||||
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
|
||||
return self.read_cookie_from_stdin();
|
||||
}
|
||||
@@ -53,7 +58,12 @@ impl ConnectHandler<'_> {
|
||||
|
||||
match prelogin {
|
||||
Prelogin::Saml(prelogin) => {
|
||||
let browser = if prelogin.support_default_browser() {
|
||||
let external_browser_supported = default_browser_auth_allowed(
|
||||
prelogin.support_default_browser(),
|
||||
is_gateway,
|
||||
portal_default_browser_enabled,
|
||||
);
|
||||
let browser = if external_browser_supported {
|
||||
self.args.browser.as_deref()
|
||||
} else if !cfg!(feature = "webview-auth") {
|
||||
bail!(
|
||||
@@ -74,7 +84,7 @@ impl ConnectHandler<'_> {
|
||||
.verbose(verbose);
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
|
||||
let use_default_browser = external_browser_supported && self.args.default_browser;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let browser_kind = if browser.is_some() || use_default_browser {
|
||||
"external"
|
||||
@@ -174,6 +184,14 @@ fn should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogi
|
||||
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
|
||||
}
|
||||
|
||||
fn default_browser_auth_allowed(
|
||||
saml_support_default_browser: bool,
|
||||
is_gateway: bool,
|
||||
portal_default_browser_enabled: bool,
|
||||
) -> bool {
|
||||
saml_support_default_browser && (!is_gateway || portal_default_browser_enabled)
|
||||
}
|
||||
|
||||
fn log_stdin_host_id(host_id: Option<&str>) {
|
||||
match host_id {
|
||||
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
|
||||
@@ -229,4 +247,21 @@ mod tests {
|
||||
assert!(!should_read_stdin_credential(false, false, false));
|
||||
assert!(!should_read_stdin_credential(false, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portal_saml_can_use_default_browser_when_supported() {
|
||||
assert!(default_browser_auth_allowed(true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_saml_requires_portal_default_browser_policy() {
|
||||
assert!(!default_browser_auth_allowed(true, true, false));
|
||||
assert!(default_browser_auth_allowed(true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_browser_auth_requires_saml_support() {
|
||||
assert!(!default_browser_auth_allowed(false, false, true));
|
||||
assert!(!default_browser_auth_allowed(false, true, true));
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ impl ConnectHandler<'_> {
|
||||
gp_params.set_is_gateway(true);
|
||||
|
||||
let prelogin = prelogin(gateway, &gp_params, self.prelogin_options(false)).await?;
|
||||
let cred = self.obtain_credential(&prelogin, gateway).await?;
|
||||
let cred = self.obtain_credential(&prelogin, gateway, false).await?;
|
||||
|
||||
let login_session = self
|
||||
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
|
||||
@@ -218,7 +218,10 @@ impl ConnectHandler<'_> {
|
||||
info!("Portal config did not provide gateway auth cookies; using gateway prelogin flow");
|
||||
}
|
||||
|
||||
let gateway_cred = match self.obtain_credential(&gateway_prelogin, gateway).await {
|
||||
let gateway_cred = match self
|
||||
.obtain_credential(&gateway_prelogin, gateway, portal_default_browser_enabled)
|
||||
.await
|
||||
{
|
||||
Ok(cred) => cred,
|
||||
Err(err) => {
|
||||
self.print_direct_gateway_recommendation(gateway);
|
||||
|
||||
@@ -159,7 +159,7 @@ impl<'a> ConnectHandler<'a> {
|
||||
|
||||
let prelogin = prelogin(portal, &gp_params, self.prelogin_options(false)).await?;
|
||||
|
||||
let cred = self.obtain_credential(&prelogin, portal).await?;
|
||||
let cred = self.obtain_credential(&prelogin, portal, false).await?;
|
||||
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
||||
|
||||
portal_config.sort_gateways(prelogin.region());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use log::info;
|
||||
use tiny_http::{Header, Response, Server};
|
||||
use tiny_http::{Header, Method, Response, Server};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) struct AuthServer {
|
||||
@@ -30,6 +30,10 @@ impl AuthServer {
|
||||
if req.url() != format!("/{}", self.auth_id) {
|
||||
let forbidden = Response::from_string("forbidden").with_status_code(403);
|
||||
let _ = req.respond(forbidden);
|
||||
} else if req.method() == &Method::Head {
|
||||
if let Err(err) = req.respond(Response::empty(200)) {
|
||||
info!("failed to respond to HEAD request: {}", err);
|
||||
}
|
||||
} else {
|
||||
let auth_response = build_auth_response(auth_request);
|
||||
if let Err(err) = req.respond(auth_response) {
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::ffi::OsStr;
|
||||
use tokio::process::Command;
|
||||
use uzers::os::unix::UserExt;
|
||||
|
||||
use super::users::get_non_root_user;
|
||||
use super::{desktop_session_env, users::get_non_root_user};
|
||||
|
||||
pub trait CommandExt {
|
||||
fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command;
|
||||
@@ -28,6 +28,8 @@ impl CommandExt for Command {
|
||||
fn into_non_root(mut self) -> anyhow::Result<Command> {
|
||||
let user = get_non_root_user().map_err(|_| anyhow::anyhow!("{:?} cannot be run as root", self))?;
|
||||
|
||||
desktop_session_env::apply(&mut self, user.uid(), user.home_dir());
|
||||
|
||||
self
|
||||
.env("HOME", user.home_dir())
|
||||
.env("USER", user.name())
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
use std::path::Path;
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
pub(super) fn apply(command: &mut Command, user_id: u32, home_dir: &Path) {
|
||||
platform::apply(command, user_id, home_dir);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod platform {
|
||||
use std::{collections::HashMap, env, fs, os::unix::fs::MetadataExt, path::Path};
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
const DESKTOP_SESSION_ENV: &[&str] = &[
|
||||
"BROWSER",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DESKTOP_SESSION",
|
||||
"DISPLAY",
|
||||
"MOZ_ENABLE_WAYLAND",
|
||||
"WAYLAND_DISPLAY",
|
||||
"XAUTHORITY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_DATA_DIRS",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
];
|
||||
|
||||
pub(super) fn apply(command: &mut Command, user_id: u32, home_dir: &Path) {
|
||||
let session_env = collect(user_id);
|
||||
|
||||
for key in DESKTOP_SESSION_ENV {
|
||||
if let Some(value) = env_value(key).or_else(|| session_env.get(*key).cloned()) {
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
let runtime_dir = env_value("XDG_RUNTIME_DIR")
|
||||
.or_else(|| session_env.get("XDG_RUNTIME_DIR").cloned())
|
||||
.unwrap_or_else(|| format!("/run/user/{user_id}"));
|
||||
command.env("XDG_RUNTIME_DIR", &runtime_dir);
|
||||
|
||||
if env_value("DBUS_SESSION_BUS_ADDRESS")
|
||||
.or_else(|| session_env.get("DBUS_SESSION_BUS_ADDRESS").cloned())
|
||||
.is_none()
|
||||
{
|
||||
command.env("DBUS_SESSION_BUS_ADDRESS", format!("unix:path={runtime_dir}/bus"));
|
||||
}
|
||||
|
||||
if env_value("XDG_DATA_HOME")
|
||||
.or_else(|| session_env.get("XDG_DATA_HOME").cloned())
|
||||
.is_none()
|
||||
{
|
||||
command.env("XDG_DATA_HOME", home_dir.join(".local/share"));
|
||||
}
|
||||
|
||||
if env_value("XDG_CONFIG_HOME")
|
||||
.or_else(|| session_env.get("XDG_CONFIG_HOME").cloned())
|
||||
.is_none()
|
||||
{
|
||||
command.env("XDG_CONFIG_HOME", home_dir.join(".config"));
|
||||
}
|
||||
|
||||
if env_value("XDG_DATA_DIRS")
|
||||
.or_else(|| session_env.get("XDG_DATA_DIRS").cloned())
|
||||
.is_none()
|
||||
{
|
||||
command.env("XDG_DATA_DIRS", default_xdg_data_dirs());
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(user_id: u32) -> HashMap<String, String> {
|
||||
let mut best = HashMap::new();
|
||||
let mut best_score = 0;
|
||||
|
||||
let Ok(entries) = fs::read_dir("/proc") else {
|
||||
return best;
|
||||
};
|
||||
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if !is_process_dir(&path) || !owned_by_user(&path, user_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let env = read_environ(&path);
|
||||
let score = score_env(&env);
|
||||
if score > best_score {
|
||||
best_score = score;
|
||||
best = env;
|
||||
}
|
||||
}
|
||||
|
||||
best
|
||||
}
|
||||
|
||||
fn is_process_dir(path: &Path) -> bool {
|
||||
path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
}
|
||||
|
||||
fn owned_by_user(path: &Path, user_id: u32) -> bool {
|
||||
path.metadata().is_ok_and(|metadata| metadata.uid() == user_id)
|
||||
}
|
||||
|
||||
fn read_environ(process_dir: &Path) -> HashMap<String, String> {
|
||||
let path = process_dir.join("environ");
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
|
||||
parse_environ(&bytes)
|
||||
}
|
||||
|
||||
fn parse_environ(bytes: &[u8]) -> HashMap<String, String> {
|
||||
bytes
|
||||
.split(|byte| *byte == b'\0')
|
||||
.filter_map(|entry| {
|
||||
let index = entry.iter().position(|byte| *byte == b'=')?;
|
||||
let (key, value) = (&entry[..index], &entry[index + 1..]);
|
||||
let key = std::str::from_utf8(key).ok()?;
|
||||
if !DESKTOP_SESSION_ENV.contains(&key) {
|
||||
return None;
|
||||
}
|
||||
let value = String::from_utf8_lossy(value).to_string();
|
||||
Some((key.to_string(), value))
|
||||
})
|
||||
.filter_map(|(key, value)| non_empty(Some(value)).map(|value| (key, value)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn score_env(env: &HashMap<String, String>) -> usize {
|
||||
let mut score = 0;
|
||||
|
||||
if env.contains_key("DBUS_SESSION_BUS_ADDRESS") {
|
||||
score += 4;
|
||||
}
|
||||
if env.contains_key("XDG_RUNTIME_DIR") {
|
||||
score += 3;
|
||||
}
|
||||
if env.contains_key("WAYLAND_DISPLAY") || env.contains_key("DISPLAY") {
|
||||
score += 3;
|
||||
}
|
||||
if env.contains_key("XDG_CURRENT_DESKTOP") {
|
||||
score += 2;
|
||||
}
|
||||
if env.contains_key("XDG_DATA_DIRS") {
|
||||
score += 1;
|
||||
}
|
||||
|
||||
score
|
||||
}
|
||||
|
||||
fn env_value(key: &str) -> Option<String> {
|
||||
non_empty(env::var(key).ok())
|
||||
}
|
||||
|
||||
fn non_empty(value: Option<String>) -> Option<String> {
|
||||
value.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
fn default_xdg_data_dirs() -> &'static str {
|
||||
"/usr/local/share:/usr/share:/var/lib/snapd/desktop"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_environ_keeps_only_desktop_session_values() {
|
||||
let env = parse_environ(b"DISPLAY=:0\0PASSWORD=secret\0XDG_DATA_DIRS=/usr/share\0EMPTY= \0");
|
||||
|
||||
assert_eq!(env.get("DISPLAY").map(String::as_str), Some(":0"));
|
||||
assert_eq!(env.get("XDG_DATA_DIRS").map(String::as_str), Some("/usr/share"));
|
||||
assert!(!env.contains_key("PASSWORD"));
|
||||
assert!(!env.contains_key("EMPTY"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn score_prefers_graphical_session_env() {
|
||||
let plain = HashMap::from([("XDG_DATA_DIRS".to_string(), "/usr/share".to_string())]);
|
||||
let graphical = HashMap::from([
|
||||
(
|
||||
"DBUS_SESSION_BUS_ADDRESS".to_string(),
|
||||
"unix:path=/run/user/1000/bus".to_string(),
|
||||
),
|
||||
("XDG_RUNTIME_DIR".to_string(), "/run/user/1000".to_string()),
|
||||
("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string()),
|
||||
]);
|
||||
|
||||
assert!(score_env(&graphical) > score_env(&plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_empty_ignores_missing_or_blank_values() {
|
||||
assert_eq!(non_empty(None), None);
|
||||
assert_eq!(non_empty(Some(" ".to_string())), None);
|
||||
assert_eq!(non_empty(Some("value".to_string())), Some("value".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
mod platform {
|
||||
use std::path::Path;
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
pub(super) fn apply(_command: &mut Command, _user_id: u32, _home_dir: &Path) {}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub(crate) mod command_traits;
|
||||
mod desktop_session_env;
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub mod auth_launcher;
|
||||
|
||||
Reference in new issue
Block a user