torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Load and build rustls mTLS 1.3 client/server configs.

use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;

use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::{ClientConfig, RootCertStore, ServerConfig};

use crate::error::{Error, Result};

#[derive(Clone)]
pub struct TlsMaterial {
    pub ca_certs: Vec<CertificateDer<'static>>,
    pub cert_chain: Vec<CertificateDer<'static>>,
    pub private_key: Arc<PrivateKeyDer<'static>>,
}

impl TlsMaterial {
    pub fn from_pem_files(
        ca_path: impl AsRef<Path>,
        cert_path: impl AsRef<Path>,
        key_path: impl AsRef<Path>,
    ) -> Result<Self> {
        let ca_certs = load_certs(ca_path.as_ref())?;
        let cert_chain = load_certs(cert_path.as_ref())?;
        let private_key = Arc::new(load_private_key(key_path.as_ref())?);
        if cert_chain.is_empty() {
            return Err(Error::Secure("certificate chain is empty".into()));
        }
        Ok(Self {
            ca_certs,
            cert_chain,
            private_key,
        })
    }

    pub fn from_der(
        ca_certs: Vec<CertificateDer<'static>>,
        cert_chain: Vec<CertificateDer<'static>>,
        private_key: PrivateKeyDer<'static>,
    ) -> Result<Self> {
        if cert_chain.is_empty() {
            return Err(Error::Secure("certificate chain is empty".into()));
        }
        Ok(Self {
            ca_certs,
            cert_chain,
            private_key: Arc::new(private_key),
        })
    }

    pub fn client_config(&self) -> Result<ClientConfig> {
        let roots = root_store(&self.ca_certs)?;
        ClientConfig::builder_with_protocol_versions(&[&rustls::version::TLS13])
            .with_root_certificates(roots)
            .with_client_auth_cert(self.cert_chain.clone(), clone_private_key(&self.private_key)?)
            .map_err(|err| Error::Secure(format!("client mTLS config: {err}")))
    }

    pub fn server_config(&self) -> Result<ServerConfig> {
        let roots = root_store(&self.ca_certs)?;
        let client_verifier = WebPkiClientVerifier::builder(Arc::new(roots))
            .build()
            .map_err(|err| Error::Secure(format!("client verifier: {err}")))?;

        ServerConfig::builder_with_protocol_versions(&[&rustls::version::TLS13])
            .with_client_cert_verifier(client_verifier)
            .with_single_cert(self.cert_chain.clone(), clone_private_key(&self.private_key)?)
            .map_err(|err| Error::Secure(format!("server mTLS config: {err}")))
    }
}

fn clone_private_key(key: &PrivateKeyDer<'static>) -> Result<PrivateKeyDer<'static>> {
    match key {
        PrivateKeyDer::Pkcs8(k) => Ok(PrivateKeyDer::Pkcs8(
            rustls::pki_types::PrivatePkcs8KeyDer::from(k.secret_pkcs8_der().to_vec()),
        )),
        PrivateKeyDer::Pkcs1(k) => Ok(PrivateKeyDer::Pkcs1(
            rustls::pki_types::PrivatePkcs1KeyDer::from(k.secret_pkcs1_der().to_vec()),
        )),
        PrivateKeyDer::Sec1(k) => Ok(PrivateKeyDer::Sec1(
            rustls::pki_types::PrivateSec1KeyDer::from(k.secret_sec1_der().to_vec()),
        )),
        other => Err(Error::Secure(format!(
            "unsupported private key type: {other:?}"
        ))),
    }
}

fn root_store(ca_certs: &[CertificateDer<'static>]) -> Result<RootCertStore> {
    let mut roots = RootCertStore::empty();
    for cert in ca_certs {
        roots
            .add(cert.clone())
            .map_err(|err| Error::Secure(format!("add CA cert: {err}")))?;
    }
    if roots.is_empty() {
        return Err(Error::Secure("CA store is empty".into()));
    }
    Ok(roots)
}

fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
    let file = crate::security::open_nofollow_read(path)
        .map_err(|err| Error::Secure(format!("open cert {}: {err}", path.display())))?;
    let mut reader = BufReader::new(file);
    let certs = rustls_pemfile::certs(&mut reader)
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|err| Error::Secure(format!("parse certs {}: {err}", path.display())))?;
    Ok(certs)
}

fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
    let file = crate::security::open_nofollow_read(path)
        .map_err(|err| Error::Secure(format!("open key {}: {err}", path.display())))?;
    let mut reader = BufReader::new(file);
    let key = rustls_pemfile::private_key(&mut reader)
        .map_err(|err| Error::Secure(format!("parse key {}: {err}", path.display())))?
        .ok_or_else(|| Error::Secure(format!("no private key in {}", path.display())))?;
    Ok(key)
}