use std::io::BufReader;
use std::sync::Arc;
use ostrya_rt as rt;
use rustls::ClientConfig;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
use crate::error::{Error, Result};
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum TrustRoots {
#[default]
System,
Pem(Vec<u8>),
DangerousAcceptAnyChain,
DangerousAcceptAny,
}
#[derive(Clone, Eq, PartialEq)]
pub struct ClientIdentity {
pub cert_chain_pem: Vec<u8>,
pub key_pem: Vec<u8>,
pub key_passphrase: Option<String>,
}
impl std::fmt::Debug for ClientIdentity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientIdentity")
.field("cert_chain_pem", &self.cert_chain_pem)
.field(
"key_pem",
&format!("<{} bytes redacted>", self.key_pem.len()),
)
.field(
"key_passphrase",
&self.key_passphrase.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TlsOptions {
pub roots: TrustRoots,
pub client_identity: Option<ClientIdentity>,
}
#[derive(Debug)]
pub(crate) struct ClientConfigs {
pub(crate) with_identity: Arc<ClientConfig>,
pub(crate) without_identity: Arc<ClientConfig>,
pub(crate) has_trust_anchors: bool,
}
pub(crate) async fn client_config(
options: &TlsOptions,
http2: bool,
https: bool,
) -> Result<ClientConfigs> {
let provider = Arc::new(rustls_graviola::default_provider());
let verification = verification(&options.roots, https, &provider).await?;
let has_trust_anchors = match &verification {
Verification::Anchors(store) => !store.is_empty(),
Verification::Bypass(_) => true,
};
let alpn = if http2 {
vec![b"h2".to_vec(), b"http/1.1".to_vec()]
} else {
vec![b"http/1.1".to_vec()]
};
let mut plain = shared(&provider, &verification)?.with_no_client_auth();
plain.alpn_protocols = alpn.clone();
let without_identity = Arc::new(plain);
let with_identity = match &options.client_identity {
Some(identity) => {
let chain = parse_certs(&identity.cert_chain_pem)?;
if chain.is_empty() {
return Err(Error::Fetch(
"client certificate holds no certificate".into(),
));
}
let key = parse_key(&identity.key_pem, identity.key_passphrase.as_deref()).await?;
let mut config = shared(&provider, &verification)?
.with_client_auth_cert(chain, key)
.map_err(|e| Error::Fetch(format!("client certificate rejected: {e}")))?;
config.alpn_protocols = alpn;
Arc::new(config)
}
None => without_identity.clone(),
};
Ok(ClientConfigs {
with_identity,
without_identity,
has_trust_anchors,
})
}
fn shared(
provider: &Arc<rustls::crypto::CryptoProvider>,
verification: &Verification,
) -> Result<rustls::ConfigBuilder<ClientConfig, rustls::client::WantsClientCert>> {
let builder = ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.map_err(|e| Error::Fetch(format!("tls setup: {e}")))?;
Ok(match verification {
Verification::Anchors(store) => builder.with_root_certificates(store.clone()),
Verification::Bypass(verifier) => builder
.dangerous()
.with_custom_certificate_verifier(verifier.clone()),
})
}
enum Verification {
Anchors(Arc<rustls::RootCertStore>),
Bypass(Arc<dyn ServerCertVerifier>),
}
async fn verification(
roots: &TrustRoots,
https: bool,
provider: &Arc<rustls::crypto::CryptoProvider>,
) -> Result<Verification> {
Ok(match roots {
TrustRoots::System => Verification::Anchors(Arc::new(system_store(https).await?)),
TrustRoots::Pem(pem) => Verification::Anchors(Arc::new(pem_store(pem)?)),
TrustRoots::DangerousAcceptAnyChain => Verification::Bypass(Arc::new(AcceptAnyChain {
provider: provider.clone(),
check_name: true,
})),
TrustRoots::DangerousAcceptAny => Verification::Bypass(Arc::new(AcceptAnyChain {
provider: provider.clone(),
check_name: false,
})),
})
}
#[derive(Debug)]
struct AcceptAnyChain {
provider: Arc<rustls::crypto::CryptoProvider>,
check_name: bool,
}
impl ServerCertVerifier for AcceptAnyChain {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
if self.check_name {
let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
rustls::client::verify_server_name(&cert, server_name)?;
}
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
}
async fn system_store(https: bool) -> Result<rustls::RootCertStore> {
let mut store = rustls::RootCertStore::empty();
let (certs, detail) = rt::unblock(|| {
let loaded = rustls_native_certs::load_native_certs();
let detail = loaded.errors.first().map(|e| e.to_string());
(loaded.certs, detail)
})
.await;
for cert in certs {
let _ = store.add(cert);
}
if store.is_empty() && https {
let detail = detail.unwrap_or_else(|| "the system trust store is empty".to_string());
return Err(Error::Fetch(format!("no trusted certificates: {detail}")));
}
Ok(store)
}
fn pem_store(pem: &[u8]) -> Result<rustls::RootCertStore> {
let mut store = rustls::RootCertStore::empty();
for cert in parse_certs(pem)? {
store
.add(cert)
.map_err(|e| Error::Fetch(format!("trust anchor rejected: {e}")))?;
}
if store.is_empty() {
return Err(Error::Fetch("trust anchors hold no certificate".into()));
}
Ok(store)
}
fn parse_certs(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
rustls_pemfile::certs(&mut BufReader::new(pem))
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|e| Error::Fetch(format!("certificate pem: {e}")))
}
const ENCRYPTED_KEY_LABEL: &[u8] = b"ENCRYPTED PRIVATE KEY";
const PLAIN_KEY_LABELS: [&[u8]; 3] = [b"PRIVATE KEY", b"RSA PRIVATE KEY", b"EC PRIVATE KEY"];
const LEGACY_ENCRYPTED_HEADER: &[u8] = b"Proc-Type:";
const LEGACY_ENCRYPTED_VALUE: &[u8] = b"4,ENCRYPTED";
enum KeySection<'a> {
Encrypted(&'a [u8]),
Plain(&'a [u8]),
}
async fn parse_key(pem: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
match first_key_section(pem) {
Some(KeySection::Encrypted(section)) => decrypt_key(section, passphrase).await,
Some(KeySection::Plain(section)) => {
if is_legacy_encrypted(section) {
return Err(Error::Fetch(
"private key pem is in the legacy openssl encrypted format. \
convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
.into(),
));
}
if passphrase.is_some() {
return Err(Error::Fetch(
"a passphrase is set for a private key pem that carries no encryption".into(),
));
}
read_plain_key(pem)
}
None => read_plain_key(pem),
}
}
fn read_plain_key(pem: &[u8]) -> Result<PrivateKeyDer<'static>> {
rustls_pemfile::private_key(&mut BufReader::new(pem))
.map_err(|e| Error::Fetch(format!("private key pem: {e}")))?
.ok_or_else(|| Error::Fetch("private key pem holds no key".into()))
}
fn first_key_section(pem: &[u8]) -> Option<KeySection<'_>> {
for (start, end) in line_ranges(pem, 0) {
let Some(label) = armor_label(pem[start..end].trim_ascii(), b"BEGIN") else {
continue;
};
if label == ENCRYPTED_KEY_LABEL {
return Some(KeySection::Encrypted(section_at(pem, start, label)));
}
if PLAIN_KEY_LABELS.contains(&label) {
return Some(KeySection::Plain(section_at(pem, start, label)));
}
}
None
}
fn section_at<'a>(pem: &'a [u8], begin: usize, label: &[u8]) -> &'a [u8] {
for (start, end) in line_ranges(pem, begin) {
if armor_label(pem[start..end].trim_ascii(), b"END") == Some(label) {
return &pem[begin..end];
}
}
&pem[begin..]
}
fn armor_label<'a>(line: &'a [u8], keyword: &[u8]) -> Option<&'a [u8]> {
line.strip_prefix(b"-----".as_slice())?
.strip_prefix(keyword)?
.strip_prefix(b" ".as_slice())?
.strip_suffix(b"-----".as_slice())
}
fn is_legacy_encrypted(section: &[u8]) -> bool {
line_ranges(section, 0).any(|(start, end)| {
section[start..end]
.trim_ascii()
.strip_prefix(LEGACY_ENCRYPTED_HEADER)
.is_some_and(|value| value.trim_ascii_start() == LEGACY_ENCRYPTED_VALUE)
})
}
fn line_ranges(pem: &[u8], from: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
let mut offset = from;
std::iter::from_fn(move || {
let start = offset;
if start >= pem.len() {
return None;
}
offset = pem[start..]
.iter()
.position(|byte| *byte == b'\n')
.map_or(pem.len(), |index| start + index + 1);
Some((start, offset))
})
}
async fn decrypt_key(section: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
let Some(passphrase) = passphrase else {
return Err(Error::Fetch(
"private key pem is encrypted, and no passphrase is set".into(),
));
};
let section = section.to_vec();
let passphrase = passphrase.to_string();
rt::unblock(move || decrypt_pkcs8(§ion, &passphrase)).await
}
fn decrypt_pkcs8(section: &[u8], passphrase: &str) -> Result<PrivateKeyDer<'static>> {
let no_key = || Error::Fetch("private key pem holds no key".into());
let text = std::str::from_utf8(section).map_err(|_| no_key())?;
let (_, document) = pkcs8::SecretDocument::from_pem(text).map_err(|_| no_key())?;
let info = document
.decode_msg::<pkcs8::EncryptedPrivateKeyInfo<'_>>()
.map_err(|e| match e.kind() {
pkcs8::der::ErrorKind::OidUnknown { oid } => unsupported_algorithm(&oid),
_ => Error::Fetch(format!("encrypted private key pem: {e}")),
})?;
let key = info.decrypt(passphrase).map_err(|e| match e {
pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::EncryptFailed) => {
Error::Fetch("the passphrase does not decrypt the private key".into())
}
pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::UnsupportedAlgorithm { oid }) => {
unsupported_algorithm(&oid)
}
pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::NoPbes1CryptSupport) => {
Error::Fetch(
"private key pem is encrypted under pkcs#5 pbes1, \
which this build does not decrypt"
.into(),
)
}
other => Error::Fetch(format!("encrypted private key: {other}")),
})?;
Ok(PrivateKeyDer::Pkcs8(key.as_bytes().to_vec().into()))
}
fn unsupported_algorithm(oid: &pkcs8::ObjectIdentifier) -> Error {
Error::Fetch(format!(
"private key pem is encrypted with algorithm {oid}, \
which this build does not decrypt"
))
}
#[cfg(test)]
mod tests {
use super::*;
use ostrya_rt::block_on;
const CA_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/ca.pem");
const CLIENT_CERT_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.pem");
const CLIENT_KEY_PEM: &[u8] = include_bytes!("../../../../tests/fixtures/tls/client.key.pem");
const CLIENT_KEY_ENC_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/client.key.enc.pem");
const CLIENT_KEY_LEGACY_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/client.key.legacy.pem");
const CLIENT_KEY_PBES1_PEM: &[u8] =
include_bytes!("../../../../tests/fixtures/tls/client.key.pbes1.pem");
const KEY_PASSPHRASE: &str = "ostrya test passphrase";
fn configs_for_key(key_pem: &[u8], passphrase: Option<&str>) -> Result<ClientConfigs> {
block_on(client_config(
&TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: Some(ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: key_pem.to_vec(),
key_passphrase: passphrase.map(str::to_string),
}),
},
true,
true,
))
}
#[test]
fn alpn_offers_h2_first_unless_disabled() {
let options = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: None,
};
let with_h2 = block_on(client_config(&options, true, true)).unwrap();
assert_eq!(
with_h2.without_identity.alpn_protocols,
vec![b"h2".to_vec(), b"http/1.1".to_vec()]
);
let without = block_on(client_config(&options, false, true)).unwrap();
assert_eq!(
without.without_identity.alpn_protocols,
vec![b"http/1.1".to_vec()]
);
}
#[test]
fn pem_anchors_are_reported_as_held() {
let options = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: None,
};
for https in [true, false] {
let configs = block_on(client_config(&options, true, https)).unwrap();
assert!(configs.has_trust_anchors, "https={https}");
}
}
#[test]
fn a_client_identity_is_accepted() {
let options = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: Some(ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: CLIENT_KEY_PEM.to_vec(),
key_passphrase: None,
}),
};
let configs = block_on(client_config(&options, true, true)).unwrap();
assert!(!Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
assert_eq!(
configs.with_identity.alpn_protocols,
configs.without_identity.alpn_protocols
);
let options = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: None,
};
let configs = block_on(client_config(&options, true, true)).unwrap();
assert!(Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
}
#[test]
fn a_bypass_needs_no_trust_store() {
for roots in [
TrustRoots::DangerousAcceptAnyChain,
TrustRoots::DangerousAcceptAny,
] {
let options = TlsOptions {
roots: roots.clone(),
client_identity: None,
};
for https in [true, false] {
let configs = block_on(client_config(&options, true, https)).unwrap();
assert!(configs.has_trust_anchors, "{roots:?} https={https}");
assert!(Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
}
}
}
#[test]
fn a_bypass_carries_a_client_identity() {
for roots in [
TrustRoots::DangerousAcceptAnyChain,
TrustRoots::DangerousAcceptAny,
] {
let options = TlsOptions {
roots,
client_identity: Some(ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: CLIENT_KEY_PEM.to_vec(),
key_passphrase: None,
}),
};
let configs = block_on(client_config(&options, true, true)).unwrap();
assert!(!Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
assert!(configs.has_trust_anchors);
}
}
#[test]
fn empty_trust_anchors_and_bad_keys_are_rejected() {
let no_roots = TlsOptions {
roots: TrustRoots::Pem(b"not a certificate\n".to_vec()),
client_identity: None,
};
let err = block_on(client_config(&no_roots, true, true)).unwrap_err();
assert!(err.to_string().contains("no certificate"), "{err}");
let no_key = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: Some(ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: CA_PEM.to_vec(),
key_passphrase: None,
}),
};
let err = block_on(client_config(&no_key, true, true)).unwrap_err();
assert!(err.to_string().contains("no key"), "{err}");
let unparsable_key = TlsOptions {
roots: TrustRoots::Pem(CA_PEM.to_vec()),
client_identity: Some(ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: b"-----BEGIN PRIVATE KEY-----\n".to_vec(),
key_passphrase: None,
}),
};
let err = block_on(client_config(&unparsable_key, true, true)).unwrap_err();
assert!(err.to_string().contains("private key pem"), "{err}");
}
#[test]
fn an_encrypted_client_key_is_decrypted() {
let configs = configs_for_key(CLIENT_KEY_ENC_PEM, Some(KEY_PASSPHRASE)).unwrap();
assert!(!Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
}
#[test]
fn the_encrypted_key_refusals_name_their_case() {
let err = configs_for_key(CLIENT_KEY_ENC_PEM, Some("not the passphrase")).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: the passphrase does not decrypt the private key"
);
let err = configs_for_key(CLIENT_KEY_ENC_PEM, None).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: private key pem is encrypted, and no passphrase is set"
);
let err = configs_for_key(CLIENT_KEY_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: a passphrase is set for a private key pem that carries no \
encryption"
);
for passphrase in [Some(KEY_PASSPHRASE), None] {
let err = configs_for_key(CLIENT_KEY_LEGACY_PEM, passphrase).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: private key pem is in the legacy openssl encrypted \
format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
);
}
}
#[test]
fn debug_redacts_the_key_and_the_passphrase() {
let identity = ClientIdentity {
cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
key_pem: CLIENT_KEY_PEM.to_vec(),
key_passphrase: Some(KEY_PASSPHRASE.to_string()),
};
let text = format!("{identity:?}");
assert!(!text.contains(KEY_PASSPHRASE), "{text}");
assert!(
text.contains("key_passphrase: Some(\"<redacted>\")"),
"{text}"
);
for line in std::str::from_utf8(CLIENT_KEY_PEM)
.unwrap()
.lines()
.filter(|line| !line.starts_with("-----"))
{
assert!(!text.contains(line), "{line} in {text}");
}
assert!(
text.contains(&format!("<{} bytes redacted>", CLIENT_KEY_PEM.len())),
"{text}"
);
assert!(text.contains("cert_chain_pem: ["), "{text}");
let without = ClientIdentity {
key_passphrase: None,
..identity
};
let text = format!("{without:?}");
assert!(text.contains("key_passphrase: None"), "{text}");
assert!(!text.contains(KEY_PASSPHRASE), "{text}");
}
#[test]
fn an_encrypted_key_is_read_out_of_a_longer_blob() {
let blobs = [
[CLIENT_KEY_ENC_PEM, b"\n"].concat(),
[CLIENT_CERT_PEM, CLIENT_KEY_ENC_PEM].concat(),
[CLIENT_KEY_ENC_PEM, CLIENT_CERT_PEM].concat(),
];
for blob in blobs {
let configs = configs_for_key(&blob, Some(KEY_PASSPHRASE)).unwrap();
assert!(!Arc::ptr_eq(
&configs.with_identity,
&configs.without_identity
));
}
}
#[test]
fn the_first_key_section_decides_the_path() {
let encrypted_first = [CLIENT_KEY_ENC_PEM, CLIENT_KEY_PEM].concat();
configs_for_key(&encrypted_first, Some(KEY_PASSPHRASE)).unwrap();
let err = configs_for_key(&encrypted_first, None).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: private key pem is encrypted, and no passphrase is set"
);
let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_ENC_PEM].concat();
configs_for_key(&plain_first, None).unwrap();
let err = configs_for_key(&plain_first, Some(KEY_PASSPHRASE)).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: a passphrase is set for a private key pem that carries no \
encryption"
);
}
#[test]
fn the_legacy_header_is_read_inside_its_own_section() {
let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_LEGACY_PEM].concat();
configs_for_key(&plain_first, None).unwrap();
let with_note = [
b"Proc-Type: 4,ENCRYPTED\n".as_slice(),
b"# Proc-Type: 4,ENCRYPTED\n".as_slice(),
CLIENT_KEY_PEM,
]
.concat();
configs_for_key(&with_note, None).unwrap();
}
#[test]
fn the_legacy_header_is_named_without_the_space() {
let text = std::str::from_utf8(CLIENT_KEY_LEGACY_PEM)
.unwrap()
.replace("Proc-Type: 4,ENCRYPTED", "Proc-Type:4,ENCRYPTED");
let err = configs_for_key(text.as_bytes(), Some(KEY_PASSPHRASE)).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: private key pem is in the legacy openssl encrypted \
format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
);
}
#[test]
fn a_pbes1_key_is_refused_by_name() {
let err = configs_for_key(CLIENT_KEY_PBES1_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
assert_eq!(
err.to_string(),
"fetch: private key pem is encrypted under pkcs#5 pbes1, \
which this build does not decrypt"
);
}
}