1use crate::Policy;
19use kute::{KuteError, Result};
20use rustls::pki_types::pem::PemObject;
21use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
22use rustls::server::WebPkiClientVerifier;
23use rustls::{ClientConfig, ClientConnection, ConnectionCommon, RootCertStore, ServerConfig, ServerConnection, SideData, StreamOwned};
24use sha2::{Digest, Sha256};
25use std::collections::BTreeMap;
26use std::io::{Read, Write};
27use std::net::TcpStream;
28use std::ops::DerefMut;
29use std::path::Path;
30use std::sync::Arc;
31
32fn tls_error(what: &str, e: impl std::fmt::Display) -> KuteError {
33 KuteError::Backend(format!("tls: {what}: {e}"))
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
38pub struct PeerIdentity {
39 pub fingerprint: String,
41}
42
43pub fn fingerprint(certificate: &CertificateDer<'_>) -> String {
45 format!("sha256:{}", kute::hex(&Sha256::digest(certificate.as_ref())))
46}
47
48#[derive(Clone, Debug, Default)]
50pub struct Access {
51 peers: BTreeMap<String, Policy>,
52}
53
54impl Access {
55 pub fn new() -> Self {
56 Self::default()
57 }
58
59 pub fn allow(&mut self, fingerprint: &str, policy: Policy) -> Result<()> {
62 let hex = fingerprint.strip_prefix("sha256:").unwrap_or("");
63 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
64 return Err(KuteError::InvalidConfig(format!("{fingerprint:?} is not a certificate fingerprint (sha256: and 64 lowercase hex digits)")));
65 }
66 self.peers.insert(fingerprint.to_string(), policy);
67 Ok(())
68 }
69
70 pub fn policy_for(&self, who: &PeerIdentity) -> Result<Policy> {
72 self.peers
73 .get(&who.fingerprint)
74 .cloned()
75 .ok_or_else(|| KuteError::Backend(format!("peer {} is authenticated but not authorized here", who.fingerprint)))
76 }
77
78 pub fn len(&self) -> usize {
79 self.peers.len()
80 }
81
82 pub fn is_empty(&self) -> bool {
83 self.peers.is_empty()
84 }
85}
86
87pub fn load_certificates(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
89 let certs = CertificateDer::pem_file_iter(path)
90 .map_err(|e| tls_error(&format!("reading {}", path.display()), e))?
91 .collect::<std::result::Result<Vec<_>, _>>()
92 .map_err(|e| tls_error(&format!("reading {}", path.display()), e))?;
93 if certs.is_empty() {
94 return Err(KuteError::InvalidConfig(format!("{} holds no certificate", path.display())));
95 }
96 Ok(certs)
97}
98
99pub fn load_private_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
101 PrivateKeyDer::from_pem_file(path).map_err(|e| tls_error(&format!("reading the key in {}", path.display()), e))
102}
103
104fn roots(authorities: Vec<CertificateDer<'static>>) -> Result<RootCertStore> {
105 let mut store = RootCertStore::empty();
106 for authority in authorities {
107 store.add(authority).map_err(|e| tls_error("a trusted authority certificate is not usable", e))?;
108 }
109 if store.is_empty() {
110 return Err(KuteError::InvalidConfig("no trusted authority was given".into()));
111 }
112 Ok(store)
113}
114
115fn provider() -> Arc<rustls::crypto::CryptoProvider> {
116 Arc::new(rustls::crypto::ring::default_provider())
117}
118
119pub fn server_config(
122 chain: Vec<CertificateDer<'static>>,
123 key: PrivateKeyDer<'static>,
124 client_authorities: Vec<CertificateDer<'static>>,
125) -> Result<Arc<ServerConfig>> {
126 let verifier = WebPkiClientVerifier::builder_with_provider(Arc::new(roots(client_authorities)?), provider())
127 .build()
128 .map_err(|e| tls_error("client verification", e))?;
129 let config = ServerConfig::builder_with_provider(provider())
130 .with_protocol_versions(&[&rustls::version::TLS13])
131 .map_err(|e| tls_error("protocol versions", e))?
132 .with_client_cert_verifier(verifier)
133 .with_single_cert(chain, key)
134 .map_err(|e| tls_error("the server certificate and key", e))?;
135 Ok(Arc::new(config))
136}
137
138pub fn client_config(
141 chain: Vec<CertificateDer<'static>>,
142 key: PrivateKeyDer<'static>,
143 server_authorities: Vec<CertificateDer<'static>>,
144) -> Result<Arc<ClientConfig>> {
145 let config = ClientConfig::builder_with_provider(provider())
146 .with_protocol_versions(&[&rustls::version::TLS13])
147 .map_err(|e| tls_error("protocol versions", e))?
148 .with_root_certificates(roots(server_authorities)?)
149 .with_client_auth_cert(chain, key)
150 .map_err(|e| tls_error("the client certificate and key", e))?;
151 Ok(Arc::new(config))
152}
153
154pub struct Secured<C, S>(StreamOwned<C, TcpStream>)
159where
160 C: DerefMut<Target = ConnectionCommon<S>>,
161 S: SideData;
162
163pub type ServerStream = Secured<ServerConnection, rustls::server::ServerConnectionData>;
165pub type ClientStream = Secured<ClientConnection, rustls::client::ClientConnectionData>;
167
168impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Read for Secured<C, S> {
169 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
170 self.0.read(buf)
171 }
172}
173
174impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Write for Secured<C, S> {
175 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
176 self.0.write(buf)
177 }
178 fn flush(&mut self) -> std::io::Result<()> {
179 self.0.flush()
180 }
181}
182
183impl<C: DerefMut<Target = ConnectionCommon<S>>, S: SideData> Drop for Secured<C, S> {
184 fn drop(&mut self) {
185 self.0.conn.send_close_notify();
186 let _ = self.0.flush();
187 }
188}
189
190fn identity(certificates: Option<&[CertificateDer<'_>]>) -> Result<PeerIdentity> {
191 let own = certificates.and_then(|c| c.first()).ok_or_else(|| KuteError::Backend("tls: the peer presented no certificate".into()))?;
192 Ok(PeerIdentity { fingerprint: fingerprint(own) })
193}
194
195pub fn accept(config: &Arc<ServerConfig>, mut tcp: TcpStream) -> Result<(ServerStream, PeerIdentity)> {
200 let mut connection = ServerConnection::new(config.clone()).map_err(|e| tls_error("starting the handshake", e))?;
201 while connection.is_handshaking() {
202 connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
203 }
204 let who = identity(connection.peer_certificates())?;
205 Ok((Secured(StreamOwned::new(connection, tcp)), who))
206}
207
208pub fn connect(config: &Arc<ClientConfig>, server_name: &str, mut tcp: TcpStream) -> Result<(ClientStream, PeerIdentity)> {
213 let name = ServerName::try_from(server_name.to_string()).map_err(|e| tls_error(&format!("server name {server_name:?}"), e))?;
214 let mut connection = ClientConnection::new(config.clone(), name).map_err(|e| tls_error("starting the handshake", e))?;
215 while connection.is_handshaking() {
216 connection.complete_io(&mut tcp).map_err(|e| tls_error("handshake", e))?;
217 }
218 let who = identity(connection.peer_certificates())?;
219 Ok((Secured(StreamOwned::new(connection, tcp)), who))
220}