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
@@ -14,7 +14,10 @@ base64.workspace = true
|
||||
dns-lookup = { workspace = true, optional = true }
|
||||
log.workspace = true
|
||||
reqwest.workspace = true
|
||||
native-tls = "0.2"
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pemfile = "2"
|
||||
p12-keystore = "0.4.1"
|
||||
sec1 = { version = "0.8.1", default-features = false, features = ["der"] }
|
||||
pem.workspace = true
|
||||
pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
@@ -54,16 +57,15 @@ env_logger = { workspace = true, optional = true }
|
||||
log-reload = { version = "0.1", optional = true }
|
||||
|
||||
[target.'cfg(any(target_os="macos", target_os="ios"))'.dependencies]
|
||||
security-framework = "3"
|
||||
oslog = { version = "0.2", default-features = false, optional = true }
|
||||
|
||||
# Dependencies for Linux and other OSes only
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(not(any(target_os = "macos", target_os = "ios")))'.dependencies]
|
||||
openssl.workspace = true
|
||||
version-compare = "0.2"
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
pkg-config = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
openssl.workspace = true
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=src/utils/certificate/gnutls.c");
|
||||
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
if !matches!(target.as_str(), "macos" | "linux" | "freebsd" | "openbsd") {
|
||||
return;
|
||||
}
|
||||
let mut package = pkg_config::Config::new();
|
||||
package.atleast_version("3.6").cargo_metadata(false);
|
||||
let library = package
|
||||
.probe("gnutls")
|
||||
.expect("GnuTLS development files are required for desktop certificate import");
|
||||
let mut build = cc::Build::new();
|
||||
build.file("src/utils/certificate/gnutls.c");
|
||||
for include in library.include_paths {
|
||||
build.include(include);
|
||||
}
|
||||
build.compile("gp_certificate_import");
|
||||
// GNU linkers must see the shim before its GnuTLS dependency (--as-needed).
|
||||
package
|
||||
.cargo_metadata(true)
|
||||
.probe("gnutls")
|
||||
.expect("GnuTLS was probed above");
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Public identity compatibility and native import behavior.
|
||||
//! Public identity compatibility and owned material lifecycle.
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use gpapi::utils::request::{ClientIdentity, RequestIdentityError};
|
||||
@@ -31,23 +31,9 @@ fn rsa_pkcs8_loads_without_a_password() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_pkcs8_records_native_import_compatibility() {
|
||||
let result = load("ec-cert.pem", "ec-pkcs8.pem", None);
|
||||
if cfg!(target_os = "macos") {
|
||||
// Apple native-tls import currently rejects this P-256 PKCS#8 fixture.
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.unwrap().key_data().unwrap(),
|
||||
fs::read(fixture("ec-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
fn ec_pkcs8_loads_on_every_platform() {
|
||||
let identity = load("ec-cert.pem", "ec-pkcs8.pem", None).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), fs::read(fixture("ec-pkcs8.pem")).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -63,23 +49,13 @@ fn encrypted_pkcs8_keys_normalize_to_the_same_private_key() {
|
||||
("ec-pbes2.pem", "ec-pkcs8.pem", "ec-cert.pem"),
|
||||
] {
|
||||
let result = load(certificate, key, Some(PASSWORD));
|
||||
if cfg!(target_os = "macos") && certificate == "ec-cert.pem" {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.downcast_ref::<reqwest::Error>()
|
||||
.unwrap()
|
||||
.is_builder()
|
||||
);
|
||||
} else {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture(expected)).unwrap(),
|
||||
"{key}"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
}
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key}: {error}"));
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture(expected)).unwrap(),
|
||||
"{key}"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
for (password, missing) in [(None, true), (Some("incorrect"), false)] {
|
||||
let error = load(certificate, key, password).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
@@ -128,7 +104,7 @@ fn rsa_pkcs1_normalizes_to_pkcs8_in_separate_and_combined_files() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_rsa_pkcs1_is_rejected_by_native_import() {
|
||||
fn malformed_rsa_pkcs1_is_rejected_before_connection() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("invalid-key.pem");
|
||||
fs::write(&source, pem::encode(&pem::Pem::new("RSA PRIVATE KEY", vec![0x30, 0]))).unwrap();
|
||||
@@ -138,7 +114,11 @@ fn malformed_rsa_pkcs1_is_rejected_by_native_import() {
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<reqwest::Error>().is_some());
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("Check that the private key matches the certificate")
|
||||
);
|
||||
}
|
||||
|
||||
fn check_archive(name: &str, password: &str) {
|
||||
@@ -211,15 +191,12 @@ fn pkcs12_password_errors_explain_how_to_recover() {
|
||||
assert!(message.contains("PKCS#12"), "{message}");
|
||||
assert!(message.contains("password") && message.contains("file"), "{message}");
|
||||
assert!(!format!("{error:?}").contains("incorrect"));
|
||||
assert!(error.chain().any(|cause| cause.is::<reqwest::Error>()));
|
||||
assert!(error.chain().any(|cause| cause.is::<p12_keystore::error::Error>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// Apple's native importer rejects this empty-password fixture; its native
|
||||
// compatibility decision is covered by archive_snapshot_and_pfx_preserve_native_import_contract.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn empty_pkcs12_password_survives_loading_and_transport() {
|
||||
let archive = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
for password in [None, Some("")] {
|
||||
@@ -239,26 +216,6 @@ fn pkcs12_accepts_non_ascii_passwords() {
|
||||
|
||||
#[test]
|
||||
fn legacy_rc2_pkcs12_checks_password_and_archive_integrity() {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if std::env::var_os("GP_IDENTITY_LEGACY_TEST_CHILD").is_none() {
|
||||
// OpenSSL providers are process-global. Exercise the existing legacy-mode
|
||||
// configuration in an isolated process, without affecting parallel tests.
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let config = directory.path().join("openssl.cnf");
|
||||
fs::write(&config, gpapi::utils::openssl::openssl_conf()).unwrap();
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_rc2_pkcs12_checks_password_and_archive_integrity",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("OPENSSL_CONF", config)
|
||||
.env("GP_IDENTITY_LEGACY_TEST_CHILD", "1")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
check_archive("legacy-rc2.p12", PASSWORD);
|
||||
}
|
||||
|
||||
@@ -307,7 +264,12 @@ fn pbes2_legacy_ciphers_remain_supported() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() {
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
@@ -326,121 +288,65 @@ fn legacy_pkcs8_conversion_preserves_the_key_and_password_errors() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_pkcs8_matches_previous_linux_openssl_processing() {
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
let previous = openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, PASSWORD.as_bytes())
|
||||
.unwrap()
|
||||
.private_key_to_pem_pkcs8()
|
||||
.unwrap();
|
||||
let identity = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), previous);
|
||||
assert!(openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, b"incorrect").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
const CHILD: &str = "GP_LEGACY_CONVERTER_TEST";
|
||||
if let Ok(case) = std::env::var(CHILD) {
|
||||
let started = std::time::Instant::now();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(PASSWORD)).unwrap_err();
|
||||
assert!(
|
||||
started.elapsed() < std::time::Duration::from_secs(12),
|
||||
"conversion exceeded its deadline"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
let message = format!("{error:?}");
|
||||
assert!(message.contains("Convert the key to modern PKCS#8"));
|
||||
assert!(!message.contains(PASSWORD));
|
||||
assert!(!message.contains("PRIVATE KEY"));
|
||||
if case == "missing" {
|
||||
assert!(message.contains("unavailable"));
|
||||
} else if case.starts_with("timeout") {
|
||||
assert!(message.contains("timed out"));
|
||||
}
|
||||
for key in ["rsa-pkcs8.pem", "rsa-pbes2-sha256.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// PATH is process-global; isolate executable discovery from parallel tests.
|
||||
for (case, script) in [
|
||||
("missing", None),
|
||||
(
|
||||
"unsupported",
|
||||
Some("#!/bin/sh\nprintf 'unsupported: fixture-password PRIVATE KEY' >&2\nexit 1\n"),
|
||||
),
|
||||
("invalid-output", Some("#!/bin/sh\nprintf 'invalid converted key'\n")),
|
||||
("timeout-wrapper", Some("#!/bin/sh\n/bin/sleep 14\n")),
|
||||
("timeout-exited-wrapper", Some("#!/bin/sh\n/bin/sleep 14 &\nexit 0\n")),
|
||||
] {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn identity_import_does_not_use_converter_executables() {
|
||||
const CHILD: &str = "GP_IDENTITY_NO_COMMANDS";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
if let Some(script) = script {
|
||||
let executable = directory.path().join("openssl");
|
||||
fs::write(&executable, script).unwrap();
|
||||
fs::set_permissions(executable, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"legacy_pkcs8_converter_failures_are_terminal_and_modern_keys_need_no_executable",
|
||||
"--nocapture",
|
||||
])
|
||||
.args(["--exact", "identity_import_does_not_use_converter_executables"])
|
||||
.env(CHILD, "1")
|
||||
.env("PATH", directory.path())
|
||||
.env(CHILD, case)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "converter case: {case}");
|
||||
assert!(status.success());
|
||||
return;
|
||||
}
|
||||
for key in ["rsa-pkcs8.pem", "rsa-traditional-aes256.pem", "rsa-pbes1-3des.pem"] {
|
||||
let identity = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
check_archive("legacy-rc2.p12", PASSWORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn encrypted_key_import_accepts_long_passwords() {
|
||||
for length in [1023, 1024] {
|
||||
let identity = load(
|
||||
"rsa-cert.pem",
|
||||
&format!("rsa-pbes1-3des-password-{length}.pem"),
|
||||
Some(&"x".repeat(length)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
identity.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_converter_reports_its_password_length_limit_without_requesting_a_retry() {
|
||||
let password = "x".repeat(1024);
|
||||
let encrypted = fs::read(fixture("rsa-pbes1-3des-password-1024.pem")).unwrap();
|
||||
// The previous linked API accepted this boundary. The CLI cannot carry it;
|
||||
// report that limitation rather than calling the correct password wrong.
|
||||
openssl::pkey::PKey::private_key_from_pem_passphrase(&encrypted, password.as_bytes()).unwrap();
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des-password-1024.pem", Some(&password)).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
assert!(error.to_string().contains("1023-byte"));
|
||||
let accepted = load(
|
||||
"rsa-cert.pem",
|
||||
"rsa-pbes1-3des-password-1023.pem",
|
||||
Some(&"x".repeat(1023)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
accepted.key_data().unwrap(),
|
||||
fs::read(fixture("rsa-pkcs8.pem")).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "desktop")]
|
||||
fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords() {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn encrypted_key_import_keeps_original_files_and_redacts_passwords() {
|
||||
let original = fs::read(fixture("rsa-pbes1-3des.pem")).unwrap();
|
||||
for password in [
|
||||
PASSWORD,
|
||||
@@ -452,16 +358,15 @@ fn legacy_conversion_keeps_original_files_and_rejects_line_breaks_in_passwords()
|
||||
let result = load("rsa-cert.pem", "rsa-pbes1-3des.pem", Some(password));
|
||||
if password == PASSWORD {
|
||||
result.unwrap();
|
||||
} else if password != "incorrect" {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::LegacyKeyConversion(_))
|
||||
));
|
||||
} else {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::DecryptError("PEM"))
|
||||
));
|
||||
let error = result.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(password));
|
||||
if !password.contains('\0') {
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::DecryptError("PEM"))
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(fs::read(fixture("rsa-pbes1-3des.pem")).unwrap(), original);
|
||||
}
|
||||
@@ -535,7 +440,7 @@ fn prepared_pem_round_trip_retains_snapshot_and_private_file_lifecycle() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_snapshot_and_pfx_preserve_native_import_contract() {
|
||||
fn archive_snapshot_and_pfx_preserve_prepared_identity() {
|
||||
use zeroize::Zeroizing;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("identity.pfx");
|
||||
@@ -554,12 +459,7 @@ fn archive_snapshot_and_pfx_preserve_native_import_contract() {
|
||||
assert!(restored.key_data().is_none());
|
||||
assert!(!format!("{restored:?}").contains(PASSWORD));
|
||||
let empty = fs::read(fixture("empty-password.p12")).unwrap();
|
||||
// Preserve the native backend's existing empty-password decision.
|
||||
let expected = reqwest::Identity::from_pkcs12_der(&empty, "").is_ok();
|
||||
assert_eq!(
|
||||
ClientIdentity::from_data(Zeroizing::new(empty), None, Some("")).is_ok(),
|
||||
expected
|
||||
);
|
||||
assert!(ClientIdentity::from_data(Zeroizing::new(empty), None, Some("")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -712,11 +612,62 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "desktop"))]
|
||||
#[test]
|
||||
fn portable_legacy_pkcs8_is_explicitly_unsupported() {
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let error = load("rsa-cert.pem", "rsa-pbes1-3des.pem", password).unwrap_err();
|
||||
fn pkcs12_without_bag_ids_or_mac_matches_the_key_instead_of_bag_order() {
|
||||
let data = fs::read(fixture("no-bag-ids.p12")).unwrap();
|
||||
let archive = p12_keystore::Pkcs12Archive::from_pkcs12(&data, "").unwrap();
|
||||
assert!(archive.keys[0].local_key_id.is_none());
|
||||
assert!(archive.certs.iter().all(|bag| bag.local_key_id.is_none()));
|
||||
assert_eq!(
|
||||
archive.certs[0].cert.as_der(),
|
||||
pem::parse(fs::read(fixture("root.pem")).unwrap()).unwrap().contents()
|
||||
);
|
||||
for password in [None, Some("")] {
|
||||
let identity = ClientIdentity::from_data(data.clone().into(), None, password).unwrap();
|
||||
assert_eq!(identity.certificate_data(), data);
|
||||
assert!(identity.key_data().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pkcs12_rejects_mismatched_and_multiple_identities() {
|
||||
for (name, ambiguous) in [("mismatched.p12", false), ("multiple-identities.p12", true)] {
|
||||
let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err();
|
||||
match error.downcast_ref::<RequestIdentityError>() {
|
||||
Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous),
|
||||
Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous),
|
||||
other => panic!("{name}: unexpected archive error: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_identity_accepts_certificate_pem_without_a_final_newline() {
|
||||
let certificate = fs::read(fixture("rsa-cert.pem")).unwrap();
|
||||
let certificate = certificate.trim_ascii_end().to_vec();
|
||||
let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap();
|
||||
let identity = ClientIdentity::from_data(
|
||||
zeroize::Zeroizing::new(certificate.clone()),
|
||||
Some(zeroize::Zeroizing::new(key)),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(identity.certificate_data(), certificate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_pkcs12_password_rejects_nul_before_native_tunnel_setup() {
|
||||
let password = "private\0password";
|
||||
let error = ClientIdentity::load(fixture("no-bag-ids.p12").to_str().unwrap(), None, Some(password)).unwrap_err();
|
||||
assert!(error.to_string().contains("NUL"));
|
||||
assert!(!format!("{error:?}").contains(password));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
#[test]
|
||||
fn ios_reports_unsupported_legacy_encryption_without_a_native_importer() {
|
||||
for key in ["rsa-pbes1-3des.pem", "rsa-traditional-aes256.pem"] {
|
||||
let error = load("rsa-cert.pem", key, Some(PASSWORD)).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
|
||||
@@ -12,9 +12,9 @@ OPENSSL_BIN=/path/to/openssl bash generate.sh
|
||||
```
|
||||
|
||||
Generation is random; it replaces the keys, certificates, and archives together.
|
||||
The test runner reads checked-in files. Legacy standalone conversion tests
|
||||
require an `openssl` executable on PATH (OpenSSL or compatible LibreSSL).
|
||||
No fixture generation is needed to run the tests.
|
||||
The test runner reads checked-in files and needs no converter executable.
|
||||
No fixture generation is needed to run the tests. OpenSSL is used only by the
|
||||
optional fixture-generation script, not identity import.
|
||||
|
||||
| Files | Contents |
|
||||
| --- | --- |
|
||||
@@ -24,38 +24,32 @@ No fixture generation is needed to run the tests.
|
||||
| `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` |
|
||||
| `rsa-pbes2-sha1.pem`, `rsa-pbes2-sha256.pem` | Encrypted PKCS#8, AES256-CBC/PBKDF2 with SHA1 or SHA256 PRF |
|
||||
| `rsa-pbes2-aes-{128,192}-cbc-{sha1,sha256}.pem` | AES128/192-CBC with PBKDF2 SHA1/SHA256 |
|
||||
| `rsa-pbes2-des3-{sha1,sha256}.pem` | PBES2 3DES-CBC with PBKDF2 SHA1/SHA256; distinct from the legacy PBE scheme handled by optional conversion |
|
||||
| `rsa-pbes2-des3-{sha1,sha256}.pem` | PBES2 3DES-CBC with PBKDF2 SHA1/SHA256; distinct from the PKCS#12 PBE scheme handled by GnuTLS |
|
||||
| `rsa-pbes2-des.pem` | PBES2 DES-CBC/PBKDF2-SHA256; Rust processing requires no native legacy provider |
|
||||
| `rsa-pbes2-scrypt.pem` | PBES2 AES256-CBC with scrypt |
|
||||
| `rsa-pbes1-3des-password-{1023,1024}.pem` | Same legacy encryption with passwords at the CLI input boundary; the linked importer accepts 1024 bytes, while the converter reports its 1023-byte limit explicitly |
|
||||
| `rsa-pbes1-3des.pem` | Legacy PKCS#12 SHA1/3DES scheme inside standalone encrypted PKCS#8; optional OpenSSL executable conversion case |
|
||||
| `empty-password.p12` | RSA leaf/key/root with an empty password, preserving native backend acceptance |
|
||||
| `rsa-pbes1-3des-password-{1023,1024}.pem` | Same encryption with 1023- and 1024-byte passwords; both import without executable line limits |
|
||||
| `rsa-pbes1-3des.pem` | Legacy PKCS#12 SHA1/3DES scheme inside standalone encrypted PKCS#8; private GnuTLS import case |
|
||||
| `empty-password.p12` | RSA leaf/key/root with an empty password, accepted with omitted or empty password |
|
||||
| `ec-pbes2.pem` | Encrypted EC PKCS#8, AES256-CBC/PBKDF2-SHA256 |
|
||||
| `modern.p12`, `unicode-password.p12` | Leaf/key/root, AES256-CBC/PBKDF2-SHA256, SHA256 MAC; RSA and EC respectively |
|
||||
| `certificate-only.pfx`, `key-only.pfx` | Incomplete PKCS#12 archives: certificate without key, and key without certificate; password `fixture-password` |
|
||||
| `legacy-rc2.p12` | Issue #437 case: RC2-40 certificate bags, SHA1/3DES key bag, SHA1 MAC |
|
||||
|
||||
`tests/client_identity.rs` records native import compatibility and the owned
|
||||
identity lifecycle. `tests/identity_encoding.rs` covers container normalization:
|
||||
DER certificates and keys, RSA PKCS#1, Linux/BSD EC SEC1 and traditional encrypted
|
||||
PEM, first-key selection, malformed encryption headers, and archive extension
|
||||
capitalization. macOS rejects SEC1 and traditional encrypted PEM before password
|
||||
handling. Its native importer also rejects the P-256 PKCS#8 PEM fixture, although
|
||||
its native PKCS#12 import accepts the EC archive. Legacy-provider setup is isolated
|
||||
in a child process on Linux/BSD.
|
||||
`tests/client_identity.rs` covers all supported key families, password failures,
|
||||
archive integrity, certificate/key matching, retained snapshots, private-file
|
||||
permissions and cleanup. `tests/identity_encoding.rs` covers PEM/DER, RSA PKCS#1,
|
||||
EC SEC1, traditional encrypted PEM, first-key selection, malformed encryption
|
||||
headers and archive extension capitalization. Rustls validates RSA and EC keys
|
||||
on all supported targets; desktop legacy encrypted-key imports use GnuTLS.
|
||||
PBES2, including scrypt, stays in Rust. The no-executable child test runs with an
|
||||
empty PATH and imports both legacy key families and RC2 PKCS#12.
|
||||
|
||||
Standalone PKCS#8 PBE-SHA1-3DES uses optional OpenSSL executable conversion,
|
||||
with missing/wrong passwords preserving the old Linux prompt/retry contract.
|
||||
Other unsupported schemes retain explicit conversion guidance. PBES2 DES/3DES
|
||||
use Rust processing and need no executable. Child-process tests isolate PATH
|
||||
for absent/unsupported/stalled converters, invalid output, and secret-free errors.
|
||||
Timeout coverage includes wrappers whose descendants retain pipes after the
|
||||
wrapper exits or is killed; all pipe I/O shares the process deadline.
|
||||
Linux/BSD additionally compare the result with the former linked OpenSSL importer.
|
||||
Archive integrity checks change the UTF-16 friendly name without changing the
|
||||
MAC. Decrypted output is compared with independent plaintext fixture keys.
|
||||
Unit tests in `utils/request.rs` cover missing keys, large local files and request
|
||||
client construction.
|
||||
|
||||
The tests check archive integrity by changing the UTF-16 friendly name without
|
||||
changing the MAC, and compare normalized PEM output against the independent
|
||||
checked-in plaintext key. Public integration tests cover first-key selection,
|
||||
retained snapshots, private-file permissions and cleanup, `.pfx`, empty-password
|
||||
backend behavior, and chain retention. Unit tests in `utils/request.rs` cover
|
||||
missing keys, large local files, and native request-client construction.
|
||||
The unencrypted, MAC-less `no-bag-ids.p12`, `mismatched.p12`, and
|
||||
`multiple-identities.p12` contain only the same public test keys/certificates.
|
||||
They exercise PKCS#12 bags without optional attributes, reversed certificate
|
||||
order/unrelated certificates, and terminal mismatched/ambiguous identities.
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Assemble public, unencrypted PKCS#12 fixtures; no cryptography is performed."""
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def pem(name):
|
||||
lines = (ROOT / name).read_text().splitlines()
|
||||
return base64.b64decode("".join(line for line in lines if not line.startswith("-----")))
|
||||
|
||||
|
||||
def tlv(tag, content):
|
||||
length = len(content)
|
||||
encoded = length.to_bytes(max(1, (length.bit_length() + 7) // 8), "big")
|
||||
prefix = bytes([length]) if length < 128 else bytes([128 + len(encoded)]) + encoded
|
||||
return bytes([tag]) + prefix + content
|
||||
|
||||
|
||||
def sequence(*items):
|
||||
return tlv(0x30, b"".join(items))
|
||||
|
||||
|
||||
def oid(value):
|
||||
return tlv(6, bytes.fromhex(value))
|
||||
|
||||
|
||||
def explicit(content):
|
||||
return tlv(0xA0, content)
|
||||
|
||||
|
||||
def data(content):
|
||||
return sequence(oid("2a864886f70d010701"), explicit(tlv(4, content)))
|
||||
|
||||
|
||||
def key(name):
|
||||
return sequence(oid("2a864886f70d010c0a0101"), explicit(pem(name)))
|
||||
|
||||
|
||||
def certificate(name):
|
||||
cert_bag = sequence(oid("2a864886f70d01091601"), explicit(tlv(4, pem(name))))
|
||||
return sequence(oid("2a864886f70d010c0a0103"), explicit(cert_bag))
|
||||
|
||||
|
||||
def archive(name, *bags):
|
||||
(ROOT / name).write_bytes(sequence(tlv(2, b"\x03"), data(sequence(data(sequence(*bags))))))
|
||||
|
||||
|
||||
archive("no-bag-ids.p12", certificate("root.pem"), certificate("ec-cert.pem"),
|
||||
key("rsa-pkcs8.pem"), certificate("rsa-cert.pem"))
|
||||
archive("mismatched.p12", key("rsa-pkcs8.pem"), certificate("ec-cert.pem"), certificate("root.pem"))
|
||||
archive("multiple-identities.p12", key("rsa-pkcs8.pem"), key("ec-pkcs8.pem"),
|
||||
certificate("rsa-cert.pem"), certificate("ec-cert.pem"))
|
||||
@@ -75,3 +75,6 @@ done
|
||||
-name fixture -passout pass:fixture-password -out certificate-only.pfx
|
||||
"$openssl_bin" pkcs12 -export -nocerts -inkey rsa-pkcs8.pem \
|
||||
-name fixture -passout pass:fixture-password -out key-only.pfx
|
||||
|
||||
# Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags.
|
||||
python3 "$(dirname "$0")/generate-plain-pfx.py"
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -65,41 +65,40 @@ fn encrypted_der_preserves_password_errors() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_sec1_normalizes_on_linux_and_bsd_and_is_terminal_on_macos() {
|
||||
fn ec_sec1_pem_and_der_are_portable() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("ec.der");
|
||||
fs::write(&key, pem::parse(bytes("ec-sec1.pem")).unwrap().contents()).unwrap();
|
||||
for source in [fixture("ec-sec1.pem"), key] {
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = load(&fixture("ec-cert.pem"), &source, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedKeyFormat)
|
||||
));
|
||||
} else {
|
||||
assert_eq!(result.unwrap().key_data().unwrap(), bytes("ec-pkcs8.pem"));
|
||||
}
|
||||
let identity = load(&fixture("ec-cert.pem"), &source, password).unwrap();
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("ec-sec1.pem"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traditional_encrypted_pem_has_platform_specific_support_and_password_errors() {
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn traditional_encrypted_pem_preserves_password_errors() {
|
||||
for algorithm in ["rsa", "ec"] {
|
||||
for cipher in ["aes128", "aes192", "aes256", "des3"] {
|
||||
let certificate = fixture(&format!("{algorithm}-cert.pem"));
|
||||
let key = fixture(&format!("{algorithm}-traditional-{cipher}.pem"));
|
||||
for password in [None, Some("incorrect"), Some(PASSWORD)] {
|
||||
let result = load(&certificate, &key, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password == Some(PASSWORD) {
|
||||
if password == Some(PASSWORD) {
|
||||
let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}"));
|
||||
assert_eq!(identity.key_data().unwrap(), bytes(&format!("{algorithm}-pkcs8.pem")));
|
||||
let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap();
|
||||
let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap();
|
||||
assert!(
|
||||
actual.public_eq(&expected),
|
||||
"{key:?}: imported key differs from the fixture"
|
||||
);
|
||||
assert!(identity.key_password().is_none());
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
@@ -115,7 +114,12 @@ fn traditional_encrypted_pem_has_platform_specific_support_and_password_errors()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn traditional_passphrase_with_nul_returns_a_redacted_terminal_error() {
|
||||
let error = load(
|
||||
&fixture("rsa-cert.pem"),
|
||||
@@ -130,11 +134,16 @@ fn traditional_passphrase_with_nul_returns_a_redacted_terminal_error() {
|
||||
for diagnostic in [error.to_string(), format!("{error:?}")] {
|
||||
assert!(!diagnostic.contains("secret-password"));
|
||||
assert!(!diagnostic.contains("do-not-log"));
|
||||
assert!(!diagnostic.contains("115, 101, 99, 114, 101, 116"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
fn first_traditional_encrypted_key_controls_combined_pem_loading() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let source = directory.path().join("combined.pem");
|
||||
@@ -144,24 +153,14 @@ fn first_traditional_encrypted_key_controls_combined_pem_loading() {
|
||||
combined.extend(bytes("rsa-traditional-aes256.pem"));
|
||||
combined.extend(bytes("rsa-pkcs8.pem"));
|
||||
fs::write(&source, &combined).unwrap();
|
||||
for password in [None, Some(PASSWORD)] {
|
||||
let result = ClientIdentity::load(source.to_str().unwrap(), None, password);
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
} else if password.is_none() {
|
||||
assert!(matches!(
|
||||
result.unwrap_err().downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
} else {
|
||||
let identity = result.unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
}
|
||||
}
|
||||
let error = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap_err();
|
||||
assert!(matches!(
|
||||
error.downcast_ref::<RequestIdentityError>(),
|
||||
Some(RequestIdentityError::NoPassphrase("PEM"))
|
||||
));
|
||||
let identity = ClientIdentity::load(source.to_str().unwrap(), None, Some(PASSWORD)).unwrap();
|
||||
assert_eq!(identity.certificate_data(), chain);
|
||||
assert_eq!(identity.key_data().unwrap(), bytes("rsa-pkcs8.pem"));
|
||||
assert_eq!(fs::read(source).unwrap(), combined);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user