Skip to main content

openmoat_proxy/
tls.rs

1//! TLS termination for brokered secrets (ADR-043).
2//!
3//! For a host whose secret says `tls: terminate`, `openmoat run`'s proxy ends
4//! the agent's TLS itself, with a leaf for the host that its own certificate
5//! authority signs, reads and checks each request in the clear, puts the value
6//! in, and opens its own TLS to the host, verified against the system's roots
7//! with the same server name. The agent trusts that CA only inside the run.
8//!
9//! - The CA ([`new_ca`]) is name-constrained to the terminated hosts, so it
10//!   cannot vouch for any other name, and is made by a person (`openmoat proxy
11//!   ca init`); the CLI keeps it where no sandbox lets the agent read and pins
12//!   it in the policy lock.
13//! - [`Tls::new`] checks, for each host, that a leaf the CA signs verifies for
14//!   that host and today, the way a client will check it.
15//! - Only `http/1.1` is offered to the agent, so a client that speaks HTTP/2
16//!   alone fails the handshake instead of sending what the proxy cannot read.
17
18mod 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
35/// The one application protocol the proxy speaks inside a terminated tunnel.
36const HTTP_1_1: &[u8] = b"http/1.1";
37
38/// Why a CA cannot be made or used, or a terminated connection set up.
39#[derive(Debug, thiserror::Error)]
40#[non_exhaustive]
41pub enum TlsError {
42    /// No host to make a CA for.
43    #[error("no secret sets `tls: terminate`, so there is no host to make a CA for")]
44    NoHosts,
45    /// The clock reads a day no certificate can be written for.
46    #[error("the system clock is before 1970 or past the year 9000")]
47    Clock,
48    /// The CA key file holds no ECDSA P-256 key.
49    #[error("the CA key is not the ECDSA P-256 key `openmoat proxy ca init` writes")]
50    Key,
51    /// The CA certificate file holds no certificate.
52    #[error("the CA certificate file holds no PEM certificate")]
53    Cert,
54    /// A host no certificate can name.
55    #[error("{0} is not a name a certificate can carry")]
56    Host(String),
57    /// A leaf the CA signs for the host does not verify: another key, a host
58    /// outside its name constraints, or a CA that expired.
59    #[error("the OpenMoat proxy CA does not cover {host} today ({why})")]
60    Uncovered {
61        /// The host.
62        host: String,
63        /// What the verification said.
64        why: String,
65    },
66    /// No root certificate to verify upstream hosts with.
67    #[error("no trusted root certificates found on this system to verify upstream hosts")]
68    NoRoots,
69    /// rcgen could not make a certificate.
70    #[error("making a certificate: {0}")]
71    Certificate(String),
72    /// rustls refused a configuration.
73    #[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
87/// A new CA, as the files `openmoat proxy ca init` writes. The key is zeroed
88/// when dropped and left out of `Debug`.
89pub struct CaFiles {
90    /// The certificate, PEM: what clients inside `openmoat run` trust.
91    pub cert_pem: String,
92    /// The private key, PKCS #8 PEM: only the proxy reads it.
93    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
102/// Make a CA that may sign for `hosts` (and names under them) alone, valid
103/// from yesterday for a year.
104pub 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
112/// How long a CA [`new_ca`] makes is valid, in days.
113pub const CA_VALID_DAYS: i64 = ca::CA_DAYS;
114
115/// What upstream certificates are verified against.
116#[derive(Debug, Clone)]
117pub enum Roots {
118    /// The operating system's trust store (`rustls-native-certs`).
119    System,
120    /// These PEM certificates alone: tests, or a private CA.
121    Pem(String),
122}
123
124/// One proxy run's termination: the CA's signer, the leaves made from it and
125/// the configuration upstream connections use.
126pub struct Tls {
127    provider: Arc<CryptoProvider>,
128    signer: ca::Signer,
129    ca: CertificateDer<'static>,
130    upstream: Arc<ClientConfig>,
131    /// Per host, the server configuration holding today's leaf.
132    leaves: Mutex<HashMap<String, (Day, Arc<ServerConfig>)>>,
133    /// Per host, whether the CA may sign for it ([`Tls::covers`]).
134    covered: Mutex<HashMap<String, bool>>,
135}
136
137impl std::fmt::Debug for Tls {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.debug_struct("Tls").finish_non_exhaustive()
140    }
141}
142
143impl Tls {
144    /// Termination with the CA in `cert_pem` and `key_pem`, verifying
145    /// upstreams against `roots`. Refused unless the key signs leaves that
146    /// verify, today, for every one of `hosts`.
147    pub fn new(
148        cert_pem: &str,
149        key_pem: &str,
150        roots: &Roots,
151        hosts: &[String],
152    ) -> Result<Self, TlsError> {
153        let provider = Arc::new(rustls::crypto::ring::default_provider());
154        let ca = CertificateDer::from_pem_slice(cert_pem.as_bytes()).map_err(|_| TlsError::Cert)?;
155        let tls = Self {
156            signer: ca::Signer::new(key_pem)?,
157            upstream: Arc::new(upstream_config(roots, &provider)?),
158            provider,
159            ca,
160            leaves: Mutex::new(HashMap::new()),
161            covered: Mutex::new(HashMap::new()),
162        };
163        for host in hosts {
164            tls.check(host)?;
165        }
166        Ok(tls)
167    }
168
169    /// Whether the CA signs leaves that verify for `host`: its name
170    /// constraints cover it. A host a repository's `requests:` entry adds
171    /// after the CA was made is not covered, and is not terminated (ADR-062).
172    /// Checked once per host and remembered.
173    #[must_use]
174    pub fn covers(&self, host: &str) -> bool {
175        let mut covered = self
176            .covered
177            .lock()
178            .unwrap_or_else(std::sync::PoisonError::into_inner);
179        *covered
180            .entry(host.to_ascii_lowercase())
181            .or_insert_with(|| self.check(host).is_ok())
182    }
183
184    /// Whether a leaf for `host` verifies against the CA alone today, the
185    /// check a client makes: chain, validity and name constraints.
186    fn check(&self, host: &str) -> Result<(), TlsError> {
187        let uncovered = |why: String| TlsError::Uncovered {
188            host: host.to_owned(),
189            why,
190        };
191        let mut roots = RootCertStore::empty();
192        roots
193            .add(self.ca.clone())
194            .map_err(|e| uncovered(e.to_string()))?;
195        let verifier =
196            WebPkiServerVerifier::builder_with_provider(Arc::new(roots), self.provider.clone())
197                .build()
198                .map_err(|e| uncovered(e.to_string()))?;
199        let (leaf, _) = self.signer.leaf(host, Day::today()?)?;
200        let name = server_name(host)?;
201        verifier
202            .verify_server_cert(
203                &CertificateDer::from(leaf),
204                &[],
205                &name,
206                &[],
207                UnixTime::now(),
208            )
209            .map(drop)
210            .map_err(|e| uncovered(e.to_string()))
211    }
212
213    /// A server connection presenting today's leaf for `host`, offering
214    /// `http/1.1` only.
215    pub(crate) fn accept(&self, host: &str) -> Result<ServerConnection, TlsError> {
216        let config = self.server_config(host)?;
217        ServerConnection::new(config).map_err(|e| TlsError::config(&e))
218    }
219
220    /// A client connection to `host`, verified against the upstream roots
221    /// with `host` as the server name.
222    pub(crate) fn connect(&self, host: &str) -> Result<ClientConnection, TlsError> {
223        ClientConnection::new(self.upstream.clone(), server_name(host)?)
224            .map_err(|e| TlsError::config(&e))
225    }
226
227    fn server_config(&self, host: &str) -> Result<Arc<ServerConfig>, TlsError> {
228        let today = Day::today()?;
229        // A poisoned cache only lost leaves; they are made again.
230        let mut leaves = self
231            .leaves
232            .lock()
233            .unwrap_or_else(std::sync::PoisonError::into_inner);
234        if let Some((day, config)) = leaves.get(host)
235            && *day == today
236        {
237            return Ok(config.clone());
238        }
239        let (cert, key) = self.signer.leaf(host, today)?;
240        let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.to_vec()));
241        let certified =
242            CertifiedKey::from_der(vec![CertificateDer::from(cert)], key, &self.provider)
243                .map_err(|e| TlsError::config(&e))?;
244        let mut config = ServerConfig::builder_with_provider(self.provider.clone())
245            .with_safe_default_protocol_versions()
246            .map_err(|e| TlsError::config(&e))?
247            .with_no_client_auth()
248            .with_cert_resolver(Arc::new(rustls::sign::SingleCertAndKey::from(certified)));
249        config.alpn_protocols = vec![HTTP_1_1.to_vec()];
250        let config = Arc::new(config);
251        leaves.insert(host.to_owned(), (today, config.clone()));
252        Ok(config)
253    }
254}
255
256fn server_name(host: &str) -> Result<ServerName<'static>, TlsError> {
257    ServerName::try_from(host.to_owned()).map_err(|_| TlsError::Host(host.to_owned()))
258}
259
260/// The client configuration for upstream TLS, also audit delivery's
261/// (`post.rs`): `roots` only, safe protocol versions, `http/1.1`.
262pub(crate) fn upstream_config(
263    roots: &Roots,
264    provider: &Arc<CryptoProvider>,
265) -> Result<ClientConfig, TlsError> {
266    let mut store = RootCertStore::empty();
267    match roots {
268        Roots::System => {
269            // Certificates the store holds that rustls cannot use are skipped,
270            // as browsers skip them.
271            let found = rustls_native_certs::load_native_certs();
272            store.add_parsable_certificates(found.certs);
273        }
274        Roots::Pem(pem) => {
275            let certs = CertificateDer::pem_slice_iter(pem.as_bytes())
276                .collect::<Result<Vec<_>, _>>()
277                .map_err(|_| TlsError::Cert)?;
278            store.add_parsable_certificates(certs);
279        }
280    }
281    if store.is_empty() {
282        return Err(TlsError::NoRoots);
283    }
284    let mut config = ClientConfig::builder_with_provider(provider.clone())
285        .with_safe_default_protocol_versions()
286        .map_err(|e| TlsError::config(&e))?
287        .with_root_certificates(store)
288        .with_no_client_auth();
289    config.alpn_protocols = vec![HTTP_1_1.to_vec()];
290    Ok(config)
291}
292
293#[cfg(test)]
294mod tests;