mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
682 lines
22 KiB
Rust
682 lines
22 KiB
Rust
use std::{
|
|
borrow::Cow,
|
|
cell::RefCell,
|
|
fs,
|
|
sync::{Arc, Mutex},
|
|
};
|
|
|
|
use anyhow::{Context, bail};
|
|
use clap::Args;
|
|
use common::constants::{GP_CLIENT_VERSION, GP_USER_AGENT};
|
|
use gpapi::{
|
|
auth::SamlAuthResult,
|
|
clap::{ToVerboseArg, args::Os},
|
|
credential::{Credential, PasswordCredential},
|
|
error::PortalError,
|
|
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
|
|
gp_params::{ClientOs, GpParams},
|
|
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
|
|
process::{
|
|
auth_launcher::SamlAuthLauncher,
|
|
users::{get_non_root_user, get_user_by_name},
|
|
},
|
|
utils::{host_utils, request::RequestIdentityError, shutdown_signal},
|
|
};
|
|
use inquire::{Password, PasswordDisplayMode, Select, Text};
|
|
use log::{info, warn};
|
|
use openconnect::Vpn;
|
|
use tokio::{runtime::Handle, task::JoinHandle};
|
|
|
|
use crate::{
|
|
GP_CLIENT_LOCK_FILE,
|
|
cli::SharedArgs,
|
|
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
|
|
};
|
|
|
|
struct GatewayLoginSession {
|
|
cookie: String,
|
|
extension_auth: SessionExtensionAuth,
|
|
}
|
|
|
|
#[derive(Args)]
|
|
pub(crate) struct ConnectArgs {
|
|
#[arg(help = "The portal server to connect to")]
|
|
server: String,
|
|
|
|
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
|
|
gateway: Option<String>,
|
|
|
|
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
|
|
user: Option<String>,
|
|
|
|
#[arg(long, help = "Read the password from standard input")]
|
|
passwd_on_stdin: bool,
|
|
|
|
#[arg(long, help = "Read the cookie from standard input")]
|
|
cookie_on_stdin: bool,
|
|
|
|
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
|
|
script: Option<String>,
|
|
|
|
#[arg(long, short, help = "The IFNAME for tunnel interface")]
|
|
interface: Option<String>,
|
|
|
|
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
|
|
script_tun: bool,
|
|
|
|
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
|
|
as_gateway: bool,
|
|
|
|
#[arg(
|
|
long,
|
|
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path",
|
|
default_missing_value = "",
|
|
num_args=0..=1
|
|
)]
|
|
hip: Option<String>,
|
|
|
|
#[arg(long, help = "The user used to run the HIP script")]
|
|
hip_user: Option<String>,
|
|
|
|
#[arg(
|
|
short,
|
|
long,
|
|
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
|
|
)]
|
|
certificate: Option<String>,
|
|
|
|
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
|
|
sslkey: Option<String>,
|
|
|
|
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
|
|
key_password: Option<String>,
|
|
|
|
#[arg(long, help = "Deprecated: Use the '--hip-user' option instead")]
|
|
csd_user: Option<String>,
|
|
|
|
#[arg(long, help = "Deprecated: Use the '--hip' option instead")]
|
|
csd_wrapper: Option<String>,
|
|
|
|
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
|
|
reconnect_timeout: u32,
|
|
|
|
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
|
|
mtu: Option<u32>,
|
|
|
|
#[arg(long, help = "Do not ask for IPv6 connectivity")]
|
|
disable_ipv6: bool,
|
|
|
|
#[arg(
|
|
long,
|
|
help = "The user agent to use, if not specified, it will be generated based on the OS and client version"
|
|
)]
|
|
user_agent: Option<String>,
|
|
|
|
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
|
|
os: Os,
|
|
|
|
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
|
|
os_version: Option<String>,
|
|
|
|
#[arg(long, help = "The GP client version to emulate, e.g., '6.2.4-49'")]
|
|
client_version: Option<String>,
|
|
|
|
#[arg(long, help = "Disable DTLS and ESP")]
|
|
no_dtls: bool,
|
|
|
|
#[arg(
|
|
long = "local-hostname",
|
|
help = "Same as the '--local-hostname' option in the openconnect command"
|
|
)]
|
|
local_hostname: Option<String>,
|
|
|
|
#[arg(
|
|
long = "force-dpd",
|
|
help = "Same as the '--force-dpd' option in the openconnect command"
|
|
)]
|
|
dpd_interval: Option<u32>,
|
|
|
|
#[arg(
|
|
long = "no-xmlpost",
|
|
help = "Same as the '--no-xmlpost' option in the openconnect command"
|
|
)]
|
|
no_xmlpost: bool,
|
|
|
|
#[cfg(feature = "webview-auth")]
|
|
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
|
|
hidpi: bool,
|
|
|
|
#[cfg(feature = "webview-auth")]
|
|
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
|
|
clean: bool,
|
|
|
|
#[cfg(feature = "webview-auth")]
|
|
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
|
|
default_browser: bool,
|
|
|
|
#[cfg(feature = "webview-auth")]
|
|
#[arg(
|
|
long,
|
|
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.",
|
|
default_missing_value = "default",
|
|
num_args=0..=1
|
|
)]
|
|
browser: Option<String>,
|
|
}
|
|
|
|
impl ConnectArgs {
|
|
fn default_os() -> Os {
|
|
#[cfg(target_os = "macos")]
|
|
return Os::Mac;
|
|
#[cfg(target_os = "windows")]
|
|
return Os::Windows;
|
|
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
|
return Os::Linux;
|
|
}
|
|
|
|
fn os_version(&self) -> &str {
|
|
if let Some(os_version) = self.os_version.as_deref() {
|
|
return os_version;
|
|
}
|
|
|
|
match self.os {
|
|
Os::Linux => host_utils::get_linux_os_string(),
|
|
Os::Windows => host_utils::get_windows_os_string(),
|
|
Os::Mac => host_utils::get_macos_os_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) struct ConnectHandler<'a> {
|
|
args: &'a ConnectArgs,
|
|
shared_args: &'a SharedArgs<'a>,
|
|
latest_key_password: RefCell<Option<String>>,
|
|
password_from_stdin: RefCell<Option<String>>,
|
|
cookie_from_stdin: RefCell<Option<String>>,
|
|
}
|
|
|
|
impl<'a> ConnectHandler<'a> {
|
|
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
|
|
Self {
|
|
args,
|
|
shared_args,
|
|
latest_key_password: Default::default(),
|
|
password_from_stdin: Default::default(),
|
|
cookie_from_stdin: Default::default(),
|
|
}
|
|
}
|
|
|
|
fn user_agent(&self) -> Cow<'_, str> {
|
|
if let Some(user_agent) = self.args.user_agent.as_deref() {
|
|
Cow::Borrowed(user_agent)
|
|
} else {
|
|
let client_version = self.args.client_version.as_deref().unwrap_or(GP_CLIENT_VERSION);
|
|
Cow::Owned(format!(
|
|
"{}/{} ({})",
|
|
GP_USER_AGENT,
|
|
client_version,
|
|
self.args.os_version()
|
|
))
|
|
}
|
|
}
|
|
|
|
fn build_gp_params(&self) -> GpParams {
|
|
let mut builder = GpParams::builder();
|
|
builder
|
|
.user_agent(&self.user_agent())
|
|
.client_os(ClientOs::from(&self.args.os))
|
|
.os_version(self.args.os_version().to_owned())
|
|
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
|
.certificate(self.args.certificate.clone())
|
|
.sslkey(self.args.sslkey.clone())
|
|
.key_password(self.latest_key_password.borrow().clone());
|
|
|
|
if let Some(local_hostname) = self.args.local_hostname.as_deref() {
|
|
builder.computer(local_hostname);
|
|
}
|
|
|
|
builder.build()
|
|
}
|
|
|
|
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
|
|
#[cfg(feature = "webview-auth")]
|
|
if self.args.default_browser && self.args.browser.is_some() {
|
|
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
|
|
}
|
|
|
|
// Warn if deprecated options are used and will be removed in the future
|
|
if self.args.csd_user.is_some() {
|
|
warn!(
|
|
"The '--csd-user' option is deprecated and will be removed in future releases, please use the '--hip-user' option instead"
|
|
);
|
|
}
|
|
|
|
if self.args.csd_wrapper.is_some() {
|
|
warn!(
|
|
"The '--csd-wrapper' option is deprecated and will be removed in future releases, please use the '--hip' option instead"
|
|
);
|
|
}
|
|
|
|
self.latest_key_password.replace(self.args.key_password.clone());
|
|
|
|
loop {
|
|
let Err(err) = self.handle_impl().await else {
|
|
return Ok(());
|
|
};
|
|
|
|
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
|
|
return Err(err);
|
|
};
|
|
|
|
match root_cause {
|
|
RequestIdentityError::NoKey => {
|
|
eprintln!("ERROR: No private key found in the certificate file");
|
|
eprintln!("ERROR: Please provide the private key file using the `-k` option");
|
|
return Ok(());
|
|
}
|
|
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
|
|
// Decrypt the private key error, ask for the key password
|
|
let message = format!("Enter the {} passphrase:", cert_type);
|
|
let password = Password::new(&message)
|
|
.without_confirmation()
|
|
.with_display_mode(PasswordDisplayMode::Masked)
|
|
.prompt()?;
|
|
|
|
self.latest_key_password.replace(Some(password));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
|
|
let server = self.args.server.as_str();
|
|
let as_gateway = self.args.as_gateway;
|
|
|
|
if as_gateway {
|
|
info!("Treating the server as a gateway");
|
|
return self
|
|
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
|
|
.await;
|
|
}
|
|
|
|
let Err(err) = self.connect_portal_with_prelogin(server).await else {
|
|
return Ok(());
|
|
};
|
|
|
|
warn!("Failed to connect portal with prelogin: {}", err);
|
|
if err.root_cause().downcast_ref::<PortalError>().is_some() {
|
|
info!("Trying the gateway authentication workflow...");
|
|
self
|
|
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
|
|
.await?;
|
|
|
|
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
|
|
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
|
|
|
|
Ok(())
|
|
} else {
|
|
Err(err)
|
|
}
|
|
}
|
|
|
|
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
|
|
let gp_params = self.build_gp_params();
|
|
|
|
let prelogin = prelogin(portal, &gp_params).await?;
|
|
|
|
let cred = self.obtain_credential(&prelogin, portal).await?;
|
|
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
|
|
|
|
let selected_gateway = match &self.args.gateway {
|
|
Some(gateway) => portal_config
|
|
.find_gateway(gateway)
|
|
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
|
|
None => {
|
|
portal_config.sort_gateways(prelogin.region());
|
|
let gateways = portal_config.gateways();
|
|
|
|
if gateways.len() > 1 {
|
|
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
|
|
.with_vim_mode(true)
|
|
.prompt()?;
|
|
info!("Connecting to the selected gateway: {}", gateway);
|
|
gateway
|
|
} else {
|
|
info!("Connecting to the only available gateway: {}", gateways[0]);
|
|
gateways[0]
|
|
}
|
|
}
|
|
};
|
|
|
|
let gateway = selected_gateway.server();
|
|
let cred = portal_config.auth_cookie().into();
|
|
|
|
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await {
|
|
Ok(login_session) => login_session,
|
|
Err(err) => {
|
|
info!("Gateway login failed: {}", err);
|
|
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
|
|
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
|
|
return self
|
|
.connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session)
|
|
.await;
|
|
}
|
|
};
|
|
|
|
// Use the client version from the command line argument if specified, otherwise
|
|
// use the version from the portal config if available
|
|
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
|
|
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
|
|
|
|
self
|
|
.connect_gateway(
|
|
portal,
|
|
gateway,
|
|
&login_session.cookie,
|
|
client_version,
|
|
allow_extend_session,
|
|
login_session.extension_auth,
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn connect_gateway_with_prelogin(
|
|
&self,
|
|
portal: &str,
|
|
gateway: &str,
|
|
client_version: Option<&str>,
|
|
allow_extend_session: bool,
|
|
) -> anyhow::Result<()> {
|
|
info!("Performing the gateway authentication...");
|
|
|
|
let mut gp_params = self.build_gp_params();
|
|
gp_params.set_is_gateway(true);
|
|
|
|
let prelogin = prelogin(gateway, &gp_params).await?;
|
|
let cred = self.obtain_credential(&prelogin, gateway).await?;
|
|
|
|
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?;
|
|
|
|
self
|
|
.connect_gateway(
|
|
portal,
|
|
gateway,
|
|
&login_session.cookie,
|
|
client_version,
|
|
allow_extend_session,
|
|
login_session.extension_auth,
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn login_gateway(
|
|
&self,
|
|
gateway: &str,
|
|
cred: &Credential,
|
|
gp_params: &GpParams,
|
|
) -> anyhow::Result<GatewayLoginSession> {
|
|
let mut gp_params = gp_params.clone();
|
|
|
|
loop {
|
|
match gateway_login(gateway, cred, &gp_params).await? {
|
|
GatewayLogin::Cookie(cookie) => {
|
|
return Ok(GatewayLoginSession {
|
|
cookie,
|
|
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
|
|
});
|
|
}
|
|
GatewayLogin::Mfa(message, input_str) => {
|
|
let otp = Text::new(&message).prompt()?;
|
|
gp_params.set_input_str(&input_str);
|
|
gp_params.set_otp(&otp);
|
|
|
|
info!("Retrying gateway login with MFA...");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn connect_gateway(
|
|
&self,
|
|
portal: &str,
|
|
gateway: &str,
|
|
cookie: &str,
|
|
client_version: Option<&str>,
|
|
allow_extend_session: bool,
|
|
extension_auth: SessionExtensionAuth,
|
|
) -> anyhow::Result<()> {
|
|
let mtu = self.args.mtu.unwrap_or(0);
|
|
let (hip, csd_wrapper) = self.determine_hip_script();
|
|
let hip_user = self.determine_hip_user();
|
|
let csd_uid = get_uid(&hip_user)?;
|
|
|
|
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned();
|
|
let os_version = self.args.os_version().to_owned();
|
|
let client_version = client_version.map(|s| s.to_owned());
|
|
let session_ctx = build_session_context(SessionContextInput {
|
|
portal: portal.to_string(),
|
|
gateway: gateway.to_string(),
|
|
cookie: cookie.to_string(),
|
|
user_agent: self.user_agent().into_owned(),
|
|
os: ClientOs::from(&self.args.os),
|
|
os_version: os_version.clone(),
|
|
client_version: client_version.clone(),
|
|
certificate: self.args.certificate.clone(),
|
|
sslkey: self.args.sslkey.clone(),
|
|
key_password: self.latest_key_password.borrow().clone(),
|
|
disable_ipv6: self.args.disable_ipv6,
|
|
extension_auth: Some(extension_auth),
|
|
});
|
|
let vpn = Vpn::builder(gateway, cookie)
|
|
.script(self.args.script.clone())
|
|
.interface(self.args.interface.clone())
|
|
.script_tun(self.args.script_tun)
|
|
.user_agent(self.user_agent().into_owned())
|
|
.os(Some(os))
|
|
.os_version(Some(os_version))
|
|
.client_version(client_version)
|
|
.certificate(self.args.certificate.clone())
|
|
.sslkey(self.args.sslkey.clone())
|
|
.key_password(self.latest_key_password.borrow().clone())
|
|
.hip(hip)
|
|
.csd_uid(csd_uid)
|
|
.csd_wrapper(csd_wrapper)
|
|
.reconnect_timeout(self.args.reconnect_timeout)
|
|
.mtu(mtu)
|
|
.disable_ipv6(self.args.disable_ipv6)
|
|
.no_dtls(self.args.no_dtls)
|
|
.local_hostname(self.args.local_hostname.clone())
|
|
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
|
|
.no_xmlpost(self.args.no_xmlpost)
|
|
.build()?;
|
|
|
|
let vpn = Arc::new(vpn);
|
|
let vpn_clone = vpn.clone();
|
|
let runtime_handle = Handle::current();
|
|
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
|
|
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
|
|
let session_task_on_connect = Arc::clone(&session_task);
|
|
let session_ctx_on_connect = Arc::clone(&session_ctx);
|
|
|
|
// Listen for the interrupt signal in the background
|
|
tokio::spawn(async move {
|
|
shutdown_signal().await;
|
|
info!("Received the interrupt signal, disconnecting...");
|
|
vpn_clone.disconnect();
|
|
});
|
|
|
|
vpn.connect(move |vpn_session_info| {
|
|
write_pid_file();
|
|
|
|
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
|
|
return;
|
|
};
|
|
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
|
|
info!("VPN session info: {}", session_info.log_summary());
|
|
|
|
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
|
|
session_task_on_connect.lock().unwrap().replace(task);
|
|
});
|
|
|
|
if let Some(task) = session_task.lock().unwrap().take() {
|
|
task.abort();
|
|
}
|
|
|
|
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
|
|
info!("Removing PID file");
|
|
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
|
|
if self.args.cookie_on_stdin {
|
|
return self.read_cookie_from_stdin();
|
|
}
|
|
|
|
let is_gateway = prelogin.is_gateway();
|
|
|
|
match prelogin {
|
|
Prelogin::Saml(prelogin) => {
|
|
let browser = if prelogin.support_default_browser() {
|
|
self.args.browser.as_deref()
|
|
} else if !cfg!(feature = "webview-auth") {
|
|
bail!(
|
|
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
|
|
);
|
|
} else {
|
|
None
|
|
};
|
|
|
|
let os_version = self.args.os_version();
|
|
let verbose = self.shared_args.verbose.to_verbose_arg();
|
|
let user_agent = self.user_agent();
|
|
let auth_launcher = SamlAuthLauncher::new(&self.args.server)
|
|
.gateway(is_gateway)
|
|
.saml_request(prelogin.saml_request())
|
|
.user_agent(&user_agent)
|
|
.os(self.args.os.as_str())
|
|
.os_version(Some(&os_version))
|
|
.fix_openssl(self.shared_args.fix_openssl)
|
|
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
|
|
.browser(browser)
|
|
.verbose(verbose);
|
|
|
|
#[cfg(feature = "webview-auth")]
|
|
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
|
|
#[cfg(feature = "webview-auth")]
|
|
let auth_launcher = auth_launcher
|
|
.hidpi(self.args.hidpi)
|
|
.clean(self.args.clean)
|
|
.default_browser(use_default_browser);
|
|
|
|
let cred = auth_launcher.launch().await?;
|
|
Ok(cred)
|
|
}
|
|
|
|
Prelogin::Standard(prelogin) => {
|
|
let prefix = if is_gateway { "Gateway" } else { "Portal" };
|
|
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
|
|
|
|
let user = self.args.user.as_ref().map_or_else(
|
|
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|
|
|user| Ok(user.to_owned()),
|
|
)?;
|
|
|
|
let password = self.obtain_password(prelogin)?;
|
|
let password_cred = PasswordCredential::new(&user, &password);
|
|
|
|
Ok(password_cred.into())
|
|
}
|
|
}
|
|
}
|
|
|
|
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
|
|
// If the cookie has been read from stdin, use it directly
|
|
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
|
|
info!("Reusing the cookie read from standard input");
|
|
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
|
|
}
|
|
|
|
info!("Reading cookie from standard input");
|
|
|
|
let mut cookie = String::new();
|
|
std::io::stdin().read_line(&mut cookie)?;
|
|
|
|
// Considering that the gateway connection may fail even though the cookie read
|
|
// from stdin is correct. It may retry the gateway connection, so we need to
|
|
// save the cookie read from stdin to avoid reading stdin again.
|
|
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
|
|
|
|
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
|
|
Credential::try_from(auth_result)
|
|
}
|
|
|
|
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
|
|
let password = if self.args.passwd_on_stdin {
|
|
// If the password has been read from stdin, use it directly
|
|
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
|
|
info!("Reusing the password read from standard input");
|
|
return Ok(password.clone());
|
|
}
|
|
|
|
info!("Reading password from standard input");
|
|
let mut input = String::new();
|
|
std::io::stdin().read_line(&mut input)?;
|
|
let password = input.trim_end().to_owned();
|
|
// Considering that the gateway connection may fail even though the password read
|
|
// from stdin is correct. It may retry the gateway connection, so we need to
|
|
// save the password read from stdin to avoid reading stdin again.
|
|
self.password_from_stdin.replace(Some(password.clone()));
|
|
|
|
password
|
|
} else {
|
|
Password::new(&format!("{}:", prelogin.label_password()))
|
|
.without_confirmation()
|
|
.with_display_mode(PasswordDisplayMode::Masked)
|
|
.prompt()?
|
|
};
|
|
|
|
Ok(password)
|
|
}
|
|
|
|
fn determine_hip_script(&self) -> (bool, Option<String>) {
|
|
if let Some(hip) = &self.args.hip {
|
|
return if hip.is_empty() {
|
|
(true, None)
|
|
} else {
|
|
(true, Some(hip.clone()))
|
|
};
|
|
}
|
|
|
|
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
|
|
}
|
|
|
|
fn determine_hip_user(&self) -> Option<String> {
|
|
if let Some(hip_user) = &self.args.hip_user {
|
|
return Some(hip_user.clone());
|
|
}
|
|
|
|
self.args.csd_user.clone()
|
|
}
|
|
}
|
|
|
|
fn write_pid_file() {
|
|
let pid = std::process::id();
|
|
|
|
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) {
|
|
warn!("Failed to write PID file: {}", err);
|
|
} else {
|
|
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
|
|
}
|
|
}
|
|
|
|
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
|
|
if let Some(user) = user {
|
|
get_user_by_name(user).map(|user| user.uid())
|
|
} else {
|
|
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
|
|
}
|
|
}
|