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}
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    /// Termination with the CA in `cert_pem` and `key_pem`, verifying
143    /// upstreams against `roots`. Refused unless the key signs leaves that
144    /// verify, today, for every one of `hosts`.
145    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    /// Whether a leaf for `host` verifies against the CA alone today, the
167    /// check a client makes: chain, validity and name constraints.
168    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    /// A server connection presenting today's leaf for `host`, offering
196    /// `http/1.1` only.
197    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    /// A client connection to `host`, verified against the upstream roots
203    /// with `host` as the server name.
204    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        // A poisoned cache only lost leaves; they are made again.
212        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
242/// The client configuration for upstream TLS, also audit delivery's
243/// (`post.rs`): `roots` only, safe protocol versions, `http/1.1`.
244pub(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            // Certificates the store holds that rustls cannot use are skipped,
252            // as browsers skip them.
253            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;