Update to rustls 0.22

This commit is contained in:
Matt Brubeck 2023-12-18 07:56:52 -08:00
parent b1c7564046
commit 8809f9378c
5 changed files with 52 additions and 75 deletions

View file

@ -1,7 +1,9 @@
use {
rustls::{
crypto::ring::sign::any_supported_type,
pki_types::{self, CertificateDer, PrivateKeyDer},
server::{ClientHello, ResolvesServerCert},
sign::{any_supported_type, CertifiedKey, SignError},
sign::{CertifiedKey, SigningKey},
},
std::{
ffi::OsStr,
@ -13,6 +15,7 @@ use {
/// A struct that holds all loaded certificates and the respective domain
/// names.
#[derive(Debug)]
pub(crate) struct CertStore {
/// Stores the certificates and the domains they apply to, sorted by domain
/// names, longest matches first
@ -30,7 +33,7 @@ pub enum CertLoadError {
Empty,
/// the key file for the specified domain is bad (e.g. does not contain a
/// key or is invalid)
BadKey(String, SignError),
BadKey(String, rustls::Error),
/// the key file for the specified domain is missing (but a certificate
/// file was present)
MissingKey(String),
@ -74,27 +77,44 @@ fn load_domain(certs_dir: &Path, domain: String) -> Result<CertifiedKey, CertLoa
CertLoadError::MissingCert(domain)
});
}
let cert = rustls::Certificate(
let cert = CertificateDer::from(
std::fs::read(&path).map_err(|_| CertLoadError::MissingCert(domain.clone()))?,
);
// load key from file
path.set_file_name(KEY_FILE_NAME);
if !path.is_file() {
let Ok(der) = std::fs::read(&path) else {
return Err(CertLoadError::MissingKey(domain));
}
let key = rustls::PrivateKey(
std::fs::read(&path).map_err(|_| CertLoadError::MissingKey(domain.clone()))?,
);
};
// transform key to correct format
let key = match any_supported_type(&key) {
Ok(key) => key,
Err(e) => return Err(CertLoadError::BadKey(domain, e)),
};
let key = der_to_private_key(&der).map_err(|e| CertLoadError::BadKey(domain.clone(), e))?;
Ok(CertifiedKey::new(vec![cert], key))
}
/// We don't know the key type of the private key DER file, so try each
/// possible type until we find one that works.
///
/// We should probably stop doing this and use a PEM file instead:
/// https://github.com/rustls/rustls/issues/1661
fn der_to_private_key(der: &[u8]) -> Result<Arc<dyn SigningKey>, rustls::Error> {
let keys = [
PrivateKeyDer::Pkcs1(pki_types::PrivatePkcs1KeyDer::from(der)),
PrivateKeyDer::Sec1(pki_types::PrivateSec1KeyDer::from(der)),
PrivateKeyDer::Pkcs8(pki_types::PrivatePkcs8KeyDer::from(der)),
];
let mut err = None;
for key in keys {
match any_supported_type(&key) {
Ok(key) => return Ok(key),
Err(e) => err = Some(e),
}
}
Err(err.unwrap())
}
impl CertStore {
/// Load certificates from a certificate directory.
/// Certificates should be stored in a folder for each hostname, for example