feat: prepare 3.1.0 with connection details and improved authentication

Add tunnel statistics and an optional CLI dashboard, native sign-in controls and recovery, and broader client certificate support. Include platform integration fixes and the approved release notes.
This commit is contained in:
Kevin Yue committed 2026-10-19 23:47:11 +08:00
1 parent 18ed6bac1a
commit 4faa2ecb0d
158 files changed
+13752 -1038

No files matched your search

+3
View File
@@ -49,6 +49,7 @@ pub enum SamlAuthResult {
Success(SamlAuthData),
Cancelled,
Failure(String),
ServerTlsError(crate::error::ServerTlsError),
}
#[derive(Debug)]
@@ -68,6 +69,7 @@ impl SamlAuthResult {
SamlAuthResult::Success(_) => true,
SamlAuthResult::Cancelled => false,
SamlAuthResult::Failure(_) => false,
SamlAuthResult::ServerTlsError(_) => false,
}
}
@@ -76,6 +78,7 @@ impl SamlAuthResult {
SamlAuthResult::Success(auth_data) => auth_data.host_id(),
SamlAuthResult::Cancelled => None,
SamlAuthResult::Failure(_) => None,
SamlAuthResult::ServerTlsError(_) => None,
}
}
}
+48 -8
View File
@@ -4,13 +4,14 @@ use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
use log::Level;
use crate::{
error::PortalError,
error::ServerTlsErrorKind,
log_format::{LogFormat, write_json_record},
};
pub mod args;
pub trait Args {
#[cfg(not(target_os = "macos"))]
fn fix_openssl(&self) -> bool;
fn ignore_tls_errors(&self) -> bool;
@@ -26,7 +27,7 @@ pub trait Args {
/// 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 {
let Some(kind) = ServerTlsErrorKind::from_error(err) else {
return Vec::new();
};
@@ -42,14 +43,15 @@ fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
// users already see; keep it exactly.
let mut hints = Vec::new();
if err.is_legacy_openssl_error() && !args.fix_openssl() {
#[cfg(not(target_os = "macos"))]
if kind == ServerTlsErrorKind::LegacyRenegotiation && !args.fix_openssl() {
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() {
if kind == ServerTlsErrorKind::Certificate && !args.ignore_tls_errors() {
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}"
@@ -191,15 +193,25 @@ mod tests {
use anyhow::anyhow;
use super::*;
use crate::error::ServerTlsError;
fn certificate_error() -> ServerTlsError {
ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::Certificate,
}
}
#[derive(Default)]
struct TestArgs {
#[cfg(not(target_os = "macos"))]
fix_openssl: bool,
ignore_tls_errors: bool,
log_format: LogFormat,
}
impl Args for TestArgs {
#[cfg(not(target_os = "macos"))]
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
@@ -224,7 +236,7 @@ mod tests {
};
let mut out = Vec::new();
handle_error_to(&mut out, anyhow!(PortalError::TlsError), &args).expect("writing to a Vec cannot fail");
handle_error_to(&mut out, anyhow!(certificate_error()), &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() {
@@ -235,7 +247,7 @@ mod tests {
#[test]
fn a_tls_failure_suggests_ignoring_tls_errors() {
let hints = retry_hints(&anyhow!(PortalError::TlsError), &TestArgs::default());
let hints = retry_hints(&anyhow!(certificate_error()), &TestArgs::default());
assert_eq!(hints.len(), 1, "expected one hint, got {hints:?}");
assert!(hints[0].contains("--ignore-tls-errors"), "got {:?}", hints[0]);
@@ -247,6 +259,34 @@ mod tests {
);
}
#[test]
fn hints_distinguish_legacy_and_unknown_tls_and_respect_both_flags() {
let legacy = ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::LegacyRenegotiation,
};
let hints = retry_hints(&anyhow!(legacy.clone()), &TestArgs::default());
if cfg!(target_os = "macos") {
assert!(hints.is_empty());
} else {
assert_eq!(hints.len(), 1);
assert!(hints[0].contains("--fix-openssl"));
}
let args = TestArgs {
#[cfg(not(target_os = "macos"))]
fix_openssl: true,
ignore_tls_errors: true,
..Default::default()
};
assert!(retry_hints(&anyhow!(legacy), &args).is_empty());
assert!(retry_hints(&anyhow!(certificate_error()), &args).is_empty());
let other = ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::Other,
};
assert!(retry_hints(&anyhow!(other), &TestArgs::default()).is_empty());
}
/// Suggesting an option the user already passed is noise, and in JSON mode it
/// would be an extra record on every failed run.
#[test]
@@ -256,7 +296,7 @@ mod tests {
..Default::default()
};
assert!(retry_hints(&anyhow!(PortalError::TlsError), &args).is_empty());
assert!(retry_hints(&anyhow!(certificate_error()), &args).is_empty());
}
/// Most failures have no known workaround; inventing advice for them would
@@ -272,7 +312,7 @@ mod tests {
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");
write_failure(&mut out, format, &anyhow!(certificate_error()), &hints).expect("writing to a Vec cannot fail");
String::from_utf8(out).expect("output should be UTF-8")
}
+1
View File
@@ -252,6 +252,7 @@ impl TryFrom<SamlAuthResult> for Credential {
SamlAuthResult::Success(auth_data) => Ok(Self::from(auth_data)),
SamlAuthResult::Cancelled => bail!(AuthenticationCancelled),
SamlAuthResult::Failure(err) => bail!(err),
SamlAuthResult::ServerTlsError(err) => Err(err.into()),
}
}
}
+8 -9
View File
@@ -1,5 +1,8 @@
use thiserror::Error;
mod server_tls;
pub use server_tls::{ServerTlsError, ServerTlsErrorKind};
#[derive(Error, Debug)]
pub enum PortalError {
#[error("Prelogin error: {0}")]
@@ -10,18 +13,14 @@ pub enum PortalError {
#[error(transparent)]
NetworkError(#[from] reqwest::Error),
#[error("TLS error")]
TlsError,
}
impl PortalError {
pub fn is_legacy_openssl_error(&self) -> bool {
format!("{:?}", self).contains("unsafe legacy renegotiation")
}
pub fn is_tls_error(&self) -> bool {
matches!(self, PortalError::TlsError) || format!("{:?}", self).contains("certificate verify failed")
fn tls_error_kind(&self) -> Option<ServerTlsErrorKind> {
match self {
Self::NetworkError(error) => server_tls::classify(error),
_ => None,
}
}
}
+515
View File
@@ -0,0 +1,515 @@
use std::{error::Error, fmt};
use serde::{Deserialize, Serialize};
use super::PortalError;
#[cfg(target_os = "macos")]
#[path = "server_tls/macos.rs"]
mod backend;
#[cfg(not(target_os = "macos"))]
#[path = "server_tls/openssl.rs"]
mod backend;
/// A VPN HTTP TLS failure. The server identifies the configured VPN origin,
/// not necessarily the peer that failed after an HTTP redirect.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerTlsError {
pub server: String,
pub kind: ServerTlsErrorKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ServerTlsErrorKind {
Certificate,
ClientCertificateRequired,
LegacyRenegotiation,
Other,
}
impl ServerTlsError {
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
Some(Self {
server: server.origin().ascii_serialization(),
kind: classify(error)?,
})
}
}
impl fmt::Display for ServerTlsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self.kind {
ServerTlsErrorKind::Certificate => "The server's certificate could not be verified",
ServerTlsErrorKind::ClientCertificateRequired => "The server requires a client certificate",
ServerTlsErrorKind::LegacyRenegotiation => "The server requires unsafe legacy TLS renegotiation",
ServerTlsErrorKind::Other => "A secure connection to the server could not be established",
};
write!(f, "{message}: {}", self.server)
}
}
impl Error for ServerTlsError {}
impl ServerTlsErrorKind {
/// One classification interface for CLI hints and desktop error mapping.
pub fn from_error(error: &anyhow::Error) -> Option<Self> {
error.chain().find_map(|source| {
source
.downcast_ref::<ServerTlsError>()
.map(|error| error.kind)
.or_else(|| {
source
.downcast_ref::<PortalError>()
.and_then(PortalError::tls_error_kind)
})
})
}
}
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
let mut source = Some(error);
let mut fallback = None;
while let Some(error) = source {
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
return Some(tls.kind);
}
if let Some(kind) = backend::classify(error) {
return Some(kind);
}
if let Some(tls) = error.downcast_ref::<native_tls::Error>() {
let kind = classify_native(tls);
if kind != ServerTlsErrorKind::Other {
return Some(kind);
}
fallback = Some(kind);
}
source = error
.downcast_ref::<std::io::Error>()
.and_then(|error| error.get_ref().map(|inner| inner as &(dyn Error + 'static)))
.or_else(|| error.source());
}
fallback
}
fn classify_native(error: &native_tls::Error) -> ServerTlsErrorKind {
// native-tls hides some backend reason codes and verification results. Keep
// backend text matching here, scoped to a confirmed native TLS error.
let detail = format!("{error:?}").to_ascii_lowercase();
classify_native_detail(&detail)
}
fn classify_native_detail(detail: &str) -> ServerTlsErrorKind {
// native-tls forwards Security.framework's Debug representation, but hides
// its OSStatus from the public error chain. Prefer that status to localized
// text, including for peer alerts that can mention a rejected client cert.
if let Some(code) = detail
.strip_prefix("error { code: ")
.and_then(|detail| detail.split_once(','))
.and_then(|(code, _)| code.parse::<i32>().ok())
{
return classify_macos_status(code);
}
if detail.contains("unsafe legacy renegotiation") {
return ServerTlsErrorKind::LegacyRenegotiation;
}
if detail.contains("alert certificate required") {
return ServerTlsErrorKind::ClientCertificateRequired;
}
let certificate = [
"certificate verify failed",
"certificate verification failed",
"certificate was not trusted",
"certificate is not trusted",
"self signed certificate",
"hostname mismatch",
"certificate has expired",
"certificate is not yet valid",
"certificate has been revoked",
]
.iter()
.any(|reason| detail.contains(reason));
if certificate {
ServerTlsErrorKind::Certificate
} else {
ServerTlsErrorKind::Other
}
}
fn classify_macos_status(code: i32) -> ServerTlsErrorKind {
if code == -9863 {
return ServerTlsErrorKind::ClientCertificateRequired;
}
// Local server-certificate validation failures from Security/SecBase.h.
// Peer alerts (errSSLPeer*) reject our client certificate; protocol/cipher,
// keychain, and internal errors also cannot be fixed by skipping server trust.
let certificate = matches!(
code,
-9807 // errSSLXCertChainInvalid
| -9812 // errSSLUnknownRootCert
| -9813 // errSSLNoRootCert
| -9814 // errSSLCertExpired
| -9815 // errSSLCertNotYetValid
| -9843 // errSSLHostNameMismatch
| -9884 // errSSLATSLeafCertificateHashAlgorithmViolation
| -9885 // errSSLATSCertificateHashAlgorithmViolation
| -9886 // errSSLATSCertificateTrustViolation
| -67602 // errSecHostNameMismatch
| -67603 // errSecUnknownCriticalExtensionFlag
| -67604 // errSecNoBasicConstraints
| -67605 // errSecNoBasicConstraintsCA
| -67606 // errSecInvalidAuthorityKeyID
| -67607 // errSecInvalidSubjectKeyID
| -67608 // errSecInvalidKeyUsageForPolicy
| -67609 // errSecInvalidExtendedKeyUsage
| -67610 // errSecInvalidIDLinkage
| -67611 // errSecPathLengthConstraintExceeded
| -67612 // errSecInvalidRoot
| -67629 // errSecSSLBadExtendedKeyUsage
| -67654 // errSecTrustSettingDeny
| -67818 // errSecCertificateExpired
| -67819 // errSecCertificateNotValidYet
| -67820 // errSecCertificateRevoked
| -67821 // errSecCertificateSuspended
| -67826 // errSecInvalidCertAuthority
| -67843 // errSecNotTrusted
| -67899 // errSecCertificatePolicyNotAllowed
| -67900 // errSecCertificateNameNotAllowed
| -67901 // errSecCertificateValidityPeriodTooLong
| -67902 // errSecCertificateIsCA
| -67903 // errSecCertificateDuplicateExtension
| -67904 // errSecMissingQualifiedCertStatement
);
if certificate {
ServerTlsErrorKind::Certificate
} else {
ServerTlsErrorKind::Other
}
}
#[cfg(test)]
mod tests {
use super::*;
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
pkey::PKey,
rsa::Rsa,
ssl::{SslAcceptor, SslMethod, SslVerifyMode},
x509::{X509, X509NameBuilder},
};
use std::{
io::{Read, Write},
net::TcpListener,
thread,
time::Duration,
};
#[test]
fn explicit_client_certificate_requirement_has_a_distinct_kind() {
let kind = classify_native_detail("error { code: -9863, message: \"localized message\" }");
assert_eq!(serde_json::to_value(kind).unwrap(), "clientCertificateRequired");
assert_eq!(
classify_native_detail("error { code: -9842, message: \"client cert requested\" }"),
ServerTlsErrorKind::Other
);
}
#[test]
fn macos_certificate_statuses_do_not_depend_on_the_error_message() {
for code in [-67818, -67819, -67820, -67843, -67602, -67629, -67899, -67901] {
let detail = format!("error {{ code: {code}, message: \"localized message\" }}");
assert_eq!(
classify_native_detail(&detail),
ServerTlsErrorKind::Certificate,
"{code}"
);
}
}
#[test]
fn macos_peer_alerts_and_handshake_errors_are_not_certificate_validation_failures() {
for (code, message) in [
(-9800, "SSL protocol error"),
(-9801, "Cipher Suite negotiation failure"),
(-9828, "peer certificate has expired"),
(-9831, "unknown certificate authority"),
(-9850, "weak ephemeral DH key"),
] {
let detail = format!("error {{ code: {code}, message: \"{message}\" }}").to_ascii_lowercase();
assert_eq!(classify_native_detail(&detail), ServerTlsErrorKind::Other, "{code}");
}
}
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
server_with_client_auth(tls, SslVerifyMode::NONE)
}
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "localhost").unwrap();
let name = name.build();
let mut cert = X509::builder().unwrap();
cert.set_version(2).unwrap();
cert.set_subject_name(&name).unwrap();
cert.set_issuer_name(&name).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();
cert.sign(&key, MessageDigest::sha256()).unwrap();
let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
acceptor.set_private_key(&key).unwrap();
acceptor.set_certificate(&cert.build()).unwrap();
acceptor.set_verify(verify);
acceptor
.set_ca_file(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/files/client-identity/root.pem"
))
.unwrap();
let acceptor = acceptor.build();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("https://{}", listener.local_addr().unwrap());
let worker = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
let body = "<prelogin-response><status>Success</status><saml-auth-method>REDIRECT</saml-auth-method><saml-request>aHR0cHM6Ly9pZHAuZXhhbXBsZS5jb20v</saml-request></prelogin-response>";
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let mut request = [0; 8192];
if tls {
if let Ok(mut stream) = acceptor.accept(stream) {
let _ = stream.read(&mut request);
let _ = stream.write_all(response.as_bytes());
}
} else {
let _ = stream.read(&mut request);
let _ = stream.write_all(response.as_bytes());
}
});
(address, worker)
}
#[tokio::test]
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
let (address, worker) = server(true);
let profile = OsProfile::builder(ClientOs::Linux).build();
let params = GpParams::builder(profile).build();
let error = prelogin(&address, &params, PreloginOptions::default())
.await
.unwrap_err();
worker.join().unwrap();
let tls = error
.downcast_ref::<ServerTlsError>()
.unwrap_or_else(|| panic!("unclassified: {error:?}"));
assert_eq!(tls.kind, ServerTlsErrorKind::Certificate);
assert_eq!(tls.server, address);
}
#[tokio::test]
async fn certificate_bypass_allows_prelogin() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
let (address, worker) = server(true);
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
.ignore_tls_errors(true)
.build();
let result = prelogin(&address, &params, PreloginOptions::default()).await;
worker.join().unwrap();
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
}
#[tokio::test]
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
let (address, worker) = server(false);
let error = reqwest::Client::builder()
.no_proxy()
.danger_accept_invalid_certs(true)
.build()
.unwrap()
.get(&address)
.send()
.await
.unwrap_err();
worker.join().unwrap();
let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::Other);
}
#[tokio::test]
async fn connection_refused_is_not_tls() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("https://{}", listener.local_addr().unwrap());
drop(listener);
let error = reqwest::Client::builder()
.no_proxy()
.build()
.unwrap()
.get(address)
.send()
.await
.unwrap_err();
assert_eq!(classify(&error), None);
}
#[cfg(target_os = "macos")]
#[test]
fn wrapped_macos_io_status_retains_the_client_certificate_requirement() {
let error = std::io::Error::other(std::io::Error::other(security_framework::base::Error::from(-9863)));
let server = url::Url::parse("https://vpn.example.com/login?token=secret").unwrap();
let tls = ServerTlsError::from_request(&server, &error).unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::ClientCertificateRequired);
assert_eq!(tls.server, "https://vpn.example.com");
assert_eq!(classify(&std::io::Error::other("alert certificate required")), None);
}
#[test]
fn rendering_recovery_retains_client_certificate_requirement() {
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
use std::os::unix::process::ExitStatusExt;
let mut recovery = RecoveryState::default();
assert!(
recovery.recover(
&RenderingCrash {
status: std::process::ExitStatus::from_raw(71 << 8)
}
.into()
)
);
let error = recovery.terminal(
ServerTlsError {
server: "https://vpn.example.com".into(),
kind: ServerTlsErrorKind::ClientCertificateRequired,
}
.into(),
);
assert_eq!(
ServerTlsErrorKind::from_error(&error),
Some(ServerTlsErrorKind::ClientCertificateRequired)
);
}
#[tokio::test]
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build())
.ignore_tls_errors(true)
.build();
let credential = crate::credential::PasswordCredential::new("alice", "password").into();
let cancellation = tokio_util::sync::CancellationToken::new();
for operation in ["prelogin", "config", "gateway"] {
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
let error = match operation {
"prelogin" => prelogin(&address, &params, PreloginOptions::default())
.await
.err()
.unwrap(),
"config" => crate::portal::retrieve_config(&address, &credential, &params, &cancellation)
.await
.err()
.unwrap(),
_ => crate::gateway::GatewayLoginClient::new(&address, params.clone())
.unwrap()
.login(&credential, None, &cancellation)
.await
.err()
.unwrap(),
};
worker.join().unwrap();
let kind =
ServerTlsErrorKind::from_error(&error).unwrap_or_else(|| panic!("{operation}: unclassified: {error:?}"));
// Secure Transport's TLS 1.2 handshake can return only a generic peer alert.
if cfg!(target_os = "macos") {
assert!(matches!(
kind,
ServerTlsErrorKind::ClientCertificateRequired | ServerTlsErrorKind::Other
));
} else {
assert_eq!(
kind,
ServerTlsErrorKind::ClientCertificateRequired,
"{operation}: {error:?}"
);
}
}
}
#[tokio::test]
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
use crate::{
gp_params::GpParams,
os_profile::{ClientOs, OsProfile},
portal::{PreloginOptions, prelogin},
};
for required in [false, true] {
let verify = if required {
SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT
} else {
SslVerifyMode::PEER
};
let (address, worker) = server_with_client_auth(true, verify);
let mut builder = GpParams::builder(OsProfile::builder(ClientOs::Linux).build());
builder.ignore_tls_errors(true);
if required {
builder
.certificate(Some(
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/files/client-identity/rsa-cert.pem").to_owned(),
))
.sslkey(Some(
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/files/client-identity/rsa-pkcs8.pem").to_owned(),
));
}
let result = prelogin(&address, &builder.build(), PreloginOptions::default()).await;
worker.join().unwrap();
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
}
}
#[tokio::test]
async fn failed_response_reads_preserve_the_transport_cause() {
for status in [200, 403] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("http://{}", listener.local_addr().unwrap());
let worker = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut request = [0; 8192];
stream.read(&mut request).unwrap();
write!(
stream,
"HTTP/1.1 {status} Test\r\nContent-Length: 100\r\nConnection: close\r\n\r\ntruncated"
)
.unwrap();
});
let response = reqwest::Client::builder()
.no_proxy()
.build()
.unwrap()
.get(address)
.send()
.await
.unwrap();
let error = crate::utils::parse_gp_response(response).await.unwrap_err();
assert_eq!(error.status.as_u16(), status);
assert!(error.source().unwrap().is::<reqwest::Error>());
worker.join().unwrap();
}
}
}
@@ -0,0 +1,9 @@
use std::error::Error;
use super::{ServerTlsErrorKind, classify_macos_status};
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
error
.downcast_ref::<security_framework::base::Error>()
.map(|error| classify_macos_status(error.code()))
}
@@ -0,0 +1,17 @@
use std::error::Error;
use super::ServerTlsErrorKind;
pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKind> {
let stack = error.downcast_ref::<openssl::error::ErrorStack>().or_else(|| {
error
.downcast_ref::<openssl::ssl::Error>()
.and_then(openssl::ssl::Error::ssl_error)
})?;
// ERR_LIB_SSL and SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED from sslerr.h.
stack
.errors()
.iter()
.any(|error| error.library_code() == 20 && error.reason_code() == 1116)
.then_some(ServerTlsErrorKind::ClientCertificateRequired)
}
+7 -1
View File
@@ -254,12 +254,18 @@ async fn receive_gateway_login(
.await
.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
match crate::error::ServerTlsError::from_request(origin, &e) {
Some(tls) => anyhow::anyhow!(tls),
None => 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| {
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
return anyhow::anyhow!(tls);
}
warn!("Gateway login response failed: {}", err.reason);
anyhow::anyhow!("Gateway login error: {}", err.reason)
})?;
+17 -3
View File
@@ -10,7 +10,7 @@ use xmltree::Element;
use crate::{
credential::{AuthCookieCredential, Credential},
error::PortalError,
error::{PortalError, ServerTlsError},
gateway::{Gateway, parse_gateways},
gp_params::GpParams,
params,
@@ -149,6 +149,7 @@ pub async fn retrieve_config(
cancellation: &CancellationToken,
) -> anyhow::Result<PortalConfig> {
let portal = normalize_server(portal)?;
let server_url = url::Url::parse(&portal)?;
let server = remove_url_scheme(&portal);
let url = format!("{}/global-protect/getconfig.esp", portal);
@@ -170,10 +171,16 @@ pub async fn retrieve_config(
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))
match ServerTlsError::from_request(&server_url, &e) {
Some(tls) => anyhow::anyhow!(tls),
None => anyhow::anyhow!(PortalError::NetworkError(e)),
}
})?;
parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
return Err(anyhow::anyhow!(tls));
}
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("Config endpoint not found".to_string()));
}
@@ -227,16 +234,23 @@ async fn retrieve_csc_config(
let swg_nonce = csc::swg_nonce();
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
let server_url = url::Url::parse(portal)?;
info!("Portal CSC config request summary: {}", csc_req.summary());
info!("Portal CSC config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
match ServerTlsError::from_request(&server_url, &e) {
Some(tls) => anyhow::anyhow!(tls),
None => anyhow::anyhow!(PortalError::NetworkError(e)),
}
})?;
parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = ServerTlsError::from_request(&server_url, &err) {
return Err(anyhow::anyhow!(tls));
}
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
}
+8 -1
View File
@@ -135,6 +135,7 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
);
let client = Client::try_from(gp_params)?;
let server_url = url::Url::parse(&portal)?;
let mut request = client.post(&prelogin_url);
if !request_params.query.is_empty() {
@@ -146,10 +147,16 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
let res = request.send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
match crate::error::ServerTlsError::from_request(&server_url, &e) {
Some(error) => anyhow!(error),
None => anyhow!(PortalError::NetworkError(e)),
}
})?;
let res_xml = parse_gp_response(res).await.or_else(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) {
return Err(anyhow!(tls));
}
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string()))
}
+58 -3
View File
@@ -33,6 +33,7 @@ pub struct SamlAuthLauncher<'a> {
certificate: Option<&'a str>,
sslkey: Option<&'a str>,
key_password: Option<&'a str>,
#[cfg(not(target_os = "macos"))]
fix_openssl: bool,
ignore_tls_errors: bool,
#[cfg(feature = "webview-auth")]
@@ -66,6 +67,7 @@ impl<'a> SamlAuthLauncher<'a> {
certificate: None,
sslkey: None,
key_password: None,
#[cfg(not(target_os = "macos"))]
fix_openssl: false,
ignore_tls_errors: false,
#[cfg(feature = "webview-auth")]
@@ -113,6 +115,7 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
#[cfg(not(target_os = "macos"))]
pub fn fix_openssl(mut self, fix_openssl: bool) -> Self {
self.fix_openssl = fix_openssl;
self
@@ -226,6 +229,7 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--client-version").arg(client_version);
}
#[cfg(not(target_os = "macos"))]
if self.fix_openssl {
auth_cmd.arg("--fix-openssl");
}
@@ -343,10 +347,12 @@ impl<'a> SamlAuthLauncher<'a> {
}
}
/// `gpauth --browser remote` reads the pasted `globalprotectcallback:` data from the user's terminal.
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
match browser {
Some(browser) if browser.eq_ignore_ascii_case("remote") => ChildInput::Terminal,
Some(browser) if browser.eq_ignore_ascii_case("manual") || browser.eq_ignore_ascii_case("remote") => {
ChildInput::Terminal
}
_ => ChildInput::Null,
}
}
@@ -376,6 +382,53 @@ mod tests {
use super::*;
use crate::os_profile::{ClientOs, OsProfileBuilder};
#[test]
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
stderr: Vec::new(),
};
let error = decode_auth_output(output, false).unwrap_err();
assert_eq!(
error.downcast_ref::<ServerTlsError>(),
Some(&ServerTlsError {
server: "https://vpn.example.com:8443".into(),
kind: ServerTlsErrorKind::Certificate,
})
);
}
#[test]
fn client_certificate_required_result_survives_process_decoding() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
stderr: Vec::new(),
};
let error = decode_auth_output(output, false).unwrap_err();
let tls = error.downcast_ref::<ServerTlsError>().unwrap();
assert_eq!(tls.kind, ServerTlsErrorKind::ClientCertificateRequired);
assert_eq!(tls.server, "https://vpn.example.com");
}
#[test]
fn launches_with_platform_tls_options() {
let launcher = SamlAuthLauncher::new("vpn.example.com").ignore_tls_errors(true);
#[cfg(not(target_os = "macos"))]
let launcher = launcher.fix_openssl(true);
let args = child_args(launcher);
assert_eq!(
args.iter().any(|arg| arg == "--fix-openssl"),
!cfg!(target_os = "macos")
);
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
}
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux).client_version("6.0.0").build();
@@ -463,7 +516,9 @@ mod tests {
}
#[test]
fn only_a_remote_browser_reads_the_terminal() {
fn only_a_manual_browser_reads_the_terminal() {
assert!(matches!(auth_stdin(Some("manual")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("MANUAL")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("remote")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("REMOTE")), ChildInput::Terminal));
assert!(matches!(auth_stdin(Some("firefox")), ChildInput::Null));
+1
View File
@@ -5,6 +5,7 @@ use crate::service::{vpn_env::VpnEnv, vpn_state::VpnState};
/// Events that can be emitted by the service
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum WsEvent {
TunnelState(Option<crate::session::tunnel::TunnelState>),
VpnEnv(VpnEnv),
VpnState(VpnState),
ActiveGui,
+1
View File
@@ -380,6 +380,7 @@ pub struct UpdateLogLevelRequest(pub String);
/// Requests that can be sent to the service
#[derive(Debug, Deserialize, Serialize)]
pub enum WsRequest {
SetTunnelStatisticsEnabled { enabled: bool },
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
@@ -17,6 +17,9 @@ pub enum ClientMessage {
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServerMessage {
TunnelStatistics {
snapshot: crate::session::tunnel::TunnelStatisticsSnapshot,
},
Attached {
connection_id: Uuid,
current_revision: u64,
@@ -39,6 +42,7 @@ pub enum ServerMessage {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServiceResult {
TunnelStatisticsSnapshot(crate::session::tunnel::TunnelStatisticsSnapshot),
Accepted,
StoredHipReport {
report_id: String,
@@ -192,4 +196,73 @@ mod tests {
let encoded = encode(&message).unwrap();
assert!(encoded.len() <= MAX_PLAINTEXT);
}
#[test]
fn full_configuration_and_large_metadata_fit_complete_snapshot_envelopes_at_the_budget() {
use crate::{
os_profile::HostIdentity,
service::{
vpn_env::HostInfo,
vpn_state::{ConnectedInfo, VpnState},
},
session::tunnel::{MAX_CONFIGURATION_BYTES, TunnelConfiguration, TunnelPhase, TunnelState, TunnelTransport},
};
let mut configuration = TunnelConfiguration::default();
configuration.included_routes.items = vec!["r".repeat(1024); 15];
configuration.included_routes.items.push(String::new());
configuration.included_routes.total_count = 16;
let padding = MAX_CONFIGURATION_BYTES - serde_json::to_vec(&configuration).unwrap().len();
assert!(padding <= 1024);
*configuration.included_routes.items.last_mut().unwrap() = "r".repeat(padding);
assert_eq!(
serde_json::to_vec(&configuration).unwrap().len(),
MAX_CONFIGURATION_BYTES
);
let gateway = Gateway::new("Gateway".repeat(20), "vpn.example.com".into());
let info = ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway; 32]);
let snapshot = VpnEnv {
tunnel_state: Some(TunnelState {
tunnel_id: Uuid::new_v4(),
sequence: u64::MAX,
phase: TunnelPhase::Connected,
configuration_revision: u64::MAX,
configuration: Some(configuration),
transport: TunnelTransport::IpsecEsp,
elapsed_ms: u64::MAX,
}),
vpn_state: VpnState::Connected(Box::new(ConnectedInfo::new(info, None))),
vpnc_script: Some("s".repeat(1024)),
auth_executable: "a".repeat(1024),
host_info: HostInfo {
host_identity: HostIdentity::collect(),
},
};
for mut message in [
ServerMessage::Attached {
connection_id: Uuid::new_v4(),
current_revision: u64::MAX,
snapshot: snapshot.clone(),
},
ServerMessage::Snapshot {
current_revision: u64::MAX,
snapshot,
},
] {
let remaining = MAX_PLAINTEXT - encode(&message).unwrap().len();
let snapshot = match &mut message {
ServerMessage::Attached { snapshot, .. } | ServerMessage::Snapshot { snapshot, .. } => snapshot,
_ => unreachable!(),
};
// Existing host/connection metadata has no declared maximum. Fill the
// remaining envelope budget, then assert its actual boundary explicitly.
snapshot.auth_executable.push_str(&"a".repeat(remaining));
assert_eq!(encode(&message).unwrap().len(), MAX_PLAINTEXT);
let snapshot = match &mut message {
ServerMessage::Attached { snapshot, .. } | ServerMessage::Snapshot { snapshot, .. } => snapshot,
_ => unreachable!(),
};
snapshot.auth_executable.push('a');
assert!(matches!(encode(&message), Err(TransportError::MessageTooLarge)));
}
}
}
+1
View File
@@ -18,6 +18,7 @@ pub struct HostInfo {
/// to the client so that it can configure itself accordingly.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VpnEnv {
pub tunnel_state: Option<crate::session::tunnel::TunnelState>,
/// The VPN connection state
pub vpn_state: VpnState,
+1
View File
@@ -9,6 +9,7 @@ mod gateway_sessions;
pub mod network;
pub mod non_tunnel;
pub mod transport;
pub mod tunnel;
pub use connection::*;
pub use gateway_sessions::{ClientAddresses, GatewaySession, GatewaySessions};
+1 -1
View File
@@ -223,7 +223,7 @@ impl PhysicalNetwork {
}
fn fingerprint(&self) -> anyhow::Result<String> {
Ok(sha256::digest(serde_json::to_vec(&self.snapshot)?))
Ok(crate::utils::checksum::sha256_hex(serde_json::to_vec(&self.snapshot)?))
}
pub fn capture(control: &dyn CollectionControl) -> anyhow::Result<Self> {
+2 -2
View File
@@ -320,8 +320,8 @@ fn parse_hip_check(root: &Element) -> Result<HipCheck, GatewayRequestError> {
.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.
// Accept response delays up to one hour as a client policy, not a
// wire-protocol maximum.
if delay > 3600 {
return Err(GatewayRequestError::MalformedResponse);
}
+353
View File
@@ -0,0 +1,353 @@
//! Observed tunnel data, shared by standalone clients and service consumers.
//! These values describe negotiated settings, not verified operating-system state.
use serde::{Deserialize, Serialize};
use specta::Type;
use uuid::Uuid;
pub const MAX_CONFIGURATION_BYTES: usize = 16 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TunnelPhase {
Establishing,
Connected,
Reconnecting,
Ended,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TunnelTransport {
Negotiating,
IpsecEsp,
SslTls,
Unavailable,
}
impl TunnelTransport {
pub fn is_active(self) -> bool {
matches!(self, Self::IpsecEsp | Self::SslTls)
}
pub fn label(self) -> &'static str {
match self {
Self::Negotiating => "Negotiating",
Self::IpsecEsp => "IPsec (ESP)",
Self::SslTls => "SSL/TLS",
Self::Unavailable => "Unavailable",
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelList {
pub items: Vec<String>,
pub total_count: u32,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelAddress {
pub address: String,
pub netmask: Option<String>,
pub prefix_length: Option<u8>,
}
impl TunnelAddress {
pub fn display(&self) -> String {
match self.prefix_length {
Some(prefix) => format!("{}/{prefix}", self.address),
None => match &self.netmask {
Some(netmask) => format!("{} (mask {netmask})", self.address),
None => self.address.clone(),
},
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelConfiguration {
pub interface: Option<String>,
pub ipv4: Option<TunnelAddress>,
pub ipv6: Option<TunnelAddress>,
pub server_ip: Option<String>,
pub dns: TunnelList,
pub search_domains: TunnelList,
pub split_dns: TunnelList,
pub included_routes: TunnelList,
pub excluded_routes: TunnelList,
pub mtu: Option<u32>,
pub truncated: bool,
}
impl TunnelConfiguration {
/// Bound observation payloads without modifying native network configuration.
/// Whole list entries are omitted before shortening scalar text. Counts and
/// truncation flags preserve the distinction between absent and omitted data.
/// Returns false if even the fixed JSON shape cannot fit the supplied budget.
pub fn limit_encoded_size(&mut self, limit: usize) -> bool {
while serde_json::to_vec(self).expect("configuration is serializable").len() > limit {
self.truncated = true;
let lists = [
&mut self.excluded_routes,
&mut self.included_routes,
&mut self.split_dns,
&mut self.search_domains,
&mut self.dns,
];
if let Some(list) = lists.into_iter().find(|list| !list.items.is_empty()) {
list.items.pop();
list.truncated = true;
continue;
}
let mut scalars = vec![&mut self.interface, &mut self.server_ip];
if let Some(address) = &mut self.ipv4 {
scalars.push(&mut address.netmask);
if address.address.len() > 128 {
address.address.truncate(address.address.floor_char_boundary(128));
address.prefix_length = None;
}
}
if let Some(address) = &mut self.ipv6 {
scalars.push(&mut address.netmask);
if address.address.len() > 128 {
address.address.truncate(address.address.floor_char_boundary(128));
address.prefix_length = None;
}
}
match scalars
.into_iter()
.max_by_key(|value| value.as_ref().map_or(0, String::len))
{
Some(Some(text)) if !text.is_empty() => {
text.truncate(text.floor_char_boundary(text.len() / 2));
}
_ => return serde_json::to_vec(self).expect("configuration is serializable").len() <= limit,
}
}
true
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelState {
pub tunnel_id: Uuid,
#[serde(with = "decimal")]
#[specta(type = String)]
pub sequence: u64,
pub phase: TunnelPhase,
#[serde(with = "decimal")]
#[specta(type = String)]
pub configuration_revision: u64,
pub configuration: Option<TunnelConfiguration>,
pub transport: TunnelTransport,
#[serde(with = "decimal")]
#[specta(type = String)]
pub elapsed_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelStatistics {
pub tunnel_id: Uuid,
#[serde(with = "decimal")]
#[specta(type = String)]
pub sequence: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub state_sequence: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub configuration_revision: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub elapsed_ms: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub received_bytes: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub sent_bytes: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub received_packets: u64,
#[serde(with = "decimal")]
#[specta(type = String)]
pub sent_packets: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TunnelStatisticsState {
Disabled,
Waiting,
Fresh,
Stale,
Ended,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TunnelStatisticsView {
#[serde(with = "decimal")]
#[specta(type = String)]
pub sequence: u64,
pub tunnel_id: Uuid,
#[serde(with = "decimal")]
#[specta(type = String)]
pub state_sequence: u64,
pub phase: TunnelPhase,
pub transport: TunnelTransport,
pub state: TunnelStatisticsState,
#[serde(with = "decimal")]
#[specta(type = String)]
pub elapsed_ms: u64,
#[serde(with = "optional_decimal")]
#[specta(type = Option<String>)]
pub sample_age_ms: Option<u64>,
pub sample: Option<TunnelStatistics>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum TunnelUnavailableReason {
NoTunnel,
NonTunnel,
ObservationFailed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum TunnelStatisticsSnapshot {
Available(TunnelStatisticsView),
Unavailable { reason: TunnelUnavailableReason },
}
impl TunnelStatisticsSnapshot {
pub fn unavailable(reason: TunnelUnavailableReason) -> Self {
Self::Unavailable { reason }
}
pub fn view(&self) -> Option<&TunnelStatisticsView> {
match self {
Self::Available(view) => Some(view),
Self::Unavailable { .. } => None,
}
}
pub fn tunnel_id(&self) -> Option<Uuid> {
self.view().map(|view| view.tunnel_id)
}
pub fn sequence(&self) -> Option<u64> {
self.view().map(|view| view.sequence)
}
pub fn state_sequence(&self) -> Option<u64> {
self.view().map(|view| view.state_sequence)
}
pub fn disabled(&self) -> Self {
let mut snapshot = self.clone();
if let Self::Available(view) = &mut snapshot {
if view.state != TunnelStatisticsState::Ended {
view.state = TunnelStatisticsState::Disabled;
}
}
snapshot
}
pub fn stale(&self) -> Self {
let mut snapshot = self.clone();
if let Self::Available(view) = &mut snapshot {
if matches!(
view.state,
TunnelStatisticsState::Fresh | TunnelStatisticsState::Waiting
) {
view.state = TunnelStatisticsState::Stale;
}
}
snapshot
}
}
mod decimal {
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(value: &u64, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(value)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
let value = String::deserialize(deserializer)?;
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(serde::de::Error::custom("expected an unsigned decimal string"));
}
value.parse().map_err(serde::de::Error::custom)
}
}
mod optional_decimal {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(value: &Option<u64>, serializer: S) -> Result<S::Ok, S::Error> {
value.map(|value| value.to_string()).serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<u64>, D::Error> {
Option::<String>::deserialize(deserializer)?
.map(|value| {
if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(serde::de::Error::custom("expected an unsigned decimal string"));
}
value.parse().map_err(serde::de::Error::custom)
})
.transpose()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counters_above_javascript_precision_round_trip_as_decimal_strings() {
let sample = TunnelStatistics {
tunnel_id: Uuid::nil(),
sequence: 1,
state_sequence: 1,
configuration_revision: 1,
elapsed_ms: 1000,
received_bytes: (1_u64 << 53) + 1,
sent_bytes: u64::MAX,
received_packets: 3,
sent_packets: 4,
};
let value = serde_json::to_value(&sample).unwrap();
assert_eq!(value["receivedBytes"], "9007199254740993");
assert_eq!(value["sentBytes"], "18446744073709551615");
assert_eq!(
serde_json::from_value::<TunnelStatistics>(value.clone()).unwrap(),
sample
);
let mut numeric = value;
numeric["receivedBytes"] = serde_json::json!(9007199254740993_u64);
assert!(serde_json::from_value::<TunnelStatistics>(numeric).is_err());
}
#[test]
fn unavailable_has_no_synthetic_counters() {
let snapshot = TunnelStatisticsSnapshot::unavailable(TunnelUnavailableReason::NonTunnel);
let value = serde_json::to_value(&snapshot).unwrap();
assert_eq!(value, serde_json::json!({"kind": "unavailable", "reason": "nonTunnel"}));
assert_eq!(
serde_json::from_value::<TunnelStatisticsSnapshot>(value).unwrap(),
snapshot
);
}
}
+76 -3
View File
@@ -1,10 +1,43 @@
use std::path::Path;
use std::{
fmt::Write as _,
fs::File,
io::{self, Read},
path::Path,
};
use anyhow::bail;
use sha2::{Digest, Sha256};
pub fn sha256_hex(data: impl AsRef<[u8]>) -> String {
digest_hex(&Sha256::digest(data.as_ref()))
}
pub fn file_sha256(path: impl AsRef<Path>) -> io::Result<String> {
let mut file = File::open(path)?;
let mut hasher = Sha256::new();
let mut buffer = [0; 8192];
loop {
let count = match file.read(&mut buffer) {
Ok(0) => break,
Ok(count) => count,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
hasher.update(&buffer[..count]);
}
Ok(digest_hex(&hasher.finalize()))
}
fn digest_hex(digest: &[u8]) -> String {
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
write!(&mut hex, "{byte:02x}").expect("writing to a String cannot fail");
}
hex
}
pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
let file = Path::new(&path);
let checksum = sha256::try_digest(&file)?;
let checksum = file_sha256(path)?;
if checksum != expected {
bail!("Checksum mismatch, expected: {}, actual: {}", expected, checksum);
@@ -12,3 +45,43 @@ pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::Write;
use super::*;
#[test]
fn known_sha256_vectors_use_lowercase_hex() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn hashes_files_across_buffer_boundaries_and_checks_expected_digest() {
let mut file = tempfile::NamedTempFile::new().unwrap();
file.write_all(&vec![b'a'; 1_000_000]).unwrap();
let expected = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
assert_eq!(file_sha256(file.path()).unwrap(), expected);
verify_checksum(file.path().to_str().unwrap(), expected).unwrap();
assert!(verify_checksum(file.path().to_str().unwrap(), "wrong").is_err());
}
#[test]
fn hashes_empty_files_and_propagates_file_errors() {
let file = tempfile::NamedTempFile::new().unwrap();
assert_eq!(file_sha256(file.path()).unwrap(), sha256_hex(b""));
let directory = tempfile::tempdir().unwrap();
let error = file_sha256(directory.path().join("missing")).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
assert!(file_sha256(directory.path()).is_err());
}
}
+219
View File
@@ -0,0 +1,219 @@
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
use pkcs8::{
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
der::{
Decode, Reader, SliceReader, Tag, Tagged,
asn1::{AnyRef, OctetStringRef, SequenceRef},
},
};
use zeroize::Zeroizing;
use super::{request::RequestIdentityError, traditional_key};
pub(super) enum TraditionalKeyFormat {
Sec1Der,
PlainPem,
EncryptedPem,
}
struct PemBlock {
tag: String,
headers: pem::HeaderMap,
contents: Zeroizing<Vec<u8>>,
}
impl PemBlock {
fn encoded(&self) -> Zeroizing<Vec<u8>> {
let mut block = pem::Pem::new(&self.tag, self.contents.as_slice());
*block.headers_mut() = self.headers.clone();
let encoded = Zeroizing::new(pem::encode(&block).into_bytes());
// The PEM crate owns a copy of the decoded private key as well.
drop(Zeroizing::new(block.into_contents()));
encoded
}
}
fn is_pem(bytes: &[u8]) -> bool {
bytes.windows(b"-----BEGIN".len()).any(|part| part == b"-----BEGIN")
}
// Adopt decoded blocks immediately, including ignored keys in combined files.
fn blocks(bytes: &[u8]) -> Result<Vec<PemBlock>, pem::PemError> {
Ok(
pem::parse_many(bytes)?
.into_iter()
.map(|block| PemBlock {
tag: block.tag().to_owned(),
headers: block.headers().clone(),
contents: Zeroizing::new(block.into_contents()),
})
.collect(),
)
}
pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<Zeroizing<Vec<u8>>> {
let pem_input = is_pem(bytes);
let block = if pem_input {
blocks(bytes)
.map_err(|_| RequestIdentityError::InvalidKey)?
.into_iter()
.find(|block| block.tag.ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?
} else {
// Unlike combined PEM, a standalone DER certificate cannot include a key.
if x509_cert::Certificate::from_der(bytes).is_ok() {
return Err(RequestIdentityError::NoKey.into());
}
PemBlock {
tag: der_key_tag(bytes)
.map_err(|_| RequestIdentityError::InvalidKey)?
.to_owned(),
headers: pem::HeaderMap::default(),
contents: Zeroizing::new(bytes.to_vec()),
}
};
let der = &block.contents;
let document = if traditional_encryption(&block)? {
if !matches!(block.tag.as_str(), "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
return Err(RequestIdentityError::InvalidKey.into());
}
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::EncryptedPem, passphrase)?
} else {
match block.tag.as_str() {
"PRIVATE KEY" => SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?,
"RSA PRIVATE KEY" => {
// PKCS#8 stores the original PKCS#1 bytes inside an RSA algorithm envelope.
// Native TLS validates the RSA key, as it does for existing PKCS#8 input.
let algorithm = AlgorithmIdentifierRef {
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
parameters: Some(AnyRef::NULL),
};
let private_key = OctetStringRef::new(der).map_err(|_| RequestIdentityError::InvalidKey)?;
let info = PrivateKeyInfoRef::new(algorithm, private_key);
SecretDocument::encode_msg(&info).map_err(|_| RequestIdentityError::InvalidKey)?
}
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
"EC PRIVATE KEY" => {
if pem_input {
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::PlainPem, passphrase)?
} else {
traditional_key::normalize(der, TraditionalKeyFormat::Sec1Der, passphrase)?
}
}
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
}
};
PrivateKeyInfoRef::from_der(document.as_bytes()).map_err(|_| RequestIdentityError::InvalidKey)?;
let pem = document.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
Ok(Zeroizing::new(pem.as_bytes().to_vec()))
}
// Only choose a container here. The selected decoder/native importer validates
// the key. Decoding the complete outer sequence rejects concatenated DER input.
fn der_key_tag(bytes: &[u8]) -> Result<&'static str, pkcs8::der::Error> {
let sequence = <&SequenceRef>::from_der(bytes)?;
let mut reader = SliceReader::new(sequence.as_bytes())?;
let first: AnyRef = reader.decode()?;
Ok(match (first.tag(), Tag::peek(&reader)?) {
(Tag::Integer, Tag::Sequence) => "PRIVATE KEY",
(Tag::Integer, Tag::Integer) => "RSA PRIVATE KEY",
(Tag::Integer, Tag::OctetString) => "EC PRIVATE KEY",
(Tag::Sequence, Tag::OctetString) => "ENCRYPTED PRIVATE KEY",
_ => return Err(pkcs8::der::ErrorKind::Failed.into()),
})
}
fn traditional_encryption(block: &PemBlock) -> Result<bool, RequestIdentityError> {
let mut proc_type = None;
let mut dek_info = None;
for (name, value) in block.headers.iter() {
let slot = match name {
"Proc-Type" => &mut proc_type,
"DEK-Info" => &mut dek_info,
_ => continue,
};
if slot.replace(value).is_some() {
return Err(RequestIdentityError::InvalidKey);
}
}
if proc_type.is_none() && dek_info.is_none() {
return Ok(false);
}
let (Some("4,ENCRYPTED"), Some(dek_info)) = (proc_type, dek_info) else {
return Err(RequestIdentityError::InvalidKey);
};
let (cipher, iv) = dek_info.split_once(',').ok_or(RequestIdentityError::InvalidKey)?;
let block_size = match cipher {
"AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC" => 16,
"DES-EDE3-CBC" => 8,
_ => return Err(RequestIdentityError::UnsupportedEncryption),
};
if iv.len() != block_size * 2
|| !iv.bytes().all(|byte| byte.is_ascii_hexdigit())
|| block.contents.is_empty()
|| block.contents.len() % block_size != 0
{
return Err(RequestIdentityError::InvalidKey);
}
Ok(true)
}
fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
// pkcs5 collapses unknown outer PBE OIDs into a generic DER value error.
// Inspect the typed envelope first so legacy PBE is not called malformed.
let algorithm = pkcs8::der::asn1::AnyRef::from_der(der)
.and_then(|value| {
value.sequence(|reader| {
let algorithm = pkcs8::AlgorithmIdentifierRef::decode(reader)?;
let _: &pkcs8::der::asn1::OctetStringRef = reader.decode()?;
Ok(algorithm.oid)
})
})
.map_err(|_| RequestIdentityError::InvalidKey)?;
if algorithm != pkcs8::pkcs5::pbes2::PBES2_OID {
// PKCS#12 PBE-SHA1-3DES inside standalone PKCS#8 is not implemented by
// RustCrypto. Only this known legacy scheme uses the optional executable.
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
return super::legacy_pkcs8::decrypt(der, passphrase);
}
return Err(RequestIdentityError::UnsupportedEncryption.into());
}
// Decode the full encryption scheme, including its KDF/PRF/cipher, before
// asking for a password. Unsupported algorithms must not cause prompt loops.
let encrypted = EncryptedPrivateKeyInfoRef::from_der(der).map_err(|error| match error.kind() {
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
_ => RequestIdentityError::InvalidKey,
})?;
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let mut plaintext = Zeroizing::new(encrypted.encrypted_data.as_bytes().to_vec());
let decrypted = encrypted
.encryption_algorithm
.decrypt_in_place(passphrase, &mut plaintext)
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
SecretDocument::try_from(decrypted).map_err(|_| RequestIdentityError::DecryptError("PEM").into())
}
pub(super) fn certificate_chain(bytes: &[u8]) -> anyhow::Result<Zeroizing<Vec<u8>>> {
if !is_pem(bytes) {
return certificate_pem(bytes).map(|pem| Zeroizing::new(pem.into_bytes()));
}
let mut chain = Zeroizing::new(Vec::new());
for block in blocks(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)? {
if block.tag == "CERTIFICATE" {
let encoded = certificate_pem(&block.contents)?;
chain.extend_from_slice(encoded.as_bytes());
}
}
if chain.is_empty() {
return Err(RequestIdentityError::InvalidCertificate.into());
}
Ok(chain)
}
fn certificate_pem(der: &[u8]) -> anyhow::Result<String> {
x509_cert::Certificate::from_der(der).map_err(|_| RequestIdentityError::InvalidCertificate)?;
Ok(pem::encode_config(
&pem::Pem::new("CERTIFICATE", der),
pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF),
))
}
+165
View File
@@ -0,0 +1,165 @@
//! Optional compatibility conversion for standalone PKCS#12 PBE-SHA1-3DES keys.
//! The executable is a runtime option, not a linked or bundled dependency.
use std::{
io::{ErrorKind, Read, Write},
os::{fd::AsFd, unix::process::CommandExt},
process::{Child, Command, Stdio},
thread,
time::{Duration, Instant},
};
use nix::{
fcntl::{FcntlArg, OFlag, fcntl},
sys::signal::{Signal, killpg},
unistd::Pid,
};
use pkcs8::SecretDocument;
use zeroize::Zeroizing;
use super::request::RequestIdentityError::{self, LegacyKeyConversion};
const TIMEOUT: Duration = Duration::from_secs(10);
const MAX_OUTPUT: u64 = 1024 * 1024;
const MAX_PASSWORD_BYTES: usize = 1023;
// The converter owns a separate process group, including wrapper descendants.
// Clean up that group and reap the direct child on every return path.
struct Converter(Child);
impl Drop for Converter {
fn drop(&mut self) {
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
let _ = self.0.wait();
}
}
fn nonblocking(pipe: &impl AsFd) -> anyhow::Result<()> {
fcntl(pipe, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))
.map_err(|_| LegacyKeyConversion("could not configure converter pipes"))?;
Ok(())
}
// Read at most one chunk per iteration so a busy pipe cannot starve the deadline.
// Returns true only after EOF; inherited pipes remain subject to the deadline.
fn read_output(pipe: &mut impl Read, output: &mut Zeroizing<Vec<u8>>, limit: u64) -> anyhow::Result<bool> {
let mut buffer = Zeroizing::new([0u8; 8192]);
match pipe.read(buffer.as_mut_slice()) {
Ok(0) => Ok(true),
Ok(count) => {
if output.len() as u64 + count as u64 > limit {
return Err(LegacyKeyConversion("converter output exceeds the size limit").into());
}
output.extend_from_slice(&buffer[..count]);
Ok(false)
}
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => Ok(false),
Err(_) => Err(LegacyKeyConversion("could not read converter output").into()),
}
}
pub(super) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
// The command's line reader reserves one byte for a terminator. The linked
// OpenSSL API accepted 1024 bytes, but the CLI would truncate that password.
if passphrase.len() > MAX_PASSWORD_BYTES {
return Err(LegacyKeyConversion("the password exceeds OpenSSL's 1023-byte input limit").into());
}
// OpenSSL's pipe password source reads one line. Never silently truncate it.
if passphrase.contains(['\r', '\n', '\0']) {
return Err(LegacyKeyConversion("the password cannot be passed through OpenSSL's line-based input").into());
}
// Only encrypted input touches disk, in a private temporary file. The
// original file is never changed and decrypted output stays in memory.
let mut input = tempfile::NamedTempFile::new()?;
input.write_all(pem::encode(&pem::Pem::new("ENCRYPTED PRIVATE KEY", der)).as_bytes())?;
let child = Command::new("openssl")
.args([
"pkcs8", "-topk8", "-nocrypt", "-inform", "PEM", "-outform", "DER", "-in",
])
.arg(input.path())
.args(["-passin", "stdin"])
.env("LC_ALL", "C")
.process_group(0)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|_| LegacyKeyConversion("the openssl executable is unavailable"))?;
let mut converter = Converter(child);
let mut stdin = converter.0.stdin.take();
let mut stdout = converter.0.stdout.take().unwrap();
let mut stderr = converter.0.stderr.take().unwrap();
nonblocking(stdin.as_ref().unwrap())?;
nonblocking(&stdout)?;
nonblocking(&stderr)?;
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
password.push(b'\n');
let mut written = 0;
let mut input_failed = false;
let mut output = Zeroizing::new(Vec::new());
let mut diagnostic = Zeroizing::new(Vec::new());
let mut output_done = false;
let mut diagnostic_done = false;
let mut status = None;
let started = Instant::now();
let status = loop {
if started.elapsed() >= TIMEOUT {
return Err(LegacyKeyConversion("conversion timed out").into());
}
if let Some(pipe) = stdin.as_mut() {
match pipe.write(&password[written..]) {
Ok(0) => {
input_failed = true;
stdin = None;
}
Ok(count) => {
written += count;
if written == password.len() {
stdin = None;
}
}
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
Err(_) => {
input_failed = true;
stdin = None;
}
}
}
if !output_done {
output_done = read_output(&mut stdout, &mut output, MAX_OUTPUT)?;
}
if !diagnostic_done {
diagnostic_done = read_output(&mut stderr, &mut diagnostic, 16 * 1024)?;
}
if status.is_none() {
status = converter
.0
.try_wait()
.map_err(|_| LegacyKeyConversion("could not wait for the converter"))?;
}
if let Some(status) = status {
if output_done && diagnostic_done && stdin.is_none() {
break status;
}
}
thread::sleep(Duration::from_millis(20));
};
if status.success() && input_failed {
return Err(LegacyKeyConversion("could not send the password").into());
}
if !status.success() {
// Never include the command's output in user-facing errors: it can contain
// key material. Preserve the old Linux password retry contract only for
// an explicit decryption failure, not missing cipher/provider support.
if [b"bad decrypt".as_slice(), b"pkcs12 cipherfinal error".as_slice()]
.iter()
.any(|message| diagnostic.windows(message.len()).any(|window| window == *message))
{
return Err(RequestIdentityError::DecryptError("PEM").into());
}
return Err(LegacyKeyConversion("this OpenSSL installation cannot decrypt the key").into());
}
SecretDocument::try_from(output.as_slice()).map_err(|_| LegacyKeyConversion("invalid converted key").into())
}
+31 -9
View File
@@ -5,10 +5,25 @@ pub mod checksum;
pub mod crypto;
pub mod endpoint;
pub mod env_utils;
mod identity_encoding;
mod legacy_pkcs8;
pub mod lock_file;
#[cfg(not(target_os = "macos"))]
pub mod openssl;
#[cfg(target_os = "macos")]
#[path = "pkcs12_identity/macos.rs"]
mod pkcs12_identity;
#[cfg(not(target_os = "macos"))]
#[path = "pkcs12_identity/openssl.rs"]
mod pkcs12_identity;
pub mod redact;
pub mod request;
#[cfg(target_os = "macos")]
#[path = "traditional_key/macos.rs"]
mod traditional_key;
#[cfg(not(target_os = "macos"))]
#[path = "traditional_key/openssl.rs"]
mod traditional_key;
#[cfg(feature = "tauri")]
pub mod window;
@@ -51,6 +66,8 @@ pub struct GpError {
pub status: StatusCode,
pub reason: String,
body: String,
#[source]
source: Option<reqwest::Error>,
}
impl GpError {
@@ -63,9 +80,7 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
let status = res.status();
if status.is_client_error() || status.is_server_error() {
let (reason, body) = parse_gp_error(res).await;
return Err(GpError { status, reason, body });
return Err(parse_gp_error(res).await);
}
res.text().await.map_err(|err| {
@@ -75,21 +90,28 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
status,
reason: "failed to read response".to_string(),
body: "<failed to read response>".to_string(),
source: Some(err),
}
})
}
async fn parse_gp_error(res: Response) -> (String, String) {
async fn parse_gp_error(res: Response) -> GpError {
let status = res.status();
let reason = res
.headers()
.get("x-private-pan-globalprotect")
.map_or_else(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
.to_string();
let res = res.text().await.map_or_else(
|_| "<failed to read response>".to_string(),
|v| if v.is_empty() { "<empty>".to_string() } else { v },
);
let (body, source) = match res.text().await {
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
Err(error) => ("<failed to read response>".to_string(), Some(error)),
};
(reason, res)
GpError {
status,
reason,
body,
source,
}
}
@@ -0,0 +1,24 @@
use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions};
use super::request::RequestIdentityError;
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
// native-tls assumes a successful import has a last item with an identity.
// Incomplete archives violate that assumption and panic. Inspect them first
// in a private temporary keychain, never the user's default keychain.
let directory = tempfile::tempdir()?;
let keychain = CreateOptions::new()
.password(&uuid::Uuid::new_v4().to_string())
.create(directory.path().join("identity.keychain"))?;
if let Ok(imports) = Pkcs12ImportOptions::new()
.keychain(keychain)
.passphrase(password)
.import(bytes)
&& !imports.last().is_some_and(|item| item.identity.is_some())
{
return Err(RequestIdentityError::IncompletePkcs12.into());
}
// Leave failed imports to reqwest so password errors retain their existing
// classification and native error chain.
Ok(())
}
@@ -0,0 +1,14 @@
use openssl::pkcs12::Pkcs12;
use super::request::RequestIdentityError;
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
// Parse errors belong to the existing native TLS importer. A successful parse
// lets us report incomplete archives without suggesting a password change.
if let Ok(archive) = Pkcs12::from_der(bytes).and_then(|archive| archive.parse2(password))
&& (archive.pkey.is_none() || archive.cert.is_none())
{
return Err(RequestIdentityError::IncompletePkcs12.into());
}
Ok(())
}
+57 -37
View File
@@ -1,11 +1,10 @@
use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex;
use url::{Url, form_urlencoded};
pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>,
patterns: RwLock<Vec<Regex>>,
}
impl Default for Redaction {
@@ -16,56 +15,45 @@ impl Default for Redaction {
impl Redaction {
pub fn new() -> Self {
let redact_engine = RedactEngine::custom("[**********]").add_pattern(Pattern {
test: Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
group: 1,
});
Self {
redact_engine: RwLock::new(Some(redact_engine)),
patterns: RwLock::new(vec![
Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
]),
}
}
pub fn add_value(&self, text: &str) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_value(text)?,
);
Ok(())
self.add_values(&[text])
}
pub fn add_values(&self, texts: &[&str]) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
let patterns = texts
.iter()
.map(|text| Regex::new(&regex::escape(text)))
.collect::<Result<Vec<_>, _>>()?;
self
.patterns
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_values(texts.to_vec())?,
);
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redaction patterns"))?
.extend(patterns);
Ok(())
}
pub fn redact_str(&self, text: &str) -> String {
self
.redact_engine
let patterns = self
.patterns
.read()
.expect("Failed to acquire read lock on redact engine")
.as_ref()
.expect("Failed to get redact engine")
.redact_str(text)
.expect("Failed to acquire read lock on redaction patterns");
let mut redacted = text.to_owned();
// Match the original text, then replace in registration order. Matching the
// replacements would change how overlapping values are redacted.
for pattern in patterns.iter() {
for matched in pattern.find_iter(text) {
redacted = redacted.replacen(matched.as_str(), "[**********]", 1);
}
}
redacted
}
}
@@ -180,6 +168,38 @@ fn redact_query(query: Option<&str>) -> Option<String> {
mod tests {
use super::*;
#[test]
fn redacts_repeated_ipv4_addresses() {
assert_eq!(
Redaction::new().redact_str("from 192.0.2.1 to 198.51.100.9, then 192.0.2.1"),
"from [**********] to [**********], then [**********]"
);
}
#[test]
fn registered_values_are_literal_and_support_unicode() {
let redaction = Redaction::new();
redaction.add_values(&["a.b+$[x]", "秘密🔑"]).unwrap();
assert_eq!(
redaction.redact_str("a.b+$[x] 秘密🔑 a.b+$[x] aXb"),
"[**********] [**********] [**********] aXb"
);
}
#[test]
fn overlapping_values_keep_registration_order() {
let redaction = Redaction::new();
redaction.add_values(&["foobar", "foo"]).unwrap();
assert_eq!(redaction.redact_str("foobar foo"), "[**********] [**********]");
}
#[test]
fn unicode_word_characters_preserve_ipv4_boundaries() {
assert_eq!(Redaction::new().redact_str("192.0.2.1é"), "192.0.2.1é");
}
#[test]
fn it_should_not_redact_value() {
let text = "fo";
+90 -295
View File
@@ -1,10 +1,11 @@
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::{Context, ensure};
use openssl::{pkey::PKey, x509::X509};
use reqwest::Identity;
use zeroize::Zeroizing;
use super::{identity_encoding, pkcs12_identity};
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
#[error("Failed to find the private key")]
@@ -13,6 +14,24 @@ pub enum RequestIdentityError {
NoPassphrase(&'static str),
#[error("Failed to decrypt private key")]
DecryptError(&'static str),
#[error(
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
UnsupportedEncryption,
#[error(
"Could not convert the legacy private key with OpenSSL: {0}. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
)]
LegacyKeyConversion(&'static str),
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
UnsupportedKeyFormat,
#[error("Invalid private key")]
InvalidKey,
#[error("Invalid certificate or certificate chain")]
InvalidCertificate,
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
IncompletePkcs12,
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
InvalidPkcs12(#[source] reqwest::Error),
}
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
@@ -41,37 +60,17 @@ impl fmt::Debug for ClientIdentity {
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 extension = Path::new(certificate).extension().and_then(|value| value.to_str());
if extension.is_some_and(|value| value.eq_ignore_ascii_case("p12") || value.eq_ignore_ascii_case("pfx")) {
return Self::from_data(certificate_bytes, None, 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()?);
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
let identity = pem_request_identity(&certificate, &key)?;
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
@@ -90,12 +89,21 @@ impl ClientIdentity {
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key {
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
Some(key) => (pem_request_identity(&certificate, key)?, None),
None => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
pkcs12_identity::ensure_complete(&certificate, passphrase.unwrap_or_default())?;
// A blank settings field is stored as None. Try the empty password so
// passwordless archives work, but keep prompting for protected ones.
let identity = Identity::from_pkcs12_der(&certificate, passphrase.unwrap_or_default()).map_err(|error| {
if passphrase.is_none() {
RequestIdentityError::NoPassphrase("PKCS#12")
} else {
RequestIdentityError::InvalidPkcs12(error)
}
})?;
(
Identity::from_pkcs12_der(&certificate, passphrase)?,
Some(Zeroizing::new(passphrase.to_owned())),
identity,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
)
}
};
@@ -152,6 +160,20 @@ impl ClientIdentityFiles {
}
}
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
let error_context =
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
let identity = Identity::from_pkcs8_pem(certificate, key).context(error_context)?;
// Native TLS may defer the certificate/key match check until connector creation.
// Build the same client used for requests without making a network connection.
reqwest::Client::builder()
.no_proxy()
.identity(identity.clone())
.build()
.context(error_context)?;
Ok(identity)
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?,
@@ -189,50 +211,15 @@ pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>)
#[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);
}
const CERTIFICATE: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-cert.pem");
const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem");
const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem");
#[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();
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!(
@@ -244,249 +231,57 @@ mod tests {
#[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(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);
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}"),
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(CERTIFICATE).unwrap();
source.write_all(ENCRYPTED_KEY).unwrap();
for (password, missing) in [(None, true), (Some("wrong"), false)] {
let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err();
match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
Some(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
);
}
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source);
reqwest::Client::builder().identity(identity).build().unwrap();
}
#[test]
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
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);
let identity = ClientIdentity::from_data(
Zeroizing::new(CERTIFICATE.to_vec()),
Some(Zeroizing::new(KEY.to_vec())),
Some("unused password"),
)
.unwrap();
assert!(identity.key_password().is_none());
let archive = include_bytes!("../../tests/files/client-identity/modern.p12").to_vec();
let identity = ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
let files = identity.write_files(None).unwrap();
let path = files.certificate().to_owned();
assert!(path.ends_with(".p12"));
assert!(files.key().is_none());
assert_eq!(fs::metadata(&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();
assert!(!Path::new(&path).exists());
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(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(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(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(cert, Some(key), Some(passphrase));
assert!(identity.is_ok());
}
#[test]
fn create_identity_from_pem_cert_and_encrypted_key_no_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
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(cert, Some(key), None);
assert!(identity.is_ok());
}
}
#[derive(Debug, thiserror::Error)]
@@ -0,0 +1,17 @@
use pkcs8::SecretDocument;
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
pub(super) fn normalize(
_bytes: &[u8],
format: TraditionalKeyFormat,
_passphrase: Option<&str>,
) -> anyhow::Result<SecretDocument> {
Err(
match format {
TraditionalKeyFormat::EncryptedPem => RequestIdentityError::UnsupportedEncryption,
TraditionalKeyFormat::PlainPem | TraditionalKeyFormat::Sec1Der => RequestIdentityError::UnsupportedKeyFormat,
}
.into(),
)
}
@@ -0,0 +1,49 @@
use openssl::{
error::ErrorStack,
pkey::{Id, PKey},
};
use pkcs8::SecretDocument;
use zeroize::Zeroizing;
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
pub(super) fn normalize(
bytes: &[u8],
format: TraditionalKeyFormat,
passphrase: Option<&str>,
) -> anyhow::Result<SecretDocument> {
let key = match format {
TraditionalKeyFormat::Sec1Der => PKey::private_key_from_der(bytes),
TraditionalKeyFormat::PlainPem => PKey::private_key_from_pem_passphrase(bytes, b""),
TraditionalKeyFormat::EncryptedPem => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
anyhow::ensure!(
!passphrase.as_bytes().contains(&0),
"Private key passphrases containing NUL are not supported"
);
PKey::private_key_from_pem_passphrase(bytes, passphrase.as_bytes())
}
}
.map_err(import_error)?;
if !matches!(key.id(), Id::RSA | Id::EC) {
return Err(RequestIdentityError::UnsupportedKeyFormat.into());
}
let der = Zeroizing::new(
key
.private_key_to_pkcs8()
.map_err(|_| RequestIdentityError::InvalidKey)?,
);
Ok(SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?)
}
fn import_error(error: ErrorStack) -> RequestIdentityError {
// Inspect only known backend reasons. Never expose the native error stack or
// turn an unclassified decoder failure into a password retry loop.
if error.errors().iter().any(|error| error.reason() == Some("bad decrypt")) {
RequestIdentityError::DecryptError("PEM")
} else if error.errors().iter().any(|error| error.reason() == Some("unsupported")) {
RequestIdentityError::UnsupportedEncryption
} else {
RequestIdentityError::InvalidKey
}
}