Skip to content

Commit

Permalink
Support CAS authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
yuezk committed Apr 1, 2024
1 parent b2ca82e commit 9ab9998
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 23 deletions.
2 changes: 1 addition & 1 deletion apps/gpclient/src/launch_gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {

reqwest::Client::default()
.post(format!("{}/auth-data", service_endpoint))
.json(&auth_data)
.body(auth_data.to_string())
.send()
.await?
.error_for_status()?;
Expand Down
20 changes: 8 additions & 12 deletions crates/gpapi/src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::bail;
use anyhow::anyhow;
use regex::Regex;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -35,29 +35,25 @@ impl SamlAuthData {
}
}

pub fn parse_html(html: &str) -> anyhow::Result<SamlAuthData> {
pub fn from_html(html: &str) -> anyhow::Result<SamlAuthData> {
match parse_xml_tag(html, "saml-auth-status") {
Some(saml_status) if saml_status == "1" => {
let username = parse_xml_tag(html, "saml-username");
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");

if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
return Ok(SamlAuthData::new(
Ok(SamlAuthData::new(
username.unwrap(),
prelogin_cookie,
portal_userauthcookie,
));
))
} else {
Err(anyhow!("Found invalid auth data in HTML"))
}

bail!("Found invalid auth data in HTML");
}
Some(status) => {
bail!("Found invalid SAML status {} in HTML", status);
}
None => {
bail!("No auth data found in HTML");
}
Some(status) => Err(anyhow!("Found invalid SAML status {} in HTML", status)),
None => Err(anyhow!("No auth data found in HTML")),
}
}

Expand Down
88 changes: 79 additions & 9 deletions crates/gpapi/src/credential.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::HashMap;

use log::info;
use serde::{Deserialize, Serialize};
use specta::Type;

Expand Down Expand Up @@ -155,32 +156,59 @@ impl From<PasswordCredential> for CachedCredential {
}
}

#[derive(Debug, Serialize, Deserialize, Type, Clone)]
pub struct TokenCredential {
#[serde(alias = "un")]
username: String,
token: String,
}

impl TokenCredential {
pub fn username(&self) -> &str {
&self.username
}

pub fn token(&self) -> &str {
&self.token
}
}

#[derive(Debug, Serialize, Deserialize, Type, Clone)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Credential {
Password(PasswordCredential),
PreloginCookie(PreloginCookieCredential),
AuthCookie(AuthCookieCredential),
TokenCredential(TokenCredential),
CachedCredential(CachedCredential),
}

