fix: restore client certificate compatibility after OpenSSL removal

Use GnuTLS for desktop client key matching and signing without applying server certificate policy to local identities. Restore RC4 PKCS12 import and renewed certificate selection, and provide actionable unsupported identity errors.

Add HTTP and OpenConnect mutual TLS regressions. Record the unresolved TLS 1.2 ECDSA hash limitation and reject P-521 and RSA-PSS keys explicitly.
This commit is contained in:
Kevin Yue committed 2026-11-07 11:23:19 +08:00
1 parent e03a758acb
commit c476dfefb0
42 files changed
+2618 -163

No files matched your search

+3 -1
View File
@@ -16,8 +16,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 }
+99 -10
View File
@@ -22,11 +22,23 @@ pub enum ServerTlsErrorKind {
}
impl ServerTlsError {
pub(crate) fn from_request(server: &url::Url, error: &(dyn Error + 'static)) -> Option<Self> {
Some(Self {
pub(crate) fn from_request(
server: &url::Url,
error: &(dyn Error + 'static),
has_client_identity: bool,
) -> Option<anyhow::Error> {
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<ServerTlsErrorKind> {
classify_with_identity(error, false)
}
fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bool) -> Option<ServerTlsErrorKind> {
let mut source = Some(error);
while let Some(error) = source {
if let Some(tls) = error.downcast_ref::<ServerTlsError>() {
@@ -71,6 +87,14 @@ pub(super) fn classify(error: &(dyn Error + 'static)) -> Option<ServerTlsErrorKi
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateRequired) => {
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, &params, 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)
);
}
+4 -4
View File
@@ -187,8 +187,8 @@ async fn receive_gateway_login(
.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)),
}
})?;
@@ -201,8 +201,8 @@ async fn receive_gateway_login(
let endpoint = res.remote_addr();
let url = res.url().clone();
let res = parse_gp_response(res).await.map_err(|err| {
if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err) {
return anyhow::anyhow!(tls);
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);
+13 -13
View File
@@ -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<ClientBuilder> {
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)
}
}
+8 -8
View File
@@ -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(&params).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()));
+4 -4
View File
@@ -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()))
@@ -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<AnyRef<'_>>) -> Result<(), RequestIdentityError> {
if let Some(parameters) = parameters {
if parameters.tag() == Tag::ObjectIdentifier {
let curve = parameters
.decode_as::<ObjectIdentifier>()
.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::<AnyRef<'_>>::decode_explicit(reader, TagNumber(0))?.map(|field| field.value);
let point =
ContextSpecific::<BitStringRef<'_>>::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(())
}
+235
View File
@@ -44,3 +44,238 @@ void gp_key_free(unsigned char *data, size_t length) {
gnutls_free(data);
}
}
#include <gnutls/abstract.h>
#include <stdlib.h>
#include <string.h>
/* 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 <gnutls/pkcs12.h>
#include <stdint.h>
/* 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;
}
@@ -14,6 +14,15 @@ 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);
}
@@ -64,3 +73,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<Vec<u8>>, 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()),
}
}
+7 -3
View File
@@ -1,4 +1,8 @@
mod client_key;
pub(super) use client_key::{ClientKey, validate_certificate};
pub(super) mod pkcs12;
mod pkcs12_format;
#[cfg(any(
target_os = "macos",
@@ -7,7 +11,7 @@ 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",
@@ -15,6 +19,6 @@ mod legacy_key;
target_os = "openbsd"
)))]
#[path = "unsupported.rs"]
mod legacy_key;
mod platform_import;
pub(super) use legacy_key::decrypt as decrypt_key;
pub(super) use platform_import::{archive, decrypt as decrypt_key};
@@ -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<c_void>);
// 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<Vec<u8>> {
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<Mutex<NativeKey>>,
kind: c_int,
public_key: Vec<u8>,
}
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<Self> {
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<bool> {
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<Box<dyn Signer>> {
self
.schemes()
.iter()
.copied()
.find(|scheme| offered.contains(scheme))
.map(|scheme| {
Box::new(ClientSigner {
key: self.clone(),
scheme,
}) as Box<dyn Signer>
})
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
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<Vec<u8>, 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<u8> {
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::<RequestIdentityError>(),
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());
}
}
}
+38 -31
View File
@@ -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<reqwest::Identity> {
pub(in crate::utils) fn certified_key(
bytes: &[u8],
passphrase: Option<&str>,
) -> anyhow::Result<std::sync::Arc<rustls::sign::CertifiedKey>> {
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,24 +51,15 @@ 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();
@@ -68,5 +75,5 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
}
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())
}
@@ -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<ArchiveBackend, RequestIdentityError> {
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::<OctetString>().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::<EncryptedData>().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::<OctetString>().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::<EncryptedPrivateKeyInfo>::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(&parameters).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(&parameters).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)
));
}
}
}
@@ -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<dyn SigningKey>,
}
impl ClientKey {
pub(in crate::utils) fn load(key: &PrivateKeyDer<'_>) -> anyhow::Result<Self> {
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<bool> {
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<Box<dyn Signer>> {
self.key.choose_scheme(offered)
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
self.key.public_key()
}
fn algorithm(&self) -> SignatureAlgorithm {
self.key.algorithm()
}
}
@@ -5,3 +5,10 @@ pub(in crate::utils) fn decrypt(
) -> anyhow::Result<pkcs8::SecretDocument> {
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
}
pub(in crate::utils) fn archive(
_bytes: &[u8],
_passphrase: Option<&str>,
) -> anyhow::Result<(zeroize::Zeroizing<Vec<u8>>, pkcs8::SecretDocument)> {
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
}
+99
View File
@@ -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<Arc<CertifiedKey>> {
let certificates = rustls_pemfile::certs(&mut Cursor::new(certificate))
.collect::<Result<Vec<_>, _>>()
.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<CertifiedKey>,
ignore_server_certificate_errors: bool,
) -> anyhow::Result<reqwest::ClientBuilder> {
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<SignatureScheme>,
}
impl ServerCertVerifier for IgnoreServerCertificateErrors {
fn verify_server_cert(
&self,
_: &CertificateDer<'_>,
_: &[CertificateDer<'_>],
_: &ServerName<'_>,
_: &[u8],
_: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_: &[u8],
_: &CertificateDer<'_>,
_: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_: &[u8],
_: &CertificateDer<'_>,
_: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.schemes.clone()
}
}
+2 -1
View File
@@ -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()),
+1
View File
@@ -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;
+57 -57
View File
@@ -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<IdentityMaterial>,
identity: Identity,
certified_key: Arc<CertifiedKey>,
}
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<Zeroizing<Vec<u8>>>,
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
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<reqwest::ClientBuilder> {
client_tls::identity_client_builder(self.certified_key.clone(), ignore_tls_errors)
}
pub fn write_files(&self, directory: Option<&Path>) -> anyhow::Result<ClientIdentityFiles> {
@@ -149,29 +155,6 @@ impl ClientIdentityFiles {
}
}
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
let error_context =
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
let mut combined = Zeroizing::new(certificate.to_vec());
combined.push(b'\n');
combined.extend_from_slice(key);
let identity = Identity::from_pem(&combined).context(error_context)?;
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
.collect::<Result<Vec<_>, _>>()
.context(error_context)?;
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
.context(error_context)?
.context(error_context)?;
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
.context(error_context)?;
client_builder()
.no_proxy()
.identity(identity.clone())
.build()
.context(error_context)?;
Ok(identity)
}
fn read_identity_file(path: &str) -> anyhow::Result<Zeroizing<Vec<u8>>> {
Ok(Zeroizing::new(
fs::read(path).context("Failed to read client identity")?,
@@ -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<Identity> {
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::<RequestIdentityError>() {
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();
}
}
@@ -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::<RequestIdentityError>(),
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::<RequestIdentityError>(),
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();
}
@@ -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<Private> {
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<Private>, 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(&params(identity.clone(), false)).unwrap();
reqwest::Client::try_from(&params(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<Private>) -> anyhow::Result<ClientIdentity> {
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::<RequestIdentityError>(),
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(&params).unwrap();
params.prepare_client_identity().unwrap();
drop(directory);
reqwest::Client::try_from(&params).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<Private>,
version: SslVersion,
expected_client: Vec<u8>,
accept_client: bool,
) -> (String, thread::JoinHandle<bool>) {
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(&params(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(&params(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}"
);
}
}
}
}
@@ -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<Private>, 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<Result<(), String>>) {
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(&params).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");
}
+13 -16
View File
@@ -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::<RequestIdentityError>(),
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::<RequestIdentityError>(),
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::<RequestIdentityError>(),
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::<RequestIdentityError>() {
Some(RequestIdentityError::AmbiguousPkcs12) => assert!(ambiguous),
Some(RequestIdentityError::InvalidCertificate) => assert!(!ambiguous),
Some(RequestIdentityError::KeyMismatch) => assert!(!ambiguous),
other => panic!("{name}: unexpected archive error: {other:?}"),
}
}
@@ -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,19 @@ 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 |
| `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 +60,35 @@ 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_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
@@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBiTCCAS+gAwIBAgIUHDc6Wcp0MUwwtwAhR3fEY3zLSXQwCgYIKoZIzj0EAwIw
KjEoMCYGA1UEAwwfR1AgUHVibGljIGNvbXByZXNzZWQgUmVncmVzc2lvbjAeFw0y
NjExMDcwMjA2MjZaFw0zNjExMDQwMjA2MjZaMCoxKDAmBgNVBAMMH0dQIFB1Ymxp
YyBjb21wcmVzc2VkIFJlZ3Jlc3Npb24wOTATBgcqhkjOPQIBBggqhkjOPQMBBwMi
AANCb8yN/N6VTBYHE1F66qyust8GzXKAd6pfo1cEItbJFaNTMFEwHQYDVR0OBBYE
FIK3uCPt33xbuFkEkBQx2RBu3UIDMB8GA1UdIwQYMBaAFIK3uCPt33xbuFkEkBQx
2RBu3UIDMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIhALe0rg77
NMpcc8yKUnGcdWDu8GW1IE55TJf++RkJ+/JAAiBnlmSBnoZaTrPa5LEycfTJMKSN
URn6fRsbCH1z4mQ6XQ==
-----END CERTIFICATE-----
@@ -0,0 +1,4 @@
-----BEGIN EC PRIVATE KEY-----
MFcCAQEEIMIgGXJZB//8Zp7TOavSyB+7LrPKFG4eQZ8Fxx30bTzUoAoGCCqGSM49
AwEHoSQDIgADQm/MjfzelUwWBxNReuqsrrLfBs1ygHeqX6NXBCLWyRU=
-----END EC PRIVATE KEY-----
@@ -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-----
@@ -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-----
@@ -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-----
@@ -0,0 +1,7 @@
-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIB61IsG6+MaMabtPWlbajOeOFQHcYyRjgenJqZdHvPt4VW9COQZGai
NkHmp3iifcXWDegv1vY4fFmCmc9zlbbZU7qgBwYFK4EEACOhgYkDgYYABAAu5HAW
ZpjZxfu6jQ+61F5CysJzWgkc4MIB4z8kW9w0x76vUGlWPX+yw0q5EzpeEGjWV82Y
DRoEfkDRfAjk8/B/8wDNJ7oH9pepkq3DroH0v3R34C8oQwbsw/Rx9JwOECR3u2jI
gzNLtiEfiEBgucZ5MgDEgNJdB03qCvaqUmYXN7Lwog==
-----END EC PRIVATE KEY-----
@@ -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
@@ -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-----
@@ -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-----
@@ -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-----
+280
View File
@@ -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 <config.h>
#include "openconnect-internal.h"
#include <gnutls/gnutls.h>
#include <gnutls/pkcs12.h>
#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>
#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;
}
@@ -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"),
);
}