feat: prepare 3.1.0 with connection details and improved authentication

Add tunnel statistics and an optional CLI dashboard, native sign-in controls and recovery, and broader client certificate support. Include platform integration fixes and the approved release notes.
This commit is contained in:
Kevin Yue committed 2026-10-19 23:47:11 +08:00
1 parent 18ed6bac1a
commit 4faa2ecb0d
158 files changed
+13752 -1038

No files matched your search

+76 -3
View File
@@ -1,10 +1,43 @@
use std::path::Path;
use std::{
fmt::Write as _,
fs::File,
io::{self, Read},
path::Path,
};
use anyhow::bail;
use sha2::{Digest, Sha256};
pub fn sha256_hex(data: impl AsRef<[u8]>) -> String {
digest_hex(&Sha256::digest(data.as_ref()))
}
pub fn file_sha256(path: impl AsRef<Path>) -> io::Result<String> {
let mut file = File::open(path)?;
let mut hasher = Sha256::new();
let mut buffer = [0; 8192];
loop {
let count = match file.read(&mut buffer) {
Ok(0) => break,
Ok(count) => count,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
hasher.update(&buffer[..count]);
}
Ok(digest_hex(&hasher.finalize()))
}
fn digest_hex(digest: &[u8]) -> String {
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
write!(&mut hex, "{byte:02x}").expect("writing to a String cannot fail");
}
hex
}
pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
let file = Path::new(&path);
let checksum = sha256::try_digest(&file)?;
let checksum = file_sha256(path)?;
if checksum != expected {
bail!("Checksum mismatch, expected: {}, actual: {}", expected, checksum);
@@ -12,3 +45,43 @@ pub fn verify_checksum(path: &str, expected: &str) -> anyhow::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::Write;
use super::*;
#[test]
fn known_sha256_vectors_use_lowercase_hex() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn hashes_files_across_buffer_boundaries_and_checks_expected_digest() {
let mut file = tempfile::NamedTempFile::new().unwrap();
file.write_all(&vec![b'a'; 1_000_000]).unwrap();
let expected = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
assert_eq!(file_sha256(file.path()).unwrap(), expected);
verify_checksum(file.path().to_str().unwrap(), expected).unwrap();
assert!(verify_checksum(file.path().to_str().unwrap(), "wrong").is_err());
}
#[test]
fn hashes_empty_files_and_propagates_file_errors() {
let file = tempfile::NamedTempFile::new().unwrap();
assert_eq!(file_sha256(file.path()).unwrap(), sha256_hex(b""));
let directory = tempfile::tempdir().unwrap();
let error = file_sha256(directory.path().join("missing")).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
assert!(file_sha256(directory.path()).is_err());
}
}
+219
View File
@@ -0,0 +1,219 @@
//! PEM/DER normalization; usable key and certificate imports stay with native TLS.
use pkcs8::{
AlgorithmIdentifierRef, EncryptedPrivateKeyInfoRef, ObjectIdentifier, PrivateKeyInfoRef, SecretDocument,
der::{
Decode, Reader, SliceReader, Tag, Tagged,
asn1::{AnyRef, OctetStringRef, SequenceRef},
},
};
use zeroize::Zeroizing;
use super::{request::RequestIdentityError, traditional_key};
pub(super) enum TraditionalKeyFormat {
Sec1Der,
PlainPem,
EncryptedPem,
}
struct PemBlock {
tag: String,
headers: pem::HeaderMap,
contents: Zeroizing<Vec<u8>>,
}
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());
// The PEM crate owns a copy of the decoded private key as well.
drop(Zeroizing::new(block.into_contents()));
encoded
}
}
fn is_pem(bytes: &[u8]) -> bool {
bytes.windows(b"-----BEGIN".len()).any(|part| part == b"-----BEGIN")
}
// Adopt decoded blocks immediately, including ignored keys in combined files.
fn blocks(bytes: &[u8]) -> Result<Vec<PemBlock>, pem::PemError> {
Ok(
pem::parse_many(bytes)?
.into_iter()
.map(|block| PemBlock {
tag: block.tag().to_owned(),
headers: block.headers().clone(),
contents: Zeroizing::new(block.into_contents()),
})
.collect(),
)
}
pub(super) fn private_key(bytes: &[u8], passphrase: Option<&str>) -> anyhow::Result<Zeroizing<Vec<u8>>> {
let pem_input = is_pem(bytes);
let block = if pem_input {
blocks(bytes)
.map_err(|_| RequestIdentityError::InvalidKey)?
.into_iter()
.find(|block| block.tag.ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?
} else {
// Unlike combined PEM, a standalone DER certificate cannot include a key.
if x509_cert::Certificate::from_der(bytes).is_ok() {
return Err(RequestIdentityError::NoKey.into());
}
PemBlock {
tag: der_key_tag(bytes)
.map_err(|_| RequestIdentityError::InvalidKey)?
.to_owned(),
headers: pem::HeaderMap::default(),
contents: Zeroizing::new(bytes.to_vec()),
}
};
let der = &block.contents;
let document = if traditional_encryption(&block)? {
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)?
} 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.
let algorithm = AlgorithmIdentifierRef {
oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"),
parameters: Some(AnyRef::NULL),
};
let private_key = OctetStringRef::new(der).map_err(|_| RequestIdentityError::InvalidKey)?;
let info = PrivateKeyInfoRef::new(algorithm, private_key);
SecretDocument::encode_msg(&info).map_err(|_| RequestIdentityError::InvalidKey)?
}
"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)?
}
}
_ => return Err(RequestIdentityError::UnsupportedKeyFormat.into()),
}
};
PrivateKeyInfoRef::from_der(document.as_bytes()).map_err(|_| RequestIdentityError::InvalidKey)?;
let pem = document.to_pem("PRIVATE KEY", pkcs8::LineEnding::LF)?;
Ok(Zeroizing::new(pem.as_bytes().to_vec()))
}
// Only choose a container here. The selected decoder/native importer validates
// the key. Decoding the complete outer sequence rejects concatenated DER input.
fn der_key_tag(bytes: &[u8]) -> Result<&'static str, pkcs8::der::Error> {
let sequence = <&SequenceRef>::from_der(bytes)?;
let mut reader = SliceReader::new(sequence.as_bytes())?;
let first: AnyRef = reader.decode()?;
Ok(match (first.tag(), Tag::peek(&reader)?) {
(Tag::Integer, Tag::Sequence) => "PRIVATE KEY",
(Tag::Integer, Tag::Integer) => "RSA PRIVATE KEY",
(Tag::Integer, Tag::OctetString) => "EC PRIVATE KEY",
(Tag::Sequence, Tag::OctetString) => "ENCRYPTED PRIVATE KEY",
_ => return Err(pkcs8::der::ErrorKind::Failed.into()),
})
}
fn traditional_encryption(block: &PemBlock) -> Result<bool, RequestIdentityError> {
let mut proc_type = None;
let mut dek_info = None;
for (name, value) in block.headers.iter() {
let slot = match name {
"Proc-Type" => &mut proc_type,
"DEK-Info" => &mut dek_info,
_ => continue,
};
if slot.replace(value).is_some() {
return Err(RequestIdentityError::InvalidKey);
}
}
if proc_type.is_none() && dek_info.is_none() {
return Ok(false);
}
let (Some("4,ENCRYPTED"), Some(dek_info)) = (proc_type, dek_info) else {
return Err(RequestIdentityError::InvalidKey);
};
let (cipher, iv) = dek_info.split_once(',').ok_or(RequestIdentityError::InvalidKey)?;
let block_size = match cipher {
"AES-128-CBC" | "AES-192-CBC" | "AES-256-CBC" => 16,
"DES-EDE3-CBC" => 8,
_ => return Err(RequestIdentityError::UnsupportedEncryption),
};
if iv.len() != block_size * 2
|| !iv.bytes().all(|byte| byte.is_ascii_hexdigit())
|| block.contents.is_empty()
|| block.contents.len() % block_size != 0
{
return Err(RequestIdentityError::InvalidKey);
}
Ok(true)
}
fn decrypt(der: &[u8], passphrase: Option<&str>) -> anyhow::Result<SecretDocument> {
// pkcs5 collapses unknown outer PBE OIDs into a generic DER value error.
// Inspect the typed envelope first so legacy PBE is not called malformed.
let algorithm = pkcs8::der::asn1::AnyRef::from_der(der)
.and_then(|value| {
value.sequence(|reader| {
let algorithm = pkcs8::AlgorithmIdentifierRef::decode(reader)?;
let _: &pkcs8::der::asn1::OctetStringRef = reader.decode()?;
Ok(algorithm.oid)
})
})
.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.
if algorithm == pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3") {
return super::legacy_pkcs8::decrypt(der, passphrase);
}
return Err(RequestIdentityError::UnsupportedEncryption.into());
}
// Decode the full encryption scheme, including its KDF/PRF/cipher, before
// asking for a password. Unsupported algorithms must not cause prompt loops.
let encrypted = EncryptedPrivateKeyInfoRef::from_der(der).map_err(|error| match error.kind() {
pkcs8::der::ErrorKind::OidUnknown { .. } => RequestIdentityError::UnsupportedEncryption,
_ => RequestIdentityError::InvalidKey,
})?;
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let mut plaintext = Zeroizing::new(encrypted.encrypted_data.as_bytes().to_vec());
let decrypted = encrypted
.encryption_algorithm
.decrypt_in_place(passphrase, &mut plaintext)
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
SecretDocument::try_from(decrypted).map_err(|_| RequestIdentityError::DecryptError("PEM").into())
}
pub(super) fn certificate_chain(bytes: &[u8]) -> anyhow::Result<Zeroizing<Vec<u8>>> {
if !is_pem(bytes) {
return certificate_pem(bytes).map(|pem| Zeroizing::new(pem.into_bytes()));
}
let mut chain = Zeroizing::new(Vec::new());
for block in blocks(bytes).map_err(|_| RequestIdentityError::InvalidCertificate)? {
if block.tag == "CERTIFICATE" {
let encoded = certificate_pem(&block.contents)?;
chain.extend_from_slice(encoded.as_bytes());
}
}
if chain.is_empty() {
return Err(RequestIdentityError::InvalidCertificate.into());
}
Ok(chain)
}
fn certificate_pem(der: &[u8]) -> anyhow::Result<String> {
x509_cert::Certificate::from_der(der).map_err(|_| RequestIdentityError::InvalidCertificate)?;
Ok(pem::encode_config(
&pem::Pem::new("CERTIFICATE", der),
pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF),
))
}
+165
View File
@@ -0,0 +1,165 @@
//! 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())
}
+31 -9
View File
@@ -5,10 +5,25 @@ pub mod checksum;
pub mod crypto;
pub mod endpoint;
pub mod env_utils;
mod identity_encoding;
mod legacy_pkcs8;
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;
@@ -51,6 +66,8 @@ pub struct GpError {
pub status: StatusCode,
pub reason: String,
body: String,
#[source]
source: Option<reqwest::Error>,
}
impl GpError {
@@ -63,9 +80,7 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
let status = res.status();
if status.is_client_error() || status.is_server_error() {
let (reason, body) = parse_gp_error(res).await;
return Err(GpError { status, reason, body });
return Err(parse_gp_error(res).await);
}
res.text().await.map_err(|err| {
@@ -75,21 +90,28 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
status,
reason: "failed to read response".to_string(),
body: "<failed to read response>".to_string(),
source: Some(err),
}
})
}
async fn parse_gp_error(res: Response) -> (String, String) {
async fn parse_gp_error(res: Response) -> GpError {
let status = res.status();
let reason = res
.headers()
.get("x-private-pan-globalprotect")
.map_or_else(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
.to_string();
let res = res.text().await.map_or_else(
|_| "<failed to read response>".to_string(),
|v| if v.is_empty() { "<empty>".to_string() } else { v },
);
let (body, source) = match res.text().await {
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
Err(error) => ("<failed to read response>".to_string(), Some(error)),
};
(reason, res)
GpError {
status,
reason,
body,
source,
}
}
@@ -0,0 +1,24 @@
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(())
}
@@ -0,0 +1,14 @@
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(())
}
+57 -37
View File
@@ -1,11 +1,10 @@
use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex;
use url::{Url, form_urlencoded};
pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>,
patterns: RwLock<Vec<Regex>>,
}
impl Default for Redaction {
@@ -16,56 +15,45 @@ impl Default for Redaction {
impl Redaction {
pub fn new() -> Self {
let redact_engine = RedactEngine::custom("[**********]").add_pattern(Pattern {
test: Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
group: 1,
});
Self {
redact_engine: RwLock::new(Some(redact_engine)),
patterns: RwLock::new(vec![
Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(),
]),
}
}
pub fn add_value(&self, text: &str) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_value(text)?,
);
Ok(())
self.add_values(&[text])
}
pub fn add_values(&self, texts: &[&str]) -> anyhow::Result<()> {
let mut redact_engine = self
.redact_engine
let patterns = texts
.iter()
.map(|text| Regex::new(&regex::escape(text)))
.collect::<Result<Vec<_>, _>>()?;
self
.patterns
.write()
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?;
*redact_engine = Some(
redact_engine
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))?
.add_values(texts.to_vec())?,
);
.map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redaction patterns"))?
.extend(patterns);
Ok(())
}
pub fn redact_str(&self, text: &str) -> String {
self
.redact_engine
let patterns = self
.patterns
.read()
.expect("Failed to acquire read lock on redact engine")
.as_ref()
.expect("Failed to get redact engine")
.redact_str(text)
.expect("Failed to acquire read lock on redaction patterns");
let mut redacted = text.to_owned();
// Match the original text, then replace in registration order. Matching the
// replacements would change how overlapping values are redacted.
for pattern in patterns.iter() {
for matched in pattern.find_iter(text) {
redacted = redacted.replacen(matched.as_str(), "[**********]", 1);
}
}
redacted
}
}
@@ -180,6 +168,38 @@ fn redact_query(query: Option<&str>) -> Option<String> {
mod tests {
use super::*;
#[test]
fn redacts_repeated_ipv4_addresses() {
assert_eq!(
Redaction::new().redact_str("from 192.0.2.1 to 198.51.100.9, then 192.0.2.1"),
"from [**********] to [**********], then [**********]"
);
}
#[test]
fn registered_values_are_literal_and_support_unicode() {
let redaction = Redaction::new();
redaction.add_values(&["a.b+$[x]", "秘密🔑"]).unwrap();
assert_eq!(
redaction.redact_str("a.b+$[x] 秘密🔑 a.b+$[x] aXb"),
"[**********] [**********] [**********] aXb"
);
}
#[test]
fn overlapping_values_keep_registration_order() {
let redaction = Redaction::new();
redaction.add_values(&["foobar", "foo"]).unwrap();
assert_eq!(redaction.redact_str("foobar foo"), "[**********] [**********]");
}
#[test]
fn unicode_word_characters_preserve_ipv4_boundaries() {
assert_eq!(Redaction::new().redact_str("192.0.2.1é"), "192.0.2.1é");
}
#[test]
fn it_should_not_redact_value() {
let text = "fo";
+90 -295
View File
@@ -1,10 +1,11 @@
use std::{fmt, fs, io::Write, path::Path, sync::Arc};
use anyhow::{Context, ensure};
use openssl::{pkey::PKey, x509::X509};
use reqwest::Identity;
use zeroize::Zeroizing;
use super::{identity_encoding, pkcs12_identity};
#[derive(Debug, thiserror::Error)]
pub enum RequestIdentityError {
#[error("Failed to find the private key")]
@@ -13,6 +14,24 @@ pub enum RequestIdentityError {
NoPassphrase(&'static str),
#[error("Failed to decrypt private key")]
DecryptError(&'static str),
#[error(
"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")]
InvalidKey,
#[error("Invalid certificate or certificate chain")]
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")]
InvalidPkcs12(#[source] reqwest::Error),
}
/// Loaded once by the authentication owner. PEM keys are decrypted once; PKCS#12
@@ -41,37 +60,17 @@ impl fmt::Debug for ClientIdentity {
impl ClientIdentity {
pub fn load(certificate: &str, key: Option<&str>, passphrase: Option<&str>) -> anyhow::Result<Self> {
let certificate_bytes = read_identity_file(certificate)?;
if certificate.ends_with(".p12") || certificate.ends_with(".pfx") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
return Self::from_data(certificate_bytes, None, Some(passphrase));
let extension = Path::new(certificate).extension().and_then(|value| value.to_str());
if extension.is_some_and(|value| value.eq_ignore_ascii_case("p12") || value.eq_ignore_ascii_case("pfx")) {
return Self::from_data(certificate_bytes, None, passphrase);
}
let key_bytes = match key {
Some(path) => read_identity_file(path)?,
None => certificate_bytes.clone(),
};
// Keep the previous first-private-key rule: unrelated later blocks must not
// change which key is selected or whether the caller is prompted.
let key = pem::parse_many(&*key_bytes)?
.into_iter()
.find(|pem| pem.tag().ends_with("PRIVATE KEY"))
.ok_or(RequestIdentityError::NoKey)?;
let key_pem = Zeroizing::new(pem::encode(&key));
let key = if key.tag().ends_with("ENCRYPTED PRIVATE KEY") {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PEM"))?;
let key = PKey::private_key_from_pem_passphrase(key_pem.as_bytes(), passphrase.as_bytes())
.map_err(|_| RequestIdentityError::DecryptError("PEM"))?;
Zeroizing::new(key.private_key_to_pem_pkcs8()?)
} else {
Zeroizing::new(key_pem.as_bytes().to_vec())
};
// Strip private-key blocks before importing the certificate chain: macOS
// otherwise imports the same key twice for combined PEM files.
let mut certificate = Zeroizing::new(Vec::new());
for cert in X509::stack_from_pem(&certificate_bytes)? {
certificate.extend(cert.to_pem()?);
}
let identity = Identity::from_pkcs8_pem(&certificate, &key)?;
let key = Zeroizing::new(PKey::private_key_from_pem(&key)?.private_key_to_pem_pkcs8()?);
let key = identity_encoding::private_key(&key_bytes, passphrase)?;
let certificate = identity_encoding::certificate_chain(&certificate_bytes)?;
let identity = pem_request_identity(&certificate, &key)?;
Ok(Self {
material: Arc::new(IdentityMaterial {
certificate,
@@ -90,12 +89,21 @@ impl ClientIdentity {
passphrase: Option<&str>,
) -> anyhow::Result<Self> {
let (identity, passphrase) = match &key {
Some(key) => (Identity::from_pkcs8_pem(&certificate, key)?, None),
Some(key) => (pem_request_identity(&certificate, key)?, None),
None => {
let passphrase = passphrase.ok_or(RequestIdentityError::NoPassphrase("PKCS#12"))?;
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)
}
})?;
(
Identity::from_pkcs12_der(&certificate, passphrase)?,
Some(Zeroizing::new(passphrase.to_owned())),
identity,
Some(Zeroizing::new(passphrase.unwrap_or_default().to_owned())),
)
}
};
@@ -152,6 +160,20 @@ impl ClientIdentityFiles {
}
}
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()
.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")?,
@@ -189,50 +211,15 @@ pub fn create_identity(cert: &str, key: Option<&str>, passphrase: Option<&str>)
#[cfg(test)]
mod tests {
use super::*;
use openssl::pkcs12::Pkcs12;
fn generated_identity() -> (Vec<u8>, Vec<u8>) {
use openssl::{asn1::Asn1Time, hash::MessageDigest, rsa::Rsa, x509::X509NameBuilder};
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
name.append_entry_by_text("CN", "identity-fixture").unwrap();
let name = name.build();
let mut certificate = X509::builder().unwrap();
certificate.set_version(2).unwrap();
certificate.set_subject_name(&name).unwrap();
certificate.set_issuer_name(&name).unwrap();
certificate.set_pubkey(&key).unwrap();
certificate
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
.unwrap();
certificate.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
certificate.sign(&key, MessageDigest::sha256()).unwrap();
(
certificate.build().to_pem().unwrap(),
key.private_key_to_pem_pkcs8().unwrap(),
)
}
#[test]
fn pem_uses_first_private_key_without_prompting_for_later_encrypted_keys() {
let (certificate, key) = generated_identity();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"unused")
.unwrap();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(&encrypted).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.key_data().unwrap(), key);
}
const CERTIFICATE: &[u8] = include_bytes!("../../tests/files/client-identity/rsa-cert.pem");
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 pem_without_key_reports_missing_key_even_with_passphrase() {
let (certificate, _) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(CERTIFICATE).unwrap();
for passphrase in [None, Some("unused")] {
let error = ClientIdentity::load(source.path().to_str().unwrap(), None, passphrase).unwrap_err();
assert!(matches!(
@@ -244,249 +231,57 @@ mod tests {
#[test]
fn local_identity_loading_is_not_limited_by_service_message_size() {
let (certificate, key) = generated_identity();
let mut source = tempfile::NamedTempFile::new().unwrap();
source.write_all(&certificate).unwrap();
source.write_all(&key).unwrap();
source.write_all(CERTIFICATE).unwrap();
source.write_all(KEY).unwrap();
source.write_all(&vec![b'\n'; 33 * 1024]).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, None).unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert_eq!(identity.certificate_data(), CERTIFICATE);
assert_eq!(identity.key_data().unwrap(), KEY);
}
#[test]
fn pem_passphrases_preserve_prompt_errors_and_accept_separate_keys() {
let (certificate, key) = generated_identity();
let mut cert_file = tempfile::NamedTempFile::new().unwrap();
cert_file.write_all(&certificate).unwrap();
let mut key_file = tempfile::NamedTempFile::new().unwrap();
let encrypted = PKey::private_key_from_pem(&key)
.unwrap()
.private_key_to_pem_pkcs8_passphrase(openssl::symm::Cipher::aes_256_cbc(), b"correct")
.unwrap();
key_file.write_all(&encrypted).unwrap();
let cert = cert_file.path().to_str().unwrap();
let key_path = Some(key_file.path().to_str().unwrap());
for (passphrase, missing) in [(None, true), (Some("wrong"), false)] {
let error = ClientIdentity::load(cert, key_path, passphrase).unwrap_err();
match error.downcast_ref::<RequestIdentityError>().unwrap() {
RequestIdentityError::NoPassphrase("PEM") => assert!(missing),
RequestIdentityError::DecryptError("PEM") => assert!(!missing),
other => panic!("Unexpected identity error: {other}"),
fn create_identity_preserves_password_errors_and_builds_a_native_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();
match error.downcast_ref::<RequestIdentityError>() {
Some(RequestIdentityError::NoPassphrase("PEM")) => assert!(missing),
Some(RequestIdentityError::DecryptError("PEM")) => assert!(!missing),
other => panic!("Unexpected identity error: {other:?}"),
}
}
let loaded = ClientIdentity::load(cert, key_path, Some("correct")).unwrap();
assert_eq!(loaded.key_data().unwrap(), key);
fs::write(key_file.path(), &key).unwrap();
for passphrase in [None, Some("ignored for unencrypted key")] {
assert_eq!(
ClientIdentity::load(cert, key_path, passphrase)
.unwrap()
.key_data()
.unwrap(),
key
);
}
let identity = create_identity(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
drop(source);
reqwest::Client::builder().identity(identity).build().unwrap();
}
#[test]
fn loaded_identity_survives_original_file_replacement_and_owns_private_files() {
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
use std::os::unix::fs::PermissionsExt;
let (certificate, key) = generated_identity();
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("combined.pem");
let mut combined = certificate.clone();
combined.extend(&key);
fs::write(&source, &combined).unwrap();
let identity = ClientIdentity::load(source.to_str().unwrap(), None, None).unwrap();
fs::write(&source, "changed after authentication").unwrap();
assert_eq!(identity.certificate_data(), certificate);
assert_eq!(identity.key_data().unwrap(), key);
assert!(!format!("{identity:?}").contains("PRIVATE KEY"));
let files = identity.write_files(Some(directory.path())).unwrap();
let certificate_path = files.certificate().to_owned();
let key_path = files.key().unwrap().to_owned();
assert_eq!(fs::read(&certificate_path).unwrap(), certificate);
assert_eq!(fs::read(&key_path).unwrap(), key);
assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600);
let identity = ClientIdentity::from_data(
Zeroizing::new(CERTIFICATE.to_vec()),
Some(Zeroizing::new(KEY.to_vec())),
Some("unused password"),
)
.unwrap();
assert!(identity.key_password().is_none());
let archive = include_bytes!("../../tests/files/client-identity/modern.p12").to_vec();
let identity = ClientIdentity::from_data(Zeroizing::new(archive), None, Some("fixture-password")).unwrap();
let files = identity.write_files(None).unwrap();
let path = files.certificate().to_owned();
assert!(path.ends_with(".p12"));
assert!(files.key().is_none());
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&certificate_path).exists());
assert!(!Path::new(&key_path).exists());
// The request identity remains valid after its original files disappear.
fs::remove_file(&source).unwrap();
assert!(!Path::new(&path).exists());
reqwest::Client::builder()
.identity(identity.request_identity())
.build()
.unwrap();
}
#[test]
fn pkcs12_preserves_original_data_password_and_owned_native_files() {
let (certificate, key) = generated_identity();
let certificate = X509::from_pem(&certificate).unwrap();
let key = PKey::private_key_from_pem(&key).unwrap();
let mut builder = Pkcs12::builder();
builder.name("identity-fixture").pkey(&key).cert(&certificate);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
for suffix in [".p12", ".pfx"] {
let mut source = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
source.write_all(&encoded).unwrap();
let path = source.path().to_str().unwrap();
assert!(ClientIdentity::load(path, None, None).is_err());
assert!(ClientIdentity::load(path, None, Some("wrong")).is_err());
// PKCS#12 has always ignored a separately configured key path.
let identity = ClientIdentity::load(path, Some("missing-key-file"), Some("fixture-password")).unwrap();
fs::write(source.path(), b"replaced after login").unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
assert_eq!(identity.key_password(), Some("fixture-password"));
assert!(!format!("{identity:?}").contains("fixture-password"));
let files = identity.write_files(None).unwrap();
assert!(files.certificate().ends_with(".p12"));
assert!(files.key().is_none());
ClientIdentity::load(files.certificate(), files.key(), identity.key_password()).unwrap();
let owned_path = files.certificate().to_owned();
drop(files);
assert!(!Path::new(&owned_path).exists());
}
let empty_password = builder.build2("").unwrap().to_der().unwrap();
// Empty-password support varies by native backend and PKCS#12 algorithms.
// Match the previous native import instead of introducing another parser.
let previously_accepted = Identity::from_pkcs12_der(&empty_password, "").is_ok();
assert_eq!(
ClientIdentity::from_data(Zeroizing::new(empty_password), None, Some("")).is_ok(),
previously_accepted
);
}
#[test]
fn pkcs12_retains_chain_without_reordering_or_reencoding() {
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
rsa::Rsa,
stack::Stack,
x509::{X509NameBuilder, extension::BasicConstraints},
};
fn certificate(
name: &str,
parent: Option<(&X509, &PKey<openssl::pkey::Private>)>,
ca: bool,
) -> (X509, PKey<openssl::pkey::Private>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut subject = X509NameBuilder::new().unwrap();
subject.append_entry_by_text("CN", name).unwrap();
let subject = subject.build();
let mut cert = X509::builder().unwrap();
cert.set_version(2).unwrap();
let serial = openssl::bn::BigNum::from_u32(name.len() as u32)
.unwrap()
.to_asn1_integer()
.unwrap();
cert.set_serial_number(&serial).unwrap();
cert.set_subject_name(&subject).unwrap();
cert
.set_issuer_name(parent.map(|(cert, _)| cert.subject_name()).unwrap_or(&subject))
.unwrap();
cert.set_pubkey(&key).unwrap();
cert.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap();
cert.set_not_after(&Asn1Time::days_from_now(1).unwrap()).unwrap();
if ca {
cert
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
.unwrap();
}
cert
.sign(parent.map(|(_, key)| key).unwrap_or(&key), MessageDigest::sha256())
.unwrap();
(cert.build(), key)
}
let (root, root_key) = certificate("root", None, true);
let (intermediate, intermediate_key) = certificate("intermediate", Some((&root, &root_key)), true);
let (leaf, key) = certificate("client", Some((&intermediate, &intermediate_key)), false);
// This is the reverse CA stack consumed by the previous native-tls path.
let mut ca = Stack::new().unwrap();
ca.push(root.clone()).unwrap();
ca.push(intermediate.clone()).unwrap();
let mut builder = Pkcs12::builder();
builder.name("chain-fixture").pkey(&key).cert(&leaf).ca(ca);
let encoded = builder.build2("fixture-password").unwrap().to_der().unwrap();
let mut source = tempfile::Builder::new().suffix(".p12").tempfile().unwrap();
source.write_all(&encoded).unwrap();
let identity = ClientIdentity::load(source.path().to_str().unwrap(), None, Some("fixture-password")).unwrap();
assert_eq!(identity.certificate_data(), encoded);
assert!(identity.key_data().is_none());
ClientIdentity::from_data(
Zeroizing::new(identity.certificate_data().to_vec()),
None,
identity.key_password(),
)
.unwrap();
}
#[test]
fn create_identity_from_pem_requires_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let identity = create_identity(cert, None, None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_with_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity(cert, None, Some(passphrase));
assert!(identity.is_ok());
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_unencrypted_key() {
let cert = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity(cert, None, None);
println!("{:?}", identity);
assert!(identity.is_ok());
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_cert_and_encrypted_key() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let passphrase = "badssl.com";
let identity = create_identity(cert, Some(key), Some(passphrase));
assert!(identity.is_ok());
}
#[test]
fn create_identity_from_pem_cert_and_encrypted_key_no_passphrase() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client.pem";
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_err());
assert!(identity.unwrap_err().to_string().contains("No passphrase provided"));
}
#[test]
#[cfg(not(target_os = "macos"))]
fn create_identity_from_pem_cert_and_unencrypted_key() {
let cert = "tests/files/badssl.com-client.pem";
let key = "tests/files/badssl.com-client-unencrypted.pem";
let identity = create_identity(cert, Some(key), None);
assert!(identity.is_ok());
}
}
#[derive(Debug, thiserror::Error)]
@@ -0,0 +1,17 @@
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(),
)
}
@@ -0,0 +1,49 @@
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
}
}