mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
chore: promote GP Connect 3.3.1 sources and Nix packages (#699)
* 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. * fix: select PKCS12 issuers by certificate signature Handle CA rollover and self-issued intermediates by checking issuer signatures. Preserve RSA-PSS signature parameters during GnuTLS verification and keep the original archive for OpenConnect. Add mutual-TLS regression coverage for certificate bag order and RSA-PSS salt lengths. Verified 53 targeted tests plus gpapi, desktop-core, and iOS compile checks. * fix: add gateway login diagnostics and scope platform dependencies * chore: prepare GP Connect 3.3.1 release
This commit is contained in:
1 parent
e03a758acb
commit
408536807c
55 files changed
+3288
-203
No files matched your search
@@ -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(())
|
||||
}
|
||||
@@ -44,3 +44,272 @@ void gp_key_free(unsigned char *data, size_t length) {
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
|
||||
#include <gnutls/abstract.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Check only the signature, not whether this local certificate is trusted,
|
||||
* current, or has extensions understood by the client. */
|
||||
int gp_certificate_verify_signature(
|
||||
const unsigned char *certificate, size_t certificate_length,
|
||||
const unsigned char *issuer_key, size_t issuer_key_length,
|
||||
const unsigned char *message, size_t message_length,
|
||||
const unsigned char *signature, size_t signature_length) {
|
||||
gnutls_x509_crt_t child = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
int result, algorithm;
|
||||
if (certificate_length > UINT_MAX || issuer_key_length > UINT_MAX ||
|
||||
message_length > UINT_MAX || signature_length > UINT_MAX) return -1;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return -1;
|
||||
gnutls_datum_t child_data = {(unsigned char *)certificate, (unsigned int)certificate_length};
|
||||
gnutls_datum_t key_data = {(unsigned char *)issuer_key, (unsigned int)issuer_key_length};
|
||||
gnutls_datum_t data = {(unsigned char *)message, (unsigned int)message_length};
|
||||
gnutls_datum_t sig = {(unsigned char *)signature, (unsigned int)signature_length};
|
||||
result = gnutls_x509_crt_init(&child);
|
||||
if (result >= 0) result = gnutls_x509_crt_import(child, &child_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import(public_key, &key_data, GNUTLS_X509_FMT_DER);
|
||||
if (result >= 0) {
|
||||
algorithm = gnutls_x509_crt_get_signature_algorithm(child);
|
||||
if (algorithm < 0) result = algorithm;
|
||||
else result = gnutls_pubkey_verify_data2(public_key, algorithm,
|
||||
GNUTLS_VERIFY_ALLOW_BROKEN | GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1, &data, &sig) >= 0;
|
||||
}
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (child != NULL) gnutls_x509_crt_deinit(child);
|
||||
gnutls_global_deinit();
|
||||
return result < 0 ? -1 : result;
|
||||
}
|
||||
|
||||
/* Stable private kinds, independent of the native enum values. */
|
||||
struct gp_client_key {
|
||||
gnutls_privkey_t signer;
|
||||
gnutls_pubkey_t public_key;
|
||||
};
|
||||
|
||||
void gp_client_key_delete(struct gp_client_key *key) {
|
||||
if (key == NULL) return;
|
||||
if (key->public_key != NULL) gnutls_pubkey_deinit(key->public_key);
|
||||
if (key->signer != NULL) gnutls_privkey_deinit(key->signer);
|
||||
free(key);
|
||||
gnutls_global_deinit();
|
||||
}
|
||||
|
||||
int gp_client_key_new(const unsigned char *data, size_t length, int *kind,
|
||||
struct gp_client_key **output) {
|
||||
gnutls_x509_privkey_t input = NULL;
|
||||
struct gp_client_key *key = NULL;
|
||||
int result, algorithm;
|
||||
*output = NULL;
|
||||
*kind = 9;
|
||||
if (length > UINT_MAX || gnutls_global_init() < 0) return 1;
|
||||
key = calloc(1, sizeof(*key));
|
||||
if (key == NULL) { gnutls_global_deinit(); return 1; }
|
||||
result = gnutls_x509_privkey_init(&input);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(input, &bytes, GNUTLS_X509_FMT_DER, NULL, 0);
|
||||
}
|
||||
if (result < 0) goto invalid;
|
||||
algorithm = gnutls_x509_privkey_get_pk_algorithm(input);
|
||||
if (algorithm == GNUTLS_PK_RSA_PSS) { *kind = 5; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_DSA) { *kind = 7; goto unsupported; }
|
||||
if (algorithm == GNUTLS_PK_EDDSA_ED448) { *kind = 8; goto unsupported; }
|
||||
result = gnutls_privkey_init(&key->signer);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_privkey_import_x509(key->signer, input, GNUTLS_PRIVKEY_IMPORT_COPY);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_init(&key->public_key);
|
||||
if (result < 0) goto invalid;
|
||||
result = gnutls_pubkey_import_privkey(key->public_key, key->signer, 0, 0);
|
||||
if (result < 0) goto invalid;
|
||||
if (algorithm == GNUTLS_PK_RSA) *kind = 0;
|
||||
else if (algorithm == GNUTLS_PK_EDDSA_ED25519) *kind = 4;
|
||||
else if (algorithm == GNUTLS_PK_ECDSA) {
|
||||
gnutls_ecc_curve_t curve;
|
||||
gnutls_datum_t x = {NULL, 0}, y = {NULL, 0};
|
||||
result = gnutls_pubkey_export_ecc_raw(key->public_key, &curve, &x, &y);
|
||||
gnutls_free(x.data);
|
||||
gnutls_free(y.data);
|
||||
if (result < 0) goto invalid;
|
||||
if (curve == GNUTLS_ECC_CURVE_SECP256R1) *kind = 1;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP384R1) *kind = 2;
|
||||
else if (curve == GNUTLS_ECC_CURVE_SECP521R1) { *kind = 3; goto unsupported; }
|
||||
else { *kind = 6; goto unsupported; }
|
||||
} else goto unsupported;
|
||||
gnutls_x509_privkey_deinit(input);
|
||||
*output = key;
|
||||
return 0;
|
||||
unsupported:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 2;
|
||||
invalid:
|
||||
if (input != NULL) gnutls_x509_privkey_deinit(input);
|
||||
gp_client_key_delete(key);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int gp_client_key_public(struct gp_client_key *key, unsigned char **output, size_t *length) {
|
||||
gnutls_datum_t bytes = {NULL, 0};
|
||||
int result = gnutls_pubkey_export2(key->public_key, GNUTLS_X509_FMT_DER, &bytes);
|
||||
*output = bytes.data;
|
||||
*length = bytes.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
int gp_client_key_matches(struct gp_client_key *key, const unsigned char *data, size_t length) {
|
||||
gnutls_x509_crt_t certificate = NULL;
|
||||
gnutls_pubkey_t public_key = NULL;
|
||||
unsigned char key_id[32], cert_id[32];
|
||||
size_t key_id_length = sizeof(key_id), cert_id_length = sizeof(cert_id);
|
||||
int result;
|
||||
if (length > UINT_MAX) return -1;
|
||||
result = gnutls_x509_crt_init(&certificate);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t bytes = {(unsigned char *)data, (unsigned int)length};
|
||||
result = gnutls_x509_crt_import(certificate, &bytes, GNUTLS_X509_FMT_DER);
|
||||
}
|
||||
if (result >= 0) result = gnutls_pubkey_init(&public_key);
|
||||
if (result >= 0) result = gnutls_pubkey_import_x509(public_key, certificate, 0);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(key->public_key, GNUTLS_KEYID_USE_SHA256, key_id, &key_id_length);
|
||||
if (result >= 0) result = gnutls_pubkey_get_key_id(public_key, GNUTLS_KEYID_USE_SHA256, cert_id, &cert_id_length);
|
||||
if (public_key != NULL) gnutls_pubkey_deinit(public_key);
|
||||
if (certificate != NULL) gnutls_x509_crt_deinit(certificate);
|
||||
if (result < 0) return result;
|
||||
return key_id_length == cert_id_length && !memcmp(key_id, cert_id, key_id_length);
|
||||
}
|
||||
|
||||
int gp_client_key_sign(struct gp_client_key *key, unsigned short scheme,
|
||||
const unsigned char *message, size_t length,
|
||||
unsigned char **output, size_t *output_length) {
|
||||
gnutls_sign_algorithm_t algorithm;
|
||||
unsigned int flags = 0;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return -1;
|
||||
switch (scheme) {
|
||||
case 0x0804: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA256; break;
|
||||
case 0x0805: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA384; break;
|
||||
case 0x0806: algorithm = GNUTLS_SIGN_RSA_PSS_RSAE_SHA512; break;
|
||||
case 0x0401: algorithm = GNUTLS_SIGN_RSA_SHA256; break;
|
||||
case 0x0501: algorithm = GNUTLS_SIGN_RSA_SHA384; break;
|
||||
case 0x0601: algorithm = GNUTLS_SIGN_RSA_SHA512; break;
|
||||
case 0x0403: algorithm = GNUTLS_SIGN_ECDSA_SECP256R1_SHA256; break;
|
||||
case 0x0503: algorithm = GNUTLS_SIGN_ECDSA_SECP384R1_SHA384; break;
|
||||
case 0x0807: algorithm = GNUTLS_SIGN_EDDSA_ED25519; break;
|
||||
default: return -1;
|
||||
}
|
||||
if (scheme >= 0x0804 && scheme <= 0x0806)
|
||||
flags = GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH;
|
||||
gnutls_datum_t bytes = {(unsigned char *)message, (unsigned int)length};
|
||||
gnutls_datum_t signature = {NULL, 0};
|
||||
int result = gnutls_privkey_sign_data2(key->signer, algorithm, flags, &bytes, &signature);
|
||||
*output = signature.data;
|
||||
*output_length = signature.size;
|
||||
return result;
|
||||
}
|
||||
|
||||
#include <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;
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use pkcs8::der::{Encode, asn1::ObjectIdentifier};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_certificate_verify_signature(
|
||||
certificate: *const u8,
|
||||
certificate_length: usize,
|
||||
issuer_key: *const u8,
|
||||
issuer_key_length: usize,
|
||||
message: *const u8,
|
||||
message_length: usize,
|
||||
signature: *const u8,
|
||||
signature_length: usize,
|
||||
) -> c_int;
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
@@ -14,9 +25,58 @@ unsafe extern "C" {
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_pkcs12_identity(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
password: *const c_char,
|
||||
certificate: *mut *mut u8,
|
||||
certificate_length: *mut usize,
|
||||
key: *mut *mut u8,
|
||||
key_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
certificate: &x509_cert::Certificate,
|
||||
issuer: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
const RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
|
||||
const RSA_PSS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
|
||||
let mut issuer_key = issuer.tbs_certificate().subject_public_key_info().clone();
|
||||
if certificate.signature_algorithm().oid == RSA_PSS {
|
||||
if !matches!(issuer_key.algorithm.oid, RSA | RSA_PSS) {
|
||||
return Ok(false);
|
||||
}
|
||||
// GnuTLS's generic verifier takes PSS parameters from the imported key.
|
||||
// Give this verification operation the certificate's full AlgorithmIdentifier,
|
||||
// including salt length, rather than the default implied by its signature enum.
|
||||
// This temporary SPKI never changes the certificates sent to the server.
|
||||
issuer_key.algorithm = certificate.signature_algorithm().clone();
|
||||
}
|
||||
let issuer_key = issuer_key.to_der()?;
|
||||
let certificate = certificate.to_der()?;
|
||||
let result = unsafe {
|
||||
gp_certificate_verify_signature(
|
||||
certificate.as_ptr(),
|
||||
certificate.len(),
|
||||
issuer_key.as_ptr(),
|
||||
issuer_key.len(),
|
||||
message.as_ptr(),
|
||||
message.len(),
|
||||
signature.as_ptr(),
|
||||
signature.len(),
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => Ok(false),
|
||||
1 => Ok(true),
|
||||
_ => Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
}
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
@@ -64,3 +124,55 @@ pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
bytes: &[u8],
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(Zeroizing<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()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use pkcs8::der::{Decode, Encode};
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
/// Identify the signing issuer, without applying trust, expiry or extension policy
|
||||
/// to a local identity. The VPN server remains responsible for those checks.
|
||||
pub(super) fn is_issuer(certificate: &[u8], issuer: &[u8]) -> anyhow::Result<bool> {
|
||||
let child = x509_cert::Certificate::from_der(certificate).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
let parent = x509_cert::Certificate::from_der(issuer).map_err(|_| RequestIdentityError::InvalidCertificate)?;
|
||||
if child.tbs_certificate().issuer() != parent.tbs_certificate().subject() {
|
||||
return Ok(false);
|
||||
}
|
||||
let signature = child
|
||||
.signature()
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
super::platform_import::verify_certificate_signature(&child, &parent, &child.tbs_certificate().to_der()?, signature)
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
mod client_key;
|
||||
mod issuer;
|
||||
pub(super) use client_key::{ClientKey, validate_certificate};
|
||||
|
||||
pub(super) mod pkcs12;
|
||||
mod pkcs12_format;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
@@ -7,14 +12,14 @@ pub(super) mod pkcs12;
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod legacy_key;
|
||||
mod platform_import;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
#[path = "portable_import.rs"]
|
||||
mod platform_import;
|
||||
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
pub(super) use platform_import::{archive, decrypt as decrypt_key};
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,38 +51,36 @@ pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyh
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
let mut matches = Vec::new();
|
||||
for (index, cert) in certs.iter().enumerate() {
|
||||
if signing_key.matches_certificate(cert.as_der())? {
|
||||
matches.push(index);
|
||||
}
|
||||
}
|
||||
let leaf = match matches.first() {
|
||||
Some(leaf) => *leaf,
|
||||
None => return Err(RequestIdentityError::KeyMismatch.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if current.subject() == current.issuer() {
|
||||
if super::issuer::is_issuer(current.as_der(), current.as_der())? {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
let mut parent = None;
|
||||
for (index, candidate) in certs.iter().enumerate() {
|
||||
if super::issuer::is_issuer(current.as_der(), candidate.as_der())? {
|
||||
parent = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(parent) = parent else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
client_tls::pem_certified_key(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -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(¶meters).map_err(|error| match error.kind() {
|
||||
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
|
||||
_ => RequestIdentityError::InvalidCertificate,
|
||||
})?;
|
||||
} else if matches!(oid, RC4_128 | DES3 | RC2_40) {
|
||||
Pkcs12PbeParams::from_der(¶meters).map_err(invalid)?;
|
||||
if oid == RC4_128 {
|
||||
*selected = ArchiveBackend::NativeRc4;
|
||||
}
|
||||
} else {
|
||||
return Err(RequestIdentityError::UnsupportedEncryption);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn published_archive_formats_choose_their_importer_from_metadata() {
|
||||
for name in [
|
||||
"modern.p12",
|
||||
"legacy-rc2.p12",
|
||||
"empty-password.p12",
|
||||
"unicode-password.p12",
|
||||
"no-bag-ids.p12",
|
||||
] {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/files/client-identity")
|
||||
.join(name);
|
||||
assert_eq!(
|
||||
backend(&std::fs::read(path).unwrap()).unwrap(),
|
||||
ArchiveBackend::Rust,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
backend(include_bytes!(
|
||||
"../../../tests/files/client-identity/legacy-RC4-128.p12"
|
||||
))
|
||||
.unwrap(),
|
||||
ArchiveBackend::NativeRc4
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_archive_encryption_is_terminal_before_password_handling() {
|
||||
for bytes in [
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-RC2-128.p12").as_slice(),
|
||||
include_bytes!("../../../tests/files/client-identity/legacy-2DES.p12").as_slice(),
|
||||
] {
|
||||
assert!(matches!(
|
||||
backend(bytes),
|
||||
Err(RequestIdentityError::UnsupportedEncryption)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Portable certificate verification; native legacy import is unavailable here.
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
use pkcs8::der::{Decode, Encode, asn1::AnyRef};
|
||||
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn archive(
|
||||
_bytes: &[u8],
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<(zeroize::Zeroizing<Vec<u8>>, pkcs8::SecretDocument)> {
|
||||
Err(RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
|
||||
pub(super) fn verify_certificate_signature(
|
||||
child: &x509_cert::Certificate,
|
||||
parent: &x509_cert::Certificate,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
let public_key = parent.tbs_certificate().subject_public_key_info();
|
||||
let key_algorithm = public_key.algorithm.to_der()?;
|
||||
let signature_algorithm = child.signature_algorithm().to_der()?;
|
||||
let key_algorithm = AnyRef::from_der(&key_algorithm)?.value();
|
||||
let signature_algorithm = AnyRef::from_der(&signature_algorithm)?.value();
|
||||
let key = public_key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(RequestIdentityError::InvalidCertificate)?;
|
||||
Ok(
|
||||
rustls::crypto::ring::default_provider()
|
||||
.signature_verification_algorithms
|
||||
.all
|
||||
.iter()
|
||||
.any(|algorithm| {
|
||||
algorithm.public_key_alg_id().as_ref() == key_algorithm
|
||||
&& algorithm.signature_alg_id().as_ref() == signature_algorithm
|
||||
&& algorithm.verify_signature(key, message, signature).is_ok()
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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()),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user