1mod ca;
19mod date;
20
21use std::collections::HashMap;
22use std::sync::{Arc, Mutex};
23
24use rustls::client::WebPkiServerVerifier;
25use rustls::client::danger::ServerCertVerifier as _;
26use rustls::crypto::CryptoProvider;
27use rustls::pki_types::pem::PemObject as _;
28use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
29use rustls::sign::CertifiedKey;
30use rustls::{ClientConfig, ClientConnection, RootCertStore, ServerConfig, ServerConnection};
31use zeroize::Zeroizing;
32
33pub(crate) use self::date::Day;
34
35const HTTP_1_1: &[u8] = b"http/1.1";
37
38#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum TlsError {
42 #[error("no secret sets `tls: terminate`, so there is no host to make a CA for")]
44 NoHosts,
45 #[error("the system clock is before 1970 or past the year 9000")]
47 Clock,
48 #[error("the CA key is not the ECDSA P-256 key `openmoat proxy ca init` writes")]
50 Key,
51 #[error("the CA certificate file holds no PEM certificate")]
53 Cert,
54 #[error("{0} is not a name a certificate can carry")]
56 Host(String),
57 #[error("the OpenMoat proxy CA does not cover {host} today ({why})")]
60 Uncovered {
61 host: String,
63 why: String,
65 },
66 #[error("no trusted root certificates found on this system to verify upstream hosts")]
68 NoRoots,
69 #[error("making a certificate: {0}")]
71 Certificate(String),
72 #[error("TLS configuration: {0}")]
74 Config(String),
75}
76
77impl TlsError {
78 fn rcgen(e: &rcgen::Error) -> Self {
79 Self::Certificate(e.to_string())
80 }
81
82 fn config(e: &rustls::Error) -> Self {
83 Self::Config(e.to_string())
84 }
85}
86
87pub struct CaFiles {
90 pub cert_pem: String,
92 pub key_pem: Zeroizing<String>,
94}
95
96impl std::fmt::Debug for CaFiles {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("CaFiles").finish_non_exhaustive()
99 }
100}
101
102pub fn new_ca(hosts: &[String]) -> Result<CaFiles, TlsError> {
105 let made = ca::generate(hosts, Day::today()?)?;
106 Ok(CaFiles {
107 cert_pem: made.cert,
108 key_pem: made.key,
109 })
110}
111
112pub const CA_VALID_DAYS: i64 = ca::CA_DAYS;
114
115#[derive(Debug, Clone)]
117pub enum Roots {
118 System,
120 Pem(String),
122}
123
124pub struct Tls {
127 provider: Arc<CryptoProvider>,
128 signer: ca::Signer,
129 ca: CertificateDer<'static>,
130 upstream: Arc<ClientConfig>,
131 leaves: Mutex<HashMap<String, (Day, Arc<ServerConfig>)>>,
133}
134
135impl std::fmt::Debug for Tls {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 f.debug_struct("Tls").finish_non_exhaustive()
138 }
139}
140
141impl Tls {
142 pub fn new(
146 cert_pem: &str,
147 key_pem: &str,
148 roots: &Roots,
149 hosts: &[String],
150 ) -> Result<Self, TlsError> {
151 let provider = Arc::new(rustls::crypto::ring::default_provider());
152 let ca = CertificateDer::from_pem_slice(cert_pem.as_bytes()).map_err(|_| TlsError::Cert)?;
153 let tls = Self {
154 signer: ca::Signer::new(key_pem)?,
155 upstream: Arc::new(upstream_config(roots, &provider)?),
156 provider,
157 ca,
158 leaves: Mutex::new(HashMap::new()),
159 };
160 for host in hosts {
161 tls.check(host)?;
162 }
163 Ok(tls)
164 }
165
166 fn check(&self, host: &str) -> Result<(), TlsError> {
169 let uncovered = |why: String| TlsError::Uncovered {
170 host: host.to_owned(),
171 why,
172 };
173 let mut roots = RootCertStore::empty();
174 roots
175 .add(self.ca.clone())
176 .map_err(|e| uncovered(e.to_string()))?;
177 let verifier =
178 WebPkiServerVerifier::builder_with_provider(Arc::new(roots), self.provider.clone())
179 .build()
180 .map_err(|e| uncovered(e.to_string()))?;
181 let (leaf, _) = self.signer.leaf(host, Day::today()?)?;
182 let name = server_name(host)?;
183 verifier
184 .verify_server_cert(
185 &CertificateDer::from(leaf),
186 &[],
187 &name,
188 &[],
189 UnixTime::now(),
190 )
191 .map(drop)
192 .map_err(|e| uncovered(e.to_string()))
193 }
194
195 pub(crate) fn accept(&self, host: &str) -> Result<ServerConnection, TlsError> {
198 let config = self.server_config(host)?;
199 ServerConnection::new(config).map_err(|e| TlsError::config(&e))
200 }
201
202 pub(crate) fn connect(&self, host: &str) -> Result<ClientConnection, TlsError> {
205 ClientConnection::new(self.upstream.clone(), server_name(host)?)
206 .map_err(|e| TlsError::config(&e))
207 }
208
209 fn server_config(&self, host: &str) -> Result<Arc<ServerConfig>, TlsError> {
210 let today = Day::today()?;
211 let mut leaves = self
213 .leaves
214 .lock()
215 .unwrap_or_else(std::sync::PoisonError::into_inner);
216 if let Some((day, config)) = leaves.get(host)
217 && *day == today
218 {
219 return Ok(config.clone());
220 }
221 let (cert, key) = self.signer.leaf(host, today)?;
222 let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.to_vec()));
223 let certified =
224 CertifiedKey::from_der(vec![CertificateDer::from(cert)], key, &self.provider)
225 .map_err(|e| TlsError::config(&e))?;
226 let mut config = ServerConfig::builder_with_provider(self.provider.clone())
227 .with_safe_default_protocol_versions()
228 .map_err(|e| TlsError::config(&e))?
229 .with_no_client_auth()
230 .with_cert_resolver(Arc::new(rustls::sign::SingleCertAndKey::from(certified)));
231 config.alpn_protocols = vec![HTTP_1_1.to_vec()];
232 let config = Arc::new(config);
233 leaves.insert(host.to_owned(), (today, config.clone()));
234 Ok(config)
235 }
236}
237
238fn server_name(host: &str) -> Result<ServerName<'static>, TlsError> {
239 ServerName::try_from(host.to_owned()).map_err(|_| TlsError::Host(host.to_owned()))
240}
241
242pub(crate) fn upstream_config(
245 roots: &Roots,
246 provider: &Arc<CryptoProvider>,
247) -> Result<ClientConfig, TlsError> {
248 let mut store = RootCertStore::empty();
249 match roots {
250 Roots::System => {
251 let found = rustls_native_certs::load_native_certs();
254 store.add_parsable_certificates(found.certs);
255 }
256 Roots::Pem(pem) => {
257 let certs = CertificateDer::pem_slice_iter(pem.as_bytes())
258 .collect::<Result<Vec<_>, _>>()
259 .map_err(|_| TlsError::Cert)?;
260 store.add_parsable_certificates(certs);
261 }
262 }
263 if store.is_empty() {
264 return Err(TlsError::NoRoots);
265 }
266 let mut config = ClientConfig::builder_with_provider(provider.clone())
267 .with_safe_default_protocol_versions()
268 .map_err(|e| TlsError::config(&e))?
269 .with_root_certificates(store)
270 .with_no_client_auth();
271 config.alpn_protocols = vec![HTTP_1_1.to_vec()];
272 Ok(config)
273}
274
275#[cfg(test)]
276mod tests;