impl Credential {
/// Create a credential from a globalprotectcallback:<base64 encoded string>
pub fn parse_gpcallback(auth_data: &str) -> anyhow::Result<Self> {
/// Create a credential from a globalprotectcallback:<base64 encoded string>,
/// or globalprotectcallback:cas-as=1&[email protected]&token=very_long_string
pub fn from_gpcallback(auth_data: &str) -> anyhow::Result<Self> {
// Remove the surrounding quotes
let auth_data = auth_data.trim_matches('"');
let auth_data = auth_data.trim_start_matches("globalprotectcallback:");
let auth_data = decode_to_string(auth_data)?;
let auth_data = SamlAuthData::parse_html(&auth_data)?;

Self::try_from(auth_data)
if auth_data.starts_with("cas-as") {
info!("Got token auth data: {}", auth_data);
let token_cred: TokenCredential = serde_urlencoded::from_str(auth_data)?;
Ok(Self::TokenCredential(token_cred))
} else {
info!("Parsing SAML auth data...");
let auth_data = decode_to_string(auth_data)?;
let auth_data = SamlAuthData::from_html(&auth_data)?;

Self::try_from(auth_data)
}
}

pub fn username(&self) -> &str {
match self {
Credential::Password(cred) => cred.username(),
Credential::PreloginCookie(cred) => cred.username(),
Credential::AuthCookie(cred) => cred.username(),
Credential::TokenCredential(cred) => cred.username(),
Credential::CachedCredential(cred) => cred.username(),
}
}
Expand All @@ -189,20 +217,23 @@ impl Credential {
let mut params = HashMap::new();
params.insert("user", self.username());

let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None),
Credential::PreloginCookie(cred) => (None, Some(cred.prelogin_cookie()), None, None),
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::PreloginCookie(cred) => (None, Some(cred.prelogin_cookie()), None, None, None),
Credential::AuthCookie(cred) => (
None,
None,
Some(cred.user_auth_cookie()),
Some(cred.prelogon_user_auth_cookie()),
None,
),
Credential::TokenCredential(cred) => (None, None, None, None, Some(cred.token())),
Credential::CachedCredential(cred) => (
cred.password(),
None,
Some(cred.auth_cookie.user_auth_cookie()),
Some(cred.auth_cookie.prelogon_user_auth_cookie()),
None,
),
};

Expand All @@ -214,6 +245,10 @@ impl Credential {
portal_prelogonuserauthcookie.unwrap_or_default(),
);

if let Some(token) = token {
params.insert("token", token);
}

params
}
}
Expand Down Expand Up @@ -245,3 +280,38 @@ impl From<&CachedCredential> for Credential {
Self::CachedCredential(value.clone())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn cred_from_gpcallback_cas() {
let auth_data = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";

let cred = Credential::from_gpcallback(auth_data).unwrap();

match cred {
Credential::TokenCredential(token_cred) => {
assert_eq!(token_cred.username(), "[email protected]");
assert_eq!(token_cred.token(), "very_long_string");
}
_ => panic!("Expected TokenCredential"),
}
}

#[test]
fn cred_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";

let cred = Credential::from_gpcallback(auth_data).unwrap();

match cred {
Credential::PreloginCookie(cred) => {
assert_eq!(cred.username(), "[email protected]");
assert_eq!(cred.prelogin_cookie(), "prelogin-cookie");
}
_ => panic!("Expected PreloginCookieCredential")
}
}
}
13 changes: 13 additions & 0 deletions crates/gpapi/src/gp_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub struct GpParams {
computer: String,
ignore_tls_errors: bool,
prefer_default_browser: bool,
cas_support: bool,
}

impl GpParams {
Expand Down Expand Up @@ -83,6 +84,10 @@ impl GpParams {
self.prefer_default_browser
}

pub fn cas_support(&self) -> bool {
self.cas_support
}

pub fn client_os(&self) -> &str {
self.client_os.as_str()
}
Expand Down Expand Up @@ -132,6 +137,7 @@ pub struct GpParamsBuilder {
computer: String,
ignore_tls_errors: bool,
prefer_default_browser: bool,
cas_support: bool,
}

impl GpParamsBuilder {
Expand All @@ -145,6 +151,7 @@ impl GpParamsBuilder {
computer: whoami::hostname(),
ignore_tls_errors: false,
prefer_default_browser: false,
cas_support: false,
}
}

Expand Down Expand Up @@ -188,6 +195,11 @@ impl GpParamsBuilder {
self
}

pub fn cas_support(&mut self, cas_support: bool) -> &mut Self {
self.cas_support = cas_support;
self
}

pub fn build(&self) -> GpParams {
GpParams {
is_gateway: self.is_gateway,
Expand All @@ -198,6 +210,7 @@ impl GpParamsBuilder {
computer: self.computer.clone(),
ignore_tls_errors: self.ignore_tls_errors,
prefer_default_browser: self.prefer_default_browser,
cas_support: self.cas_support,
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion crates/gpapi/src/portal/prelogin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,19 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
let mut params = gp_params.to_params();

params.insert("tmp", "tmp");
if gp_params.prefer_default_browser() {
// CAS support requires external browser
if gp_params.prefer_default_browser() || gp_params.cas_support() {
params.insert("default-browser", "1");
}

if gp_params.cas_support() {
params.insert("cas-support", "yes");
}

params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k));

info!("Prelogin with params: {:?}", params);

let client = Client::builder()
.danger_accept_invalid_certs(gp_params.ignore_tls_errors())
.user_agent(user_agent)
Expand Down

0 comments on commit 9ab9998

Please sign in to comment.