Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/src/tls/mint.rs

12.1 KiB, 1 run

created by r1870400018:76014, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A certificate authority that lives only in memory and can vouch only for the names it was
2//! given, for a TLS-terminating proxy that must show a client a certificate for a host it does
3//! not own.
4//!
5//! RFC 5280 has no "strictly below" form of a dNSName constraint, so a `Suffix(".x.y")` rule
6//! permits `x.y` itself in the CA's name constraints, and an `Exact("x.y")` rule permits every
7//! host below `x.y`. `Mint::leaf` is the narrower gate: the constraints bound what a stolen key
8//! could do, and the rules bound what the `Mint` will do.
9
10use crate::tls::{
11 ensure_crypto_provider,
12 pem_certificate,
13};
14
15use oxedyne_fe2o3_core::prelude::*;
16
17use std::{
18 collections::HashMap,
19 fmt,
20 net::IpAddr,
21 sync::{
22 Arc,
23 Mutex,
24 },
25 time::{
26 Duration,
27 SystemTime,
28 UNIX_EPOCH,
29 },
30};
31
32use rcgen::{
33 BasicConstraints,
34 Certificate,
35 CertificateParams,
36 CidrSubnet,
37 DistinguishedName,
38 DnType,
39 ExtendedKeyUsagePurpose,
40 GeneralSubtree,
41 IsCa,
42 KeyUsagePurpose,
43 NameConstraints,
44 SanType,
45 PKCS_ECDSA_P256_SHA256,
46};
47use tokio_rustls::rustls::{
48 crypto::ring::sign::any_ecdsa_type,
49 pki_types::{
50 CertificateDer,
51 PrivateKeyDer,
52 PrivatePkcs8KeyDer,
53 },
54 server::{
55 ClientHello,
56 ResolvesServerCert,
57 },
58 sign::CertifiedKey,
59};
60
61
62pub const MINT_LEAF_SECS: i64 = 24 * 3_600; // A leaf's lifetime.
63pub const MINT_RENEW_SECS: i64 = 3_600; // A leaf with less left is re-issued.
64pub const MINT_BACKDATE_SECS: i64 = 3_600; // notBefore lies this far back, for skew.
65pub const MINT_LEAF_CACHE_MAX: usize = 1_024; // Leaves held at once.
66
67/// A name, or a family of names, a [`Mint`] may vouch for.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub enum NameRule {
70 Exact(String), // One host, `pypi.org`.
71 Suffix(String), // Every host strictly below a domain, `.pythonhosted.org`.
72}
73
74impl NameRule {
75
76 /// The rule with its name checked and in lower case.
77 fn normal(&self) -> Outcome<Self> {
78 match self {
79 Self::Exact(n) => Ok(Self::Exact(res!(dns_name(n)))),
80 Self::Suffix(s) => match s.strip_prefix('.') {
81 Some(d) => Ok(Self::Suffix(fmt!(".{}", res!(dns_name(d))))),
82 None => Err(err!(
83 "The suffix rule {:?} must begin with a '.'.", s;
84 Invalid, Input)),
85 },
86 }
87 }
88
89 /// Does the rule admit this host name, already checked and in lower case?
90 pub fn admits(&self, name: &str) -> bool {
91 match self {
92 Self::Exact(n) => name == n,
93 Self::Suffix(s) => name.len() > s.len() && name.ends_with(s.as_str()),
94 }
95 }
96
97 fn subtree(&self) -> GeneralSubtree {
98 match self {
99 Self::Exact(n) => GeneralSubtree::DnsName(n.clone()),
100 Self::Suffix(s) => GeneralSubtree::DnsName(s.trim_start_matches('.').to_string()),
101 }
102 }
103}
104
105/// The host name in lower case without a trailing dot, refused if it is not a DNS host name:
106/// an IP address, a wildcard, an empty or over-long label, or a label with a character outside
107/// letters, digits and `-`.
108pub fn dns_name(s: &str) -> Outcome<String> {
109 let n = s.strip_suffix('.').unwrap_or(s).to_ascii_lowercase();
110 if n.parse::<IpAddr>().is_ok() {
111 return Err(err!("{:?} is an IP address, not a host name.", s; Invalid, Input));
112 }
113 if n.is_empty() || n.len() > 253 {
114 return Err(err!("{:?} is not a host name: it is {} bytes long.", s, n.len();
115 Invalid, Input));
116 }
117 let mut last = "";
118 for label in n.split('.') {
119 let ok = !label.is_empty()
120 && label.len() <= 63
121 && !label.starts_with('-')
122 && !label.ends_with('-')
123 && label.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
124 if !ok {
125 return Err(err!("{:?} is not a host name: its label {:?} is not a DNS label.",
126 s, label; Invalid, Input));
127 }
128 last = label;
129 }
130 // A top-level label of digits alone is how an address in another notation looks.
131 if last.bytes().all(|b| b.is_ascii_digit()) {
132 return Err(err!("{:?} is not a host name: its last label is numeric.", s;
133 Invalid, Input));
134 }
135 Ok(n)
136}
137
138/// An in-memory ECDSA P-256 certificate authority, constrained to the names in its rules, that
139/// issues a 24-hour leaf per host name on demand and serves it by SNI as a rustls
140/// [`ResolvesServerCert`].
141///
142/// The CA's key is held here and nowhere else: no method returns or serialises it, and `Debug`
143/// omits it. The CA certificate carries a critical name-constraints extension permitting the
144/// rules' dNSName subtrees and excluding every IPv4 and IPv6 address, so even a leaked key cannot
145/// vouch for an address or for a name outside the rules to a client that honours the extension.
146pub struct Mint {
147 ca: Certificate, // The CA, with its key.
148 ca_der: CertificateDer<'static>,
149 ca_pem: String,
150 rules: Vec<NameRule>,
151 not_after: i64, // The CA's, in Unix seconds.
152 leaves: Mutex<HashMap<String, (Arc<CertifiedKey>, i64)>>, // Name to leaf and its expiry.
153}
154
155impl fmt::Debug for Mint {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.debug_struct("Mint")
158 .field("rules", &self.rules)
159 .field("not_after", &self.not_after)
160 .finish_non_exhaustive()
161 }
162}
163
164impl Mint {
165
166 /// A new CA, with a fresh key, for the given rules.
167 ///
168 /// # Arguments
169 /// * `ca_days` - the CA's lifetime in days, at least one.
170 pub fn new(names: &[NameRule], ca_days: u32) -> Outcome<Self> {
171 ensure_crypto_provider();
172 let now = res!(now_secs());
173 let (params, rules) = res!(Self::ca_params_at(names, ca_days, now));
174 let ca = res!(Certificate::from_params(params), Init);
175 let der = res!(ca.serialize_der(), Init);
176 let ca_pem = pem_certificate(&der);
177 Ok(Self {
178 ca,
179 ca_der: CertificateDer::from(der),
180 ca_pem,
181 rules,
182 not_after: now + i64::from(ca_days) * 86_400,
183 leaves: Mutex::new(HashMap::new()),
184 })
185 }
186
187 /// The parameters `new` gives its CA, without a key. Public so that a test can build a CA of
188 /// exactly this shape and sign with it what a `Mint` itself never would.
189 ///
190 /// # Arguments
191 /// * `ca_days` - the CA's lifetime in days, at least one.
192 pub fn ca_params(names: &[NameRule], ca_days: u32) -> Outcome<CertificateParams> {
193 let now = res!(now_secs());
194 let (params, _) = res!(Self::ca_params_at(names, ca_days, now));
195 Ok(params)
196 }
197
198 fn ca_params_at(
199 names: &[NameRule],
200 ca_days: u32,
201 now: i64,
202 )
203 -> Outcome<(CertificateParams, Vec<NameRule>)>
204 {
205 // No permitted subtree would be no constraint at all.
206 if names.is_empty() {
207 return Err(err!("A Mint needs at least one name rule."; Invalid, Input, Missing));
208 }
209 if ca_days == 0 {
210 return Err(err!("A Mint's CA must last at least one day."; Invalid, Input));
211 }
212 let mut rules = Vec::with_capacity(names.len());
213 for r in names {
214 rules.push(res!(r.normal()));
215 }
216 let mut p = CertificateParams::default();
217 p.alg = &PKCS_ECDSA_P256_SHA256;
218 validity(&mut p, now - MINT_BACKDATE_SECS, now + i64::from(ca_days) * 86_400);
219 let mut dn = DistinguishedName::new();
220 dn.push(DnType::CommonName, "fe2o3 Mint");
221 p.distinguished_name = dn;
222 p.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
223 p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
224 p.name_constraints = Some(NameConstraints {
225 permitted_subtrees: rules.iter().map(|r| r.subtree()).collect(),
226 excluded_subtrees: vec![
227 GeneralSubtree::IpAddress(CidrSubnet::V4([0; 4], [0; 4])), // 0.0.0.0/0
228 GeneralSubtree::IpAddress(CidrSubnet::V6([0; 16], [0; 16])), // ::/0
229 ],
230 });
231 Ok((p, rules))
232 }
233
234 /// The CA certificate, PEM-encoded, for a client's trust store.
235 pub fn ca_pem(&self) -> String {
236 self.ca_pem.clone()
237 }
238
239 pub fn ca_der(&self) -> CertificateDer<'static> {
240 self.ca_der.clone()
241 }
242
243 pub fn rules(&self) -> &[NameRule] {
244 &self.rules
245 }
246
247 /// Will the CA expire within `secs`? A clock before 1970 counts as yes.
248 pub fn expires_within(&self, secs: u64) -> bool {
249 match now_secs() {
250 Ok(now) => self.not_after.saturating_sub(now) < i64::try_from(secs).unwrap_or(i64::MAX),
251 Err(_) => true,
252 }
253 }
254
255 /// The leaf for `name`, with the chain `[leaf, CA]`, from the cache unless it has under an
256 /// hour left. A name no rule admits is refused.
257 pub fn leaf(&self, name: &str) -> Outcome<Arc<CertifiedKey>> {
258 let name = res!(dns_name(name));
259 if !self.rules.iter().any(|r| r.admits(&name)) {
260 return Err(err!("The Mint refuses {:?}: no name rule admits it.", name;
261 Invalid, Input));
262 }
263 let now = res!(now_secs());
264 let mut leaves = lock_mutex!(self.leaves);
265 if let Some((ck, until)) = leaves.get(&name) {
266 if until - now >= MINT_RENEW_SECS {
267 return Ok(ck.clone());
268 }
269 }
270 let (ck, until) = res!(self.issue(&name, now));
271 // A suffix rule admits names without end, chosen by whoever sends the SNI.
272 if leaves.len() >= MINT_LEAF_CACHE_MAX {
273 leaves.retain(|_, (_, u)| *u - now >= MINT_RENEW_SECS);
274 if leaves.len() >= MINT_LEAF_CACHE_MAX {
275 leaves.clear();
276 }
277 }
278 leaves.insert(name, (ck.clone(), until));
279 Ok(ck)
280 }
281
282 fn issue(&self, name: &str, now: i64) -> Outcome<(Arc<CertifiedKey>, i64)> {
283 let until = std::cmp::min(now + MINT_LEAF_SECS, self.not_after);
284 let mut p = CertificateParams::default();
285 p.alg = &PKCS_ECDSA_P256_SHA256;
286 validity(&mut p, now - MINT_BACKDATE_SECS, until);
287 p.subject_alt_names = vec![SanType::DnsName(name.to_string())];
288 let mut dn = DistinguishedName::new();
289 dn.push(DnType::CommonName, name);
290 p.distinguished_name = dn;
291 p.is_ca = IsCa::ExplicitNoCa;
292 p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
293 p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
294 p.use_authority_key_identifier_extension = true;
295 let cert = res!(Certificate::from_params(p), Init);
296 let der = res!(cert.serialize_der_with_signer(&self.ca), Init);
297 let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.serialize_private_key_der()));
298 let signer = res!(any_ecdsa_type(&key), Init);
299 let chain = vec![CertificateDer::from(der), self.ca_der.clone()];
300 Ok((Arc::new(CertifiedKey::new(chain, signer)), until))
301 }
302}
303
304/// The SNI picks the leaf. No SNI, or a name the `Mint` refuses, answers `None`, and rustls then
305/// aborts the handshake.
306impl ResolvesServerCert for Mint {
307 fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
308 match hello.server_name() {
309 Some(n) => self.leaf(n).ok(),
310 None => None,
311 }
312 }
313}
314
315fn now_secs() -> Outcome<i64> {
316 match SystemTime::now().duration_since(UNIX_EPOCH) {
317 Ok(d) => Ok(i64::try_from(d.as_secs()).unwrap_or(i64::MAX)),
318 Err(e) => Err(err!(e, "The system clock reads before 1970."; Init, Invalid)),
319 }
320}
321
322/// Sets notBefore and notAfter from Unix times, through rcgen's own `OffsetDateTime`, so the
323/// crate need not depend on `time` to name it.
324fn validity(p: &mut CertificateParams, from: i64, to: i64) {
325 let epoch = rcgen::date_time_ymd(1970, 1, 1);
326 p.not_before = epoch + Duration::from_secs(u64::try_from(from).unwrap_or(0));
327 p.not_after = epoch + Duration::from_secs(u64::try_from(to).unwrap_or(0));
328}