use crate::Policy;
use kute::{KuteError, Result};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use rustls::server::WebPkiClientVerifier;
use rustls::{ClientConfig, ClientConnection, ConnectionCommon, RootCertStore, ServerConfig, ServerConnection, SideData, StreamOwned};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::ops::DerefMut;
use std::path::Path;
use std::sync::Arc;
fn tls_error(what: &str, e: impl std::fmt::Display) -> KuteError {
KuteError::Backend(format!("tls: {what}: {e}"))
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct PeerIdentity {
pub fingerprint: String,
}
pub fn fingerprint(certificate: &CertificateDer<'_>) -> String {
format!("sha256:{}", kute::hex(&Sha256::digest(certificate.as_ref())))
}
#[derive(Clone, Debug, Default)]
pub struct Access {
peers: BTreeMap<String, Policy>,
}
impl Access {
pub fn new() -> Self {
Self::default()
}
pub fn allow(&mut self, fingerprint: &str, policy: Policy) -> Result<()> {
let hex = fingerprint.strip_prefix("sha256:").unwrap_or("");
if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return Err(KuteError::InvalidConfig(format!("{fingerprint:?} is not a certificate fingerprint (sha256: and 64 lowercase hex digits)")));
}
self.peers.insert(fingerprint.to_string(), policy);
Ok(())
}
pub fn policy_for(&self, who: &PeerIdentity) -> Result<Policy> {
self.peers
.get(&who.fingerprint)
.cloned()
.ok_or_else(|| KuteError::Backend(format!("peer {} is authenticated but not authorized here", who.fingerprint)))
}
pub fn len(&self) -> usize {
self.peers.len()
}
pub fn is_empty(&self) -> bool {
self.peers.is_empty()
}
}
pub fn load_certificates(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
let certs = CertificateDer::pem_file_iter(path)
.map_err(|e| tls_error(&format!("reading {}", path.display()), e))?
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|e| tls_error(&format!("reading {}", path.display()), e))?;
if certs.is_empty() {
return Err(KuteError::InvalidConfig(format!("{} holds no certificate", path.display())));
}
Ok(certs)
}
pub fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_file(path).map_err(|e| tls_error(&format!("reading the key in {}", path.display()), e))
}
fn roots(authorities: Vec<CertificateDer<'static>>) -> Result<RootCertStore> {
let mut store = RootCertStore::empty();
for authority in authorities {
store.add(authority).map_err(|e| tls_error("a trusted authority certificate is not usable", e))?;
}
if store.is_empty() {
return Err(KuteError::InvalidConfig("no trusted authority was given".into()));
}
Ok(store)
}
fn provider() -> Arc<rustls::crypto::CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
pub fn server_config(
chain: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
client_authorities: Vec<CertificateDer<'static>>,
) -> Result<Arc<ServerConfig>> {
let verifier = WebPkiClientVerifier::builder_with_provider(Arc::new(roots(client_authorities)?), provider())
.build()
.map_err(|e| tls_error("client verification", e))?;
let config = ServerConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(|e| tls_error("protocol versions", e))?
.with_client_cert_verifier(verifier)
.with_single_cert(chain, key)
.map_err(|e| tls_error("the server certificate and key", e))?;
Ok(Arc::new(config))
}
pub fn client_config(
chain: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
server_authorities: Vec<CertificateDer<'static>>,
) -> Result<Arc<ClientConfig>> {
let config = ClientConfig::builder_with_provider(provider())
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(|e| tls_error("protocol versions", e))?
.with_root_certificates(roots(server_authorities)?)
.with_client_auth_cert(chain, key)
.map_err(|e| tls_error("the client certificate and key", e))?;
Ok(Arc::new(config))
}
pub struct Secured<C, S>(StreamOwned<C, TcpStream>)
where
C: DerefMut<Target = ConnectionCommon<S>>,
S: SideData;
pub type ServerStream = Secured<ServerConnection, rustls::server::ServerConnectionData>;
pub type ClientStream = Secured<ClientConnection, rustls::client::ClientConnectionData>;
impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Read for Secured<C, S> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Write for Secured<C, S> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.0.flush()
}
}
impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Drop for Secured<C, S> {
fn drop(&mut self) {
self.0.conn.send_close_notify();
let _ = self.0.flush();
}
}
fn identity(certificates: Option<&[CertificateDer<'_>]>) -> Result<PeerIdentity> {
let own = certificates.and_then(|c| c.first()).ok_or_else(|| KuteError::Backend("tls: the peer presented no certificate".into()))?;
Ok(PeerIdentity { fingerprint: fingerprint(own) })
}
pub fn accept(config: &Arc<ServerConfig>, mut tcp: TcpStream) -> Result<(ServerStream, PeerIdentity)> {
let mut connection = ServerConnection::new(config.clone()).map_err(|e| tls_error("starting the handshake", e))?;
while connection.is_handshaking() {
connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
}
let who = identity(connection.peer_certificates())?;
Ok((Secured(StreamOwned::new(connection, tcp)), who))
}
pub fn connect(config: &Arc<ClientConfig>, server_name: &str, mut tcp: TcpStream) -> Result<(ClientStream, PeerIdentity)> {
let name = ServerName::try_from(server_name.to_string()).map_err(|e| tls_error(&format!("server name {server_name:?}"), e))?;
let mut connection = ClientConnection::new(config.clone(), name).map_err(|e| tls_error("starting the handshake", e))?;
while connection.is_handshaking() {
connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
}
let who = identity(connection.peer_certificates())?;
Ok((Secured(StreamOwned::new(connection, tcp)), who))
}