diff --git a/Cargo.lock b/Cargo.lock index c30de18..6959de6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -292,7 +292,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "auth" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "block2", @@ -547,7 +547,7 @@ dependencies = [ [[package]] name = "browser-launcher" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "log", @@ -911,7 +911,7 @@ dependencies = [ [[package]] name = "common" -version = "3.3.0" +version = "3.3.1" dependencies = [ "tempfile", ] @@ -2115,7 +2115,7 @@ dependencies = [ [[package]] name = "gpapi" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "base64 0.23.1", @@ -2124,6 +2124,7 @@ dependencies = [ "chrono", "clap", "clap-verbosity-flag", + "cms", "common", "directories", "dns-lookup", @@ -2142,6 +2143,7 @@ dependencies = [ "oslog", "p12-keystore", "pem", + "pkcs12", "pkcs8", "pkg-config", "proptest", @@ -2149,7 +2151,7 @@ dependencies = [ "reqwest", "rustls", "rustls-pemfile", - "sec1", + "rustls-platform-verifier", "serde", "serde_json", "serde_urlencoded", @@ -2174,7 +2176,7 @@ dependencies = [ [[package]] name = "gpauth" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "auth", @@ -2193,7 +2195,7 @@ dependencies = [ [[package]] name = "gpclient" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "clap", @@ -2224,7 +2226,7 @@ dependencies = [ [[package]] name = "gpgui-helper" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "clap", @@ -2245,7 +2247,7 @@ dependencies = [ [[package]] name = "gphip" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "askama", @@ -2262,7 +2264,7 @@ dependencies = [ [[package]] name = "gpservice" -version = "3.3.0" +version = "3.3.1" dependencies = [ "anyhow", "axum", @@ -2297,7 +2299,7 @@ dependencies = [ [[package]] name = "gptunnel" -version = "3.3.0" +version = "3.3.1" dependencies = [ "gpapi", "log", @@ -2309,7 +2311,7 @@ dependencies = [ [[package]] name = "gpvpnc" -version = "3.3.0" +version = "3.3.1" dependencies = [ "log", ] @@ -3823,7 +3825,7 @@ dependencies = [ [[package]] name = "openconnect" -version = "3.3.0" +version = "3.3.1" dependencies = [ "autotools", "cc", @@ -4880,16 +4882,6 @@ dependencies = [ "sha2 0.11.1", ] -[[package]] -name = "sec1" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" -dependencies = [ - "der", - "zeroize", -] - [[package]] name = "security-framework" version = "3.7.0" diff --git a/Cargo.toml b/Cargo.toml index 3f910a6..85d8a0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ members = [ [workspace.package] rust-version = "1.91" -version = "3.3.0" +version = "3.3.1" authors = ["Kevin Yue "] homepage = "https://github.com/yuezk/GlobalProtect-openconnect" edition = "2024" @@ -24,7 +24,6 @@ base64 = { version = "0.23", default-features = false, features = ["std"] } chrono = "0.4" clap = { version = "4", features = ["derive"] } clap-verbosity-flag = "3" -ctrlc = "3.4" directories = "6.0" dns-lookup = "4.0.2" env_logger = "0.11" diff --git a/apps/gpclient/src/connect/flow_tests.rs b/apps/gpclient/src/connect/flow_tests.rs index 8ace769..d0725b8 100644 --- a/apps/gpclient/src/connect/flow_tests.rs +++ b/apps/gpclient/src/connect/flow_tests.rs @@ -511,3 +511,62 @@ printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}' ); } } + +#[tokio::test] +async fn unsupported_and_malformed_identities_fail_before_password_prompt_or_network_connection() { + use gpapi::utils::request::RequestIdentityError; + let directory = tempfile::tempdir().unwrap(); + let malformed = directory.path().join("invalid.p12"); + std::fs::write(&malformed, b"not a certificate archive").unwrap(); + let fixtures = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/gpapi/tests/files/client-identity"); + + for (certificate, key, expected) in [ + ( + fixtures.join("rsa-pss-cert.pem"), + Some(fixtures.join("rsa-pss.pem")), + "algorithm", + ), + (fixtures.join("legacy-RC2-128.p12"), None, "encryption"), + (malformed, None, "malformed"), + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let server = format!("https://{}", listener.local_addr().unwrap()); + let mut argv = vec![ + "test".to_owned(), + server, + "--as-gateway".to_owned(), + "--certificate".to_owned(), + certificate.to_string_lossy().into_owned(), + ]; + if let Some(key) = key { + argv.extend(["--sslkey".to_owned(), key.to_string_lossy().into_owned()]); + } + let args = TestArgs::parse_from(argv).connect; + let lock = directory.path().join("client.pid"); + let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0); + let shared = SharedArgs { + ignore_tls_errors: false, + lock_file: &lock, + verbose: &verbose, + log_format: LogFormat::Text, + }; + let handler = ConnectHandler::new(&args, &shared); + let error = tokio::time::timeout(Duration::from_secs(2), handler.handle_attempt()) + .await + .expect("identity failure must not wait for a password or server") + .unwrap_err(); + match (expected, error.downcast_ref::()) { + ("algorithm", Some(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"))) => {} + ("encryption", Some(RequestIdentityError::UnsupportedEncryption)) => {} + ("malformed", Some(RequestIdentityError::InvalidPkcs12(_) | RequestIdentityError::InvalidCertificate)) => {} + _ => panic!("{expected}: unexpected failure {error:#}"), + } + assert!( + tokio::time::timeout(Duration::from_millis(20), listener.accept()) + .await + .is_err(), + "{expected}: local identity failure must precede network access" + ); + } +} diff --git a/apps/gpclient/src/connect/mod.rs b/apps/gpclient/src/connect/mod.rs index f5aec04..a81aa68 100644 --- a/apps/gpclient/src/connect/mod.rs +++ b/apps/gpclient/src/connect/mod.rs @@ -186,6 +186,8 @@ impl<'a> ConnectHandler<'a> { match identity_error { RequestIdentityError::UnsupportedEncryption | RequestIdentityError::UnsupportedKeyFormat + | RequestIdentityError::UnsupportedKeyAlgorithm(_) + | RequestIdentityError::KeyMismatch | RequestIdentityError::InvalidKey | RequestIdentityError::InvalidCertificate | RequestIdentityError::IncompletePkcs12 @@ -206,8 +208,12 @@ impl<'a> ConnectHandler<'a> { return Ok(()); } RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => { - let message = format!("Enter the {} passphrase:", cert_type); - let password = Password::new(&message) + let message = if *cert_type == "PKCS#12" { + "Enter the certificate file password:" + } else { + "Enter the private key password:" + }; + let password = Password::new(message) .without_confirmation() .with_display_mode(PasswordDisplayMode::Masked) .prompt()?; diff --git a/changelog.md b/changelog.md index cc88e36..287b2bc 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,20 @@ # Changelog +## 3.3.1 + +### Improved + +- Made client certificate errors clearer and added more detail to gateway sign-in logs. + +### Fixed + +- Restored support for client certificates with private extensions and legacy RC4-encrypted PKCS#12 files. +- Fixed certificate chain selection for PKCS#12 files containing multiple possible issuers. +- Fixed certificate validation and recovery guidance in both desktop interfaces. +- Fixed Native Shell Settings windows failing to activate from the macOS menu or reopening on the wrong page. +- Fixed keyboard navigation and Escape handling in the macOS Native Shell interface. +- Fixed AUR package builds and dependency metadata. + ## 3.3.0 ### Added diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 238e293..ca6646b 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -8,7 +8,6 @@ license = "MIT" [dependencies] nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true } common = { path = "../common" } -directories = { workspace = true, optional = true } anyhow.workspace = true base64.workspace = true dns-lookup = { workspace = true, optional = true } @@ -16,8 +15,10 @@ log.workspace = true reqwest.workspace = true rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls-pemfile = "2" +rustls-platform-verifier = "0.7" p12-keystore = "0.4.1" -sec1 = { version = "0.8.1", default-features = false, features = ["der"] } +pkcs12 = { version = "=0.2.0-pre.0", default-features = false } +cms = { version = "=0.3.0-pre.1", default-features = false } pem.workspace = true pkcs8 = { version = "0.11", features = ["pem", "encryption", "sha1-insecure", "3des", "des-insecure"] } x509-cert = { version = "0.3", default-features = false } @@ -43,7 +44,6 @@ chrono.workspace = true humantime.workspace = true netdev = { workspace = true, optional = true } socket2 = { version = "0.6", features = ["all"], optional = true } -os_info = { version = "3", default-features = false, optional = true } snow.workspace = true zeroize = { workspace = true, features = ["serde"] } getrandom = "0.4" @@ -64,8 +64,15 @@ oslog = { version = "0.2", default-features = false, optional = true } gtk = { version = "0.18", optional = true } [target.'cfg(target_os="linux")'.dependencies] +directories = { workspace = true, optional = true } libloading = { version = "0.9", optional = true } +[target.'cfg(target_os="macos")'.dependencies] +os_info = { version = "3", default-features = false, optional = true } + +[target.'cfg(target_os="windows")'.dependencies] +os_info = { version = "3", default-features = false } + [build-dependencies] cc = "1" pkg-config = "0.3" @@ -78,8 +85,8 @@ tokio = { workspace = true, features = ["test-util"] } [features] default = ["desktop"] -desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:os_info", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"] -tauri = ["desktop", "dep:tauri", "dep:gtk"] +desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:uzers", "dep:netdev", "dep:whoami", "dep:dns-lookup", "dep:socket2", "dep:libloading"] +tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"] clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"] webview-auth = [] logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] diff --git a/crates/gpapi/src/error/server_tls.rs b/crates/gpapi/src/error/server_tls.rs index 87c638c..ec13926 100644 --- a/crates/gpapi/src/error/server_tls.rs +++ b/crates/gpapi/src/error/server_tls.rs @@ -22,11 +22,23 @@ pub enum ServerTlsErrorKind { } impl ServerTlsError { - pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option { - Some(Self { + pub(crate) fn from_request( + server: &url::Url, + error: &(dyn Error + 'static), + has_client_identity: bool, + ) -> Option { + let kind = classify_with_identity(error, has_client_identity)?; + let error = anyhow::Error::new(Self { server: server.origin().ascii_serialization(), - kind: classify(error)?, - }) + kind, + }); + if has_client_identity && kind == ServerTlsErrorKind::ClientCertificateRequired { + Some(error.context( + "The VPN server could not use the configured client certificate. Check it with your VPN administrator", + )) + } else { + Some(error) + } } } @@ -60,6 +72,10 @@ impl ServerTlsErrorKind { } pub(super) fn classify(error: &(dyn Error + 'static)) -> Option { + classify_with_identity(error, false) +} + +fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option { let mut source = Some(error); while let Some(error) = source { if let Some(tls) = error.downcast_ref::() { @@ -71,6 +87,14 @@ pub(super) fn classify(error: &(dyn Error + 'static)) -> Option { ServerTlsErrorKind::ClientCertificateRequired } + rustls::Error::AlertReceived( + rustls::AlertDescription::BadCertificate + | rustls::AlertDescription::UnsupportedCertificate + | rustls::AlertDescription::CertificateRevoked + | rustls::AlertDescription::CertificateExpired + | rustls::AlertDescription::CertificateUnknown + | rustls::AlertDescription::UnknownCA, + ) if has_client_identity => ServerTlsErrorKind::ClientCertificateRequired, _ => ServerTlsErrorKind::Other, }); } @@ -123,6 +147,39 @@ mod tests { assert_eq!(classify(&std::io::Error::other("certificate verify failed")), None); } + #[test] + fn configured_identity_peer_errors_have_actionable_copy_without_becoming_server_trust_failures() { + let server = url::Url::parse("https://vpn.example.com/private/login").unwrap(); + for alert in [ + rustls::AlertDescription::CertificateRequired, + rustls::AlertDescription::BadCertificate, + rustls::AlertDescription::UnknownCA, + ] { + let error = rustls::Error::AlertReceived(alert); + let configured = ServerTlsError::from_request(&server, &error, true).unwrap(); + assert_eq!( + ServerTlsErrorKind::from_error(&configured), + Some(ServerTlsErrorKind::ClientCertificateRequired) + ); + let message = configured.to_string(); + assert!( + message.contains("configured client certificate") && message.contains("VPN administrator"), + "{message}" + ); + assert!( + !message.contains("password") && !message.contains("passphrase"), + "{message}" + ); + assert!(!message.contains("/private/login")); + } + let trust_error = rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer); + let classified = ServerTlsError::from_request(&server, &trust_error, true).unwrap(); + assert_eq!( + ServerTlsErrorKind::from_error(&classified), + Some(ServerTlsErrorKind::Certificate) + ); + } + fn server(tls: bool) -> (String, thread::JoinHandle<()>) { server_with_client_auth(tls, SslVerifyMode::NONE) } @@ -226,8 +283,8 @@ mod tests { .await .unwrap_err(); worker.join().unwrap(); - let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error).unwrap(); - assert_eq!(tls.kind, ServerTlsErrorKind::Other); + let tls = ServerTlsError::from_request(&url::Url::parse(&address).unwrap(), &error, false).unwrap(); + assert_eq!(ServerTlsErrorKind::from_error(&tls), Some(ServerTlsErrorKind::Other)); } #[tokio::test] @@ -314,6 +371,38 @@ mod tests { } } + #[tokio::test] + async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() { + use crate::{ + gp_params::GpParams, + os_profile::{ClientOs, OsProfile}, + portal::{PreloginOptions, prelogin}, + utils::request::ClientIdentity, + }; + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/files/client-identity"); + let identity = ClientIdentity::load( + fixtures.join("rsa-critical-extension.pem").to_str().unwrap(), + Some(fixtures.join("rsa-pkcs8.pem").to_str().unwrap()), + None, + ) + .unwrap(); + let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(crate::os_profile::test_snapshot())) + .client_identity(Some(identity)) + .ignore_tls_errors(true) + .build(); + let (address, worker) = server_with_client_auth(true, SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); + let error = prelogin(&address, ¶ms, PreloginOptions::default()) + .await + .unwrap_err(); + worker.join().unwrap(); + assert_eq!( + ServerTlsErrorKind::from_error(&error), + Some(ServerTlsErrorKind::ClientCertificateRequired) + ); + assert!(error.to_string().contains("configured client certificate"), "{error:#}"); + assert!(!error.to_string().contains("passphrase")); + } + #[tokio::test] async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() { use crate::{ @@ -411,10 +500,10 @@ mod tests { .await .unwrap_err(); assert_eq!( - ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error) - .unwrap() - .kind, - ServerTlsErrorKind::Certificate + ServerTlsErrorKind::from_error( + &ServerTlsError::from_request(&url::Url::parse(&server).unwrap(), &error, false).unwrap() + ), + Some(ServerTlsErrorKind::Certificate) ); } diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index 2cd7f69..d52661d 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -18,7 +18,7 @@ use crate::{ gp_params::GpParams, params::gateway_login::{self, GatewayLoginInput}, session::GatewayAuthentication, - utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, + utils::{normalize_server, parse_gp_response, redact::redact_uri, remove_url_scheme, xml::ElementExt}, }; pub enum GatewayLogin { @@ -181,14 +181,14 @@ async fn receive_gateway_login( log_gateway_login_context(context, client_ip, gp_params); let res = client - .post(login_url) + .post(&login_url) .form(&request_params.body) .send() .await .map_err(|e| { warn!("Network error: {:?}", e); - match crate::error::ServerTlsError::from_request(origin, &e) { - Some(tls) => anyhow::anyhow!(tls), + match crate::error::ServerTlsError::from_request(origin, &e, gp_params.has_client_identity()) { + Some(tls) => tls, None => anyhow::anyhow!(PortalError::NetworkError(e)), } })?; @@ -200,14 +200,30 @@ async fn receive_gateway_login( .map(<[u8]>::to_vec); let endpoint = res.remote_addr(); let url = res.url().clone(); + let http_version = res.version(); + let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned(); let res = parse_gp_response(res).await.map_err(|err| { - if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) { - return anyhow::anyhow!(tls); + // Redirect paths and query strings can contain authentication tokens. Log + // only the redacted origin and whether the response is from the login path. + warn!( + "Gateway login response failed: status={}, reason={}, http={:?}, origin={}, port={:?}, redirected={}, login_endpoint={}, content_type={:?}, client_certificate={}, ignore_tls_errors={}", + err.status, + err.reason, + http_version, + redact_uri(&url.origin().ascii_serialization()), + url.port_or_known_default(), + url.as_str() != login_url, + url.path() == "/ssl-vpn/login.esp", + content_type, + gp_params.has_client_identity(), + gp_params.ignore_tls_errors(), + ); + if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) { + return tls; } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return anyhow::anyhow!(crate::error::AuthenticationRejected); } - warn!("Gateway login response failed: {}", err.reason); anyhow::anyhow!("Gateway login error: {}", err.reason) })?; @@ -429,6 +445,85 @@ mod tests { .build() } + #[tokio::test] + async fn failed_login_logs_http_context_without_credentials_or_redirect_tokens() { + use std::cell::RefCell; + + thread_local! { + static MESSAGES: RefCell> = const { RefCell::new(Vec::new()) }; + } + struct Logger; + impl log::Log for Logger { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + + fn log(&self, record: &log::Record<'_>) { + let message = record.args().to_string(); + if message.starts_with("Gateway login response failed:") { + MESSAGES.with_borrow_mut(|messages| messages.push(message)); + } + } + + fn flush(&self) {} + } + log::set_logger(&Logger).unwrap(); + log::set_max_level(log::LevelFilter::Warn); + + for (status, reason, redirected) in [ + (403, None, false), + (502, None, true), + (401, Some("access denied"), false), + ] { + let body = "response-body-secret"; + let mut responses = Vec::new(); + if redirected { + responses.push( + "HTTP/1.1 307 Temporary Redirect\r\nLocation: /path-secret?token=query-secret\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(), + ); + } + let reason_header = reason + .map(|reason| format!("x-private-pan-globalprotect: {reason}\r\n")) + .unwrap_or_default(); + responses.push(format!( + "HTTP/1.1 {status} Error\r\nContent-Type: text/html\r\nSet-Cookie: cookie-secret\r\n{reason_header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )); + let (_, origin, server) = crate::session::transport::tests::login_gateway(responses).await; + let mut client = GatewayLoginClient::new(origin.as_str(), test_params()).unwrap(); + let credential = crate::credential::PasswordCredential::new("username-secret", "password-secret").into(); + let error = client + .login(&credential, None, &CancellationToken::new()) + .await + .err() + .unwrap(); + server.await.unwrap(); + + assert_eq!( + error.to_string(), + format!("Gateway login error: {}", reason.unwrap_or("")) + ); + let messages = MESSAGES.with_borrow_mut(std::mem::take); + assert_eq!(messages.len(), 1); + let message = &messages[0]; + for expected in [ + format!("status={status}"), + format!("reason={}", reason.unwrap_or("")), + format!("port={:?}", origin.port()), + format!("redirected={redirected}"), + format!("login_endpoint={}", !redirected), + "http=HTTP/1.1".into(), + "content_type=Some(\"text/html\")".into(), + "client_certificate=false".into(), + "ignore_tls_errors=false".into(), + ] { + assert!(message.contains(&expected), "missing {expected}: {message}"); + } + assert!(!message.contains("secret"), "sensitive data in diagnostic: {message}"); + assert!(!message.contains("127.0.0.1"), "unredacted origin: {message}"); + } + } + #[tokio::test] async fn gateway_login_cancels_stalled_headers_and_body() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; diff --git a/crates/gpapi/src/gp_params.rs b/crates/gpapi/src/gp_params.rs index aa7637e..6dad0d2 100644 --- a/crates/gpapi/src/gp_params.rs +++ b/crates/gpapi/src/gp_params.rs @@ -6,7 +6,7 @@ use zeroize::Zeroize; use crate::{ os_profile::{ClientOs, HostIdentity, OsProfile}, - utils::request::{ClientIdentity, create_identity}, + utils::request::ClientIdentity, }; #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type, Default)] @@ -160,21 +160,21 @@ impl GpParams { self.prepared_identity.as_ref() } + pub(crate) fn has_client_identity(&self) -> bool { + self.prepared_identity.is_some() || self.certificate.is_some() + } + pub(crate) fn client_builder(&self) -> anyhow::Result { - let mut builder = crate::utils::request::client_builder() - .tls_info(true) - .danger_accept_invalid_certs(self.ignore_tls_errors) - .user_agent(self.user_agent()); - if let Some(identity) = &self.prepared_identity { - builder = builder.identity(identity.request_identity()); + let builder = if let Some(identity) = &self.prepared_identity { + identity.client_builder(self.ignore_tls_errors)? } else if let Some(cert) = self.certificate.as_deref() { info!("Using client certificate authentication..."); - builder = builder.identity(create_identity( - cert, - self.sslkey.as_deref(), - self.key_password.as_deref(), - )?); - } + ClientIdentity::load(cert, self.sslkey.as_deref(), self.key_password.as_deref())? + .client_builder(self.ignore_tls_errors)? + } else { + crate::utils::request::client_builder().danger_accept_invalid_certs(self.ignore_tls_errors) + }; + let builder = builder.tls_info(true).user_agent(self.user_agent()); Ok(builder) } } diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 1d2cf96..e6baa6e 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -201,15 +201,15 @@ pub async fn retrieve_config( result = async { let res = client.post(&url).form(&request_params.body).send().await.map_err(|e| { warn!("Network error: {:?}", e); - match ServerTlsError::from_request(&server_url, &e) { - Some(tls) => anyhow::anyhow!(tls), + match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) { + Some(tls) => tls, None => anyhow::anyhow!(PortalError::NetworkError(e)), } })?; parse_gp_response(res).await.or_else(|err| { - if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { - return Err(anyhow::anyhow!(tls)); + if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { + return Err(tls); } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); @@ -274,15 +274,15 @@ async fn retrieve_csc_config( let res = client.post(&url).form(¶ms).send().await.map_err(|e| { warn!("Network error: {:?}", e); - match ServerTlsError::from_request(&server_url, &e) { - Some(tls) => anyhow::anyhow!(tls), + match ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) { + Some(tls) => tls, None => anyhow::anyhow!(PortalError::NetworkError(e)), } })?; parse_gp_response(res).await.or_else(|err| { - if let Some(tls) = ServerTlsError::from_request(&server_url, &err) { - return Err(anyhow::anyhow!(tls)); + if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { + return Err(tls); } if err.status == StatusCode::NOT_FOUND { bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 23e14ac..241f577 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -152,15 +152,15 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio let res = request.send().await.map_err(|e| { warn!("Network error: {:?}", e); - match crate::error::ServerTlsError::from_request(&server_url, &e) { - Some(error) => anyhow!(error), + match crate::error::ServerTlsError::from_request(&server_url, &e, gp_params.has_client_identity()) { + Some(error) => error, None => anyhow!(PortalError::NetworkError(e)), } })?; let res_xml = parse_gp_response(res).await.or_else(|err| { - if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err) { - return Err(anyhow!(tls)); + if let Some(tls) = crate::error::ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { + return Err(tls); } if err.status == StatusCode::NOT_FOUND { bail!(PortalError::PreloginError("Prelogin endpoint not found".to_string())) diff --git a/crates/gpapi/src/utils/certificate/client_key.rs b/crates/gpapi/src/utils/certificate/client_key.rs new file mode 100644 index 0000000..905e14a --- /dev/null +++ b/crates/gpapi/src/utils/certificate/client_key.rs @@ -0,0 +1,133 @@ +//! Client identity capabilities, separate from peer certificate policy. +use pkcs8::{ + ObjectIdentifier, PrivateKeyInfoRef, + der::{ + Decode, Reader, Tag, TagNumber, Tagged, + asn1::{AnyRef, BitStringRef, ContextSpecific, OctetStringRef}, + }, +}; +use rustls::pki_types::PrivateKeyDer; + +use crate::utils::request::RequestIdentityError; + +#[cfg(any( + target_os = "macos", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" +))] +#[path = "native_key.rs"] +mod implementation; +#[cfg(not(any( + target_os = "macos", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" +)))] +#[path = "portable_key.rs"] +mod implementation; + +pub(in crate::utils) use implementation::ClientKey; + +const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"); +const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"); +const EC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); +const ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112"); +const ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113"); +const P521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35"); +const DSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10040.4.1"); + +fn validate_algorithm(oid: ObjectIdentifier) -> Result<(), RequestIdentityError> { + match oid { + RSA | EC | ED25519 => Ok(()), + RSA_PSS => Err(RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS")), + ED448 => Err(RequestIdentityError::UnsupportedKeyAlgorithm("Ed448")), + DSA => Err(RequestIdentityError::UnsupportedKeyAlgorithm("DSA")), + _ => Err(RequestIdentityError::UnsupportedKeyAlgorithm( + "an unknown key algorithm", + )), + } +} + +fn validate_ec_parameters(parameters: Option>) -> Result<(), RequestIdentityError> { + if let Some(parameters) = parameters { + if parameters.tag() == Tag::ObjectIdentifier { + let curve = parameters + .decode_as::() + .map_err(|_| RequestIdentityError::InvalidKey)?; + if curve == P521 { + return Err(RequestIdentityError::UnsupportedKeyAlgorithm("P-521")); + } + return Ok(()); + } + return Err(RequestIdentityError::UnsupportedKeyAlgorithm( + "EC with explicit parameters", + )); + } + Ok(()) +} + +fn validate_ec_point(point: &[u8]) -> Result<(), RequestIdentityError> { + if matches!(point.first(), Some(2 | 3)) { + return Err(RequestIdentityError::UnsupportedKeyAlgorithm( + "EC with compressed public keys", + )); + } + Ok(()) +} + +fn validate_sec1(bytes: &[u8]) -> anyhow::Result<()> { + let (parameters, point) = AnyRef::from_der(bytes) + .and_then(|sequence| { + sequence.sequence(|reader| { + let version: u8 = reader.decode()?; + if version != 1 { + return Err(reader.error(Tag::Integer.value_error())); + } + let _: &OctetStringRef = reader.decode()?; + let parameters = ContextSpecific::>::decode_explicit(reader, TagNumber(0))?.map(|field| field.value); + let point = + ContextSpecific::>::decode_explicit(reader, TagNumber(1))?.map(|field| field.value); + Ok((parameters, point)) + }) + }) + .map_err(|_| RequestIdentityError::InvalidKey)?; + validate_ec_parameters(parameters)?; + if let Some(point) = point { + validate_ec_point(point.as_bytes().ok_or(RequestIdentityError::InvalidKey)?)?; + } + Ok(()) +} + +pub(super) fn validate_private_key(key: &PrivateKeyDer<'_>) -> anyhow::Result<()> { + match key { + PrivateKeyDer::Pkcs8(key) => { + let info = PrivateKeyInfoRef::from_der(key.secret_pkcs8_der()).map_err(|_| RequestIdentityError::InvalidKey)?; + validate_algorithm(info.algorithm.oid)?; + if info.algorithm.oid == EC { + validate_ec_parameters(info.algorithm.parameters)?; + validate_sec1(info.private_key.as_bytes())?; + } + } + PrivateKeyDer::Sec1(key) => validate_sec1(key.secret_sec1_der())?, + PrivateKeyDer::Pkcs1(_) => {} + _ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()), + } + Ok(()) +} + +pub(in crate::utils) fn validate_certificate(bytes: &[u8]) -> anyhow::Result<()> { + let certificate = x509_cert::Certificate::from_der(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)?; + let public_key = certificate.tbs_certificate().subject_public_key_info(); + validate_algorithm(public_key.algorithm.oid)?; + if public_key.algorithm.oid == EC { + validate_ec_parameters(public_key.algorithm.parameters.as_ref().map(|value| value.into()))?; + validate_ec_point( + public_key + .subject_public_key + .as_bytes() + .ok_or(RequestIdentityError::InvalidCertificate)?, + )?; + } + Ok(()) +} diff --git a/crates/gpapi/src/utils/certificate/gnutls.c b/crates/gpapi/src/utils/certificate/gnutls.c index 7ec81ef..33a749a 100644 --- a/crates/gpapi/src/utils/certificate/gnutls.c +++ b/crates/gpapi/src/utils/certificate/gnutls.c @@ -44,3 +44,272 @@ void gp_key_free(unsigned char *data, size_t length) { gnutls_free(data); } } + +#include +#include +#include + +/* Check only the signature, not whether this local certificate is trusted, + * current, or has extensions understood by the client. */ +int gp_certificate_verify_signature( + const unsigned char *certificate, size_t certificate_length, + const unsigned char *issuer_key, size_t issuer_key_length, + const unsigned char *message, size_t message_length, + const unsigned char *signature, size_t signature_length) { + gnutls_x509_crt_t child = NULL; + gnutls_pubkey_t public_key = NULL; + int result, algorithm; + if (certificate_length > UINT_MAX || issuer_key_length > UINT_MAX || + message_length > UINT_MAX || signature_length > UINT_MAX) return -1; + result = gnutls_global_init(); + if (result < 0) return -1; + gnutls_datum_t child_data = {(unsigned char *)certificate, (unsigned int)certificate_length}; + gnutls_datum_t key_data = {(unsigned char *)issuer_key, (unsigned int)issuer_key_length}; + gnutls_datum_t data = {(unsigned char *)message, (unsigned int)message_length}; + gnutls_datum_t sig = {(unsigned char *)signature, (unsigned int)signature_length}; + result = gnutls_x509_crt_init(&child); + if (result >= 0) result = gnutls_x509_crt_import(child, &child_data, GNUTLS_X509_FMT_DER); + if (result >= 0) result = gnutls_pubkey_init(&public_key); + if (result >= 0) result = gnutls_pubkey_import(public_key, &key_data, GNUTLS_X509_FMT_DER); + if (result >= 0) { + algorithm = gnutls_x509_crt_get_signature_algorithm(child); + if (algorithm < 0) result = algorithm; + else result = gnutls_pubkey_verify_data2(public_key, algorithm, + GNUTLS_VERIFY_ALLOW_BROKEN | GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1, &data, &sig) >= 0; + } + if (public_key != NULL) gnutls_pubkey_deinit(public_key); + if (child != NULL) gnutls_x509_crt_deinit(child); + gnutls_global_deinit(); + return result < 0 ? -1 : result; +} + +/* Stable private kinds, independent of the native enum values. */ +struct gp_client_key { + gnutls_privkey_t signer; + gnutls_pubkey_t public_key; +}; + +void gp_client_key_delete(struct gp_client_key *key) { + if (key == NULL) return; + if (key->public_key != NULL) gnutls_pubkey_deinit(key->public_key); + if (key->signer != NULL) gnutls_privkey_deinit(key->signer); + free(key); + gnutls_global_deinit(); +} + +int gp_client_key_new(const unsigned char *data, size_t length, int *kind, + struct gp_client_key **output) { + gnutls_x509_privkey_t input = NULL; + struct gp_client_key *key = NULL; + int result, algorithm; + *output = NULL; + *kind = 9; + if (length > UINT_MAX || gnutls_global_init() < 0) return 1; + key = calloc(1, sizeof(*key)); + if (key == NULL) { gnutls_global_deinit(); return 1; } + result = gnutls_x509_privkey_init(&input); + if (result >= 0) { + gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length}; + result = gnutls_x509_privkey_import2(input, &bytes, GNUTLS_X509_FMT_DER, NULL, 0); + } + if (result < 0) goto invalid; + algorithm = gnutls_x509_privkey_get_pk_algorithm(input); + if (algorithm == GNUTLS_PK_RSA_PSS) { *kind = 5; goto unsupported; } + if (algorithm == GNUTLS_PK_DSA) { *kind = 7; goto unsupported; } + if (algorithm == GNUTLS_PK_EDDSA_ED448) { *kind = 8; goto unsupported; } + result = gnutls_privkey_init(&key->signer); + if (result < 0) goto invalid; + result = gnutls_privkey_import_x509(key->signer, input, GNUTLS_PRIVKEY_IMPORT_COPY); + if (result < 0) goto invalid; + result = gnutls_pubkey_init(&key->public_key); + if (result < 0) goto invalid; + result = gnutls_pubkey_import_privkey(key->public_key, key->signer, 0, 0); + if (result < 0) goto invalid; + if (algorithm == GNUTLS_PK_RSA) *kind = 0; + else if (algorithm == GNUTLS_PK_EDDSA_ED25519) *kind = 4; + else if (algorithm == GNUTLS_PK_ECDSA) { + gnutls_ecc_curve_t curve; + gnutls_datum_t x = {NULL, 0}, y = {NULL, 0}; + result = gnutls_pubkey_export_ecc_raw(key->public_key, &curve, &x, &y); + gnutls_free(x.data); + gnutls_free(y.data); + if (result < 0) goto invalid; + if (curve == GNUTLS_ECC_CURVE_SECP256R1) *kind = 1; + else if (curve == GNUTLS_ECC_CURVE_SECP384R1) *kind = 2; + else if (curve == GNUTLS_ECC_CURVE_SECP521R1) { *kind = 3; goto unsupported; } + else { *kind = 6; goto unsupported; } + } else goto unsupported; + gnutls_x509_privkey_deinit(input); + *output = key; + return 0; +unsupported: + if (input != NULL) gnutls_x509_privkey_deinit(input); + gp_client_key_delete(key); + return 2; +invalid: + if (input != NULL) gnutls_x509_privkey_deinit(input); + gp_client_key_delete(key); + return 1; +} + +int gp_client_key_public(struct gp_client_key *key, unsigned char **output, size_t *length) { + gnutls_datum_t bytes = {NULL, 0}; + int result = gnutls_pubkey_export2(key->public_key, GNUTLS_X509_FMT_DER, &bytes); + *output = bytes.data; + *length = bytes.size; + return result; +} + +int gp_client_key_matches(struct gp_client_key *key, const unsigned char *data, size_t length) { + gnutls_x509_crt_t certificate = NULL; + gnutls_pubkey_t public_key = NULL; + unsigned char key_id[32], cert_id[32]; + size_t key_id_length = sizeof(key_id), cert_id_length = sizeof(cert_id); + int result; + if (length > UINT_MAX) return -1; + result = gnutls_x509_crt_init(&certificate); + if (result >= 0) { + gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length}; + result = gnutls_x509_crt_import(certificate, &bytes, GNUTLS_X509_FMT_DER); + } + if (result >= 0) result = gnutls_pubkey_init(&public_key); + if (result >= 0) result = gnutls_pubkey_import_x509(public_key, certificate, 0); + if (result >= 0) result = gnutls_pubkey_get_key_id(key->public_key, GNUTLS_KEYID_USE_SHA256, key_id, &key_id_length); + if (result >= 0) result = gnutls_pubkey_get_key_id(public_key, GNUTLS_KEYID_USE_SHA256, cert_id, &cert_id_length); + if (public_key != NULL) gnutls_pubkey_deinit(public_key); + if (certificate != NULL) gnutls_x509_crt_deinit(certificate); + if (result < 0) return result; + return key_id_length == cert_id_length && !memcmp(key_id, cert_id, key_id_length); +} + +int gp_client_key_sign(struct gp_client_key *key, unsigned short scheme, + const unsigned char *message, size_t length, + unsigned char **output, size_t *output_length) { + gnutls_sign_algorithm_t algorithm; + unsigned int flags = 0; + *output = NULL; + *output_length = 0; + if (length > UINT_MAX) return -1; + switch (scheme) { + case 0x0804: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA256; break; + case 0x0805: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA384; break; + case 0x0806: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA512; break; + case 0x0401: algorithm = GNUTLS_SIGN_RSA_SHA256; break; + case 0x0501: algorithm = GNUTLS_SIGN_RSA_SHA384; break; + case 0x0601: algorithm = GNUTLS_SIGN_RSA_SHA512; break; + case 0x0403: algorithm = GNUTLS_SIGN_ECDSA_SECP256R1_SHA256; break; + case 0x0503: algorithm = GNUTLS_SIGN_ECDSA_SECP384R1_SHA384; break; + case 0x0807: algorithm = GNUTLS_SIGN_EDDSA_ED25519; break; + default: return -1; + } + if (scheme >= 0x0804 && scheme <= 0x0806) + flags = GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH; + gnutls_datum_t bytes = {(unsigned char *)message, (unsigned int)length}; + gnutls_datum_t signature = {NULL, 0}; + int result = gnutls_privkey_sign_data2(key->signer, algorithm, flags, &bytes, &signature); + *output = signature.data; + *output_length = signature.size; + return result; +} + +#include +#include + +/* Invoked only after Rust has identified the supported RC4 archive scheme. + * Integrity and identity-count checks precede the native leaf selection. */ +int gp_pkcs12_identity(const unsigned char *input, size_t length, const char *password, + unsigned char **certificate, size_t *certificate_length, + unsigned char **private_key, size_t *private_key_length) { + gnutls_pkcs12_t archive = NULL; + gnutls_x509_privkey_t key = NULL; + gnutls_x509_crt_t *chain = NULL, *extra = NULL; + unsigned int chain_length = 0, extra_length = 0; + gnutls_datum_t exported_key = {NULL, 0}; + unsigned int key_count = 0, cert_count = 0; + int result, status = 5; + *certificate = NULL; + *certificate_length = 0; + *private_key = NULL; + *private_key_length = 0; + if (length > UINT_MAX || gnutls_global_init() < 0) return 5; + result = gnutls_pkcs12_init(&archive); + if (result >= 0) { + gnutls_datum_t bytes = {(unsigned char *)input, (unsigned int)length}; + result = gnutls_pkcs12_import(archive, &bytes, GNUTLS_X509_FMT_DER, 0); + } + if (result < 0) goto out; + result = gnutls_pkcs12_verify_mac(archive, password); + if (result == GNUTLS_E_MAC_VERIFY_FAILED) { status = 1; goto out; } + if (result < 0 && result != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) goto out; + for (int index = 0; ; index++) { + gnutls_pkcs12_bag_t bag; + result = gnutls_pkcs12_bag_init(&bag); + if (result < 0) goto out; + result = gnutls_pkcs12_get_bag(archive, index, bag); + if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { + gnutls_pkcs12_bag_deinit(bag); + break; + } + if (result >= 0 && gnutls_pkcs12_bag_get_type(bag, 0) == GNUTLS_BAG_ENCRYPTED) + result = gnutls_pkcs12_bag_decrypt(bag, password); + if (result < 0) { + gnutls_pkcs12_bag_deinit(bag); + if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1; + else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4; + goto out; + } + int count = gnutls_pkcs12_bag_get_count(bag); + if (count < 0) { gnutls_pkcs12_bag_deinit(bag); goto out; } + for (int item = 0; item < count; item++) { + int type = gnutls_pkcs12_bag_get_type(bag, item); + if (type == GNUTLS_BAG_PKCS8_KEY || type == GNUTLS_BAG_PKCS8_ENCRYPTED_KEY) key_count++; + if (type == GNUTLS_BAG_CERTIFICATE) cert_count++; + } + gnutls_pkcs12_bag_deinit(bag); + } + if (key_count == 0 || cert_count == 0) { status = 2; goto out; } + if (key_count != 1) { status = 3; goto out; } + result = gnutls_pkcs12_simple_parse(archive, password, &key, &chain, &chain_length, + &extra, &extra_length, NULL, GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED); + if (result < 0) { + if (result == GNUTLS_E_DECRYPTION_FAILED) status = 1; + else if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE) status = 4; + else if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) status = 6; + goto out; + } + if (key == NULL || chain_length == 0) { status = 2; goto out; } + result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER, NULL, GNUTLS_PKCS_PLAIN, &exported_key); + if (result < 0) goto out; + for (unsigned int index = 0; index < chain_length; index++) { + gnutls_datum_t part = {NULL, 0}; + result = gnutls_x509_crt_export2(chain[index], GNUTLS_X509_FMT_PEM, &part); + if (result < 0) goto out; + if (part.size > SIZE_MAX - *certificate_length) { gnutls_free(part.data); goto out; } + unsigned char *buffer = gnutls_realloc(*certificate, *certificate_length + part.size); + if (buffer == NULL) { gnutls_free(part.data); goto out; } + memcpy(buffer + *certificate_length, part.data, part.size); + *certificate = buffer; + *certificate_length += part.size; + gnutls_free(part.data); + } + *private_key = exported_key.data; + *private_key_length = exported_key.size; + exported_key.data = NULL; + exported_key.size = 0; + status = 0; +out: + if (status != 0) { + gp_key_free(*certificate, *certificate_length); + *certificate = NULL; + *certificate_length = 0; + } + gp_key_free(exported_key.data, exported_key.size); + if (key != NULL) gnutls_x509_privkey_deinit(key); + for (unsigned int index = 0; index < chain_length; index++) gnutls_x509_crt_deinit(chain[index]); + for (unsigned int index = 0; index < extra_length; index++) gnutls_x509_crt_deinit(extra[index]); + gnutls_free(chain); + gnutls_free(extra); + if (archive != NULL) gnutls_pkcs12_deinit(archive); + gnutls_global_deinit(); + return status; +} diff --git a/crates/gpapi/src/utils/certificate/gnutls.rs b/crates/gpapi/src/utils/certificate/gnutls.rs index a6eaeda..10eb531 100644 --- a/crates/gpapi/src/utils/certificate/gnutls.rs +++ b/crates/gpapi/src/utils/certificate/gnutls.rs @@ -1,11 +1,22 @@ use std::ffi::{c_char, c_int}; use pkcs8::SecretDocument; +use pkcs8::der::{Encode, asn1::ObjectIdentifier}; use zeroize::Zeroizing; use crate::utils::request::RequestIdentityError; unsafe extern "C" { + fn gp_certificate_verify_signature( + certificate: *const u8, + certificate_length: usize, + issuer_key: *const u8, + issuer_key_length: usize, + message: *const u8, + message_length: usize, + signature: *const u8, + signature_length: usize, + ) -> c_int; fn gp_key_import( input: *const u8, length: usize, @@ -14,9 +25,58 @@ unsafe extern "C" { output: *mut *mut u8, output_length: *mut usize, ) -> c_int; + fn gp_pkcs12_identity( + input: *const u8, + length: usize, + password: *const c_char, + certificate: *mut *mut u8, + certificate_length: *mut usize, + key: *mut *mut u8, + key_length: *mut usize, + ) -> c_int; fn gp_key_free(data: *mut u8, length: usize); } +pub(super) fn verify_certificate_signature( + certificate: &x509_cert::Certificate, + issuer: &x509_cert::Certificate, + message: &[u8], + signature: &[u8], +) -> anyhow::Result { + const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"); + const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"); + let mut issuer_key = issuer.tbs_certificate().subject_public_key_info().clone(); + if certificate.signature_algorithm().oid == RSA_PSS { + if !matches!(issuer_key.algorithm.oid, RSA | RSA_PSS) { + return Ok(false); + } + // GnuTLS's generic verifier takes PSS parameters from the imported key. + // Give this verification operation the certificate's full AlgorithmIdentifier, + // including salt length, rather than the default implied by its signature enum. + // This temporary SPKI never changes the certificates sent to the server. + issuer_key.algorithm = certificate.signature_algorithm().clone(); + } + let issuer_key = issuer_key.to_der()?; + let certificate = certificate.to_der()?; + let result = unsafe { + gp_certificate_verify_signature( + certificate.as_ptr(), + certificate.len(), + issuer_key.as_ptr(), + issuer_key.len(), + message.as_ptr(), + message.len(), + signature.as_ptr(), + signature.len(), + ) + }; + match result { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(RequestIdentityError::InvalidCertificate.into()), + } +} + struct ExportedKey { data: *mut u8, length: usize, @@ -64,3 +124,55 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str _ => Err(RequestIdentityError::InvalidKey.into()), } } + +pub(in crate::utils) fn archive( + bytes: &[u8], + passphrase: Option<&str>, +) -> anyhow::Result<(Zeroizing>, SecretDocument)> { + let mut password = Zeroizing::new(passphrase.unwrap_or_default().as_bytes().to_vec()); + anyhow::ensure!( + !password.contains(&0), + "PKCS#12 passphrases containing NUL are not supported" + ); + password.push(0); + let mut certificate = ExportedKey { + data: std::ptr::null_mut(), + length: 0, + }; + let mut key = ExportedKey { + data: std::ptr::null_mut(), + length: 0, + }; + let result = unsafe { + gp_pkcs12_identity( + bytes.as_ptr(), + bytes.len(), + password.as_ptr().cast(), + &mut certificate.data, + &mut certificate.length, + &mut key.data, + &mut key.length, + ) + }; + match result { + 0 => { + anyhow::ensure!( + !certificate.data.is_null() && certificate.length > 0, + "Invalid certificate file" + ); + anyhow::ensure!(!key.data.is_null() && key.length > 0, "Invalid private key"); + let certificate = + Zeroizing::new(unsafe { std::slice::from_raw_parts(certificate.data, certificate.length) }.to_vec()); + let key = SecretDocument::try_from(unsafe { std::slice::from_raw_parts(key.data, key.length) }) + .map_err(|_| RequestIdentityError::InvalidKey)?; + Ok((certificate, key)) + } + 1 if passphrase.is_none() => Err(RequestIdentityError::NoPassphrase("PKCS#12").into()), + 1 => Err(RequestIdentityError::InvalidPkcs12(p12_keystore::error::Error::InvalidData).into()), + 2 => Err(RequestIdentityError::IncompletePkcs12.into()), + 3 => Err(RequestIdentityError::AmbiguousPkcs12.into()), + 4 => Err(RequestIdentityError::UnsupportedEncryption.into()), + 6 => Err(RequestIdentityError::KeyMismatch.into()), + _ => Err(RequestIdentityError::InvalidCertificate.into()), + } +} diff --git a/crates/gpapi/src/utils/certificate/issuer.rs b/crates/gpapi/src/utils/certificate/issuer.rs new file mode 100644 index 0000000..bf51539 --- /dev/null +++ b/crates/gpapi/src/utils/certificate/issuer.rs @@ -0,0 +1,18 @@ +use pkcs8::der::{Decode, Encode}; + +use crate::utils::request::RequestIdentityError; + +/// Identify the signing issuer, without applying trust, expiry or extension policy +/// to a local identity. The VPN server remains responsible for those checks. +pub(super) fn is_issuer(certificate: &[u8], issuer: &[u8]) -> anyhow::Result { + let child = x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?; + let parent = x509_cert::Certificate::from_der(issuer).map_err(|_| RequestIdentityError::InvalidCertificate)?; + if child.tbs_certificate().issuer() != parent.tbs_certificate().subject() { + return Ok(false); + } + let signature = child + .signature() + .as_bytes() + .ok_or(RequestIdentityError::InvalidCertificate)?; + super::platform_import::verify_certificate_signature(&child, &parent, &child.tbs_certificate().to_der()?, signature) +} diff --git a/crates/gpapi/src/utils/certificate/mod.rs b/crates/gpapi/src/utils/certificate/mod.rs index 0d363be..864543c 100644 --- a/crates/gpapi/src/utils/certificate/mod.rs +++ b/crates/gpapi/src/utils/certificate/mod.rs @@ -1,4 +1,9 @@ +mod client_key; +mod issuer; +pub(super) use client_key::{ClientKey, validate_certificate}; + pub(super) mod pkcs12; +mod pkcs12_format; #[cfg(any( target_os = "macos", @@ -7,14 +12,14 @@ pub(super) mod pkcs12; target_os = "openbsd" ))] #[path = "gnutls.rs"] -mod legacy_key; +mod platform_import; #[cfg(not(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd" )))] -#[path = "unsupported.rs"] -mod legacy_key; +#[path = "portable_import.rs"] +mod platform_import; -pub(super) use legacy_key::decrypt as decrypt_key; +pub(super) use platform_import::{archive, decrypt as decrypt_key}; diff --git a/crates/gpapi/src/utils/certificate/native_key.rs b/crates/gpapi/src/utils/certificate/native_key.rs new file mode 100644 index 0000000..802bcfa --- /dev/null +++ b/crates/gpapi/src/utils/certificate/native_key.rs @@ -0,0 +1,307 @@ +use std::{ + ffi::{c_int, c_void}, + fmt, + ptr::NonNull, + sync::{Arc, Mutex}, +}; + +use crate::utils::request::RequestIdentityError; +use rustls::{ + SignatureAlgorithm, SignatureScheme, + pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer}, + sign::{Signer, SigningKey}, +}; + +unsafe extern "C" { + fn gp_client_key_new(data: *const u8, length: usize, kind: *mut c_int, output: *mut *mut c_void) -> c_int; + fn gp_client_key_delete(key: *mut c_void); + fn gp_client_key_public(key: *mut c_void, output: *mut *mut u8, length: *mut usize) -> c_int; + fn gp_client_key_matches(key: *mut c_void, cert: *const u8, length: usize) -> c_int; + fn gp_client_key_sign( + key: *mut c_void, + scheme: u16, + message: *const u8, + length: usize, + output: *mut *mut u8, + output_length: *mut usize, + ) -> c_int; + fn gp_key_free(data: *mut u8, length: usize); +} + +struct NativeKey(NonNull); + +// The handle is not thread-affine. All access and final release occur under its +// Rust owner; shared operations use the mutex in ClientKey. +unsafe impl Send for NativeKey {} + +impl Drop for NativeKey { + fn drop(&mut self) { + unsafe { gp_client_key_delete(self.0.as_ptr()) }; + } +} + +struct NativeBytes { + data: *mut u8, + length: usize, +} +impl Drop for NativeBytes { + fn drop(&mut self) { + unsafe { gp_key_free(self.data, self.length) }; + } +} +impl NativeBytes { + fn new() -> Self { + Self { + data: std::ptr::null_mut(), + length: 0, + } + } + fn copy(&self) -> anyhow::Result> { + anyhow::ensure!( + !self.data.is_null() && self.length > 0, + "Client certificate operation failed" + ); + Ok(unsafe { std::slice::from_raw_parts(self.data, self.length) }.to_vec()) + } +} + +#[derive(Clone)] +pub(in crate::utils) struct ClientKey { + key: Arc>, + kind: c_int, + public_key: Vec, +} + +impl fmt::Debug for ClientKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ClientKey") + .field("algorithm", &self.algorithm()) + .finish_non_exhaustive() + } +} + +impl ClientKey { + pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result { + super::validate_private_key(key)?; + let bytes = key.secret_der(); + let mut kind = 0; + let mut pointer = std::ptr::null_mut(); + let result = unsafe { gp_client_key_new(bytes.as_ptr(), bytes.len(), &mut kind, &mut pointer) }; + if result == 2 { + let algorithm = match kind { + 3 => "P-521", + 5 => "RSA-PSS", + 6 => "an unsupported elliptic curve", + 7 => "DSA", + 8 => "Ed448", + _ => "an unknown key algorithm", + }; + return Err(RequestIdentityError::UnsupportedKeyAlgorithm(algorithm).into()); + } + if result != 0 { + return Err(RequestIdentityError::InvalidKey.into()); + } + let key = NativeKey(NonNull::new(pointer).ok_or(RequestIdentityError::InvalidKey)?); + let mut exported = NativeBytes::new(); + let result = unsafe { gp_client_key_public(key.0.as_ptr(), &mut exported.data, &mut exported.length) }; + anyhow::ensure!(result == 0, "Could not read the client certificate's public key"); + Ok(Self { + key: Arc::new(Mutex::new(key)), + kind, + public_key: exported.copy()?, + }) + } + + pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result { + let key = self + .key + .lock() + .map_err(|_| anyhow::anyhow!("The client certificate is unavailable"))?; + match unsafe { gp_client_key_matches(key.0.as_ptr(), certificate.as_ptr(), certificate.len()) } { + 1 => Ok(true), + 0 => Ok(false), + _ => Err(RequestIdentityError::InvalidCertificate.into()), + } + } + + fn schemes(&self) -> &'static [SignatureScheme] { + use SignatureScheme::*; + match self.kind { + 0 => &[ + RSA_PSS_SHA512, + RSA_PSS_SHA384, + RSA_PSS_SHA256, + RSA_PKCS1_SHA512, + RSA_PKCS1_SHA384, + RSA_PKCS1_SHA256, + ], + // Rustls does not expose the negotiated TLS version here. Keep TLS 1.3 + // curve/hash requirements; TLS 1.2 cross-curve hash offers remain unsupported. + 1 => &[ECDSA_NISTP256_SHA256], + 2 => &[ECDSA_NISTP384_SHA384], + 4 => &[ED25519], + _ => &[], + } + } +} + +impl SigningKey for ClientKey { + fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option> { + self + .schemes() + .iter() + .copied() + .find(|scheme| offered.contains(scheme)) + .map(|scheme| { + Box::new(ClientSigner { + key: self.clone(), + scheme, + }) as Box + }) + } + fn public_key(&self) -> Option> { + Some(SubjectPublicKeyInfoDer::from(self.public_key.as_slice())) + } + fn algorithm(&self) -> SignatureAlgorithm { + match self.kind { + 0 => SignatureAlgorithm::RSA, + 4 => SignatureAlgorithm::ED25519, + _ => SignatureAlgorithm::ECDSA, + } + } +} + +#[derive(Debug)] +struct ClientSigner { + key: ClientKey, + scheme: SignatureScheme, +} +impl Signer for ClientSigner { + fn sign(&self, message: &[u8]) -> Result, rustls::Error> { + let error = || rustls::Error::General("Could not sign with the client certificate".into()); + let key = self.key.key.lock().map_err(|_| error())?; + let mut output = NativeBytes::new(); + let result = unsafe { + gp_client_key_sign( + key.0.as_ptr(), + self.scheme.into(), + message.as_ptr(), + message.len(), + &mut output.data, + &mut output.length, + ) + }; + if result != 0 { + return Err(error()); + } + output.copy().map_err(|_| error()) + } + fn scheme(&self) -> SignatureScheme { + self.scheme + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openssl::{ + hash::MessageDigest, + pkey::PKey, + rsa::Padding, + sign::{RsaPssSaltlen, Verifier}, + }; + + fn fixture(name: &str) -> Vec { + std::fs::read( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/files/client-identity") + .join(name), + ) + .unwrap() + } + + fn native_key(bytes: &[u8]) -> ClientKey { + let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes)) + .unwrap() + .unwrap(); + ClientKey::load(&key).unwrap() + } + + #[test] + fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() { + let bytes = fixture("rsa-pkcs8.pem"); + let key = native_key(&bytes); + let oracle = PKey::private_key_from_pem(&bytes).unwrap(); + let message = b"client authentication regression"; + for (scheme, digest, pss) in [ + (SignatureScheme::RSA_PSS_SHA256, MessageDigest::sha256(), true), + (SignatureScheme::RSA_PSS_SHA384, MessageDigest::sha384(), true), + (SignatureScheme::RSA_PSS_SHA512, MessageDigest::sha512(), true), + (SignatureScheme::RSA_PKCS1_SHA256, MessageDigest::sha256(), false), + (SignatureScheme::RSA_PKCS1_SHA384, MessageDigest::sha384(), false), + (SignatureScheme::RSA_PKCS1_SHA512, MessageDigest::sha512(), false), + ] { + let signer = key.choose_scheme(&[scheme]).unwrap(); + assert_eq!(signer.scheme(), scheme); + let signature = signer.sign(message).unwrap(); + let mut verifier = Verifier::new(digest, &oracle).unwrap(); + if pss { + verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap(); + verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap(); + verifier.set_rsa_mgf1_md(digest).unwrap(); + } + assert!(verifier.verify_oneshot(&signature, message).unwrap(), "{scheme:?}"); + } + assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none()); + } + + #[test] + fn p256_signatures_verify_with_an_independent_backend() { + let bytes = fixture("ec-pkcs8.pem"); + let key = native_key(&bytes); + let oracle = PKey::private_key_from_pem(&bytes).unwrap(); + let signer = key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).unwrap(); + let message = b"native client key signature"; + let signature = signer.sign(message).unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap(); + assert!(verifier.verify_oneshot(&signature, message).unwrap()); + assert!(key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256]).is_none()); + } + + #[test] + fn unsupported_key_types_fail_at_import() { + for (name, algorithm) in [("ec-p521.pem", "P-521"), ("rsa-pss.pem", "RSA-PSS")] { + let bytes = fixture(name); + let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes)) + .unwrap() + .unwrap(); + let error = ClientKey::load(&private_key).unwrap_err(); + assert!(matches!(error.downcast_ref::(), + Some(RequestIdentityError::UnsupportedKeyAlgorithm(actual)) if *actual == algorithm)); + } + } + + #[test] + fn a_key_remains_usable_when_shared_clients_sign_concurrently() { + let key = native_key(&fixture("rsa-pkcs8.pem")); + let mut workers = Vec::new(); + for _ in 0..4 { + let key = key.clone(); + workers.push(std::thread::spawn(move || { + key + .choose_scheme(&[SignatureScheme::RSA_PSS_SHA256]) + .unwrap() + .sign(b"shared identity") + .unwrap() + })); + } + let oracle = PKey::private_key_from_pem(&fixture("rsa-pkcs8.pem")).unwrap(); + for worker in workers { + let signature = worker.join().unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha256(), &oracle).unwrap(); + verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap(); + verifier.set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH).unwrap(); + assert!(verifier.verify_oneshot(&signature, b"shared identity").unwrap()); + } + } +} diff --git a/crates/gpapi/src/utils/certificate/pkcs12.rs b/crates/gpapi/src/utils/certificate/pkcs12.rs index d6415b4..73212e5 100644 --- a/crates/gpapi/src/utils/certificate/pkcs12.rs +++ b/crates/gpapi/src/utils/certificate/pkcs12.rs @@ -1,22 +1,37 @@ use p12_keystore::Pkcs12Archive; -use rustls::{ - pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}, - sign::CertifiedKey, +use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; + +use super::{ + ClientKey, + pkcs12_format::{self, ArchiveBackend}, }; +use crate::utils::{client_tls, request::RequestIdentityError}; -use crate::utils::request::{RequestIdentityError, pem_request_identity}; - -pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result { +pub(in crate::utils) fn certified_key( + bytes: &[u8], + passphrase: Option<&str>, +) -> anyhow::Result> { 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 pkcs12_format::backend(bytes)? == ArchiveBackend::NativeRc4 { + let (certificate, key) = super::archive(bytes, passphrase)?; + let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?; + return client_tls::pem_certified_key(&certificate, key.as_bytes()); + } + let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| match error { + p12_keystore::error::Error::UnsupportedEncryptionScheme | p12_keystore::error::Error::UnsupportedMacAlgorithm => { + RequestIdentityError::UnsupportedEncryption } + p12_keystore::error::Error::MacError(_) + | p12_keystore::error::Error::UnpadError + | p12_keystore::error::Error::Pkcs5Error(_) + if passphrase.is_none() => + { + RequestIdentityError::NoPassphrase("PKCS#12") + } + error => RequestIdentityError::InvalidPkcs12(error), })?; if archive.keys.is_empty() || archive.certs.is_empty() { return Err(RequestIdentityError::IncompletePkcs12.into()); @@ -25,7 +40,8 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh return Err(RequestIdentityError::AmbiguousPkcs12.into()); } let key = &archive.keys[0].key; - let provider = rustls::crypto::ring::default_provider(); + let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec())); + let signing_key = ClientKey::load(&private_key)?; let mut certs = Vec::new(); for bag in &archive.certs { if !certs @@ -35,38 +51,36 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh 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 matches = Vec::new(); + for (index, cert) in certs.iter().enumerate() { + if signing_key.matches_certificate(cert.as_der())? { + matches.push(index); + } + } + let leaf = match matches.first() { + Some(leaf) => *leaf, + None => return Err(RequestIdentityError::KeyMismatch.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() { + if super::issuer::is_issuer(current.as_der(), current.as_der())? { break; } - let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else { + let mut parent = None; + for (index, candidate) in certs.iter().enumerate() { + if super::issuer::is_issuer(current.as_der(), candidate.as_der())? { + parent = Some(index); + break; + } + } + let Some(parent) = parent 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()) + client_tls::pem_certified_key(&chain, key.as_bytes()) } diff --git a/crates/gpapi/src/utils/certificate/pkcs12_format.rs b/crates/gpapi/src/utils/certificate/pkcs12_format.rs new file mode 100644 index 0000000..06b5a9c --- /dev/null +++ b/crates/gpapi/src/utils/certificate/pkcs12_format.rs @@ -0,0 +1,137 @@ +//! Select an archive importer from decoded encryption metadata, before passwords. +use cms::encrypted_data::EncryptedData; +use pkcs8::{ + ObjectIdentifier, + der::{ + Decode, Encode, + asn1::{ContextSpecific, OctetString}, + }, +}; +use pkcs12::{ + AuthenticatedSafe, + pbe_params::{EncryptedPrivateKeyInfo, Pkcs12PbeParams}, + pfx::Pfx, + safe_bag::SafeContents, +}; + +use crate::utils::request::RequestIdentityError; + +const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"); +const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6"); +const ENCRYPTED_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2"); +const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13"); +const RC4_128: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.1"); +const DES3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3"); +const RC2_40: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.6"); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ArchiveBackend { + Rust, + NativeRc4, +} + +fn invalid(_: pkcs8::der::Error) -> RequestIdentityError { + RequestIdentityError::InvalidCertificate +} + +/// Inspect only visible metadata. Encrypted safe contents remain opaque until +/// the selected importer verifies the MAC and decrypts them. +pub(super) fn backend(bytes: &[u8]) -> Result { + let pfx = Pfx::from_der(bytes).map_err(invalid)?; + if pfx.auth_safe.content_type != DATA { + return Err(RequestIdentityError::UnsupportedEncryption); + } + let contents = pfx.auth_safe.content.decode_as::().map_err(invalid)?; + let safes = AuthenticatedSafe::from_der(contents.as_bytes()).map_err(invalid)?; + let mut selected = ArchiveBackend::Rust; + for safe in safes { + if safe.content_type == ENCRYPTED_DATA { + let encrypted = safe.content.decode_as::().map_err(invalid)?; + let algorithm = encrypted.enc_content_info.content_enc_alg; + inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?; + } else if safe.content_type == DATA { + let contents = safe.content.decode_as::().map_err(invalid)?; + let bags = SafeContents::from_der(contents.as_bytes()).map_err(invalid)?; + for bag in bags { + if bag.bag_id == ENCRYPTED_KEY { + let encrypted = ContextSpecific::::from_der(&bag.bag_value).map_err(invalid)?; + let algorithm = encrypted.value.encryption_algorithm; + inspect_algorithm(algorithm.oid, algorithm.parameters.as_ref(), &mut selected)?; + } + } + } else { + return Err(RequestIdentityError::UnsupportedEncryption); + } + } + Ok(selected) +} + +fn inspect_algorithm( + oid: ObjectIdentifier, + parameters: Option<&pkcs8::der::Any>, + selected: &mut ArchiveBackend, +) -> Result<(), RequestIdentityError> { + let parameters = parameters + .ok_or(RequestIdentityError::InvalidCertificate)? + .to_der() + .map_err(invalid)?; + if oid == PBES2 { + pkcs8::pkcs5::pbes2::Parameters::from_der(¶meters).map_err(|error| match error.kind() { + pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption, + _ => RequestIdentityError::InvalidCertificate, + })?; + } else if matches!(oid, RC4_128 | DES3 | RC2_40) { + Pkcs12PbeParams::from_der(¶meters).map_err(invalid)?; + if oid == RC4_128 { + *selected = ArchiveBackend::NativeRc4; + } + } else { + return Err(RequestIdentityError::UnsupportedEncryption); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn published_archive_formats_choose_their_importer_from_metadata() { + for name in [ + "modern.p12", + "legacy-rc2.p12", + "empty-password.p12", + "unicode-password.p12", + "no-bag-ids.p12", + ] { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/files/client-identity") + .join(name); + assert_eq!( + backend(&std::fs::read(path).unwrap()).unwrap(), + ArchiveBackend::Rust, + "{name}" + ); + } + assert_eq!( + backend(include_bytes!( + "../../../tests/files/client-identity/legacy-RC4-128.p12" + )) + .unwrap(), + ArchiveBackend::NativeRc4 + ); + } + + #[test] + fn unsupported_archive_encryption_is_terminal_before_password_handling() { + for bytes in [ + include_bytes!("../../../tests/files/client-identity/legacy-RC2-128.p12").as_slice(), + include_bytes!("../../../tests/files/client-identity/legacy-2DES.p12").as_slice(), + ] { + assert!(matches!( + backend(bytes), + Err(RequestIdentityError::UnsupportedEncryption) + )); + } + } +} diff --git a/crates/gpapi/src/utils/certificate/portable_import.rs b/crates/gpapi/src/utils/certificate/portable_import.rs new file mode 100644 index 0000000..7532c6a --- /dev/null +++ b/crates/gpapi/src/utils/certificate/portable_import.rs @@ -0,0 +1,46 @@ +//! Portable certificate verification; native legacy import is unavailable here. +use crate::utils::request::RequestIdentityError; +use pkcs8::der::{Decode, Encode, asn1::AnyRef}; + +pub(in crate::utils) fn decrypt( + _bytes: &[u8], + _pem: bool, + _passphrase: Option<&str>, +) -> anyhow::Result { + Err(RequestIdentityError::UnsupportedEncryption.into()) +} + +pub(in crate::utils) fn archive( + _bytes: &[u8], + _passphrase: Option<&str>, +) -> anyhow::Result<(zeroize::Zeroizing>, pkcs8::SecretDocument)> { + Err(RequestIdentityError::UnsupportedEncryption.into()) +} + +pub(super) fn verify_certificate_signature( + child: &x509_cert::Certificate, + parent: &x509_cert::Certificate, + message: &[u8], + signature: &[u8], +) -> anyhow::Result { + let public_key = parent.tbs_certificate().subject_public_key_info(); + let key_algorithm = public_key.algorithm.to_der()?; + let signature_algorithm = child.signature_algorithm().to_der()?; + let key_algorithm = AnyRef::from_der(&key_algorithm)?.value(); + let signature_algorithm = AnyRef::from_der(&signature_algorithm)?.value(); + let key = public_key + .subject_public_key + .as_bytes() + .ok_or(RequestIdentityError::InvalidCertificate)?; + Ok( + rustls::crypto::ring::default_provider() + .signature_verification_algorithms + .all + .iter() + .any(|algorithm| { + algorithm.public_key_alg_id().as_ref() == key_algorithm + && algorithm.signature_alg_id().as_ref() == signature_algorithm + && algorithm.verify_signature(key, message, signature).is_ok() + }), + ) +} diff --git a/crates/gpapi/src/utils/certificate/portable_key.rs b/crates/gpapi/src/utils/certificate/portable_key.rs new file mode 100644 index 0000000..d84e92a --- /dev/null +++ b/crates/gpapi/src/utils/certificate/portable_key.rs @@ -0,0 +1,41 @@ +use crate::utils::request::RequestIdentityError; +use pkcs8::der::{Decode, Encode}; +use rustls::{ + SignatureAlgorithm, SignatureScheme, + pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer}, + sign::{Signer, SigningKey}, +}; +use std::sync::Arc; + +#[derive(Debug)] +pub(in crate::utils) struct ClientKey { + key: Arc, +} + +impl ClientKey { + pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result { + super::validate_private_key(key)?; + let key = rustls::crypto::ring::default_provider() + .key_provider + .load_private_key(key.clone_key()) + .map_err(|_| RequestIdentityError::InvalidKey)?; + Ok(Self { key }) + } + pub(in crate::utils) fn matches_certificate(&self, certificate: &[u8]) -> anyhow::Result { + let certificate = + x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?; + let key = self.key.public_key().ok_or(RequestIdentityError::InvalidKey)?; + Ok(certificate.tbs_certificate().subject_public_key_info().to_der()? == key.as_ref()) + } +} +impl SigningKey for ClientKey { + fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option> { + self.key.choose_scheme(offered) + } + fn public_key(&self) -> Option> { + self.key.public_key() + } + fn algorithm(&self) -> SignatureAlgorithm { + self.key.algorithm() + } +} diff --git a/crates/gpapi/src/utils/certificate/unsupported.rs b/crates/gpapi/src/utils/certificate/unsupported.rs deleted file mode 100644 index ef7d5ad..0000000 --- a/crates/gpapi/src/utils/certificate/unsupported.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub(in crate::utils) fn decrypt( - _bytes: &[u8], - _pem: bool, - _passphrase: Option<&str>, -) -> anyhow::Result { - Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into()) -} diff --git a/crates/gpapi/src/utils/client_tls.rs b/crates/gpapi/src/utils/client_tls.rs new file mode 100644 index 0000000..862d69e --- /dev/null +++ b/crates/gpapi/src/utils/client_tls.rs @@ -0,0 +1,99 @@ +//! Local identity matching is separate from the peer's certificate validation. +use std::{io::Cursor, sync::Arc}; + +use pkcs8::der::Decode; +use rustls::{ + ClientConfig, DigitallySignedStruct, SignatureScheme, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, UnixTime}, + sign::{CertifiedKey, SingleCertAndKey}, +}; +use rustls_platform_verifier::BuilderVerifierExt; + +use super::{ + certificate::{ClientKey, validate_certificate}, + request::RequestIdentityError, +}; + +pub(super) fn pem_certified_key(certificate: &[u8], key: &[u8]) -> anyhow::Result> { + let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate)) + .collect::, _>>() + .map_err(|_| RequestIdentityError::InvalidCertificate)?; + let private_key = rustls_pemfile::private_key(&mut Cursor::new(key)) + .map_err(|_| RequestIdentityError::InvalidKey)? + .ok_or(RequestIdentityError::NoKey)?; + let signing_key = Arc::new(ClientKey::load(&private_key)?); + let leaf = certificates.first().ok_or(RequestIdentityError::InvalidCertificate)?; + validate_certificate(leaf)?; + if !signing_key.matches_certificate(leaf)? { + return Err(RequestIdentityError::KeyMismatch.into()); + } + for certificate in certificates.iter().skip(1) { + x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?; + } + // The local key has been matched without applying peer certificate policy. + Ok(Arc::new(CertifiedKey::new(certificates, signing_key))) +} + +pub(super) fn identity_client_builder( + identity: Arc, + ignore_server_certificate_errors: bool, +) -> anyhow::Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let config = ClientConfig::builder_with_provider(provider.clone()).with_safe_default_protocol_versions()?; + let config = if ignore_server_certificate_errors { + config + .dangerous() + .with_custom_certificate_verifier(Arc::new(IgnoreServerCertificateErrors { + schemes: provider.signature_verification_algorithms.supported_schemes(), + })) + } else { + // Match Reqwest's default system trust store, including private enterprise CAs. + config.with_platform_verifier()? + }; + let mut config = config.with_client_cert_resolver(Arc::new(SingleCertAndKey::from(identity))); + config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + Ok(super::request::client_builder().tls_backend_preconfigured(config)) +} + +/// Equivalent to Reqwest's danger_accept_invalid_certs(true), used only when +/// the user explicitly enables the existing ignore-certificate-errors setting. +#[derive(Debug)] +struct IgnoreServerCertificateErrors { + schemes: Vec, +} + +impl ServerCertVerifier for IgnoreServerCertificateErrors { + fn verify_server_cert( + &self, + _: &CertificateDer<'_>, + _: &[CertificateDer<'_>], + _: &ServerName<'_>, + _: &[u8], + _: UnixTime, + ) -> Result { + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + _: &[u8], + _: &CertificateDer<'_>, + _: &DigitallySignedStruct, + ) -> Result { + Ok(HandshakeSignatureValid::assertion()) + } + + fn verify_tls13_signature( + &self, + _: &[u8], + _: &CertificateDer<'_>, + _: &DigitallySignedStruct, + ) -> Result { + Ok(HandshakeSignatureValid::assertion()) + } + + fn supported_verify_schemes(&self) -> Vec { + self.schemes.clone() + } +} diff --git a/crates/gpapi/src/utils/identity_encoding.rs b/crates/gpapi/src/utils/identity_encoding.rs index 9df50e8..fae456b 100644 --- a/crates/gpapi/src/utils/identity_encoding.rs +++ b/crates/gpapi/src/utils/identity_encoding.rs @@ -90,7 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res } "ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?, "EC PRIVATE KEY" => { - sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?; + // The signing provider validates both named and explicitly encoded curves. + SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?; return Ok(block.encoded()); } _ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()), diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index fca6a9f..c33a57d 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -3,6 +3,7 @@ pub mod xml; pub mod base64; mod certificate; pub mod checksum; +mod client_tls; pub mod crypto; #[cfg(feature = "desktop")] pub mod endpoint; diff --git a/crates/gpapi/src/utils/request.rs b/crates/gpapi/src/utils/request.rs index df18bab..97cc05f 100644 --- a/crates/gpapi/src/utils/request.rs +++ b/crates/gpapi/src/utils/request.rs @@ -1,34 +1,40 @@ use std::{fmt, fs, io::Write, path::Path, sync::Arc}; use anyhow::{Context, ensure}; -use reqwest::Identity; +use rustls::sign::CertifiedKey; use zeroize::Zeroizing; -use super::{certificate::pkcs12, identity_encoding}; +use super::{certificate::pkcs12, client_tls, identity_encoding}; #[derive(Debug, thiserror::Error)] pub enum RequestIdentityError { - #[error("Failed to find the private key")] + #[error("No private key was found. Choose the matching key file")] NoKey, - #[error("No passphrase provided")] + #[error("This certificate or key is password-protected. Enter its password")] NoPassphrase(&'static str), - #[error("Failed to decrypt private key")] + #[error("Could not unlock the certificate or key. Check the password and file")] DecryptError(&'static str), - #[error( - "Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it" - )] + #[error("This certificate or key uses unsupported encryption. Re-export it with AES encryption")] UnsupportedEncryption, - #[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")] + #[error("This private key format is not supported. Choose a PEM key or a PKCS#12 certificate file")] UnsupportedKeyFormat, - #[error("Invalid private key")] + #[error( + "This client certificate uses an unsupported key type ({0}). Ask your VPN administrator for an RSA or P-256 certificate" + )] + UnsupportedKeyAlgorithm(&'static str), + #[error("The private key does not match this certificate. Choose the matching key file")] + KeyMismatch, + #[error("The private key file is invalid. Choose a different key file")] InvalidKey, - #[error("Invalid certificate or certificate chain")] + #[error("The certificate file is invalid. Choose a different certificate file")] InvalidCertificate, #[error("The PKCS#12 file must contain both a client certificate and its private key")] IncompletePkcs12, - #[error("Could not open the PKCS#12 certificate. Check the password and certificate file")] + #[error("Could not open the PKCS#12 file. Check the password or choose another file")] InvalidPkcs12(#[source] p12_keystore::error::Error), - #[error("The PKCS#12 file must contain one matching client identity")] + #[error( + "The certificate file contains more than one matching identity. Choose a file with one client certificate and key" + )] AmbiguousPkcs12, } @@ -38,7 +44,7 @@ pub enum RequestIdentityError { #[derive(Clone)] pub struct ClientIdentity { material: Arc, - identity: Identity, + certified_key: Arc, } struct IdentityMaterial { @@ -68,14 +74,14 @@ impl ClientIdentity { }; let key = identity_encoding::private_key(&key_bytes, passphrase)?; let certificate = identity_encoding::certificate_chain(&certificate_bytes)?; - let identity = pem_request_identity(&certificate, &key)?; + let certified_key = client_tls::pem_certified_key(&certificate, &key)?; Ok(Self { material: Arc::new(IdentityMaterial { certificate, key: Some(key), passphrase: None, }), - identity, + certified_key, }) } @@ -86,12 +92,12 @@ impl ClientIdentity { key: Option>>, passphrase: Option<&str>, ) -> anyhow::Result { - let (identity, passphrase) = match &key { - Some(key) => (pem_request_identity(&certificate, key)?, None), + let (certified_key, passphrase) = match &key { + Some(key) => (client_tls::pem_certified_key(&certificate, key)?, None), None => { - let identity = pkcs12::identity(&certificate, passphrase)?; + let certified_key = pkcs12::certified_key(&certificate, passphrase)?; ( - identity, + certified_key, Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())), ) } @@ -102,7 +108,7 @@ impl ClientIdentity { key, passphrase, }), - identity, + certified_key, }) } @@ -115,8 +121,8 @@ impl ClientIdentity { pub fn key_password(&self) -> Option<&str> { self.material.passphrase.as_ref().map(|value| value.as_str()) } - pub(crate) fn request_identity(&self) -> Identity { - self.identity.clone() + pub(crate) fn client_builder(&self, ignore_tls_errors: bool) -> anyhow::Result { + client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors) } pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result { @@ -149,29 +155,6 @@ impl ClientIdentityFiles { } } -pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result { - let error_context = - "Client certificate and private key cannot be used together. Check that the private key matches the certificate"; - 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::, _>>() - .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() - .context(error_context)?; - Ok(identity) -} - fn read_identity_file(path: &str) -> anyhow::Result>> { Ok(Zeroizing::new( fs::read(path).context("Failed to read client identity")?, @@ -208,12 +191,6 @@ pub fn client_builder() -> reqwest::ClientBuilder { 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 { - Ok(ClientIdentity::load(cert, key, passphrase)?.request_identity()) -} - #[cfg(test)] mod tests { use super::*; @@ -222,6 +199,29 @@ mod tests { const KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pkcs8.pem"); const ENCRYPTED_KEY: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-pbes2-sha256.pem"); + #[test] + fn unsupported_identity_errors_explain_the_action_without_blaming_passwords_or_key_matching() { + for error in [ + RequestIdentityError::UnsupportedKeyAlgorithm("RSA-PSS"), + RequestIdentityError::UnsupportedEncryption, + RequestIdentityError::UnsupportedKeyFormat, + ] { + let message = error.to_string(); + assert!( + message.contains("unsupported") || message.contains("not supported"), + "{message}" + ); + assert!( + message.contains("Ask ") || message.contains("Re-export ") || message.contains("Choose "), + "{message}" + ); + assert!( + !message.contains("password") && !message.contains("does not match"), + "{message}" + ); + } + } + #[test] fn pem_without_key_reports_missing_key_even_with_passphrase() { let mut source = tempfile::NamedTempFile::new().unwrap(); @@ -247,21 +247,21 @@ mod tests { } #[test] - fn create_identity_preserves_password_errors_and_builds_a_request_client() { + fn identity_loading_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(); for (password, missing) in [(None, true), (Some("wrong"), false)] { - let error = create_identity(source.path().to_str().unwrap(), None, password).unwrap_err(); + let error = ClientIdentity::load(source.path().to_str().unwrap(), None, password).unwrap_err(); match error.downcast_ref::() { Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing), Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing), other => panic!("Unexpected identity error: {other:?}"), } } - let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap(); + let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap(); drop(source); - client_builder().identity(identity).build().unwrap(); + identity.client_builder(false).unwrap().build().unwrap(); } #[test] @@ -283,7 +283,7 @@ mod tests { assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); drop(files); assert!(!Path::new(&path).exists()); - client_builder().identity(identity.request_identity()).build().unwrap(); + identity.client_builder(false).unwrap().build().unwrap(); } } diff --git a/crates/gpapi/tests/certificate_compatibility.rs b/crates/gpapi/tests/certificate_compatibility.rs new file mode 100644 index 0000000..b0910e0 --- /dev/null +++ b/crates/gpapi/tests/certificate_compatibility.rs @@ -0,0 +1,150 @@ +//! Supported desktop identities and actionable failures for unsupported inputs. +#![cfg(any( + target_os = "macos", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" +))] +use gpapi::utils::request::{ClientIdentity, RequestIdentityError}; +use openssl::{ + asn1::Asn1Time, + bn::BigNum, + hash::MessageDigest, + pkey::PKey, + stack::Stack, + x509::{X509, X509NameBuilder}, +}; +use std::{fs, path::PathBuf}; +use zeroize::Zeroizing; + +fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/files/client-identity") + .join(name) +} + +fn assert_unsupported_key(certificate: &str, key: &str) { + let error = ClientIdentity::load( + fixture(certificate).to_str().unwrap(), + Some(fixture(key).to_str().unwrap()), + None, + ) + .unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(RequestIdentityError::UnsupportedKeyAlgorithm(_)) + ), + "{error:#}" + ); + let message = error.to_string(); + assert!(message.contains("unsupported"), "{message}"); + assert!(message.contains("VPN administrator"), "{message}"); + assert!( + !message.contains("password") && !message.contains("does not match"), + "{message}" + ); +} + +#[test] +fn compressed_ec_certificate_reports_an_unsupported_encoding() { + assert_unsupported_key("ec-compressed-cert.pem", "ec-pkcs8.pem"); +} + +#[test] +fn compressed_ec_private_key_reports_an_unsupported_encoding() { + assert_unsupported_key("ec-compressed-cert.pem", "ec-compressed.pem"); +} + +#[test] +fn explicit_ec_parameters_report_an_unsupported_encoding() { + assert_unsupported_key("ec-explicit-cert.pem", "ec-explicit.pem"); +} + +#[test] +fn p521_key_reports_the_known_tls_capability_limit() { + assert_unsupported_key("ec-p521-cert.pem", "ec-p521.pem"); +} + +#[test] +fn rsa_pss_key_reports_the_known_tls_capability_limit() { + assert_unsupported_key("rsa-pss-cert.pem", "rsa-pss.pem"); +} + +fn legacy_archive(name: &str) { + let path = fixture(name); + let bytes = fs::read(&path).unwrap(); + let identity = ClientIdentity::load(path.to_str().unwrap(), None, Some("fixture-password")) + .unwrap_or_else(|error| panic!("{name}: {error:#}")); + assert_eq!(identity.certificate_data(), bytes); + assert!(ClientIdentity::load(path.to_str().unwrap(), None, Some("incorrect")).is_err()); +} + +fn unsupported_archive(name: &str) { + let path = fixture(name); + let bytes = fs::read(&path).unwrap(); + for password in [None, Some("fixture-password"), Some("incorrect"), Some("")] { + for error in [ + ClientIdentity::load(path.to_str().unwrap(), None, password).unwrap_err(), + ClientIdentity::from_data(Zeroizing::new(bytes.clone()), None, password).unwrap_err(), + ] { + assert!( + matches!( + error.downcast_ref::(), + Some(RequestIdentityError::UnsupportedEncryption) + ), + "{name}: {error:#}" + ); + assert!(error.to_string().contains("AES"), "{error}"); + } + } +} + +#[test] +fn legacy_rc2_128_pkcs12_explains_the_unsupported_encryption() { + unsupported_archive("legacy-RC2-128.p12"); +} +#[test] +fn legacy_rc4_128_pkcs12_is_usable() { + legacy_archive("legacy-RC4-128.p12"); +} +#[test] +fn legacy_two_key_3des_pkcs12_explains_the_unsupported_encryption() { + unsupported_archive("legacy-2DES.p12"); +} + +#[test] +fn renewed_pkcs12_with_one_key_is_accepted_without_artificial_ambiguity() { + let key = PKey::private_key_from_pem(&fs::read(fixture("rsa-pkcs8.pem")).unwrap()).unwrap(); + let mut name = X509NameBuilder::new().unwrap(); + name.append_entry_by_text("CN", "Public renewed identity").unwrap(); + let name = name.build(); + let mut certs = Vec::new(); + for serial in [10, 11] { + let mut builder = X509::builder().unwrap(); + builder.set_version(2).unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_issuer_name(&name).unwrap(); + builder.set_pubkey(&key).unwrap(); + builder + .set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap()) + .unwrap(); + builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap(); + builder.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap(); + builder.sign(&key, MessageDigest::sha256()).unwrap(); + certs.push(builder.build()); + } + let mut extra = Stack::new().unwrap(); + extra.push(certs[0].clone()).unwrap(); + let mut builder = openssl::pkcs12::Pkcs12::builder(); + builder.name("renewed").pkey(&key).cert(&certs[1]).ca(extra); + let archive = builder.build2("fixture-password").unwrap().to_der().unwrap(); + // Independent oracle for this bag order. Native bag-order permutation tests + // establish selection; localKeyId alone does not override native ordering. + let parsed = openssl::pkcs12::Pkcs12::from_der(&archive) + .unwrap() + .parse2("fixture-password") + .unwrap(); + assert_eq!(parsed.cert.unwrap().to_der().unwrap(), certs[1].to_der().unwrap()); + ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap(); +} diff --git a/crates/gpapi/tests/client_certificate_chain.rs b/crates/gpapi/tests/client_certificate_chain.rs new file mode 100644 index 0000000..31da392 --- /dev/null +++ b/crates/gpapi/tests/client_certificate_chain.rs @@ -0,0 +1,238 @@ +//! A PKCS#12 CA rollover must send the intermediate that signed the client. +use gpapi::{ + gp_params::GpParams, + os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile}, + utils::request::ClientIdentity, +}; +use openssl::{ + asn1::Asn1Time, + bn::BigNum, + ec::{EcGroup, EcKey}, + hash::MessageDigest, + nid::Nid, + pkey::{PKey, Private}, + ssl::{SslAcceptor, SslMethod, SslVerifyMode}, + stack::Stack, + x509::{ + X509, X509NameBuilder, + extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectKeyIdentifier}, + }, +}; +use std::{ + io::{Read, Write}, + net::TcpListener, + thread, + time::Duration, +}; +use zeroize::Zeroizing; + +fn key() -> PKey { + PKey::from_ec_key(EcKey::generate(&EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap()).unwrap()).unwrap() +} + +fn certificate( + name: &str, + key: &PKey, + issuer: Option<(&X509, &PKey)>, + serial: u32, + ca: bool, + key_identifiers: bool, +) -> X509 { + let mut subject = X509NameBuilder::new().unwrap(); + subject.append_entry_by_text("CN", name).unwrap(); + let subject = subject.build(); + let mut cert = X509::builder().unwrap(); + cert.set_version(2).unwrap(); + cert + .set_serial_number(&BigNum::from_u32(serial).unwrap().to_asn1_integer().unwrap()) + .unwrap(); + cert.set_subject_name(&subject).unwrap(); + cert + .set_issuer_name(issuer.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject)) + .unwrap(); + cert.set_pubkey(key).unwrap(); + cert + .set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap()) + .unwrap(); + cert + .set_not_after(&Asn1Time::from_unix(4_000_000_000).unwrap()) + .unwrap(); + let mut constraints = BasicConstraints::new(); + if ca { + constraints.ca(); + } + cert.append_extension(constraints.critical().build().unwrap()).unwrap(); + let mut usage = KeyUsage::new(); + if ca { + usage.key_cert_sign(); + } else { + usage.digital_signature(); + } + cert.append_extension(usage.critical().build().unwrap()).unwrap(); + if key_identifiers { + let identifier = SubjectKeyIdentifier::new() + .build(&cert.x509v3_context(None, None)) + .unwrap(); + cert.append_extension(identifier).unwrap(); + if let Some((parent, _)) = issuer { + let identifier = AuthorityKeyIdentifier::new() + .keyid(true) + .build(&cert.x509v3_context(Some(parent), None)) + .unwrap(); + cert.append_extension(identifier).unwrap(); + } + } + cert + .sign(issuer.map(|(_, key)| key).unwrap_or(key), MessageDigest::sha256()) + .unwrap(); + cert.build() +} + +#[tokio::test] +async fn pkcs12_ca_rollover_authenticates_in_both_bag_orders() { + for self_issued in [false, true] { + let root_key = key(); + // Ordinary rollover also works without AKI/SKI. The self-issued chain + // needs key identifiers so the independent server distinguishes its root. + let root = certificate("Root", &root_key, None, 1, true, self_issued); + let issuer_name = if self_issued { "Root" } else { "Issuing CA" }; + let old_key = key(); + let old = certificate(issuer_name, &old_key, Some((&root, &root_key)), 2, true, self_issued); + let current_key = key(); + let current = certificate( + issuer_name, + ¤t_key, + Some((&root, &root_key)), + 3, + true, + self_issued, + ); + let client_key = key(); + let leaf = certificate( + "Client", + &client_key, + Some((¤t, ¤t_key)), + 4, + false, + self_issued, + ); + for old_first in [true, false] { + let mut ca = Stack::new().unwrap(); + let intermediates = if old_first { [&old, ¤t] } else { [¤t, &old] }; + for cert in intermediates { + ca.push(cert.clone()).unwrap(); + } + ca.push(root.clone()).unwrap(); + authenticate(&root, ¤t, &leaf, &client_key, ca).await; + } + } +} + +async fn authenticate(root: &X509, current: &X509, leaf: &X509, client_key: &PKey, ca: Stack) { + let archive = openssl::pkcs12::Pkcs12::builder() + .pkey(client_key) + .cert(leaf) + .ca(ca) + .build2("test") + .unwrap() + .to_der() + .unwrap(); + let identity = ClientIdentity::from_data(Zeroizing::new(archive.clone()), None, Some("test")).unwrap(); + assert_eq!( + identity.certificate_data(), + archive, + "OpenConnect must retain the original archive" + ); + let profile = OsProfile::builder(ClientOs::Linux).build(HostSnapshot { + runtime_os: ClientOs::Linux, + identity: HostIdentity::application("test".into(), "test".into()), + os_version: "test".into(), + software_version: "test".into(), + }); + let params = GpParams::builder(profile) + .client_identity(Some(identity)) + .ignore_tls_errors(true) + .build(); + let client = reqwest::Client::try_from(¶ms).unwrap(); + let server_key = key(); + let mut server = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap(); + server + .set_certificate(&certificate("Server", &server_key, None, 5, false, false)) + .unwrap(); + server.set_private_key(&server_key).unwrap(); + server.cert_store_mut().add_cert(root.clone()).unwrap(); + server.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); + let server = server.build(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("https://{}", listener.local_addr().unwrap()); + let expected_leaf = leaf.to_der().unwrap(); + let expected_issuer = current.to_der().unwrap(); + let worker = thread::spawn(move || { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let socket = loop { + match listener.accept() { + Ok((socket, _)) => break socket, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => { + thread::sleep(Duration::from_millis(5)) + } + Err(error) => return Err(error.to_string()), + } + }; + socket.set_nonblocking(false).unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + socket.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut socket = server.accept(socket).map_err(|error| error.to_string())?; + assert_eq!( + socket.ssl().peer_certificate().unwrap().to_der().unwrap(), + expected_leaf + ); + assert!( + socket + .ssl() + .peer_cert_chain() + .unwrap() + .iter() + .any(|cert| cert.to_der().unwrap() == expected_issuer) + ); + let mut request = [0; 4096]; + socket.read(&mut request).map_err(|error| error.to_string())?; + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .map_err(|error| error.to_string()) + }); + let response = client.get(address).timeout(Duration::from_secs(5)).send().await; + let server_result = worker.join().unwrap(); + assert!(server_result.is_ok(), "{server_result:?}; {response:?}"); + assert_eq!(response.unwrap().text().await.unwrap(), "ok"); +} + +#[tokio::test] +async fn pkcs12_pss_certificate_signature_parameters_authenticate() { + let root = X509::from_pem(include_bytes!("files/client-identity/pss-chain-root.pem")).unwrap(); + let issuer = X509::from_pem(include_bytes!("files/client-identity/pss-chain-issuer.pem")).unwrap(); + let client_key = PKey::private_key_from_pem(include_bytes!("files/client-identity/rsa-pkcs8.pem")).unwrap(); + let wrong_key = PKey::from_rsa(openssl::rsa::Rsa::generate(2048).unwrap()).unwrap(); + let wrong_issuer = certificate("PSS Issuing CA", &wrong_key, None, 6, true, false); + for certificate in [ + include_bytes!("files/client-identity/pss-chain-salt-20.pem").as_slice(), + include_bytes!("files/client-identity/pss-chain-salt-32.pem").as_slice(), + include_bytes!("files/client-identity/pss-chain-salt-48.pem").as_slice(), + ] { + let leaf = X509::from_pem(certificate).unwrap(); + assert!(leaf.verify(&issuer.public_key().unwrap()).unwrap()); + for wrong_first in [true, false] { + let mut ca = Stack::new().unwrap(); + let candidates = if wrong_first { + [&wrong_issuer, &issuer] + } else { + [&issuer, &wrong_issuer] + }; + for candidate in candidates { + ca.push(candidate.clone()).unwrap(); + } + ca.push(root.clone()).unwrap(); + authenticate(&root, &issuer, &leaf, &client_key, ca).await; + } + } +} diff --git a/crates/gpapi/tests/client_certificate_extensions.rs b/crates/gpapi/tests/client_certificate_extensions.rs new file mode 100644 index 0000000..f56eb8b --- /dev/null +++ b/crates/gpapi/tests/client_certificate_extensions.rs @@ -0,0 +1,419 @@ +//! Issue #697: local identity matching must not apply a peer's extension policy. +//! OpenSSL is an independent test oracle/server, never a product import backend. +use std::{ + fs, + io::{Read, Write}, + net::TcpListener, + thread, + time::Duration, +}; + +use gpapi::{ + gp_params::GpParams, + os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile}, + utils::request::{ClientIdentity, RequestIdentityError}, +}; +use openssl::{ + asn1::{Asn1Object, Asn1OctetString, Asn1Time}, + ec::{EcGroup, EcKey}, + hash::MessageDigest, + nid::Nid, + pkey::{Id, PKey, Private}, + ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode, SslVersion}, + x509::{X509, X509Extension, X509NameBuilder}, +}; +use zeroize::Zeroizing; + +const PASSWORD: &str = "fixture-password"; + +fn key(family: &str) -> PKey { + if family == "ec-p384" { + let group = EcGroup::from_curve_name(Nid::SECP384R1).unwrap(); + return PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap(); + } + if family == "ed25519" { + return PKey::generate_ed25519().unwrap(); + } + let bytes: &[u8] = match family { + "rsa" => include_bytes!("files/client-identity/rsa-pkcs8.pem"), + "ec" => include_bytes!("files/client-identity/ec-pkcs8.pem"), + _ => panic!("unknown key family"), + }; + PKey::private_key_from_pem(bytes).unwrap() +} + +fn certificate(key: &PKey, extension: Option<(&str, bool, &[u8])>) -> X509 { + let mut name = X509NameBuilder::new().unwrap(); + name.append_entry_by_text("CN", "Public regression identity").unwrap(); + let name = name.build(); + let mut cert = X509::builder().unwrap(); + cert.set_version(2).unwrap(); + cert.set_subject_name(&name).unwrap(); + cert.set_issuer_name(&name).unwrap(); + cert.set_pubkey(key).unwrap(); + cert + .set_not_before(&Asn1Time::from_unix(1_700_000_000).unwrap()) + .unwrap(); + cert + .set_not_after(&Asn1Time::from_unix(4_000_000_000).unwrap()) + .unwrap(); + if let Some((oid, critical, value)) = extension { + let oid = Asn1Object::from_str(oid).unwrap(); + let value = Asn1OctetString::new_from_bytes(value).unwrap(); + cert + .append_extension(X509Extension::new_from_der(&oid, critical, &value).unwrap()) + .unwrap(); + } + let digest = if key.id() == Id::ED25519 { + MessageDigest::null() + } else { + MessageDigest::sha256() + }; + cert.sign(key, digest).unwrap(); + cert.build() +} + +fn private_extension() -> Option<(&'static str, bool, &'static [u8])> { + Some(("1.3.6.1.4.1.55555.1", true, &[0x05, 0x00])) +} + +fn params(identity: ClientIdentity, ignore_tls_errors: bool) -> GpParams { + let snapshot = HostSnapshot { + runtime_os: ClientOs::Linux, + identity: HostIdentity::application("regression-test".into(), "public-test-id".into()), + os_version: "test".into(), + software_version: "test".into(), + }; + GpParams::builder(OsProfile::builder(ClientOs::Linux).build(snapshot)) + .client_identity(Some(identity)) + .ignore_tls_errors(ignore_tls_errors) + .build() +} + +fn assert_usable(identity: ClientIdentity) { + reqwest::Client::try_from(¶ms(identity.clone(), false)).unwrap(); + reqwest::Client::try_from(¶ms(identity.clone(), true)).unwrap(); + let restored = ClientIdentity::from_data( + Zeroizing::new(identity.certificate_data().to_vec()), + identity.key_data().map(|key| Zeroizing::new(key.to_vec())), + identity.key_password(), + ) + .unwrap(); + assert_eq!(restored.certificate_data(), identity.certificate_data()); + let files = restored.write_files(None).unwrap(); + ClientIdentity::load(files.certificate(), files.key(), restored.key_password()).unwrap(); +} + +#[derive(Clone, Copy, Debug)] +enum Container { + SeparatePem, + CombinedPem, + Der, + Pkcs12, + Snapshot, +} + +fn load(container: Container, cert: &X509, key: &PKey) -> anyhow::Result { + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("client.pem"); + let key_path = directory.path().join("client.key"); + let key_pem = key.private_key_to_pem_pkcs8().unwrap(); + fs::write(&key_path, &key_pem).unwrap(); + match container { + Container::SeparatePem => { + fs::write(&source, cert.to_pem().unwrap()).unwrap(); + ClientIdentity::load(source.to_str().unwrap(), Some(key_path.to_str().unwrap()), None) + } + Container::CombinedPem => { + let mut combined = cert.to_pem().unwrap(); + combined.extend(&key_pem); + fs::write(&source, combined).unwrap(); + ClientIdentity::load(source.to_str().unwrap(), None, None) + } + Container::Der => { + fs::write(&source, cert.to_der().unwrap()).unwrap(); + fs::write(&key_path, key.private_key_to_pkcs8().unwrap()).unwrap(); + ClientIdentity::load(source.to_str().unwrap(), Some(key_path.to_str().unwrap()), None) + } + Container::Pkcs12 => { + let mut archive = openssl::pkcs12::Pkcs12::builder(); + archive.name("public regression identity").pkey(key).cert(cert); + let archive = archive.build2(PASSWORD).unwrap().to_der().unwrap(); + let source = directory.path().join("client.p12"); + fs::write(&source, archive).unwrap(); + ClientIdentity::load(source.to_str().unwrap(), None, Some(PASSWORD)) + } + Container::Snapshot => ClientIdentity::from_data( + Zeroizing::new(cert.to_pem().unwrap()), + Some(Zeroizing::new(key_pem)), + None, + ), + } +} + +fn extension_matrix(container: Container) { + let cases: &[(&str, Option<(&str, bool, &[u8])>)] = &[ + ("no extensions", None), + ( + "private noncritical", + Some(("1.3.6.1.4.1.55555.1", false, &[0x05, 0x00])), + ), + ("private critical", private_extension()), + // Netscape certificate type and Microsoft certificate template name are + // realistic enterprise extensions that WebPKI does not interpret. + ( + "Netscape client type", + Some(("2.16.840.1.113730.1.1", true, &[0x03, 0x02, 0x07, 0x80])), + ), + ( + "Microsoft template", + Some(("1.3.6.1.4.1.311.20.2", true, &[0x1e, 0x02, 0x00, b'A'])), + ), + ( + "critical key usage", + Some(("2.5.29.15", true, &[0x03, 0x02, 0x07, 0x80])), + ), + ( + "critical client EKU", + Some(( + "2.5.29.37", + true, + &[0x30, 0x0a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02], + )), + ), + ]; + for family in ["rsa", "ec", "ec-p384", "ed25519"] { + let key = key(family); + for &(name, extension) in cases { + let cert = certificate(&key, extension); + // The previous OpenSSL backend accepts this local certificate/key pair. + let mut oracle = SslConnector::builder(SslMethod::tls()).unwrap(); + oracle.set_certificate(&cert).unwrap(); + oracle.set_private_key(&key).unwrap(); + oracle.check_private_key().unwrap(); + let identity = + load(container, &cert, &key).unwrap_or_else(|error| panic!("{container:?}/{family}/{name}: {error:#}")); + if !matches!(container, Container::Pkcs12) { + assert_eq!(identity.certificate_data(), cert.to_pem().unwrap()); + } + assert_usable(identity); + } + } +} + +#[test] +fn separate_pem_extension_matrix() { + extension_matrix(Container::SeparatePem); +} +#[test] +fn combined_pem_extension_matrix() { + extension_matrix(Container::CombinedPem); +} +#[test] +fn der_extension_matrix() { + extension_matrix(Container::Der); +} +#[test] +fn pkcs12_extension_matrix() { + extension_matrix(Container::Pkcs12); +} +#[test] +fn snapshot_extension_matrix() { + extension_matrix(Container::Snapshot); +} + +#[test] +fn critical_extensions_do_not_hide_a_mismatched_private_key() { + for family in ["rsa", "ec"] { + let cert = certificate(&key(family), private_extension()); + let wrong_family = if family == "rsa" { "ec" } else { "rsa" }; + let same_family_wrong_key = if family == "rsa" { + PKey::from_rsa(openssl::rsa::Rsa::generate(2048).unwrap()).unwrap() + } else { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap() + }; + // PEM and service snapshots can carry mismatched material. OpenSSL's + // PKCS#12 writer itself rejects a mismatch; existing archive fixtures cover it. + for wrong_key in [key(wrong_family), same_family_wrong_key] { + for container in [ + Container::SeparatePem, + Container::CombinedPem, + Container::Der, + Container::Snapshot, + ] { + let error = load(container, &cert, &wrong_key).unwrap_err(); + assert!( + matches!( + error.downcast_ref::(), + Some(RequestIdentityError::KeyMismatch) + ), + "{error:#}" + ); + } + } + } +} + +#[test] +fn cli_identity_preparation_keeps_critical_extensions_after_source_files_are_removed() { + let key = key("rsa"); + let cert = certificate(&key, private_extension()); + let directory = tempfile::tempdir().unwrap(); + let source = directory.path().join("client.pem"); + let key_path = directory.path().join("client.key"); + fs::write(&source, cert.to_pem().unwrap()).unwrap(); + fs::write(&key_path, key.private_key_to_pem_pkcs8().unwrap()).unwrap(); + let identity = load(Container::Snapshot, &cert, &key).unwrap(); + let profile = params(identity, false).os_profile().clone(); + // Start with the unprepared path used by the reported gateway prelogin. + let mut params = GpParams::builder(profile) + .certificate(Some(source.to_string_lossy().into_owned())) + .sslkey(Some(key_path.to_string_lossy().into_owned())) + .build(); + reqwest::Client::try_from(¶ms).unwrap(); + params.prepare_client_identity().unwrap(); + drop(directory); + reqwest::Client::try_from(¶ms).unwrap(); + assert_eq!( + params.client_identity().unwrap().certificate_data(), + cert.to_pem().unwrap() + ); +} + +#[test] +fn critical_extension_in_a_chain_preserves_every_certificate() { + let key = key("rsa"); + let cert = certificate(&key, private_extension()); + let mut chain = cert.to_pem().unwrap(); + chain.extend(include_bytes!("files/client-identity/root.pem")); + let identity = ClientIdentity::from_data( + Zeroizing::new(chain.clone()), + Some(Zeroizing::new(key.private_key_to_pem_pkcs8().unwrap())), + None, + ) + .unwrap(); + assert_eq!(identity.certificate_data(), chain); + assert_usable(identity); +} + +fn server( + cert: &X509, + key: &PKey, + version: SslVersion, + expected_client: Vec, + accept_client: bool, +) -> (String, thread::JoinHandle) { + let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap(); + acceptor.set_certificate(cert).unwrap(); + acceptor.set_private_key(key).unwrap(); + acceptor.set_min_proto_version(Some(version)).unwrap(); + acceptor.set_max_proto_version(Some(version)).unwrap(); + // Model a VPN that understands this private extension. TLS still verifies + // CertificateVerify; the server also checks the exact leaf bytes below. + acceptor.set_verify_callback( + SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT, + move |_, _| accept_client, + ); + let acceptor = acceptor.build(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("https://{}", listener.local_addr().unwrap()); + let worker = thread::spawn(move || { + // Bound failures even if client construction or connection fails. + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + if std::time::Instant::now() >= deadline { + return false; + } + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("{error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let Ok(mut stream) = acceptor.accept(stream) else { + return false; + }; + let peer = stream.ssl().peer_certificate().unwrap(); + assert_eq!( + peer.to_der().unwrap(), + expected_client, + "the original signed certificate must be sent unchanged" + ); + assert!(peer.verify(&peer.public_key().unwrap()).unwrap()); + let mut request = [0; 4096]; + if stream.read(&mut request).is_err() { + return false; + } + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .is_ok() + }); + (address, worker) +} + +#[tokio::test] +async fn critical_extension_identity_completes_tls12_and_tls13_client_authentication() { + let server_key = key("rsa"); + let server_cert = certificate(&server_key, None); + for family in ["rsa", "ec", "ec-p384", "ed25519"] { + let key = key(family); + let cert = certificate(&key, private_extension()); + for container in [Container::SeparatePem, Container::Pkcs12] { + for version in [SslVersion::TLS1_2, SslVersion::TLS1_3] { + let identity = load(container, &cert, &key).unwrap(); + let client = reqwest::Client::try_from(¶ms(identity, true)).unwrap(); + let (address, worker) = server(&server_cert, &server_key, version, cert.to_der().unwrap(), true); + let result = client.get(address).timeout(Duration::from_secs(5)).send().await; + assert!( + worker.join().unwrap(), + "{family}/{container:?}/{version:?}: server did not complete client authentication" + ); + assert_eq!(result.unwrap().text().await.unwrap(), "ok"); + } + } + } +} + +#[tokio::test] +async fn client_extensions_do_not_disable_server_trust_or_peer_rejection() { + let key = key("rsa"); + let cert = certificate(&key, private_extension()); + let server_cert = certificate(&key, None); + for (ignore_server_errors, accept_client) in [(false, true), (true, false)] { + for version in [SslVersion::TLS1_2, SslVersion::TLS1_3] { + let identity = load(Container::SeparatePem, &cert, &key).unwrap(); + let client = reqwest::Client::try_from(¶ms(identity, ignore_server_errors)).unwrap(); + let (address, worker) = server(&server_cert, &key, version, cert.to_der().unwrap(), accept_client); + let result = client.get(address).timeout(Duration::from_secs(5)).send().await; + assert!( + result.is_err(), + "server trust and peer rejection must still be enforced" + ); + assert!(!worker.join().unwrap()); + let error = result.unwrap_err(); + assert!( + !error.is_timeout(), + "expected a TLS rejection, not a timeout: {error:?}" + ); + let details = format!("{error:?}"); + if ignore_server_errors { + assert!( + details.contains("AlertReceived"), + "expected the server's client-certificate rejection: {details}" + ); + } else { + assert!( + details.contains("InvalidCertificate"), + "expected server certificate validation to fail: {details}" + ); + } + } + } +} diff --git a/crates/gpapi/tests/client_certificate_tls12_hash.rs b/crates/gpapi/tests/client_certificate_tls12_hash.rs new file mode 100644 index 0000000..b4d8dd1 --- /dev/null +++ b/crates/gpapi/tests/client_certificate_tls12_hash.rs @@ -0,0 +1,156 @@ +//! Recorded 3.2 compatibility gap: TLS 1.2 ECDSA hashes are not curve-bound. +//! OpenSSL is a test-only baseline and peer, never a product TLS backend. +#![cfg(any( + target_os = "macos", + target_os = "linux", + target_os = "freebsd", + target_os = "openbsd" +))] + +use std::{ + io::{Read, Write}, + net::{TcpListener, TcpStream}, + thread, + time::{Duration, Instant}, +}; + +use gpapi::{ + gp_params::GpParams, + os_profile::{ClientOs, HostIdentity, HostSnapshot, OsProfile}, + utils::request::ClientIdentity, +}; +use openssl::{ + asn1::Asn1Time, + ec::{EcGroup, EcKey}, + hash::MessageDigest, + nid::Nid, + pkey::{PKey, Private}, + ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode, SslVersion}, + x509::{X509, X509NameBuilder}, +}; +use zeroize::Zeroizing; + +fn identity(curve: Nid, name: &str) -> (PKey, X509) { + let group = EcGroup::from_curve_name(curve).unwrap(); + let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap(); + let mut subject = X509NameBuilder::new().unwrap(); + subject.append_entry_by_text("CN", name).unwrap(); + let subject = subject.build(); + let mut certificate = X509::builder().unwrap(); + certificate.set_version(2).unwrap(); + certificate.set_subject_name(&subject).unwrap(); + certificate.set_issuer_name(&subject).unwrap(); + certificate.set_pubkey(&key).unwrap(); + certificate + .set_not_before(&Asn1Time::days_from_now(0).unwrap()) + .unwrap(); + certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap(); + certificate.sign(&key, MessageDigest::sha256()).unwrap(); + (key, certificate.build()) +} + +fn sha256_only_tls12_peer(expected: &X509) -> (String, thread::JoinHandle>) { + let (key, certificate) = identity(Nid::X9_62_PRIME256V1, "Public TLS 1.2 peer"); + let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap(); + acceptor.set_certificate(&certificate).unwrap(); + acceptor.set_private_key(&key).unwrap(); + acceptor.set_min_proto_version(Some(SslVersion::TLS1_2)).unwrap(); + acceptor.set_max_proto_version(Some(SslVersion::TLS1_2)).unwrap(); + // P-256 server authentication works with this list. The P-384 client must + // also sign with SHA-256, which is allowed in TLS 1.2 but not TLS 1.3. + acceptor.set_sigalgs_list("ECDSA+SHA256").unwrap(); + let expected = expected.to_der().unwrap(); + let pinned = expected.clone(); + acceptor.set_verify_callback( + SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT, + move |_, context| { + context.error_depth() == 0 + && context + .current_cert() + .is_some_and(|certificate| certificate.to_der().unwrap() == pinned) + }, + ); + let acceptor = acceptor.build(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + let stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => { + thread::sleep(Duration::from_millis(5)); + } + Err(error) => return Err(format!("Accepting TLS peer: {error}")), + } + }; + stream.set_nonblocking(false).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + stream.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + // SSL_accept checks the client's CertificateVerify proof of possession. + let mut stream = acceptor + .accept(stream) + .map_err(|error| format!("Client authentication: {error}"))?; + assert_eq!(stream.ssl().version2(), Some(SslVersion::TLS1_2)); + assert_eq!(stream.ssl().peer_certificate().unwrap().to_der().unwrap(), expected); + let mut request = [0; 4096]; + let length = stream.read(&mut request).map_err(|error| error.to_string())?; + assert!(length > 0); + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .map_err(|error| error.to_string()) + }); + (address, worker) +} + +#[test] +fn openssl_baseline_authenticates_p384_with_tls12_sha256() { + let (key, certificate) = identity(Nid::SECP384R1, "Public P-384 client"); + let (address, peer) = sha256_only_tls12_peer(&certificate); + let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); + connector.set_certificate(&certificate).unwrap(); + connector.set_private_key(&key).unwrap(); + // This fixture isolates client authentication; the peer pins the exact leaf. + connector.set_verify(SslVerifyMode::NONE); + let socket = TcpStream::connect(address).unwrap(); + socket.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + socket.set_write_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut stream = connector.build().connect("localhost", socket).unwrap(); + stream.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap(); + let mut response = [0; 1024]; + assert!(stream.read(&mut response).unwrap() > 0); + peer.join().unwrap().unwrap(); +} + +#[tokio::test] +#[ignore = "Known regression from 3.2: P-384 signs only SHA-384; Rustls SigningKey has no negotiated version to safely allow TLS 1.2 SHA-256 while preserving TLS 1.3 curve binding"] +async fn p384_authenticates_with_tls12_sha256() { + let (key, certificate) = identity(Nid::SECP384R1, "Public P-384 client"); + let identity = ClientIdentity::from_data( + Zeroizing::new(certificate.to_pem().unwrap()), + Some(Zeroizing::new(key.private_key_to_pem_pkcs8().unwrap())), + None, + ) + .unwrap(); + let snapshot = HostSnapshot { + runtime_os: ClientOs::Linux, + identity: HostIdentity::application("regression-test".into(), "public-test-id".into()), + os_version: "test".into(), + software_version: "test".into(), + }; + let params = GpParams::builder(OsProfile::builder(ClientOs::Linux).build(snapshot)) + .client_identity(Some(identity)) + .ignore_tls_errors(true) + .build(); + let client = reqwest::Client::try_from(¶ms).unwrap(); + let (address, peer) = sha256_only_tls12_peer(&certificate); + let response = client + .get(format!("https://{address}")) + .timeout(Duration::from_secs(5)) + .send() + .await; + let authentication = peer.join().unwrap(); + assert!(authentication.is_ok(), "{authentication:?}; HTTP result: {response:?}"); + assert_eq!(response.unwrap().text().await.unwrap(), "ok"); +} diff --git a/crates/gpapi/tests/client_identity.rs b/crates/gpapi/tests/client_identity.rs index e445437..71640cf 100644 --- a/crates/gpapi/tests/client_identity.rs +++ b/crates/gpapi/tests/client_identity.rs @@ -114,11 +114,10 @@ fn malformed_rsa_pkcs1_is_rejected_before_connection() { None, ) .unwrap_err(); - assert!( - error - .to_string() - .contains("Check that the private key matches the certificate") - ); + assert!(matches!( + error.downcast_ref::(), + Some(RequestIdentityError::InvalidKey) + )); } fn check_archive(name: &str, password: &str) { @@ -604,17 +603,15 @@ fn mismatched_certificate_key_is_rejected_before_request_client_creation() { let certificate = fs::read(fixture("root.pem")).unwrap(); let key = fs::read(fixture("rsa-pkcs8.pem")).unwrap(); let error = load("root.pem", "rsa-pkcs8.pem", None).unwrap_err(); - assert!( - error - .to_string() - .contains("Check that the private key matches the certificate") - ); + assert!(matches!( + error.downcast_ref::(), + Some(RequestIdentityError::KeyMismatch) + )); let error = ClientIdentity::from_data(certificate.into(), Some(key.into()), None).unwrap_err(); - assert!( - error - .to_string() - .contains("Check that the private key matches the certificate") - ); + assert!(matches!( + error.downcast_ref::(), + Some(RequestIdentityError::KeyMismatch) + )); } #[test] @@ -640,7 +637,7 @@ fn pkcs12_rejects_mismatched_and_multiple_identities() { let error = ClientIdentity::load(fixture(name).to_str().unwrap(), None, None).unwrap_err(); match error.downcast_ref::() { Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous), - Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous), + Some(RequestIdentityError::KeyMismatch) => assert!(!ambiguous), other => panic!("{name}: unexpected archive error: {other:?}"), } } diff --git a/crates/gpapi/tests/files/client-identity/README.md b/crates/gpapi/tests/files/client-identity/README.md index 1d78390..dcca817 100644 --- a/crates/gpapi/tests/files/client-identity/README.md +++ b/crates/gpapi/tests/files/client-identity/README.md @@ -19,6 +19,7 @@ optional fixture-generation script, not identity import. | Files | Contents | | --- | --- | | `root.pem`, `rsa-cert.pem`, `ec-cert.pem` | Test root and issued RSA-2048 / P-256 client certificates, SHA256 signatures | +| `rsa-critical-extension.pem` | Self-signed certificate for the existing RSA key with a private critical extension; issue #697 desktop validation regression | | `rsa-pkcs8.pem`, `ec-pkcs8.pem` | Plain PKCS#8 keys; expected normalized output | | `rsa-pkcs1.pem`, `ec-sec1.pem` | Same keys in traditional containers | | `{rsa,ec}-traditional-{aes128,aes192,aes256,des3}.pem` | Traditional encrypted PEM with AES-CBC or 3DES-CBC; password `fixture-password` | @@ -34,13 +35,20 @@ optional fixture-generation script, not identity import. | `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 | +| `ec-p521.pem`, `ec-p521-cert.pem` | Valid P-521 identity; explicit unsupported-key error until HTTP negotiation parity exists | +| `rsa-pss.pem`, `rsa-pss-cert.pem` | Valid RSA-PSS identity; explicit unsupported-key error until Rustls negotiation parity exists | +| `pss-chain-{root,issuer}.pem`, `pss-chain-salt-{20,32,48}.pem` | RSA client certificates signed with RSA-PSS/SHA256 and different salt lengths; client key is `rsa-pkcs8.pem`. Regenerate with `generate-pss-chain.sh` | +| `ec-{compressed,explicit}.pem`, matching `-cert.pem` files | Valid OpenSSL inputs rejected by the tested GnuTLS backend; actionable unsupported-encoding tests | +| `legacy-RC4-128.p12` | SHA1/RC4-128 key encryption and SHA1/3DES certificate encryption; native archive import | +| `legacy-RC2-128.p12`, `legacy-2DES.p12` | Unsupported archive encryption; terminal AES re-export guidance with any password | + `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. +headers and archive extension capitalization. Desktop GnuTLS validates and signs client keys; portable builds keep the Rust +implementation. Legacy encrypted-key imports use the private GnuTLS shim. Legacy PKCS#12 SHA1/3DES keys use a consistent limit of 127 UTF-16 code units (256 bytes including the terminator), matching older supported GnuTLS releases. Longer passwords report a clear error without exposing the password. @@ -53,6 +61,41 @@ 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. +`tests/client_certificate_extensions.rs` covers issue #697 with generated +RSA, P-256, P-384 and Ed25519 identities: no extensions, private critical and +noncritical extensions, critical Netscape client type, Microsoft template, +key usage and client EKU. Each is exercised as separate PEM, combined PEM, +DER, PKCS#12 and a service snapshot, including snapshot/file round trips and +request-client construction. Independent OpenSSL checks establish local key +compatibility. TLS 1.2/1.3 tests verify client authentication with PEM and +PKCS#12 and confirm the original signed certificate is sent unchanged. Negative +cases retain key mismatch errors, server trust checks and server rejection of +a client certificate. The checked-in critical-extension fixture also covers +the shared certificate validation used by both desktop shells. + +`tests/certificate_compatibility.rs` checks RC4-128 import, renewed identities and P-521 rejection, +and typed, actionable errors for unsupported algorithms, +EC encodings and archive encryption. The OpenConnect integration suite checks +the real loader/handshake separately from these HTTP/import tests. + +Desktop local matching and signing use GnuTLS. The VPN server validates client +certificate extensions and trust; HTTP server trust still uses the platform +verifier with Rustls/ring. RSA-PSS and P-521 key types deliberately fail before connecting +until the HTTP transport can negotiate them correctly on both TLS versions. +This differs from ordinary RSA keys producing RSA-PSS signatures, which remain +supported. OpenSSL remains development-only. + +`tests/client_certificate_chain.rs` checks mutual TLS with PKCS#12 CA rollover, +including self-issued intermediates and both certificate bag orders. It also +checks RSA-PSS certificate signatures with 20-, 32-, and 48-byte salts against +a same-name, wrong-key issuer. The server must receive the original leaf and +correct intermediate; OpenConnect must retain the original archive. + +`tests/client_certificate_tls12_hash.rs` records the remaining TLS 1.2 P-384 +with SHA-256-only peer request gap: the OpenSSL baseline passes, while the +replacement reproducer is explicitly ignored pending negotiated-version-aware +signing. TLS 1.3 curve restrictions must remain intact. + 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 diff --git a/crates/gpapi/tests/files/client-identity/ec-compressed-cert.pem b/crates/gpapi/tests/files/client-identity/ec-compressed-cert.pem new file mode 100644 index 0000000..4c7fd69 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-compressed-cert.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBiTCCAS+gAwIBAgIUHDc6Wcp0MUwwtwAhR3fEY3zLSXQwCgYIKoZIzj0EAwIw +KjEoMCYGA1UEAwwfR1AgUHVibGljIGNvbXByZXNzZWQgUmVncmVzc2lvbjAeFw0y +NjExMDcwMjA2MjZaFw0zNjExMDQwMjA2MjZaMCoxKDAmBgNVBAMMH0dQIFB1Ymxp +YyBjb21wcmVzc2VkIFJlZ3Jlc3Npb24wOTATBgcqhkjOPQIBBggqhkjOPQMBBwMi +AANCb8yN/N6VTBYHE1F66qyust8GzXKAd6pfo1cEItbJFaNTMFEwHQYDVR0OBBYE +FIK3uCPt33xbuFkEkBQx2RBu3UIDMB8GA1UdIwQYMBaAFIK3uCPt33xbuFkEkBQx +2RBu3UIDMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIhALe0rg77 +NMpcc8yKUnGcdWDu8GW1IE55TJf++RkJ+/JAAiBnlmSBnoZaTrPa5LEycfTJMKSN +URn6fRsbCH1z4mQ6XQ== +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/ec-compressed.pem b/crates/gpapi/tests/files/client-identity/ec-compressed.pem new file mode 100644 index 0000000..4f797c2 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-compressed.pem @@ -0,0 +1,4 @@ +-----BEGIN EC PRIVATE KEY----- +MFcCAQEEIMIgGXJZB//8Zp7TOavSyB+7LrPKFG4eQZ8Fxx30bTzUoAoGCCqGSM49 +AwEHoSQDIgADQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRU= +-----END EC PRIVATE KEY----- diff --git a/crates/gpapi/tests/files/client-identity/ec-explicit-cert.pem b/crates/gpapi/tests/files/client-identity/ec-explicit-cert.pem new file mode 100644 index 0000000..6ef414a --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-explicit-cert.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICmTCCAj+gAwIBAgIUNb1E0mpnr5RBM1FR96iDr4We5r0wCgYIKoZIzj0EAwIw +KDEmMCQGA1UEAwwdR1AgUHVibGljIGV4cGxpY2l0IFJlZ3Jlc3Npb24wHhcNMjYx +MTA3MDIwNjI2WhcNMzYxMTA0MDIwNjI2WjAoMSYwJAYDVQQDDB1HUCBQdWJsaWMg +ZXhwbGljaXQgUmVncmVzc2lvbjCCAUswggEDBgcqhkjOPQIBMIH3AgEBMCwGByqG +SM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP///////////////zBbBCD///// +AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6k+ez671VdpiGvGUd +BrDMU7D2O848PifSYEsDFQDEnTYIhucEk2pmeOETnSa3gZ9+kARBBGsX0fLhLEJH ++Lzm5WOkQPJ3A32BLeszoPShOUXYmMKWT+NC4v4af5uO5+tKfA+eFivOM1drMV7O +y7ZAaDe/UfUCIQD/////AAAAAP//////////vOb6racXnoTzucrC/GMlUQIBAQNC +AARCb8yN/N6VTBYHE1F66qyust8GzXKAd6pfo1cEItbJFapMj+oEjBtrobfNydlo +CucLD5ewywG9O2mG6IMei49bo1MwUTAdBgNVHQ4EFgQUbJK+tR9aD33KGW9Ed7lV +x1BX7qwwHwYDVR0jBBgwFoAUbJK+tR9aD33KGW9Ed7lVx1BX7qwwDwYDVR0TAQH/ +BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiAHTMFLSyvWxcE198z6beN5B4+0LnsW +96Y06HhX5+uzaAIhANZHyKvAU4wDnTslafc7ch3ETQPBhWppgiTKHqE0+jUI +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/ec-explicit.pem b/crates/gpapi/tests/files/client-identity/ec-explicit.pem new file mode 100644 index 0000000..eeb82f2 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-explicit.pem @@ -0,0 +1,10 @@ +-----BEGIN EC PRIVATE KEY----- +MIIBaAIBAQQgwiAZclkH//xmntM5q9LIH7sus8oUbh5BnwXHHfRtPNSggfowgfcC +AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA//////////////// +MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr +vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE +axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W +K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8 +YyVRAgEBoUQDQgAEQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRWqTI/q +BIwba6G3zcnZaArnCw+XsMsBvTtphuiDHouPWw== +-----END EC PRIVATE KEY----- diff --git a/crates/gpapi/tests/files/client-identity/ec-p521-cert.pem b/crates/gpapi/tests/files/client-identity/ec-p521-cert.pem new file mode 100644 index 0000000..0f3a31e --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-p521-cert.pem @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICJDCCAYagAwIBAgIURE3nvaUdT7yk7gTwyhUFyCE1+K8wCgYIKoZIzj0EAwIw +JDEiMCAGA1UEAwwZR1AgUHVibGljIHA1MjEgUmVncmVzc2lvbjAeFw0yNjExMDcw +MjA2MjZaFw0zNjExMDQwMjA2MjZaMCQxIjAgBgNVBAMMGUdQIFB1YmxpYyBwNTIx +IFJlZ3Jlc3Npb24wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABAAu5HAWZpjZxfu6 +jQ+61F5CysJzWgkc4MIB4z8kW9w0x76vUGlWPX+yw0q5EzpeEGjWV82YDRoEfkDR +fAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jIgzNLtiEf +iEBgucZ5MgDEgNJdB03qCvaqUmYXN7LwoqNTMFEwHQYDVR0OBBYEFOsuLBWpYWC7 +PHAVmEE4a4gypkYaMB8GA1UdIwQYMBaAFOsuLBWpYWC7PHAVmEE4a4gypkYaMA8G +A1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDgYsAMIGHAkEPBtWqP2e1ZLiXH3V5 +Zp21p4uWCJiJxasdl3iuGgKbJiSUSM9m/90iLhan+j/RTkxW8Yt5KkWDTNFQac17 +7oSymAJCAROy25Xz7ScbLRbh2CquVzelxmxQtrWZmr2C6hNOG8vZat4qOigwmz/1 +ZRn2bQL5Gh0J21ohAXpzWgpLlXp1O4Bf +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/ec-p521.pem b/crates/gpapi/tests/files/client-identity/ec-p521.pem new file mode 100644 index 0000000..b39b8d5 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/ec-p521.pem @@ -0,0 +1,7 @@ +-----BEGIN EC PRIVATE KEY----- +MIHcAgEBBEIB61IsG6+MaMabtPWlbajOeOFQHcYyRjgenJqZdHvPt4VW9COQZGai +NkHmp3iifcXWDegv1vY4fFmCmc9zlbbZU7qgBwYFK4EEACOhgYkDgYYABAAu5HAW +ZpjZxfu6jQ+61F5CysJzWgkc4MIB4z8kW9w0x76vUGlWPX+yw0q5EzpeEGjWV82Y +DRoEfkDRfAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jI +gzNLtiEfiEBgucZ5MgDEgNJdB03qCvaqUmYXN7Lwog== +-----END EC PRIVATE KEY----- diff --git a/crates/gpapi/tests/files/client-identity/generate-pss-chain.sh b/crates/gpapi/tests/files/client-identity/generate-pss-chain.sh new file mode 100644 index 0000000..4b816c3 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/generate-pss-chain.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Public test certificates only; uses the existing public RSA client key. +set -euo pipefail +cd "$(dirname "$0")" +openssl_bin=${OPENSSL_BIN:-openssl} +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +"$openssl_bin" req -x509 -newkey rsa:2048 -noenc -sha256 -days 3650 \ + -subj '/CN=PSS Chain Root' -addext 'basicConstraints=critical,CA:TRUE' \ + -keyout "$scratch/root.key" -out pss-chain-root.pem +"$openssl_bin" req -new -newkey rsa:2048 -noenc -subj '/CN=PSS Issuing CA' \ + -keyout "$scratch/issuer.key" -out "$scratch/issuer.csr" +printf 'basicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign\n' > "$scratch/ca.ext" +"$openssl_bin" x509 -req -in "$scratch/issuer.csr" -CA pss-chain-root.pem \ + -CAkey "$scratch/root.key" -set_serial 2 -days 3650 -sha256 \ + -extfile "$scratch/ca.ext" -out pss-chain-issuer.pem +"$openssl_bin" req -new -key rsa-pkcs8.pem -subj '/CN=PSS Signed Client' -out "$scratch/client.csr" +printf 'basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\n' > "$scratch/client.ext" +for salt_length in 20 32 48; do + "$openssl_bin" x509 -req -in "$scratch/client.csr" -CA pss-chain-issuer.pem \ + -CAkey "$scratch/issuer.key" -set_serial "$salt_length" -days 3650 -sha256 \ + -sigopt rsa_padding_mode:pss -sigopt "rsa_pss_saltlen:$salt_length" \ + -extfile "$scratch/client.ext" -out "pss-chain-salt-$salt_length.pem" +done diff --git a/crates/gpapi/tests/files/client-identity/generate.sh b/crates/gpapi/tests/files/client-identity/generate.sh index e7a3dad..d47e15e 100644 --- a/crates/gpapi/tests/files/client-identity/generate.sh +++ b/crates/gpapi/tests/files/client-identity/generate.sh @@ -17,6 +17,19 @@ for algorithm in rsa ec; do "$openssl_bin" x509 -req -in "$scratch/$algorithm.csr" -CA root.pem -CAkey "$scratch/root.key" \ -set_serial 10 -days 3650 -sha256 -out "$algorithm-cert.pem" done +# Issue #697: the local identity must allow a server-specific critical extension. +"$openssl_bin" req -new -x509 -key rsa-pkcs8.pem -sha256 -days 3650 \ + -subj '/CN=GP Critical Extension Regression' \ + -addext '1.3.6.1.4.1.55555.1=critical,DER:05:00' -out rsa-critical-extension.pem +# Compatibility and unsupported-input fixtures use the same public test keys. +"$openssl_bin" ec -in ec-pkcs8.pem -conv_form compressed -out ec-compressed.pem +"$openssl_bin" ec -in ec-pkcs8.pem -param_enc explicit -out ec-explicit.pem +"$openssl_bin" ecparam -name secp521r1 -genkey -noout -out ec-p521.pem +"$openssl_bin" genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -out rsa-pss.pem +for variant in ec-compressed ec-explicit ec-p521 rsa-pss; do + "$openssl_bin" req -new -x509 -key "$variant.pem" -sha256 -days 3650 \ + -subj "/CN=GP Public $variant Regression" -out "$variant-cert.pem" +done "$openssl_bin" rsa -in rsa-pkcs8.pem -traditional -out rsa-pkcs1.pem "$openssl_bin" ec -in ec-pkcs8.pem -out ec-sec1.pem for cipher in aes128 aes192 aes256 des3; do @@ -70,6 +83,14 @@ done "$openssl_bin" pkcs8 -provider default -provider legacy -topk8 -in rsa-pkcs8.pem \ -v2 des-cbc -v2prf hmacWithSHA256 -passout pass:fixture-password -out rsa-pbes2-des.pem +# RC4-128 was usable with the former OpenSSL legacy provider and OpenConnect. +# RC2-128 and two-key 3DES deliberately exercise unsupported-encryption errors. +for scheme in RC4-128 RC2-128 2DES; do + "$openssl_bin" pkcs12 -export -legacy -inkey rsa-pkcs8.pem -in rsa-cert.pem \ + -keypbe "PBE-SHA1-$scheme" -certpbe PBE-SHA1-3DES \ + -passout pass:fixture-password -out "legacy-$scheme.p12" +done + # Incomplete identity archives exercise validation before native TLS import. "$openssl_bin" pkcs12 -export -nokeys -in rsa-cert.pem \ -name fixture -passout pass:fixture-password -out certificate-only.pfx @@ -78,3 +99,4 @@ done # Plain PKCS#12 bags let the import tests omit optional IDs and reorder bags. python3 "$(dirname "$0")/generate-plain-pfx.py" +bash "$(dirname "$0")/generate-pss-chain.sh" diff --git a/crates/gpapi/tests/files/client-identity/legacy-2DES.p12 b/crates/gpapi/tests/files/client-identity/legacy-2DES.p12 new file mode 100644 index 0000000..7dc49b1 Binary files /dev/null and b/crates/gpapi/tests/files/client-identity/legacy-2DES.p12 differ diff --git a/crates/gpapi/tests/files/client-identity/legacy-RC2-128.p12 b/crates/gpapi/tests/files/client-identity/legacy-RC2-128.p12 new file mode 100644 index 0000000..6c23a1c Binary files /dev/null and b/crates/gpapi/tests/files/client-identity/legacy-RC2-128.p12 differ diff --git a/crates/gpapi/tests/files/client-identity/legacy-RC4-128.p12 b/crates/gpapi/tests/files/client-identity/legacy-RC4-128.p12 new file mode 100644 index 0000000..e0aacc4 Binary files /dev/null and b/crates/gpapi/tests/files/client-identity/legacy-RC4-128.p12 differ diff --git a/crates/gpapi/tests/files/client-identity/pss-chain-issuer.pem b/crates/gpapi/tests/files/client-identity/pss-chain-issuer.pem new file mode 100644 index 0000000..044702e --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/pss-chain-issuer.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEDCCAfigAwIBAgIBAjANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5QU1Mg +Q2hhaW4gUm9vdDAeFw0yNjExMDcwNTIxNTJaFw0zNjExMDQwNTIxNTJaMBkxFzAV +BgNVBAMMDlBTUyBJc3N1aW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAkjFaot6TCYfvnmfxSGfpqd2X+633FdjuaJLFf+G/EAccA7SVwtyGAJuT +/+RE3q0JO9I502mPRIWxkKOH0KU1dQK92iIup2lhc4WOtaGFvk+KGu3UrIQhgK8N +h0bEkiPcO160M3MEBo3mZGC933n/q+ean1nHcxrh3vp6t4fAUmH8B46+ww2QgUR0 +nJorVh/gAmrzRmgRfRy3FKHRh9sZLrguJqlNOe8g3x/brmFV2dd4vl1iX84+Xxs3 +9WfyrYGH0Sy3HAUv7ur5z8j9eiPTdy3UvGpDoz815WKCJNkdTvbMlDJVu0+NokLa +7q3z0CidYwVGqHlzKl6yXPp4J/ZbVwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/ +MA4GA1UdDwEB/wQEAwICBDAdBgNVHQ4EFgQUjMoHVKzTYMWxwGZvjWzCuv2roqYw +HwYDVR0jBBgwFoAUK0dvk5jU2/lvSQ4u3d0VdEQ1bTwwDQYJKoZIhvcNAQELBQAD +ggEBABr/bCjbrX3JrF8S30glfEPOwXuYsJRCWuHn4+p89x0nwEU7+DpChepRwG6n +rhsFRUz2ADrpJyw+4DaEHquGpEGirRx9QLEV9rDXAAyHK7/k1yy25pfj/CttzjXn +M6WEZPR5jRcNNBH+B7Lb55uvGQHiuZg7abuNz+lE8iUwXOsfsbXqAU7RoWpvb59f +jrDh925YPvKRIMGPqZjA9l5KzPxmBxyWZlSyTwRlZPVcAJXPRusfuCVko6kXcEJ1 +U86g8VjR03EknNSxYifXjbAlFGh2NBeJ1BeS12yTe9zlyZ1hijwC0jTlzF9fzI/K +YgwNW6V0W51+Rn2L8EyHtl0IbyU= +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/pss-chain-root.pem b/crates/gpapi/tests/files/client-identity/pss-chain-root.pem new file mode 100644 index 0000000..bdcd412 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/pss-chain-root.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEzCCAfugAwIBAgIUbtOYPmJw0zjzONdDDXnD4PWLy+8wDQYJKoZIhvcNAQEL +BQAwGTEXMBUGA1UEAwwOUFNTIENoYWluIFJvb3QwHhcNMjYxMTA3MDUyMTUxWhcN +MzYxMTA0MDUyMTUxWjAZMRcwFQYDVQQDDA5QU1MgQ2hhaW4gUm9vdDCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBANnZ/+l/MSDO3IlW57rCGg8WOSOQ1Kmy +2QoMUGCSNNrYsfmriY0BkcyX4LHyvH2FqZUE4h6IfVnY1qEaKRQYw6Rljy9unGkW +Z7a5c6N88KbZ3GgFUkn/BpFbf1FAd7AVfXwOrbUtpw43nxLmN6nXr3iYTme0aOuH +rNTnxBUq7WEMKyZNwtuKJoYBllqNr6Pth+KVtFNvXyQfqOetTi1upwObsZYVewnU +Hv5+XM9ZQ9S2pC8816B9DGm+ys0+f+mn+W9f6C+ffHhjV+aUMfgBFOIB9sl1oZNO +td+WX5yT96/b7OTwOwP/Q6eKvK+QMDEbi2K2ULMqknlUfOfeLvKPCUECAwEAAaNT +MFEwHQYDVR0OBBYEFCtHb5OY1Nv5b0kOLt3dFXRENW08MB8GA1UdIwQYMBaAFCtH +b5OY1Nv5b0kOLt3dFXRENW08MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBALrN2Eu94nDxpbSp1AfYPVr5/9yUOMfA/NjUB3OZ4q5fyPoAiTmOFZ7C +hIdnXfMZq6tKKUf1qO86HreiyHF4+JIewBPkR43uTRxRuuV37R9igbXDmYtvmUK0 ++8zgj4Y6IhXO7wqr6llIgK3LF9dkg7K1NhqvgWaGXB10YrjU5Ae1rVToN+9Yre8a +4PsbaWGQR+kchcYd1WlJJO4afBf7ecGDujwBc0k/bHX8eFmhQ94ZIh/KyONsEI3C +mmgEDeFCdWPCG+736IkrYA8SAAFqVMMQCvHDMpROUzbHFOQQIKKOUy0ErLKpwEYo +4Xn5o6uX/eWZaLv5iOcNACugZ2JwW1g= +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/pss-chain-salt-20.pem b/crates/gpapi/tests/files/client-identity/pss-chain-salt-20.pem new file mode 100644 index 0000000..ffe9553 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/pss-chain-salt-20.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDgzCCAjygAwIBAgIBFDA8BgkqhkiG9w0BAQowL6APMA0GCWCGSAFlAwQCAQUA +oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAMBkxFzAVBgNVBAMMDlBTUyBJ +c3N1aW5nIENBMB4XDTI2MTEwNzA1MjE1MloXDTM2MTEwNDA1MjE1MlowHDEaMBgG +A1UEAwwRUFNTIFNpZ25lZCBDbGllbnQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDd1Qd/iKhTpVWOjhfwPTqlaj9Ac6CKubFr0fZsVgR8r1OSmRv16e2t +jhfjjhOI0cz3S4Cqt9ZPLWIMGMugt9Y1YFHpg8gTsLrnYgRHBtA2eoBhLROLsj5x +aiUBoAYPR1vLmPyHtPuvveRepaY59AEarptx6//jf6LJQAjxTNbiU5FQsGr4ixVG +I29zsesFE0VbVSxKYdiMN+duVX7iPQSkMODWedcBEqQo17xAdvPgjtpN1AfXoDHW +ns/kpfOb2z9W1o3GG89XxA1s/IBivmIb6Dy+p7CzhCFxHmOd8Wlt8/U5W9wkphHm +HWbsF79XEBqyIoUx6Vo1kNsCezCSf9aHAgMBAAGjdTBzMAwGA1UdEwEB/wQCMAAw +DgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMCMB0GA1UdDgQWBBQ/ +cTzIdpR+vdaP5Z9fBxp5isXZMDAfBgNVHSMEGDAWgBSMygdUrNNgxbHAZm+NbMK6 +/auipjA8BgkqhkiG9w0BAQowL6APMA0GCWCGSAFlAwQCAQUAoRwwGgYJKoZIhvcN +AQEIMA0GCWCGSAFlAwQCAQUAA4IBAQAUOI4kd5ZvRevSo5kt6xoJBYmRw2jVwcqG +rVoq21h1L3cqhqYSb9oCyGcrkWcUfXY5uPAemF9wyScbLgwyGudX6ngVdHWwRVvN +dBZLRLDsviRAjN60NP06vrV/JzcQfFOL2L0tjGfYCfXdYD+0WZG8R1qtb2fHPh89 +II7O3dof2eR/GOot/JX6te7vYc3faWyNTC8SclB9tJrwAz8++tf0cuStHoLWd9jV +Gq3mhKn1ZzdJsbwTQjledIXLG6eRE6XyLHzcB6VctAt6bhVLxH8Ck/oEfGwYY2wK +tkwyNCnl35CCBRdbKxXfUJavoq8jwETZmSVnRUfWn2HUB6FDmtGm +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/pss-chain-salt-32.pem b/crates/gpapi/tests/files/client-identity/pss-chain-salt-32.pem new file mode 100644 index 0000000..dd9f347 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/pss-chain-salt-32.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDjTCCAkGgAwIBAgIBIDBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA +oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwGTEXMBUGA1UEAwwO +UFNTIElzc3VpbmcgQ0EwHhcNMjYxMTA3MDUyMTUyWhcNMzYxMTA0MDUyMTUyWjAc +MRowGAYDVQQDDBFQU1MgU2lnbmVkIENsaWVudDCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ +G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt +E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw +aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U +B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb +3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaN1MHMwDAYDVR0TAQH/ +BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0O +BBYEFD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFIzKB1Ss02DFscBm +b41swrr9q6KmMEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq +hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBIAOCAQEAHduUqnc8vvfsg8PrIRxD +qOWW0wx6BdRSd23cx1V7OaT7JMU6gvWSiiFx+aOl+REPQNNxi9yTAUDL0vPewwa9 +UZSNUy0tYVXuhZ4QfoPMZNRV2d1JekoHXgWLk39JgD363TL504MEhDoeXtIAbj/d +Ta+7aHGH6xMhwldUWMqiUkBpC4TUOsshZm92197/SRl9joTWB5G3RSREirG8LEn4 +HiTgd2AbiPXzAzA5MdIOeGWMKSF+Ey3R6Z2HzOzIrqAd3pFVPI6oHMSN6WzfHLVW +GT8LM+eQyUXTQn7B67REH+/GsolCHBUEMjyABUtZoNIxa3KOXE7GN7SQDV93UPhT +CQ== +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/pss-chain-salt-48.pem b/crates/gpapi/tests/files/client-identity/pss-chain-salt-48.pem new file mode 100644 index 0000000..14c8b97 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/pss-chain-salt-48.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDjTCCAkGgAwIBAgIBMDBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA +oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCATAwGTEXMBUGA1UEAwwO +UFNTIElzc3VpbmcgQ0EwHhcNMjYxMTA3MDUyMTUyWhcNMzYxMTA0MDUyMTUyWjAc +MRowGAYDVQQDDBFQU1MgU2lnbmVkIENsaWVudDCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ +G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt +E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw +aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U +B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb +3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaN1MHMwDAYDVR0TAQH/ +BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0O +BBYEFD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFIzKB1Ss02DFscBm +b41swrr9q6KmMEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq +hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBMAOCAQEAfRbXy5n1jSsOiKKGppzq +iRhrCJf51Le9aaf5cot/l1Q8GTFdYi8Ieu4CghsmGvfJIuRyig/aFfqXxpcFldDq +Nm4uIKRyDwygLyDau+OUaNmz1UZ2Y6FzOfyb6ujy2pEhOXr1EnQnL82MvlvbN4DT +9Dx4FgXAydtM6P6QfALvAEVy8/wjAYVCK5Xv/vKR5fFc2Rgl3DZkopcPF2pNQFN4 +E0P7GWxE+elRG952lacqHyhL4sIMoHF6AvDFUVwWoqttIfjX1272vt2yN1ej9F94 +BWyVm+sYf0fg767lsW2yFQS/1LbldjkHmxQn3qkrPhPni1zWhC5MJ6DxFLXGxkIr +kw== +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/rsa-critical-extension.pem b/crates/gpapi/tests/files/client-identity/rsa-critical-extension.pem new file mode 100644 index 0000000..31fef69 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/rsa-critical-extension.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSzCCAjOgAwIBAgIUColgV9GBymAbAEDYl4N4hI5i+icwDQYJKoZIhvcNAQEL +BQAwKzEpMCcGA1UEAwwgR1AgQ3JpdGljYWwgRXh0ZW5zaW9uIFJlZ3Jlc3Npb24w +HhcNMjYxMTA3MDA0ODI3WhcNMzYxMTA0MDA0ODI3WjArMSkwJwYDVQQDDCBHUCBD +cml0aWNhbCBFeHRlbnNpb24gUmVncmVzc2lvbjCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAN3VB3+IqFOlVY6OF/A9OqVqP0BzoIq5sWvR9mxWBHyvU5KZ +G/Xp7a2OF+OOE4jRzPdLgKq31k8tYgwYy6C31jVgUemDyBOwuudiBEcG0DZ6gGEt +E4uyPnFqJQGgBg9HW8uY/Ie0+6+95F6lpjn0ARqum3Hr/+N/oslACPFM1uJTkVCw +aviLFUYjb3Ox6wUTRVtVLEph2Iw3525VfuI9BKQw4NZ51wESpCjXvEB28+CO2k3U +B9egMdaez+Sl85vbP1bWjcYbz1fEDWz8gGK+YhvoPL6nsLOEIXEeY53xaW3z9Tlb +3CSmEeYdZuwXv1cQGrIihTHpWjWQ2wJ7MJJ/1ocCAwEAAaNnMGUwHQYDVR0OBBYE +FD9xPMh2lH691o/ln18HGnmKxdkwMB8GA1UdIwQYMBaAFD9xPMh2lH691o/ln18H +GnmKxdkwMA8GA1UdEwEB/wQFMAMBAf8wEgYJKwYBBAGDsgMBAQH/BAIFADANBgkq +hkiG9w0BAQsFAAOCAQEANDajhAeLynPhIpjeh0FJf2lwTVap0yA903pGeOziuvdc +R3eTX6DF9lXyNsfdiIR9BL+oL0fhOh8LG85dqCANIKCkKqelcI6FBUjTbZziDXxi +Xxc68XHfNs+f8Z+LLTuBo7k8vPuOxPLxTmERi5+O2dLUINAjZrQML+uzAmK3KlfZ +Ge6qWNE6k35+ZQGQwor+VHwmwJjKLHaPaZHAwhQWJer/dDcadkxLGGJ4DDt95awL +ggpS/04jM5tUxlysCQqrTHxFIiiALFPy7+Md4DRLv+oinIpcRrT2SECVWCW583JI +gWAPCoAvOOT7qMWYuba6OUidaeR7T6sgIQtZ4x9Fnw== +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/rsa-pss-cert.pem b/crates/gpapi/tests/files/client-identity/rsa-pss-cert.pem new file mode 100644 index 0000000..4a73753 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/rsa-pss-cert.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDjTCCAkGgAwIBAgIUZbovjhUmkSfk/CWcoqSraiFxygUwQQYJKoZIhvcNAQEK +MDSgDzANBglghkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEF +AKIDAgEgMCMxITAfBgNVBAMMGEdQIFB1YmxpYyBwc3MgUmVncmVzc2lvbjAeFw0y +NjExMDcwMjA2MjZaFw0zNjExMDQwMjA2MjZaMCMxITAfBgNVBAMMGEdQIFB1Ymxp +YyBwc3MgUmVncmVzc2lvbjCCASAwCwYJKoZIhvcNAQEKA4IBDwAwggEKAoIBAQDr +NsIJvoquN4qj9OIcsw8Pu/jjZMUPFGXQeejNRh1oIA+Lo0aps9IgQm2iIHlrusdO +3DbXriMvrUXEmrp10FC7JCe34oY1SahpY4/EU5acQrcANwszkN+wRxGHNmZ4jYGQ +tRZGyQIDiejvztBAWsCjSp/VfqyfCoECe21/6cKl1qZRJSPgnXlZJrYfvJeyKMoa +/GYyE1oFQRvNN56TRkT4Z4ys5kN3tl7S4GI13LohIzlej3pQeAiU+4+addJ71c29 +3UDfZfqu2p+qpcZ9y5k1dhVn/XAuiX4avQ40UYxtYMTo10h6oyU64GBfcJ05ljbb +UaX4XcC0udKPcWmH/Y2/AgMBAAGjUzBRMB0GA1UdDgQWBBSG4neJk61a5OKpTJwv +xTfMYWhzRTAfBgNVHSMEGDAWgBSG4neJk61a5OKpTJwvxTfMYWhzRTAPBgNVHRMB +Af8EBTADAQH/MEEGCSqGSIb3DQEBCjA0oA8wDQYJYIZIAWUDBAIBBQChHDAaBgkq +hkiG9w0BAQgwDQYJYIZIAWUDBAIBBQCiAwIBIAOCAQEArry92CksVDObs8ekbHPQ +tz5BF8s7yI729Dy35oH/zFT/vWOtP9vMYRF83x+g5ZzNMjdBZDm2lzVLlHOjClbp +RKxMthR+Dy8jGu2+5f+GwaOWWvIlTGJB0qssH5pKWvt5PU1f2KGuPAp4aU+1VxwA +DJXbQn5ssQxS/L/9WsQGOzvDMuMkWKxIZ+Z1YsAvBNlhYlS8OMdfDVGl5MobomVl +WU5kwNZlIDoBk3J9EXXa40xbUULCCq3bEEfIu5Mo6VgzyE8Y/EAPjI2q23wH2Map +ReT5yhKyqX6BXfUGaN9jNv/t7j6h+gXEXx5WYXb5OX557csMWRCBiHjAQUoIh3FB +7Q== +-----END CERTIFICATE----- diff --git a/crates/gpapi/tests/files/client-identity/rsa-pss.pem b/crates/gpapi/tests/files/client-identity/rsa-pss.pem new file mode 100644 index 0000000..d4e40a8 --- /dev/null +++ b/crates/gpapi/tests/files/client-identity/rsa-pss.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEuwIBADALBgkqhkiG9w0BAQoEggSnMIIEowIBAAKCAQEA6zbCCb6KrjeKo/Ti +HLMPD7v442TFDxRl0HnozUYdaCAPi6NGqbPSIEJtoiB5a7rHTtw2164jL61FxJq6 +ddBQuyQnt+KGNUmoaWOPxFOWnEK3ADcLM5DfsEcRhzZmeI2BkLUWRskCA4no787Q +QFrAo0qf1X6snwqBAnttf+nCpdamUSUj4J15WSa2H7yXsijKGvxmMhNaBUEbzTee +k0ZE+GeMrOZDd7Ze0uBiNdy6ISM5Xo96UHgIlPuPmnXSe9XNvd1A32X6rtqfqqXG +fcuZNXYVZ/1wLol+Gr0ONFGMbWDE6NdIeqMlOuBgX3CdOZY221Gl+F3AtLnSj3Fp +h/2NvwIDAQABAoIBACQNGFrU/RLXHs/4HytQmIeMAzRF2Ybw/z/1B3plpj6I4h5q +xVBfvYjwlYwqwmGBgb3eYSYtTGWo1E+I0E5xbNuaHt+qKnGCxiYiZUKCoKF3qkPa +q+6t5FMeOXC0z6o833XLWPbleoJfV2K2G1OEdWUxxri6zytwjoslBDNS+WC1xTj/ +3IOj0hQwwTToiLkqrcyG1ymCj9RR+3CJ30/QVSmj9Gg+1/9Cws3/mc3en2hjVhSw +AwCEZUD2c+Uvc+DnfOtJNeJaDrwgmuZNNPUw/SEkTtsUY6SMbY5tgrkHzNhXl5Af +aqSznvhwykxvgw/PIowgZMA1pGynicX2ajYq+KECgYEA+5OfLmT4e1tXqTgiv7Ea +pOmPR2AaAsryZNpSf5CbmmxgVrNvLtmy5PNV7QvRtsIvmoCPHZkyHmLGPIIIMu8L +G2yyFyZWSCVVieanRrxJrRZlssbHRRcu9r9LFNi1S7SgkMKknaiWQIbQFVMx/rZQ +VTiPGu+sicoPefeCuvOtOKECgYEA71l8QLRApjOHShiWPzZFn9aD23txtsbcpHD+ +pzW/yB+19gnUQA4VtIfQFvlUMmeRbu2LnIXhTqXEo4Zfkgq7o5ROtyrK/FOQ/qKr +N8C112O9vUS0ccpN31VaN66jWGPa61+a5awtEr78c153Z94Pl4iYmMFhshK79E2G +tEX3Sl8CgYBea6Bh1EmiWr0C6Ou50Gm0nWhGHJ6Gj8775Sjzcb3E7ooV4FCJX/GR +lnaYekgidK1TKo8MR9QUrXPDf/Y9z5P2ngwVPjFB8KkzEZuUo9RvHynaOFrP5oyc +1V0DnPYmTMu6qSMJfR2vaCmu50OrWpe59HlZXbz/FhRK7YdmTVClIQKBgCjFuaDc +E9c8F+PLZGzINfwQcs3ErY5ROezZQsgBI/ZXUIvlCL8QpynlqNEBEBK2CdQ3qvyy +4bqgCmtAzK74HRa0gOQ66fEp2x1FYJ1SuqdCWmQPfB2WNMXCqGer3C+Gcxh9ZMmT +FuqGlkKg6P5MmaNapYQADUBkaJgpTLUQ5htJAoGBAMpA9RbcSNPMe+POUxGb6pk3 +mSV4ymmotWtyr0GqNa/FgujjZ68TWwvhrJFD0kQap3flM3/82ThJCk9HsJ9osjPM +mNEHccfgASpPVgpkvLUjtITUb7aO1cdjHK1gFknNQSy/jZyMClfhnwvXiqqgWqme +f9Ih4LSOdrek2teuI5Mo +-----END PRIVATE KEY----- diff --git a/crates/openconnect/tests/client_identity.c b/crates/openconnect/tests/client_identity.c new file mode 100644 index 0000000..9a5ed6e --- /dev/null +++ b/crates/openconnect/tests/client_identity.c @@ -0,0 +1,280 @@ +/* Exercise the normal OpenConnect setter and GlobalProtect HTTPS path. The peer + * verifies client TLS authentication, then returns 503: no VPN is configured. */ +#include +#include "openconnect-internal.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define PRIVATE_EXTENSION "1.3.6.1.4.1.55555.1" +#define PASSWORD "fixture-password" + +struct peer { + int listener, tls13, verified; + gnutls_certificate_credentials_t credentials; + gnutls_datum_t expected; +}; + +static void path(char *output, const char *directory, const char *name) +{ + assert(snprintf(output, PATH_MAX, "%s/%s", directory, name) < PATH_MAX); +} + +static gnutls_datum_t read_file(const char *filename) +{ + gnutls_datum_t data; + FILE *file = fopen(filename, "rb"); + long length; + assert(file); + assert(!fseek(file, 0, SEEK_END)); + length = ftell(file); + assert(length > 0 && length <= UINT_MAX); + assert(!fseek(file, 0, SEEK_SET)); + data.size = length; + data.data = malloc(data.size); + assert(data.data && fread(data.data, 1, data.size, file) == data.size); + assert(!fclose(file)); + return data; +} + +static gnutls_x509_crt_t read_certificate(const char *filename) +{ + gnutls_x509_crt_t certificate; + gnutls_datum_t data = read_file(filename); + assert(!gnutls_x509_crt_init(&certificate)); + assert(!gnutls_x509_crt_import(certificate, &data, GNUTLS_X509_FMT_PEM)); + free(data.data); + return certificate; +} + +static void progress(void *data, int level, const char *format, ...) +{ + va_list arguments; + if (level > PRG_DEBUG) return; + va_start(arguments, format); + vfprintf(stderr, format, arguments); + va_end(arguments); +} + +static int reject_untrusted_server(void *data, const char *reason) +{ + fprintf(stderr, "Unexpected server verification failure: %s\n", reason); + return -EINVAL; +} + +static int cancel_password_prompt(void *data, struct oc_auth_form *form) +{ + /* A missing/wrong fixture password must fail, never block on input. */ + return 1; +} + +static int verify_client(gnutls_session_t session) +{ + struct peer *peer = gnutls_session_get_ptr(session); + unsigned int count, status; + const gnutls_datum_t *certificates = gnutls_certificate_get_peers(session, &count); + assert(certificates && count > 0); + assert(certificates[0].size == peer->expected.size); + assert(!memcmp(certificates[0].data, peer->expected.data, peer->expected.size)); + assert(!gnutls_certificate_verify_peers2(session, &status)); + assert(!status); + peer->verified = 1; + return 0; +} + +static void *serve(void *data) +{ + struct peer *peer = data; + gnutls_session_t session; + fd_set reads; + struct timeval wait = { .tv_sec = 8 }; + struct timeval timeout = { .tv_sec = 5 }; + char request[8192]; + static const char response[] = + "HTTP/1.1 503 TLS fixture complete\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + int fd; + FD_ZERO(&reads); + FD_SET(peer->listener, &reads); + assert(select(peer->listener + 1, &reads, NULL, NULL, &wait) == 1); + fd = accept(peer->listener, NULL, NULL); + assert(fd >= 0); + assert(!setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))); + assert(!setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout))); + assert(!gnutls_init(&session, GNUTLS_SERVER)); + assert(!gnutls_priority_set_direct(session, peer->tls13 + ? "NORMAL:-VERS-ALL:+VERS-TLS1.3" : "NORMAL:-VERS-ALL:+VERS-TLS1.2", NULL)); + assert(!gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, peer->credentials)); + gnutls_certificate_server_set_request(session, GNUTLS_CERT_REQUIRE); + gnutls_session_set_ptr(session, peer); + gnutls_transport_set_int(session, fd); + gnutls_handshake_set_timeout(session, 5000); + /* A successful handshake also verifies CertificateVerify proof of possession. */ + assert(!gnutls_handshake(session)); + assert(peer->verified); + assert(gnutls_protocol_get_version(session) == (peer->tls13 ? GNUTLS_TLS1_3 : GNUTLS_TLS1_2)); + assert(gnutls_record_recv(session, request, sizeof(request)) > 0); + assert(gnutls_record_send(session, response, sizeof(response) - 1) == sizeof(response) - 1); + gnutls_deinit(session); + close(fd); + return NULL; +} + +static void check(const char *name, const char *server_cert, const char *server_key, + const char *server_ca, const char *client_ca, const char *certificate, + const char *key, const char *password, gnutls_x509_crt_t expected, + int private_extension, int tls13) +{ + struct peer peer = { .tls13 = tls13 }; + struct sockaddr_in address = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) }; + socklen_t address_length = sizeof(address); + struct openconnect_info *client; + pthread_t thread; + char url[128]; + int result; + assert(!gnutls_certificate_allocate_credentials(&peer.credentials)); + assert(!gnutls_certificate_set_x509_key_file(peer.credentials, server_cert, server_key, GNUTLS_X509_FMT_PEM)); + assert(gnutls_certificate_set_x509_trust_file(peer.credentials, client_ca, GNUTLS_X509_FMT_PEM) > 0); + assert(gnutls_certificate_set_x509_trust(peer.credentials, &expected, 1) > 0); + assert(!gnutls_x509_crt_export2(expected, GNUTLS_X509_FMT_DER, &peer.expected)); + if (private_extension) { + unsigned critical = 0; + unsigned char value[2]; + size_t length = sizeof(value); + assert(!gnutls_x509_crt_get_extension_by_oid(expected, PRIVATE_EXTENSION, 0, + value, &length, &critical)); + assert(critical && length == 2 && value[0] == 5 && value[1] == 0); + /* The exact-DER pin in verify_client limits this exception to the known + * fixture extension. Chain trust and handshake signatures stay checked. */ + gnutls_certificate_set_verify_flags(peer.credentials, GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS); + } + gnutls_certificate_set_verify_function(peer.credentials, verify_client); + peer.listener = socket(AF_INET, SOCK_STREAM, 0); + assert(peer.listener >= 0); + assert(!bind(peer.listener, (struct sockaddr *)&address, sizeof(address))); + assert(!getsockname(peer.listener, (struct sockaddr *)&address, &address_length)); + assert(!listen(peer.listener, 1)); + assert(!pthread_create(&thread, NULL, serve, &peer)); + client = openconnect_vpninfo_new("Client identity regression", reject_untrusted_server, + NULL, cancel_password_prompt, progress, NULL); + assert(client); + snprintf(url, sizeof(url), "https://localhost:%u/", ntohs(address.sin_port)); + assert(!openconnect_parse_url(client, url)); + assert(!openconnect_set_protocol(client, "gp")); + assert(!openconnect_set_cafile(client, server_ca)); + assert(!openconnect_set_client_cert(client, certificate, key)); + if (password) assert(!openconnect_set_key_password(client, password)); + assert(!openconnect_set_cookie(client, "user=fixture&authcookie=fixture")); + result = openconnect_make_cstp_connection(client); + assert(result < 0); /* The fixture ends after TLS, without GP configuration. */ + openconnect_vpninfo_free(client); + assert(!pthread_join(thread, NULL)); + assert(peer.verified); + close(peer.listener); + gnutls_free(peer.expected.data); + gnutls_certificate_free_credentials(peer.credentials); + printf("%s TLS1.%d: exact client leaf, trusted server and mutual TLS passed\n", name, tls13 ? 3 : 2); +} + +static gnutls_x509_crt_t renewed_certificate(gnutls_x509_privkey_t key) +{ + gnutls_x509_crt_t certificate; + unsigned char serial[] = { 0x65 }; + time_t now = time(NULL); + assert(!gnutls_x509_crt_init(&certificate)); + assert(!gnutls_x509_crt_set_version(certificate, 3)); + assert(!gnutls_x509_crt_set_dn(certificate, "CN=Public renewed identity", NULL)); + assert(!gnutls_x509_crt_set_issuer_dn(certificate, "CN=Public renewed identity", NULL)); + assert(!gnutls_x509_crt_set_serial(certificate, serial, sizeof(serial))); + assert(!gnutls_x509_crt_set_key(certificate, key)); + assert(!gnutls_x509_crt_set_activation_time(certificate, now - 3600)); + assert(!gnutls_x509_crt_set_expiration_time(certificate, now + 86400)); + assert(!gnutls_x509_crt_set_basic_constraints(certificate, 1, -1)); + assert(!gnutls_x509_crt_sign2(certificate, certificate, key, GNUTLS_DIG_SHA256, 0)); + return certificate; +} + +static void renewal_archive(const char *filename, gnutls_x509_privkey_t key, + gnutls_x509_crt_t older, gnutls_x509_crt_t renewed, gnutls_x509_crt_t root, int reverse) +{ + gnutls_pkcs12_t archive; + gnutls_pkcs12_bag_t certificates, keys; + gnutls_datum_t output, id = { (unsigned char *)"renewed", 7 }; + FILE *file; + int renewed_index = reverse ? 1 : 0; + assert(!gnutls_pkcs12_init(&archive)); + assert(!gnutls_pkcs12_bag_init(&certificates)); + assert(gnutls_pkcs12_bag_set_crt(certificates, reverse ? older : renewed) == 0); + assert(gnutls_pkcs12_bag_set_crt(certificates, reverse ? renewed : older) == 1); + assert(gnutls_pkcs12_bag_set_crt(certificates, root) == 2); + /* Keep the bag association on the renewed leaf in both permutations. The + * baseline nevertheless selects the first certificate matching the key. */ + assert(!gnutls_pkcs12_bag_set_key_id(certificates, renewed_index, &id)); + assert(!gnutls_pkcs12_set_bag(archive, certificates)); + assert(!gnutls_pkcs12_bag_init(&keys)); + assert(gnutls_pkcs12_bag_set_privkey(keys, key, NULL, GNUTLS_PKCS_PLAIN) == 0); + assert(!gnutls_pkcs12_bag_set_key_id(keys, 0, &id)); + assert(!gnutls_pkcs12_set_bag(archive, keys)); + assert(!gnutls_pkcs12_generate_mac2(archive, GNUTLS_MAC_SHA256, PASSWORD)); + assert(!gnutls_pkcs12_export2(archive, GNUTLS_X509_FMT_DER, &output)); + file = fopen(filename, "wb"); + assert(file && fwrite(output.data, 1, output.size, file) == output.size); + assert(!fclose(file)); + gnutls_free(output.data); + gnutls_pkcs12_bag_deinit(keys); + gnutls_pkcs12_bag_deinit(certificates); + gnutls_pkcs12_deinit(archive); +} + +int main(int argc, char **argv) +{ + const char *names[] = { "critical extension", "P-521", "RSA-PSS", "RC4 PKCS12" }; + const char *certificates[] = { "rsa-critical-extension.pem", "ec-p521-cert.pem", "rsa-pss-cert.pem", "legacy-RC4-128.p12" }; + const char *keys[] = { "rsa-pkcs8.pem", "ec-p521.pem", "rsa-pss.pem", NULL }; + char certificate[PATH_MAX], key[PATH_MAX], ca[PATH_MAX], expected_file[PATH_MAX], archive[PATH_MAX]; + gnutls_x509_privkey_t renewal_key; + gnutls_x509_crt_t older, renewed, root; + gnutls_datum_t key_data; + assert(argc == 6); + signal(SIGPIPE, SIG_IGN); + alarm(30); + assert(!openconnect_init_ssl()); + path(ca, argv[1], "root.pem"); + for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++) { + gnutls_x509_crt_t expected; + path(certificate, argv[1], certificates[i]); + if (keys[i]) path(key, argv[1], keys[i]); + path(expected_file, argv[1], i == 3 ? "rsa-cert.pem" : certificates[i]); + expected = read_certificate(expected_file); + for (int tls13 = 0; tls13 <= 1; tls13++) + check(names[i], argv[2], argv[3], argv[4], ca, certificate, + keys[i] ? key : NULL, i == 3 ? PASSWORD : NULL, expected, i == 0, tls13); + gnutls_x509_crt_deinit(expected); + } + path(key, argv[1], "rsa-pkcs8.pem"); + key_data = read_file(key); + assert(!gnutls_x509_privkey_init(&renewal_key)); + assert(!gnutls_x509_privkey_import2(renewal_key, &key_data, GNUTLS_X509_FMT_PEM, NULL, 0)); + gnutls_memset(key_data.data, 0, key_data.size); + free(key_data.data); + path(expected_file, argv[1], "rsa-cert.pem"); + older = read_certificate(expected_file); + root = read_certificate(ca); + renewed = renewed_certificate(renewal_key); + for (int reverse = 0; reverse <= 1; reverse++) { + path(archive, argv[5], reverse ? "renewed-reversed.p12" : "renewed-forward.p12"); + renewal_archive(archive, renewal_key, older, renewed, root, reverse); + for (int tls13 = 0; tls13 <= 1; tls13++) + check(reverse ? "renewal reversed" : "renewal forward", argv[2], argv[3], argv[4], + ca, archive, NULL, PASSWORD, reverse ? older : renewed, 0, tls13); + } + gnutls_x509_crt_deinit(renewed); + gnutls_x509_crt_deinit(older); + gnutls_x509_crt_deinit(root); + gnutls_x509_privkey_deinit(renewal_key); + return 0; +} diff --git a/crates/openconnect/tests/client_identity.rs b/crates/openconnect/tests/client_identity.rs new file mode 100644 index 0000000..8b84079 --- /dev/null +++ b/crates/openconnect/tests/client_identity.rs @@ -0,0 +1,83 @@ +//! Actual OpenConnect credential loading and mutual TLS, without creating a VPN tunnel. +use std::{ + fs, + os::unix::process::CommandExt, + path::{Path, PathBuf}, + process::{Child, Command}, + time::{Duration, Instant}, +}; + +struct ChildGuard(Child); +impl Drop for ChildGuard { + fn drop(&mut self) { + unsafe { libc::kill(-(self.0.id() as i32), libc::SIGKILL) }; + let _ = self.0.wait(); + } +} + +fn run_bounded(command: &mut Command, log: &Path) { + let output = fs::File::create(log).unwrap(); + let mut child = ChildGuard( + command + .process_group(0) + .stdout(output.try_clone().unwrap()) + .stderr(output) + .spawn() + .unwrap(), + ); + let deadline = Instant::now() + Duration::from_secs(45); + loop { + if let Some(status) = child.0.try_wait().unwrap() { + assert!(status.success(), "{status}: {}", fs::read_to_string(log).unwrap()); + return; + } + assert!( + Instant::now() < deadline, + "Client identity test timed out: {}", + fs::read_to_string(log).unwrap() + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn client_identities_complete_openconnect_tls12_and_tls13() { + let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD")); + let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE")); + let directory = tempfile::tempdir().unwrap(); + let executable = directory.path().join("client-identity"); + let flags = Command::new("pkg-config") + .args(["--cflags", "--libs", "libxml-2.0", "gnutls"]) + .output() + .unwrap(); + assert!(flags.status.success(), "{}", String::from_utf8_lossy(&flags.stderr)); + run_bounded( + Command::new(build.join("libtool")) + .args(["--mode=link", "cc", "-pthread"]) + .arg(manifest.join("tests/client_identity.c")) + .arg("-I") + .arg(&build) + .arg("-I") + .arg(&source) + .arg("-I") + .arg(source.join("json")) + .arg(build.join("libopenconnect.la")) + .args(String::from_utf8(flags.stdout).unwrap().split_whitespace()) + .arg("-o") + .arg(&executable), + &directory.path().join("compile.log"), + ); + let server = manifest.join("deps/openconnect/tests/certs"); + run_bounded( + Command::new(build.join("libtool")) + .arg("--mode=execute") + .arg(executable) + .arg(manifest.join("../gpapi/tests/files/client-identity")) + .arg(server.join("server-cert.pem")) + .arg(server.join("server-key.pem")) + .arg(server.join("ca.pem")) + .arg(directory.path()), + &directory.path().join("runtime.log"), + ); +} diff --git a/flake.lock b/flake.lock index 54ba5af..8059b63 100644 --- a/flake.lock +++ b/flake.lock @@ -63,11 +63,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1793795574, - "narHash": "sha256-pgG/CO+txdf2sA2z6DsM+2G3F9ajfIp/3BMC4wfKMDY=", + "lastModified": 1793977579, + "narHash": "sha256-WrSODdZFVIs/Hh2NzC0bY+ROByi0bATg8WfePX8dPj8=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "13e53762c5afaf384d4614e94527a9ccfafe41d0", + "rev": "4fe25e12eb9f4c744966dd3de5a05246cf098601", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 728fa40..61a6a58 100644 --- a/flake.nix +++ b/flake.nix @@ -29,8 +29,8 @@ cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); pname = "globalprotect-openconnect"; version = cargoToml.workspace.package.version; - releaseTag = "v3.3.0"; - releaseVersion = "3.3.0"; + releaseTag = "v3.3.1"; + releaseVersion = "3.3.1"; toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; @@ -55,8 +55,8 @@ cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name; gpguiHashes = { - x86_64 = "sha256-6+rt47Cu/6uLwM3FgUaP/0qvTALF+UJRFD2nkybNCTg="; - aarch64 = "sha256-auCDdt6LMwnYJ0B9oneoPYAVfEGa/1GkIs8XkXXv85U="; + x86_64 = "sha256-yFXqpxmY222xm6Z8WgNsZgbWUwbYE3qWEeGqZxD7wTU="; + aarch64 = "sha256-8+GaeDAqX3kvjd8a7Tzv9AjtnefaZO0h4sXzOltG5GY="; }; gpguiArchive = pkgs.fetchurl { @@ -70,8 +70,8 @@ }; binaryHashes = { - x86_64 = "sha256-nsVNOfZ1JxT1mTyiHS3VYyBjbKm5+XsHC/v/fkWwK7A="; - aarch64 = "sha256-EjvkgYpOsaktnNE+Xta/GoKjILQzijW0U2bN1e/FiAQ="; + x86_64 = "sha256-JXUYT6DRMvN67No4jgJMcp0PyOzib8l0lPHM6muhb9w="; + aarch64 = "sha256-JhYLZTZvw+jdu5ewqrWSnNSW66ub1J2S4rhhwcrR43E="; }; binaryArchive = pkgs.fetchurl {