mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
refactor: replace OpenSSL transports and certificate imports
This commit is contained in:
59 files changed
+1072
-1151
No files matched your search
@@ -11,8 +11,6 @@ use crate::{
|
||||
pub mod args;
|
||||
|
||||
pub trait Args {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn fix_openssl(&self) -> bool;
|
||||
fn ignore_tls_errors(&self) -> bool;
|
||||
|
||||
/// How this program renders its logs.
|
||||
@@ -43,14 +41,6 @@ fn retry_hints(err: &anyhow::Error, args: &impl Args) -> Vec<String> {
|
||||
// users already see; keep it exactly.
|
||||
let mut hints = Vec::new();
|
||||
|
||||
#[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 kind == ServerTlsErrorKind::Certificate && !args.ignore_tls_errors() {
|
||||
let (program, rest) = command_line();
|
||||
hints.push(format!(
|
||||
@@ -204,18 +194,11 @@ mod tests {
|
||||
|
||||
#[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
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> bool {
|
||||
self.ignore_tls_errors
|
||||
}
|
||||
@@ -260,31 +243,12 @@ 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 {
|
||||
fn unknown_tls_failure_does_not_suggest_bypassing_certificate_validation() {
|
||||
let error = ServerTlsError {
|
||||
server: "https://vpn.example.com".into(),
|
||||
kind: ServerTlsErrorKind::Other,
|
||||
};
|
||||
assert!(retry_hints(&anyhow!(other), &TestArgs::default()).is_empty());
|
||||
assert!(retry_hints(&anyhow!(error), &TestArgs::default()).is_empty());
|
||||
}
|
||||
|
||||
/// Suggesting an option the user already passed is noise, and in JSON mode it
|
||||
|
||||
@@ -4,13 +4,6 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::PortalError;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[path = "server_tls/apple.rs"]
|
||||
mod backend;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[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)]
|
||||
@@ -25,7 +18,6 @@ pub struct ServerTlsError {
|
||||
pub enum ServerTlsErrorKind {
|
||||
Certificate,
|
||||
ClientCertificateRequired,
|
||||
LegacyRenegotiation,
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -43,7 +35,6 @@ impl fmt::Display for ServerTlsError {
|
||||
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)
|
||||
@@ -70,122 +61,25 @@ impl ServerTlsErrorKind {
|
||||
|
||||
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);
|
||||
if let Some(tls) = error.downcast_ref::<rustls::Error>() {
|
||||
return Some(match tls {
|
||||
rustls::Error::InvalidCertificate(_) => ServerTlsErrorKind::Certificate,
|
||||
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
|
||||
ServerTlsErrorKind::ClientCertificateRequired
|
||||
}
|
||||
_ => ServerTlsErrorKind::Other,
|
||||
});
|
||||
}
|
||||
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
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -207,39 +101,26 @@ mod tests {
|
||||
};
|
||||
|
||||
#[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\" }}");
|
||||
fn typed_tls_causes_distinguish_local_trust_from_peer_alerts() {
|
||||
for reason in [
|
||||
rustls::CertificateError::Expired,
|
||||
rustls::CertificateError::UnknownIssuer,
|
||||
] {
|
||||
let error = std::io::Error::other(std::io::Error::other(rustls::Error::InvalidCertificate(reason)));
|
||||
assert_eq!(classify(&error), Some(ServerTlsErrorKind::Certificate));
|
||||
}
|
||||
for alert in [
|
||||
rustls::AlertDescription::UnknownCA,
|
||||
rustls::AlertDescription::BadCertificate,
|
||||
] {
|
||||
assert_eq!(
|
||||
classify_native_detail(&detail),
|
||||
ServerTlsErrorKind::Certificate,
|
||||
"{code}"
|
||||
classify(&rustls::Error::AlertReceived(alert)),
|
||||
Some(ServerTlsErrorKind::Other)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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}");
|
||||
}
|
||||
let required = rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired);
|
||||
assert_eq!(classify(&required), Some(ServerTlsErrorKind::ClientCertificateRequired));
|
||||
assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None);
|
||||
}
|
||||
|
||||
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
|
||||
@@ -335,7 +216,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
|
||||
let (address, worker) = server(false);
|
||||
let error = reqwest::Client::builder()
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
@@ -354,7 +235,7 @@ mod tests {
|
||||
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()
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
@@ -365,17 +246,6 @@ mod tests {
|
||||
assert_eq!(classify(&error), None);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
#[test]
|
||||
fn rendering_recovery_retains_client_certificate_requirement() {
|
||||
@@ -436,19 +306,11 @@ mod tests {
|
||||
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:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
kind,
|
||||
ServerTlsErrorKind::ClientCertificateRequired,
|
||||
"{operation}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,6 +346,78 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
|
||||
use crate::{
|
||||
gp_params::GpParams,
|
||||
os_profile::{ClientOs, OsProfile},
|
||||
portal::{PreloginOptions, prelogin},
|
||||
};
|
||||
let fixture = |name: &str| format!("{}/tests/files/client-identity/{name}", env!("CARGO_MANIFEST_DIR"));
|
||||
for (certificate, key, password) in [
|
||||
(
|
||||
"rsa-cert.pem",
|
||||
Some("rsa-traditional-aes256.pem"),
|
||||
Some("fixture-password"),
|
||||
),
|
||||
("ec-cert.pem", Some("ec-traditional-des3.pem"), Some("fixture-password")),
|
||||
("rsa-cert.pem", Some("rsa-pbes1-3des.pem"), Some("fixture-password")),
|
||||
("rsa-cert.pem", Some("rsa-pbes2-scrypt.pem"), Some("fixture-password")),
|
||||
("ec-cert.pem", Some("ec-sec1.pem"), None),
|
||||
("modern.p12", None, Some("fixture-password")),
|
||||
("legacy-rc2.p12", None, Some("fixture-password")),
|
||||
("empty-password.p12", None, None),
|
||||
("no-bag-ids.p12", None, None),
|
||||
] {
|
||||
let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
||||
let mut builder =
|
||||
GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot()));
|
||||
builder
|
||||
.ignore_tls_errors(true)
|
||||
.certificate(Some(fixture(certificate)))
|
||||
.sslkey(key.map(fixture))
|
||||
.key_password(password.map(str::to_owned));
|
||||
let mut params = builder.build();
|
||||
params
|
||||
.prepare_client_identity()
|
||||
.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}"));
|
||||
let result = prelogin(&address, ¶ms, PreloginOptions::default()).await;
|
||||
worker.join().unwrap();
|
||||
assert!(matches!(
|
||||
result.unwrap_or_else(|error| panic!("{certificate}/{key:?}: {error:?}")),
|
||||
crate::portal::Prelogin::Saml(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Point at the GnuTLS fixture configured without RFC 5746, with a trusted test root.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires GP_TLS_TEST_SERVER and GP_TLS_TEST_CA for the external GnuTLS fixture"]
|
||||
async fn tls12_peer_without_renegotiation_extension_uses_default_policy() {
|
||||
let server = std::env::var("GP_TLS_TEST_SERVER").unwrap();
|
||||
let root = std::fs::read(std::env::var("GP_TLS_TEST_CA").unwrap()).unwrap();
|
||||
let client = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&root).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
assert!(client.get(&server).send().await.unwrap().status().is_success());
|
||||
let error = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(&server)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error)
|
||||
.unwrap()
|
||||
.kind,
|
||||
ServerTlsErrorKind::Certificate
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_response_reads_preserve_the_transport_cause() {
|
||||
for status in [200, 403] {
|
||||
@@ -500,7 +434,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
let response = reqwest::Client::builder()
|
||||
let response = crate::utils::request::client_builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
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()))
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -161,7 +161,7 @@ impl GpParams {
|
||||
}
|
||||
|
||||
pub(crate) fn client_builder(&self) -> anyhow::Result<ClientBuilder> {
|
||||
let mut builder = Client::builder()
|
||||
let mut builder = crate::utils::request::client_builder()
|
||||
.tls_info(true)
|
||||
.danger_accept_invalid_certs(self.ignore_tls_errors)
|
||||
.user_agent(self.user_agent());
|
||||
|
||||
@@ -33,8 +33,6 @@ 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")]
|
||||
hidpi: bool,
|
||||
@@ -67,8 +65,6 @@ 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")]
|
||||
hidpi: false,
|
||||
@@ -115,12 +111,6 @@ 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
|
||||
}
|
||||
|
||||
pub fn ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self {
|
||||
self.ignore_tls_errors = ignore_tls_errors;
|
||||
self
|
||||
@@ -229,11 +219,6 @@ 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");
|
||||
}
|
||||
|
||||
if self.ignore_tls_errors {
|
||||
auth_cmd.arg("--ignore-tls-errors");
|
||||
}
|
||||
@@ -419,13 +404,8 @@ mod tests {
|
||||
#[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 == "--fix-openssl"));
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn gateway_fixture(
|
||||
requests
|
||||
});
|
||||
let transport = GatewayTransport {
|
||||
client: Client::builder()
|
||||
client: crate::utils::request::client_builder()
|
||||
.redirect(Policy::none())
|
||||
.no_proxy()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <gnutls/gnutls.h>
|
||||
#include <gnutls/x509.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
|
||||
/* Only decrypted PKCS#8 leaves this interface. The Rust owner releases it with
|
||||
* gp_key_free, so GnuTLS allocation and wiping stay with the native allocator. */
|
||||
int gp_key_import(const unsigned char *input, size_t length, int pem,
|
||||
const char *password, unsigned char **output, size_t *output_length) {
|
||||
gnutls_x509_privkey_t key = NULL;
|
||||
gnutls_datum_t exported = {NULL, 0};
|
||||
int result;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return 3;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return 3;
|
||||
result = gnutls_x509_privkey_init(&key);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t data = {(unsigned char *)input, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(key, &data,
|
||||
pem ? GNUTLS_X509_FMT_PEM : GNUTLS_X509_FMT_DER, password, 0);
|
||||
}
|
||||
if (result >= 0) {
|
||||
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER,
|
||||
NULL, GNUTLS_PKCS_PLAIN, &exported);
|
||||
}
|
||||
if (key != NULL) gnutls_x509_privkey_deinit(key);
|
||||
gnutls_global_deinit();
|
||||
if (result >= 0) {
|
||||
*output = exported.data;
|
||||
*output_length = exported.size;
|
||||
return 0;
|
||||
}
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) return 1;
|
||||
if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE)
|
||||
return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
void gp_key_free(unsigned char *data, size_t length) {
|
||||
if (data != NULL) {
|
||||
gnutls_memset(data, 0, length);
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
pem: c_int,
|
||||
password: *const c_char,
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl Drop for ExportedKey {
|
||||
fn drop(&mut self) {
|
||||
// The shim owns the allocation and wipes it before releasing it.
|
||||
unsafe { gp_key_free(self.data, self.length) };
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
anyhow::ensure!(
|
||||
!passphrase.as_bytes().contains(&0),
|
||||
"Private key passphrases containing NUL are not supported"
|
||||
);
|
||||
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
|
||||
password.push(0);
|
||||
let mut exported = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
// All input slices remain live for the call; the output is owned by the guard.
|
||||
let result = unsafe {
|
||||
gp_key_import(
|
||||
bytes.as_ptr(),
|
||||
bytes.len(),
|
||||
i32::from(pem),
|
||||
password.as_ptr().cast(),
|
||||
&mut exported.data,
|
||||
&mut exported.length,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => {
|
||||
anyhow::ensure!(!exported.data.is_null() && exported.length > 0, "Invalid private key");
|
||||
// A successful shim call returns an initialized allocation of this length.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(exported.data, exported.length) };
|
||||
SecretDocument::try_from(bytes).map_err(|_| RequestIdentityError::InvalidKey.into())
|
||||
}
|
||||
1 => Err(RequestIdentityError::DecryptError("PEM").into()),
|
||||
2 => Err(RequestIdentityError::UnsupportedEncryption.into()),
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
//! 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 crate::utils::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(in crate::utils) 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())
|
||||
}
|
||||
@@ -1,18 +1,20 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "pkcs12/macos.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[path = "pkcs12/openssl.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(target_os = "ios")]
|
||||
#[path = "pkcs12/ios.rs"]
|
||||
pub(super) mod pkcs12_identity;
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[path = "traditional_key/apple.rs"]
|
||||
pub(super) mod traditional_key;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
#[path = "traditional_key/openssl.rs"]
|
||||
pub(super) mod traditional_key;
|
||||
pub(super) mod pkcs12;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
pub(super) mod legacy_pkcs8;
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod legacy_key;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
@@ -0,0 +1,72 @@
|
||||
use p12_keystore::Pkcs12Archive;
|
||||
use rustls::{
|
||||
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
sign::CertifiedKey,
|
||||
};
|
||||
|
||||
use crate::utils::request::{RequestIdentityError, pem_request_identity};
|
||||
|
||||
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
|
||||
anyhow::ensure!(
|
||||
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
})?;
|
||||
if archive.keys.is_empty() || archive.certs.is_empty() {
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
if archive.keys.len() != 1 {
|
||||
return Err(RequestIdentityError::AmbiguousPkcs12.into());
|
||||
}
|
||||
let key = &archive.keys[0].key;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
let mut certs = Vec::new();
|
||||
for bag in &archive.certs {
|
||||
if !certs
|
||||
.iter()
|
||||
.any(|cert: &&p12_keystore::Certificate| cert.as_der() == bag.cert.as_der())
|
||||
{
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if current.subject() == current.issuer() {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use security_framework::import_export::Pkcs12ImportOptions;
|
||||
pub(in crate::utils) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
if let Ok(imports) = Pkcs12ImportOptions::new().passphrase(password).import(bytes)
|
||||
&& !imports.last().is_some_and(|item| item.identity.is_some())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
pub(in crate::utils) 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(())
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
pub(in crate::utils) 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(())
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use pkcs8::SecretDocument;
|
||||
|
||||
use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) 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(),
|
||||
)
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
use openssl::{
|
||||
error::ErrorStack,
|
||||
pkey::{Id, PKey},
|
||||
};
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(in crate::utils) 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
|
||||
//! PEM/DER normalization before rustls validates usable keys and identities.
|
||||
use pkcs8::{
|
||||
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
|
||||
der::{
|
||||
@@ -8,13 +8,7 @@ use pkcs8::{
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::traditional_key, request::RequestIdentityError};
|
||||
|
||||
pub(super) enum TraditionalKeyFormat {
|
||||
Sec1Der,
|
||||
PlainPem,
|
||||
EncryptedPem,
|
||||
}
|
||||
use super::{certificate, request::RequestIdentityError};
|
||||
|
||||
struct PemBlock {
|
||||
tag: String,
|
||||
@@ -26,7 +20,9 @@ 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());
|
||||
let encoded = Zeroizing::new(
|
||||
pem::encode_config(&block, pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF)).into_bytes(),
|
||||
);
|
||||
// The PEM crate owns a copy of the decoded private key as well.
|
||||
drop(Zeroizing::new(block.into_contents()));
|
||||
encoded
|
||||
@@ -77,13 +73,13 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
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)?
|
||||
certificate::decrypt_key(&block.encoded(), true, 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.
|
||||
// Rustls validates the RSA key along with the certificate.
|
||||
let algorithm = AlgorithmIdentifierRef {
|
||||
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
|
||||
parameters: Some(AnyRef::NULL),
|
||||
@@ -94,11 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
}
|
||||
"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)?
|
||||
}
|
||||
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
return Ok(block.encoded());
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
@@ -172,12 +165,9 @@ fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocumen
|
||||
.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.
|
||||
// RustCrypto. Only this known legacy scheme uses the native importer.
|
||||
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
|
||||
#[cfg(feature = "desktop")]
|
||||
return super::certificate::legacy_pkcs8::decrypt(der, passphrase);
|
||||
#[cfg(not(feature = "desktop"))]
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
return certificate::decrypt_key(der, false, passphrase);
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
|
||||
@@ -45,7 +45,10 @@ impl LockFile {
|
||||
Ok(content) => {
|
||||
let url = format!("http://127.0.0.1:{}/health", content.trim());
|
||||
|
||||
match reqwest::get(&url).await {
|
||||
let Ok(client) = crate::utils::request::client_builder().build() else {
|
||||
return false;
|
||||
};
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => resp.status().is_success(),
|
||||
Err(_) => false,
|
||||
}
|
||||
|
||||
@@ -11,8 +11,6 @@ pub mod env_utils;
|
||||
mod identity_encoding;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod lock_file;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
|
||||
pub mod openssl;
|
||||
pub mod redact;
|
||||
pub mod request;
|
||||
#[cfg(feature = "tauri")]
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
use std::path::Path;
|
||||
|
||||
use log::{info, warn};
|
||||
use regex::Regex;
|
||||
use tempfile::NamedTempFile;
|
||||
use version_compare::{Cmp, compare_to};
|
||||
|
||||
pub fn openssl_conf() -> String {
|
||||
let option = get_openssl_option();
|
||||
|
||||
format!(
|
||||
"openssl_conf = openssl_init
|
||||
|
||||
[openssl_init]
|
||||
ssl_conf = ssl_sect
|
||||
providers = provider_sect
|
||||
|
||||
[ssl_sect]
|
||||
system_default = system_default_sect
|
||||
|
||||
[system_default_sect]
|
||||
Options = {}
|
||||
|
||||
[provider_sect]
|
||||
default = default_sect
|
||||
legacy = legacy_sect
|
||||
|
||||
[default_sect]
|
||||
activate = 1
|
||||
|
||||
[legacy_sect]
|
||||
activate = 1
|
||||
",
|
||||
option
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
|
||||
let content = openssl_conf();
|
||||
std::fs::write(path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
|
||||
let openssl_conf = NamedTempFile::new()?;
|
||||
let openssl_conf_path = openssl_conf.path();
|
||||
|
||||
fix_openssl(openssl_conf_path)?;
|
||||
unsafe { std::env::set_var("OPENSSL_CONF", openssl_conf_path) };
|
||||
|
||||
Ok(openssl_conf)
|
||||
}
|
||||
|
||||
// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled
|
||||
fn get_openssl_option() -> &'static str {
|
||||
let version_str = openssl::version::version();
|
||||
let default_option = "UnsafeLegacyServerConnect";
|
||||
|
||||
let Some(version) = extract_openssl_version(version_str) else {
|
||||
warn!("Failed to extract OpenSSL version from '{}'", version_str);
|
||||
return default_option;
|
||||
};
|
||||
|
||||
let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
warn!("Failed to compare OpenSSL version: {}", version);
|
||||
return default_option;
|
||||
}
|
||||
};
|
||||
|
||||
if older_than_3_0_4 {
|
||||
info!("Using 'UnsafeLegacyRenegotiation' option");
|
||||
"UnsafeLegacyRenegotiation"
|
||||
} else {
|
||||
info!("Using 'UnsafeLegacyServerConnect' option");
|
||||
default_option
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_openssl_version(version: &str) -> Option<&str> {
|
||||
let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap();
|
||||
re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_extract_version() {
|
||||
let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)";
|
||||
assert_eq!(extract_openssl_version(input), Some("3.4.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_format() {
|
||||
let input = "OpenSSL 1.1.1t 7 Feb 2023";
|
||||
assert_eq!(extract_openssl_version(input), Some("1.1.1t"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input() {
|
||||
let input = "Invalid string without version";
|
||||
assert_eq!(extract_openssl_version(input), None);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use anyhow::{Context, ensure};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{certificate::pkcs12_identity, identity_encoding};
|
||||
use super::{certificate::pkcs12, identity_encoding};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
@@ -18,10 +18,6 @@ pub enum RequestIdentityError {
|
||||
"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")]
|
||||
@@ -31,7 +27,9 @@ pub enum RequestIdentityError {
|
||||
#[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),
|
||||
InvalidPkcs12(#[source] p12_keystore::error::Error),
|
||||
#[error("The PKCS#12 file must contain one matching client identity")]
|
||||
AmbiguousPkcs12,
|
||||
}
|
||||
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
@@ -91,16 +89,7 @@ impl ClientIdentity {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
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)
|
||||
}
|
||||
})?;
|
||||
let identity = pkcs12::identity(&certificate, passphrase)?;
|
||||
(
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
@@ -160,13 +149,22 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
pub(super) 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()
|
||||
let mut combined = Zeroizing::new(certificate.to_vec());
|
||||
combined.push(b'\n');
|
||||
combined.extend_from_slice(key);
|
||||
let identity = Identity::from_pem(&combined).context(error_context)?;
|
||||
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(error_context)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
|
||||
.context(error_context)?
|
||||
.context(error_context)?;
|
||||
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
|
||||
.context(error_context)?;
|
||||
client_builder()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
@@ -202,6 +200,14 @@ fn write_identity_file(
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Ordinary Reqwest construction with the shared rustls provider initialized.
|
||||
pub fn client_builder() -> reqwest::ClientBuilder {
|
||||
if rustls::crypto::CryptoProvider::get_default().is_none() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
reqwest::Client::builder().tls_backend_rustls()
|
||||
}
|
||||
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
@@ -241,7 +247,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
|
||||
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
@@ -255,7 +261,7 @@ mod tests {
|
||||
}
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
reqwest::Client::builder().identity(identity).build().unwrap();
|
||||
client_builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -277,10 +283,7 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
client_builder().identity(identity.request_identity()).build().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user