mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: release GP Connect 3.3.0 with Native Shell support
This commit is contained in:
226 files changed
+7700
-5225
No files matched your search
@@ -0,0 +1,46 @@
|
||||
#include <gnutls/gnutls.h>
|
||||
#include <gnutls/x509.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
|
||||
/* Only decrypted PKCS#8 leaves this interface. The Rust owner releases it with
|
||||
* gp_key_free, so GnuTLS allocation and wiping stay with the native allocator. */
|
||||
int gp_key_import(const unsigned char *input, size_t length, int pem,
|
||||
const char *password, unsigned char **output, size_t *output_length) {
|
||||
gnutls_x509_privkey_t key = NULL;
|
||||
gnutls_datum_t exported = {NULL, 0};
|
||||
int result;
|
||||
*output = NULL;
|
||||
*output_length = 0;
|
||||
if (length > UINT_MAX) return 3;
|
||||
result = gnutls_global_init();
|
||||
if (result < 0) return 3;
|
||||
result = gnutls_x509_privkey_init(&key);
|
||||
if (result >= 0) {
|
||||
gnutls_datum_t data = {(unsigned char *)input, (unsigned int)length};
|
||||
result = gnutls_x509_privkey_import2(key, &data,
|
||||
pem ? GNUTLS_X509_FMT_PEM : GNUTLS_X509_FMT_DER, password, 0);
|
||||
}
|
||||
if (result >= 0) {
|
||||
result = gnutls_x509_privkey_export2_pkcs8(key, GNUTLS_X509_FMT_DER,
|
||||
NULL, GNUTLS_PKCS_PLAIN, &exported);
|
||||
}
|
||||
if (key != NULL) gnutls_x509_privkey_deinit(key);
|
||||
gnutls_global_deinit();
|
||||
if (result >= 0) {
|
||||
*output = exported.data;
|
||||
*output_length = exported.size;
|
||||
return 0;
|
||||
}
|
||||
if (result == GNUTLS_E_DECRYPTION_FAILED) return 1;
|
||||
if (result == GNUTLS_E_UNKNOWN_CIPHER_TYPE || result == GNUTLS_E_UNIMPLEMENTED_FEATURE)
|
||||
return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
void gp_key_free(unsigned char *data, size_t length) {
|
||||
if (data != NULL) {
|
||||
gnutls_memset(data, 0, length);
|
||||
gnutls_free(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::utils::request::RequestIdentityError;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn gp_key_import(
|
||||
input: *const u8,
|
||||
length: usize,
|
||||
pem: c_int,
|
||||
password: *const c_char,
|
||||
output: *mut *mut u8,
|
||||
output_length: *mut usize,
|
||||
) -> c_int;
|
||||
fn gp_key_free(data: *mut u8, length: usize);
|
||||
}
|
||||
|
||||
struct ExportedKey {
|
||||
data: *mut u8,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl Drop for ExportedKey {
|
||||
fn drop(&mut self) {
|
||||
// The shim owns the allocation and wipes it before releasing it.
|
||||
unsafe { gp_key_free(self.data, self.length) };
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::utils) fn decrypt(bytes: &[u8], pem: bool, passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
anyhow::ensure!(
|
||||
!passphrase.as_bytes().contains(&0),
|
||||
"Private key passphrases containing NUL are not supported"
|
||||
);
|
||||
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
|
||||
password.push(0);
|
||||
let mut exported = ExportedKey {
|
||||
data: std::ptr::null_mut(),
|
||||
length: 0,
|
||||
};
|
||||
// All input slices remain live for the call; the output is owned by the guard.
|
||||
let result = unsafe {
|
||||
gp_key_import(
|
||||
bytes.as_ptr(),
|
||||
bytes.len(),
|
||||
i32::from(pem),
|
||||
password.as_ptr().cast(),
|
||||
&mut exported.data,
|
||||
&mut exported.length,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
0 => {
|
||||
anyhow::ensure!(!exported.data.is_null() && exported.length > 0, "Invalid private key");
|
||||
// A successful shim call returns an initialized allocation of this length.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(exported.data, exported.length) };
|
||||
SecretDocument::try_from(bytes).map_err(|_| RequestIdentityError::InvalidKey.into())
|
||||
}
|
||||
1 => Err(RequestIdentityError::DecryptError("PEM").into()),
|
||||
2 => Err(RequestIdentityError::UnsupportedEncryption.into()),
|
||||
_ => Err(RequestIdentityError::InvalidKey.into()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
pub(super) mod pkcs12;
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
))]
|
||||
#[path = "gnutls.rs"]
|
||||
mod legacy_key;
|
||||
#[cfg(not(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd"
|
||||
)))]
|
||||
#[path = "unsupported.rs"]
|
||||
mod legacy_key;
|
||||
|
||||
pub(super) use legacy_key::decrypt as decrypt_key;
|
||||
@@ -0,0 +1,72 @@
|
||||
use p12_keystore::Pkcs12Archive;
|
||||
use rustls::{
|
||||
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
sign::CertifiedKey,
|
||||
};
|
||||
|
||||
use crate::utils::request::{RequestIdentityError, pem_request_identity};
|
||||
|
||||
pub(in crate::utils) fn identity(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<reqwest::Identity> {
|
||||
anyhow::ensure!(
|
||||
passphrase.is_none_or(|password| !password.as_bytes().contains(&0)),
|
||||
"PKCS#12 passphrases containing NUL are not supported"
|
||||
);
|
||||
let archive = Pkcs12Archive::from_pkcs12(bytes, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
})?;
|
||||
if archive.keys.is_empty() || archive.certs.is_empty() {
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
if archive.keys.len() != 1 {
|
||||
return Err(RequestIdentityError::AmbiguousPkcs12.into());
|
||||
}
|
||||
let key = &archive.keys[0].key;
|
||||
let provider = rustls::crypto::ring::default_provider();
|
||||
let mut certs = Vec::new();
|
||||
for bag in &archive.certs {
|
||||
if !certs
|
||||
.iter()
|
||||
.any(|cert: &&p12_keystore::Certificate| cert.as_der() == bag.cert.as_der())
|
||||
{
|
||||
certs.push(&bag.cert);
|
||||
}
|
||||
}
|
||||
let matches: Vec<_> = certs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, cert)| {
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.as_der().to_vec()));
|
||||
CertifiedKey::from_der(
|
||||
vec![CertificateDer::from(cert.as_der().to_vec())],
|
||||
private_key,
|
||||
&provider,
|
||||
)
|
||||
.is_ok()
|
||||
.then_some(index)
|
||||
})
|
||||
.collect();
|
||||
let leaf = match matches.as_slice() {
|
||||
[leaf] => *leaf,
|
||||
[] => return Err(RequestIdentityError::InvalidCertificate.into()),
|
||||
_ => return Err(RequestIdentityError::AmbiguousPkcs12.into()),
|
||||
};
|
||||
let mut current = certs.remove(leaf);
|
||||
let mut chain = Vec::new();
|
||||
loop {
|
||||
chain.extend_from_slice(pem::encode(&pem::Pem::new("CERTIFICATE", current.as_der())).as_bytes());
|
||||
if current.subject() == current.issuer() {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = certs.iter().position(|cert| cert.subject() == current.issuer()) else {
|
||||
break;
|
||||
};
|
||||
current = certs.remove(parent);
|
||||
}
|
||||
let key = pkcs8::SecretDocument::try_from(key.as_der()).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
let key = key.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
|
||||
pem_request_identity(&chain, key.as_bytes())
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(in crate::utils) fn decrypt(
|
||||
_bytes: &[u8],
|
||||
_pem: bool,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<pkcs8::SecretDocument> {
|
||||
Err(crate::utils::request::RequestIdentityError::UnsupportedEncryption.into())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
|
||||
//! PEM/DER normalization before rustls validates usable keys and identities.
|
||||
use pkcs8::{
|
||||
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
|
||||
der::{
|
||||
@@ -8,13 +8,7 @@ use pkcs8::{
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{request::RequestIdentityError, traditional_key};
|
||||
|
||||
pub(super) enum TraditionalKeyFormat {
|
||||
Sec1Der,
|
||||
PlainPem,
|
||||
EncryptedPem,
|
||||
}
|
||||
use super::{certificate, request::RequestIdentityError};
|
||||
|
||||
struct PemBlock {
|
||||
tag: String,
|
||||
@@ -26,7 +20,9 @@ impl PemBlock {
|
||||
fn encoded(&self) -> Zeroizing<Vec<u8>> {
|
||||
let mut block = pem::Pem::new(&self.tag, self.contents.as_slice());
|
||||
*block.headers_mut() = self.headers.clone();
|
||||
let encoded = Zeroizing::new(pem::encode(&block).into_bytes());
|
||||
let encoded = Zeroizing::new(
|
||||
pem::encode_config(&block, pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF)).into_bytes(),
|
||||
);
|
||||
// The PEM crate owns a copy of the decoded private key as well.
|
||||
drop(Zeroizing::new(block.into_contents()));
|
||||
encoded
|
||||
@@ -77,13 +73,13 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
if !matches!(block.tag.as_str(), "RSA PRIVATE KEY" | "EC PRIVATE KEY") {
|
||||
return Err(RequestIdentityError::InvalidKey.into());
|
||||
}
|
||||
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::EncryptedPem, passphrase)?
|
||||
certificate::decrypt_key(&block.encoded(), true, passphrase)?
|
||||
} else {
|
||||
match block.tag.as_str() {
|
||||
"PRIVATE KEY" => SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?,
|
||||
"RSA PRIVATE KEY" => {
|
||||
// PKCS#8 stores the original PKCS#1 bytes inside an RSA algorithm envelope.
|
||||
// Native TLS validates the RSA key, as it does for existing PKCS#8 input.
|
||||
// Rustls validates the RSA key along with the certificate.
|
||||
let algorithm = AlgorithmIdentifierRef {
|
||||
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
|
||||
parameters: Some(AnyRef::NULL),
|
||||
@@ -94,11 +90,8 @@ pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Res
|
||||
}
|
||||
"ENCRYPTED PRIVATE KEY" => decrypt(der, passphrase)?,
|
||||
"EC PRIVATE KEY" => {
|
||||
if pem_input {
|
||||
traditional_key::normalize(&block.encoded(), TraditionalKeyFormat::PlainPem, passphrase)?
|
||||
} else {
|
||||
traditional_key::normalize(der, TraditionalKeyFormat::Sec1Der, passphrase)?
|
||||
}
|
||||
sec1::EcPrivateKey::from_der(der).map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
return Ok(block.encoded());
|
||||
}
|
||||
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
|
||||
}
|
||||
@@ -172,9 +165,16 @@ fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocumen
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?;
|
||||
if algorithm != pkcs8::pkcs5::pbes2::PBES2_OID {
|
||||
// PKCS#12 PBE-SHA1-3DES inside standalone PKCS#8 is not implemented by
|
||||
// RustCrypto. Only this known legacy scheme uses the optional executable.
|
||||
// RustCrypto. Only this known legacy scheme uses the native importer.
|
||||
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
|
||||
return super::legacy_pkcs8::decrypt(der, passphrase);
|
||||
// Older supported GnuTLS releases allow 256 UTF-16 bytes including the terminator.
|
||||
if let Some(passphrase) = passphrase {
|
||||
anyhow::ensure!(
|
||||
passphrase.encode_utf16().count() <= 127,
|
||||
"Password is too long for this legacy key format. Re-export the key with modern encryption"
|
||||
);
|
||||
}
|
||||
return certificate::decrypt_key(der, false, passphrase);
|
||||
}
|
||||
return Err(RequestIdentityError::UnsupportedEncryption.into());
|
||||
}
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
//! Optional compatibility conversion for standalone PKCS#12 PBE-SHA1-3DES keys.
|
||||
//! The executable is a runtime option, not a linked or bundled dependency.
|
||||
use std::{
|
||||
io::{ErrorKind, Read, Write},
|
||||
os::{fd::AsFd, unix::process::CommandExt},
|
||||
process::{Child, Command, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
fcntl::{FcntlArg, OFlag, fcntl},
|
||||
sys::signal::{Signal, killpg},
|
||||
unistd::Pid,
|
||||
};
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::request::RequestIdentityError::{self, LegacyKeyConversion};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT: u64 = 1024 * 1024;
|
||||
const MAX_PASSWORD_BYTES: usize = 1023;
|
||||
|
||||
// The converter owns a separate process group, including wrapper descendants.
|
||||
// Clean up that group and reap the direct child on every return path.
|
||||
struct Converter(Child);
|
||||
|
||||
impl Drop for Converter {
|
||||
fn drop(&mut self) {
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn nonblocking(pipe: &impl AsFd) -> anyhow::Result<()> {
|
||||
fcntl(pipe, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))
|
||||
.map_err(|_| LegacyKeyConversion("could not configure converter pipes"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Read at most one chunk per iteration so a busy pipe cannot starve the deadline.
|
||||
// Returns true only after EOF; inherited pipes remain subject to the deadline.
|
||||
fn read_output(pipe: &mut impl Read, output: &mut Zeroizing<Vec<u8>>, limit: u64) -> anyhow::Result<bool> {
|
||||
let mut buffer = Zeroizing::new([0u8; 8192]);
|
||||
match pipe.read(buffer.as_mut_slice()) {
|
||||
Ok(0) => Ok(true),
|
||||
Ok(count) => {
|
||||
if output.len() as u64 + count as u64 > limit {
|
||||
return Err(LegacyKeyConversion("converter output exceeds the size limit").into());
|
||||
}
|
||||
output.extend_from_slice(&buffer[..count]);
|
||||
Ok(false)
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => Ok(false),
|
||||
Err(_) => Err(LegacyKeyConversion("could not read converter output").into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
// The command's line reader reserves one byte for a terminator. The linked
|
||||
// OpenSSL API accepted 1024 bytes, but the CLI would truncate that password.
|
||||
if passphrase.len() > MAX_PASSWORD_BYTES {
|
||||
return Err(LegacyKeyConversion("the password exceeds OpenSSL's 1023-byte input limit").into());
|
||||
}
|
||||
// OpenSSL's pipe password source reads one line. Never silently truncate it.
|
||||
if passphrase.contains(['\r', '\n', '\0']) {
|
||||
return Err(LegacyKeyConversion("the password cannot be passed through OpenSSL's line-based input").into());
|
||||
}
|
||||
|
||||
// Only encrypted input touches disk, in a private temporary file. The
|
||||
// original file is never changed and decrypted output stays in memory.
|
||||
let mut input = tempfile::NamedTempFile::new()?;
|
||||
input.write_all(pem::encode(&pem::Pem::new("ENCRYPTED PRIVATE KEY", der)).as_bytes())?;
|
||||
let child = Command::new("openssl")
|
||||
.args([
|
||||
"pkcs8", "-topk8", "-nocrypt", "-inform", "PEM", "-outform", "DER", "-in",
|
||||
])
|
||||
.arg(input.path())
|
||||
.args(["-passin", "stdin"])
|
||||
.env("LC_ALL", "C")
|
||||
.process_group(0)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|_| LegacyKeyConversion("the openssl executable is unavailable"))?;
|
||||
let mut converter = Converter(child);
|
||||
let mut stdin = converter.0.stdin.take();
|
||||
let mut stdout = converter.0.stdout.take().unwrap();
|
||||
let mut stderr = converter.0.stderr.take().unwrap();
|
||||
nonblocking(stdin.as_ref().unwrap())?;
|
||||
nonblocking(&stdout)?;
|
||||
nonblocking(&stderr)?;
|
||||
let mut password = Zeroizing::new(passphrase.as_bytes().to_vec());
|
||||
password.push(b'\n');
|
||||
let mut written = 0;
|
||||
let mut input_failed = false;
|
||||
let mut output = Zeroizing::new(Vec::new());
|
||||
let mut diagnostic = Zeroizing::new(Vec::new());
|
||||
let mut output_done = false;
|
||||
let mut diagnostic_done = false;
|
||||
let mut status = None;
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
if started.elapsed() >= TIMEOUT {
|
||||
return Err(LegacyKeyConversion("conversion timed out").into());
|
||||
}
|
||||
if let Some(pipe) = stdin.as_mut() {
|
||||
match pipe.write(&password[written..]) {
|
||||
Ok(0) => {
|
||||
input_failed = true;
|
||||
stdin = None;
|
||||
}
|
||||
Ok(count) => {
|
||||
written += count;
|
||||
if written == password.len() {
|
||||
stdin = None;
|
||||
}
|
||||
}
|
||||
Err(error) if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
|
||||
Err(_) => {
|
||||
input_failed = true;
|
||||
stdin = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !output_done {
|
||||
output_done = read_output(&mut stdout, &mut output, MAX_OUTPUT)?;
|
||||
}
|
||||
if !diagnostic_done {
|
||||
diagnostic_done = read_output(&mut stderr, &mut diagnostic, 16 * 1024)?;
|
||||
}
|
||||
if status.is_none() {
|
||||
status = converter
|
||||
.0
|
||||
.try_wait()
|
||||
.map_err(|_| LegacyKeyConversion("could not wait for the converter"))?;
|
||||
}
|
||||
if let Some(status) = status {
|
||||
if output_done && diagnostic_done && stdin.is_none() {
|
||||
break status;
|
||||
}
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
if status.success() && input_failed {
|
||||
return Err(LegacyKeyConversion("could not send the password").into());
|
||||
}
|
||||
|
||||
if !status.success() {
|
||||
// Never include the command's output in user-facing errors: it can contain
|
||||
// key material. Preserve the old Linux password retry contract only for
|
||||
// an explicit decryption failure, not missing cipher/provider support.
|
||||
if [b"bad decrypt".as_slice(), b"pkcs12 cipherfinal error".as_slice()]
|
||||
.iter()
|
||||
.any(|message| diagnostic.windows(message.len()).any(|window| window == *message))
|
||||
{
|
||||
return Err(RequestIdentityError::DecryptError("PEM").into());
|
||||
}
|
||||
return Err(LegacyKeyConversion("this OpenSSL installation cannot decrypt the key").into());
|
||||
}
|
||||
SecretDocument::try_from(output.as_slice()).map_err(|_| LegacyKeyConversion("invalid converted key").into())
|
||||
}
|
||||
@@ -45,7 +45,10 @@ impl LockFile {
|
||||
Ok(content) => {
|
||||
let url = format!("http://127.0.0.1:{}/health", content.trim());
|
||||
|
||||
match reqwest::get(&url).await {
|
||||
let Ok(client) = crate::utils::request::client_builder().build() else {
|
||||
return false;
|
||||
};
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => resp.status().is_success(),
|
||||
Err(_) => false,
|
||||
}
|
||||
|
||||
@@ -1,35 +1,26 @@
|
||||
pub mod xml;
|
||||
|
||||
pub mod base64;
|
||||
mod certificate;
|
||||
pub mod checksum;
|
||||
pub mod crypto;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod endpoint;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod env_utils;
|
||||
mod identity_encoding;
|
||||
mod legacy_pkcs8;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub mod lock_file;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub mod openssl;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "pkcs12_identity/macos.rs"]
|
||||
mod pkcs12_identity;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "pkcs12_identity/openssl.rs"]
|
||||
mod pkcs12_identity;
|
||||
pub mod redact;
|
||||
pub mod request;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "traditional_key/macos.rs"]
|
||||
mod traditional_key;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[path = "traditional_key/openssl.rs"]
|
||||
mod traditional_key;
|
||||
#[cfg(feature = "tauri")]
|
||||
pub mod window;
|
||||
|
||||
#[cfg(feature = "desktop")]
|
||||
mod shutdown_signal;
|
||||
|
||||
use log::warn;
|
||||
#[cfg(feature = "desktop")]
|
||||
pub use shutdown_signal::shutdown_signal;
|
||||
|
||||
use reqwest::{Response, StatusCode, Url};
|
||||
@@ -74,6 +65,10 @@ impl GpError {
|
||||
pub fn is_status_error(&self) -> bool {
|
||||
self.status.is_client_error() || self.status.is_server_error()
|
||||
}
|
||||
|
||||
pub fn is_authentication_rejection(&self) -> bool {
|
||||
matches!(self.status.as_u16(), 401 | 403)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
use std::path::Path;
|
||||
|
||||
use log::{info, warn};
|
||||
use regex::Regex;
|
||||
use tempfile::NamedTempFile;
|
||||
use version_compare::{Cmp, compare_to};
|
||||
|
||||
pub fn openssl_conf() -> String {
|
||||
let option = get_openssl_option();
|
||||
|
||||
format!(
|
||||
"openssl_conf = openssl_init
|
||||
|
||||
[openssl_init]
|
||||
ssl_conf = ssl_sect
|
||||
providers = provider_sect
|
||||
|
||||
[ssl_sect]
|
||||
system_default = system_default_sect
|
||||
|
||||
[system_default_sect]
|
||||
Options = {}
|
||||
|
||||
[provider_sect]
|
||||
default = default_sect
|
||||
legacy = legacy_sect
|
||||
|
||||
[default_sect]
|
||||
activate = 1
|
||||
|
||||
[legacy_sect]
|
||||
activate = 1
|
||||
",
|
||||
option
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
|
||||
let content = openssl_conf();
|
||||
std::fs::write(path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
|
||||
let openssl_conf = NamedTempFile::new()?;
|
||||
let openssl_conf_path = openssl_conf.path();
|
||||
|
||||
fix_openssl(openssl_conf_path)?;
|
||||
unsafe { std::env::set_var("OPENSSL_CONF", openssl_conf_path) };
|
||||
|
||||
Ok(openssl_conf)
|
||||
}
|
||||
|
||||
// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled
|
||||
fn get_openssl_option() -> &'static str {
|
||||
let version_str = openssl::version::version();
|
||||
let default_option = "UnsafeLegacyServerConnect";
|
||||
|
||||
let Some(version) = extract_openssl_version(version_str) else {
|
||||
warn!("Failed to extract OpenSSL version from '{}'", version_str);
|
||||
return default_option;
|
||||
};
|
||||
|
||||
let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
warn!("Failed to compare OpenSSL version: {}", version);
|
||||
return default_option;
|
||||
}
|
||||
};
|
||||
|
||||
if older_than_3_0_4 {
|
||||
info!("Using 'UnsafeLegacyRenegotiation' option");
|
||||
"UnsafeLegacyRenegotiation"
|
||||
} else {
|
||||
info!("Using 'UnsafeLegacyServerConnect' option");
|
||||
default_option
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_openssl_version(version: &str) -> Option<&str> {
|
||||
let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap();
|
||||
re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_extract_version() {
|
||||
let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)";
|
||||
assert_eq!(extract_openssl_version(input), Some("3.4.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_format() {
|
||||
let input = "OpenSSL 1.1.1t 7 Feb 2023";
|
||||
assert_eq!(extract_openssl_version(input), Some("1.1.1t"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input() {
|
||||
let input = "Invalid string without version";
|
||||
assert_eq!(extract_openssl_version(input), None);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
use security_framework::{import_export::Pkcs12ImportOptions, os::macos::keychain::CreateOptions};
|
||||
|
||||
use super::request::RequestIdentityError;
|
||||
|
||||
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
// native-tls assumes a successful import has a last item with an identity.
|
||||
// Incomplete archives violate that assumption and panic. Inspect them first
|
||||
// in a private temporary keychain, never the user's default keychain.
|
||||
let directory = tempfile::tempdir()?;
|
||||
let keychain = CreateOptions::new()
|
||||
.password(&uuid::Uuid::new_v4().to_string())
|
||||
.create(directory.path().join("identity.keychain"))?;
|
||||
if let Ok(imports) = Pkcs12ImportOptions::new()
|
||||
.keychain(keychain)
|
||||
.passphrase(password)
|
||||
.import(bytes)
|
||||
&& !imports.last().is_some_and(|item| item.identity.is_some())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
// Leave failed imports to reqwest so password errors retain their existing
|
||||
// classification and native error chain.
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
use openssl::pkcs12::Pkcs12;
|
||||
|
||||
use super::request::RequestIdentityError;
|
||||
|
||||
pub(super) fn ensure_complete(bytes: &[u8], password: &str) -> anyhow::Result<()> {
|
||||
// Parse errors belong to the existing native TLS importer. A successful parse
|
||||
// lets us report incomplete archives without suggesting a password change.
|
||||
if let Ok(archive) = Pkcs12::from_der(bytes).and_then(|archive| archive.parse2(password))
|
||||
&& (archive.pkey.is_none() || archive.cert.is_none())
|
||||
{
|
||||
return Err(RequestIdentityError::IncompletePkcs12.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use anyhow::{Context, ensure};
|
||||
use reqwest::Identity;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{identity_encoding, pkcs12_identity};
|
||||
use super::{certificate::pkcs12, identity_encoding};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RequestIdentityError {
|
||||
@@ -18,10 +18,6 @@ pub enum RequestIdentityError {
|
||||
"Unsupported private key encryption. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
UnsupportedEncryption,
|
||||
#[error(
|
||||
"Could not convert the legacy private key with OpenSSL: {0}. Convert the key to modern PKCS#8 using PBES2 with AES before importing it"
|
||||
)]
|
||||
LegacyKeyConversion(&'static str),
|
||||
#[error("Unsupported private key format. Convert the key to PKCS#8 before importing it")]
|
||||
UnsupportedKeyFormat,
|
||||
#[error("Invalid private key")]
|
||||
@@ -31,7 +27,9 @@ pub enum RequestIdentityError {
|
||||
#[error("The PKCS#12 file must contain both a client certificate and its private key")]
|
||||
IncompletePkcs12,
|
||||
#[error("Could not open the PKCS#12 certificate. Check the password and certificate file")]
|
||||
InvalidPkcs12(#[source] reqwest::Error),
|
||||
InvalidPkcs12(#[source] p12_keystore::error::Error),
|
||||
#[error("The PKCS#12 file must contain one matching client identity")]
|
||||
AmbiguousPkcs12,
|
||||
}
|
||||
|
||||
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
|
||||
@@ -91,16 +89,7 @@ impl ClientIdentity {
|
||||
let (identity, passphrase) = match &key {
|
||||
Some(key) => (pem_request_identity(&certificate, key)?, None),
|
||||
None => {
|
||||
pkcs12_identity::ensure_complete(&certificate, passphrase.unwrap_or_default())?;
|
||||
// A blank settings field is stored as None. Try the empty password so
|
||||
// passwordless archives work, but keep prompting for protected ones.
|
||||
let identity = Identity::from_pkcs12_der(&certificate, passphrase.unwrap_or_default()).map_err(|error| {
|
||||
if passphrase.is_none() {
|
||||
RequestIdentityError::NoPassphrase("PKCS#12")
|
||||
} else {
|
||||
RequestIdentityError::InvalidPkcs12(error)
|
||||
}
|
||||
})?;
|
||||
let identity = pkcs12::identity(&certificate, passphrase)?;
|
||||
(
|
||||
identity,
|
||||
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
|
||||
@@ -160,13 +149,22 @@ impl ClientIdentityFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
pub(super) fn pem_request_identity(certificate: &[u8], key: &[u8]) -> anyhow::Result<Identity> {
|
||||
let error_context =
|
||||
"Client certificate and private key cannot be used together. Check that the private key matches the certificate";
|
||||
let identity = Identity::from_pkcs8_pem(certificate, key).context(error_context)?;
|
||||
// Native TLS may defer the certificate/key match check until connector creation.
|
||||
// Build the same client used for requests without making a network connection.
|
||||
reqwest::Client::builder()
|
||||
let mut combined = Zeroizing::new(certificate.to_vec());
|
||||
combined.push(b'\n');
|
||||
combined.extend_from_slice(key);
|
||||
let identity = Identity::from_pem(&combined).context(error_context)?;
|
||||
let certificates = rustls_pemfile::certs(&mut std::io::Cursor::new(certificate))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context(error_context)?;
|
||||
let private_key = rustls_pemfile::private_key(&mut std::io::Cursor::new(key))
|
||||
.context(error_context)?
|
||||
.context(error_context)?;
|
||||
rustls::sign::CertifiedKey::from_der(certificates, private_key, &rustls::crypto::ring::default_provider())
|
||||
.context(error_context)?;
|
||||
client_builder()
|
||||
.no_proxy()
|
||||
.identity(identity.clone())
|
||||
.build()
|
||||
@@ -202,6 +200,14 @@ fn write_identity_file(
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Ordinary Reqwest construction with the shared rustls provider initialized.
|
||||
pub fn client_builder() -> reqwest::ClientBuilder {
|
||||
if rustls::crypto::CryptoProvider::get_default().is_none() {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
}
|
||||
reqwest::Client::builder().tls_backend_rustls()
|
||||
}
|
||||
|
||||
/// General request clients may load an identity directly. Session owners call
|
||||
/// ClientIdentity::load once and retain that snapshot across their lifecycle.
|
||||
pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Identity> {
|
||||
@@ -241,7 +247,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_identity_preserves_password_errors_and_builds_a_native_request_client() {
|
||||
fn create_identity_preserves_password_errors_and_builds_a_request_client() {
|
||||
let mut source = tempfile::NamedTempFile::new().unwrap();
|
||||
source.write_all(CERTIFICATE).unwrap();
|
||||
source.write_all(ENCRYPTED_KEY).unwrap();
|
||||
@@ -255,7 +261,7 @@ mod tests {
|
||||
}
|
||||
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
|
||||
drop(source);
|
||||
reqwest::Client::builder().identity(identity).build().unwrap();
|
||||
client_builder().identity(identity).build().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -277,10 +283,7 @@ mod tests {
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
drop(files);
|
||||
assert!(!Path::new(&path).exists());
|
||||
reqwest::Client::builder()
|
||||
.identity(identity.request_identity())
|
||||
.build()
|
||||
.unwrap();
|
||||
client_builder().identity(identity.request_identity()).build().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
use pkcs8::SecretDocument;
|
||||
|
||||
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(super) fn normalize(
|
||||
_bytes: &[u8],
|
||||
format: TraditionalKeyFormat,
|
||||
_passphrase: Option<&str>,
|
||||
) -> anyhow::Result<SecretDocument> {
|
||||
Err(
|
||||
match format {
|
||||
TraditionalKeyFormat::EncryptedPem => RequestIdentityError::UnsupportedEncryption,
|
||||
TraditionalKeyFormat::PlainPem | TraditionalKeyFormat::Sec1Der => RequestIdentityError::UnsupportedKeyFormat,
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
use openssl::{
|
||||
error::ErrorStack,
|
||||
pkey::{Id, PKey},
|
||||
};
|
||||
use pkcs8::SecretDocument;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{identity_encoding::TraditionalKeyFormat, request::RequestIdentityError};
|
||||
|
||||
pub(super) fn normalize(
|
||||
bytes: &[u8],
|
||||
format: TraditionalKeyFormat,
|
||||
passphrase: Option<&str>,
|
||||
) -> anyhow::Result<SecretDocument> {
|
||||
let key = match format {
|
||||
TraditionalKeyFormat::Sec1Der => PKey::private_key_from_der(bytes),
|
||||
TraditionalKeyFormat::PlainPem => PKey::private_key_from_pem_passphrase(bytes, b""),
|
||||
TraditionalKeyFormat::EncryptedPem => {
|
||||
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
|
||||
anyhow::ensure!(
|
||||
!passphrase.as_bytes().contains(&0),
|
||||
"Private key passphrases containing NUL are not supported"
|
||||
);
|
||||
PKey::private_key_from_pem_passphrase(bytes, passphrase.as_bytes())
|
||||
}
|
||||
}
|
||||
.map_err(import_error)?;
|
||||
if !matches!(key.id(), Id::RSA | Id::EC) {
|
||||
return Err(RequestIdentityError::UnsupportedKeyFormat.into());
|
||||
}
|
||||
let der = Zeroizing::new(
|
||||
key
|
||||
.private_key_to_pkcs8()
|
||||
.map_err(|_| RequestIdentityError::InvalidKey)?,
|
||||
);
|
||||
Ok(SecretDocument::try_from(der.as_slice()).map_err(|_| RequestIdentityError::InvalidKey)?)
|
||||
}
|
||||
|
||||
fn import_error(error: ErrorStack) -> RequestIdentityError {
|
||||
// Inspect only known backend reasons. Never expose the native error stack or
|
||||
// turn an unclassified decoder failure into a password retry loop.
|
||||
if error.errors().iter().any(|error| error.reason() == Some("bad decrypt")) {
|
||||
RequestIdentityError::DecryptError("PEM")
|
||||
} else if error.errors().iter().any(|error| error.reason() == Some("unsupported")) {
|
||||
RequestIdentityError::UnsupportedEncryption
|
||||
} else {
|
||||
RequestIdentityError::InvalidKey
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user