Skip to main content

netio/
acme.rs

1// acme -- certificates from a CA that speaks ACME (RFC 8555): Let's Encrypt, ZeroSSL, Google
2// Trust Services, a company's step-ca.  http-01, tls-alpn-01 (RFC 8737) and dns-01 challenges,
3// DNS names and IP addresses (RFC 8738), renewal information (ARI, RFC 9773), external
4// account binding (RFC 8555 7.3.4), profiles, key change, revocation
5//
6//   Acme::new(client, directory_url) -> Result<Acme, AcmeError>     reads the CA's directory
7//   acme.account(key, &NewAccount { contact, terms_agreed, eab, .. }) -> Account
8//   account.issue(&ids, &cert_key, &mut solver, &OrderOptions) -> Issued { chain, pem, .. }
9//       the whole issuance: an order, each authorization proved by `solver`, a certificate
10//       request for `cert_key`, the chain once the CA has issued it
11//   step by step: new_order, authorization, respond, wait_authorization, finalize,
12//       wait_order, certificate
13//   acme.renewal_info(&cert) (ARI: when to renew), account.revoke, change_key, update_contact,
14//       deactivate; revoke_with_key (by the certificate's own key)
15//   Solver: what proves control of a name -- Http01 (a netio Server's handler answers
16//       /.well-known/acme-challenge/), TlsAlpn01 (a tls::ServerConfig that answers
17//       "acme-tls/1"), a DNS provider's code of the program's own (dns01_name, dns01_value)
18//
19// Every request is a JWS (RFC 7515) signed with the account key: ES256 (P-256), ES384 (P-384),
20// RS256 (RSA) or EdDSA (Ed25519; not every CA takes it).  The CA's URLs must be https; its
21// answers are bounded (64 KiB, a certificate chain 1 MiB) and checked: the chain issued must be
22// for the certificate key and every identifier ordered.  A wait for an authorization or the
23// order follows Retry-After and ends after Acme::timeout_ms.
24
25use alloc::boxed::Box;
26use alloc::collections::BTreeMap;
27use alloc::format;
28use alloc::string::{String, ToString};
29use alloc::sync::Arc;
30use alloc::vec::Vec;
31
32use formats::json::{self, Value};
33use crypto::b64;
34use crypto::ecdsa::Curve;
35use crypto::HashAlg;
36use plat::sync::Mutex;
37
38use crate::client::{Client, HttpError};
39use crate::http::{Headers, Request, Response};
40use crate::server::Handler;
41use crate::tls::{Hello, Identity, Select, ServerConfig};
42use crate::url::Url;
43use crate::x509::{self, Cert, CertBuilder, CsrBuilder, IpAddr, PrivateKey, PubKey, SigAlg};
44
45/// Let's Encrypt's directory, and its staging one (for tests: higher rate limits, an untrusted
46/// root)
47pub const LETS_ENCRYPT: &str = "https://acme-v02.api.letsencrypt.org/directory";
48pub const LETS_ENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
49
50/// the ALPN protocol of tls-alpn-01 (RFC 8737 6.2)
51pub const ACME_TLS_ALPN: &str = "acme-tls/1";
52
53/// the longest answer of the CA (JSON), and of a certificate chain
54pub const MAX_ANSWER: usize = 64 * 1024;
55pub const MAX_CHAIN: usize = 1 << 20;
56
57const OID_ACME_IDENTIFIER: &[u64] = &[1, 3, 6, 1, 5, 5, 7, 1, 31];
58
59/// a problem document of the CA (RFC 8555 6.7, RFC 7807)
60#[derive(Clone, Debug, Default, PartialEq, Eq)]
61pub struct Problem {
62    /// the HTTP status of the answer (0 inside an object: an authorization's error)
63    pub status: u16,
64    /// "urn:ietf:params:acme:error:rateLimited", ...
65    pub kind: String,
66    pub detail: String,
67    /// the identifier a subproblem is about (RFC 8555 6.7.1)
68    pub identifier: Option<Identifier>,
69    pub subproblems: Vec<Problem>,
70    /// seconds to wait before trying again (Retry-After), when the CA says
71    pub retry_after: Option<u64>,
72}
73
74impl Problem {
75    /// whether it is the ACME error `name` ("badNonce", "rateLimited", "unauthorized", ...)
76    pub fn is(&self, name: &str) -> bool {
77        self.kind.strip_prefix("urn:ietf:params:acme:error:") == Some(name)
78    }
79
80    fn from_json(v: &Value, status: u16) -> Problem {
81        let s = |k: &str| v.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string();
82        let subproblems = v.get("subproblems").and_then(|x| x.as_array()).map(|a| a.iter().take(64).map(|p| Problem::from_json(p, 0)).collect()).unwrap_or_default();
83        Problem { status, kind: s("type"), detail: s("detail"), identifier: v.get("identifier").and_then(Identifier::from_json), subproblems, retry_after: None }
84    }
85}
86
87impl core::fmt::Display for Problem {
88    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
89        let kind = self.kind.strip_prefix("urn:ietf:params:acme:error:").unwrap_or(&self.kind);
90        write!(f, "{}: {}", kind, self.detail)?;
91        for p in &self.subproblems {
92            write!(f, "; {}", p)?;
93        }
94        Ok(())
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum AcmeError {
101    /// the request did not reach the CA, or no HTTP answer came
102    Http(HttpError),
103    /// the CA refused (its problem document)
104    Problem(Problem),
105    /// an answer of the CA that does not follow RFC 8555
106    Protocol(String),
107    /// an authorization or the order ended invalid (the CA's reason, when it gave one)
108    Invalid(String, Option<Problem>),
109    /// the solver could not set a challenge up
110    Solver(String),
111    /// the CA did not decide within Acme::timeout_ms
112    Timeout(String),
113}
114
115impl core::fmt::Display for AcmeError {
116    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
117        match self {
118            AcmeError::Http(e) => write!(f, "ACME: {}", e),
119            AcmeError::Problem(p) => write!(f, "ACME: the CA refused: {}", p),
120            AcmeError::Protocol(s) => write!(f, "ACME: {}", s),
121            AcmeError::Invalid(s, Some(p)) => write!(f, "ACME: {} ({})", s, p),
122            AcmeError::Invalid(s, None) => write!(f, "ACME: {}", s),
123            AcmeError::Solver(s) => write!(f, "ACME: the challenge could not be set up: {}", s),
124            AcmeError::Timeout(s) => write!(f, "ACME: {}", s),
125        }
126    }
127}
128
129impl From<HttpError> for AcmeError {
130    fn from(e: HttpError) -> Self {
131        AcmeError::Http(e)
132    }
133}
134
135fn proto(s: &str) -> AcmeError {
136    AcmeError::Protocol(String::from(s))
137}
138
139/// what a certificate is for
140#[derive(Clone, Debug, PartialEq, Eq)]
141pub enum Identifier {
142    /// a DNS name, lower case; "*.example.com" for a wildcard (dns-01 only)
143    Dns(String),
144    /// an IP address (RFC 8738)
145    Ip(IpAddr),
146}
147
148impl Identifier {
149    /// a name or an address ("example.com", "*.example.com", "192.0.2.1", "2001:db8::1")
150    pub fn parse(s: &str) -> Identifier {
151        match IpAddr::parse(s.trim_matches(['[', ']'])) {
152            Some(ip) => Identifier::Ip(ip),
153            None => Identifier::Dns(s.to_ascii_lowercase()),
154        }
155    }
156
157    /// the text of the identifier (an address in its RFC 5952 form)
158    pub fn value(&self) -> String {
159        match self {
160            Identifier::Dns(d) => d.clone(),
161            Identifier::Ip(ip) => format!("{}", ip),
162        }
163    }
164
165    fn to_json(&self) -> Value {
166        let ty = if matches!(self, Identifier::Dns(_)) { "dns" } else { "ip" };
167        Value::object([("type", Value::string(ty)), ("value", Value::string(self.value()))])
168    }
169
170    fn from_json(v: &Value) -> Option<Identifier> {
171        let value = v.get("value")?.as_str()?;
172        match v.get("type")?.as_str()? {
173            "dns" => Some(Identifier::Dns(value.to_ascii_lowercase())),
174            "ip" => IpAddr::parse(value).map(Identifier::Ip),
175            _ => None,
176        }
177    }
178
179    /// the name a validator puts in server_name for tls-alpn-01: the name, or for an address
180    /// its reverse DNS name (RFC 8738 6)
181    pub fn tls_name(&self) -> String {
182        match self {
183            Identifier::Dns(d) => d.clone(),
184            Identifier::Ip(IpAddr::V4(a)) => format!("{}.{}.{}.{}.in-addr.arpa", a[3], a[2], a[1], a[0]),
185            Identifier::Ip(IpAddr::V6(a)) => {
186                let mut s = String::new();
187                for b in a.iter().rev() {
188                    s.push_str(&format!("{:x}.{:x}.", b & 0xf, b >> 4));
189                }
190                s.push_str("ip6.arpa");
191                s
192            }
193        }
194    }
195}
196
197/// the CA's directory (RFC 8555 7.1.1)
198#[derive(Clone, Debug, Default, PartialEq, Eq)]
199pub struct Directory {
200    pub new_nonce: String,
201    pub new_account: String,
202    pub new_order: String,
203    pub revoke_cert: String,
204    pub key_change: String,
205    /// pre-authorization (most CAs have none)
206    pub new_authz: Option<String>,
207    /// renewal information (RFC 9773)
208    pub renewal_info: Option<String>,
209    /// what an account must agree to (NewAccount::terms_agreed)
210    pub terms_of_service: Option<String>,
211    pub website: Option<String>,
212    /// the names a CAA record must name for this CA
213    pub caa_identities: Vec<String>,
214    /// accounts need an external account binding (NewAccount::eab)
215    pub external_account_required: bool,
216    /// the certificate profiles offered: (name, description)
217    pub profiles: Vec<(String, String)>,
218}
219
220/// an answer of the CA, and the URL it answered
221struct Answer {
222    status: u16,
223    headers: Headers,
224    body: Vec<u8>,
225    url: String,
226}
227
228impl Answer {
229    fn json(&self) -> Result<Value, AcmeError> {
230        let limits = json::Limits { bytes: MAX_ANSWER, ..json::Limits::default() };
231        json::parse_with_limits(&self.body, limits).map_err(|_| proto("an answer of the CA that is not JSON"))
232    }
233
234    fn location(&self) -> Result<String, AcmeError> {
235        let l = self.headers.get("Location").ok_or_else(|| proto("an answer without Location"))?;
236        https_url(&resolve(&self.url, l))
237    }
238
239    fn retry_after(&self) -> Option<u64> {
240        retry_after(self.headers.get("Retry-After")?)
241    }
242
243    /// the URLs of Link headers with this relation (RFC 8288: <url>;rel="up")
244    fn links(&self, rel: &str) -> Vec<String> {
245        let mut out = Vec::new();
246        for (k, v) in &self.headers.0 {
247            if !k.eq_ignore_ascii_case("link") {
248                continue;
249            }
250            for part in v.split(',') {
251                let Some((url, params)) = part.trim().strip_prefix('<').and_then(|p| p.split_once('>')) else { continue };
252                let has = params.split(';').any(|p| {
253                    let p = p.trim();
254                    p.strip_prefix("rel=").is_some_and(|r| r.trim_matches('"').split_ascii_whitespace().any(|x| x.eq_ignore_ascii_case(rel)))
255                });
256                if has {
257                    if let Ok(u) = https_url(&resolve(&self.url, url)) {
258                        out.push(u);
259                    }
260                }
261            }
262        }
263        out
264    }
265}
266
267/// a URL of a Location or Link header against the URL of the request (RFC 9110 10.2.2,
268/// RFC 8288 3.2), as RFC 3986 5.2 resolves a reference: absolute on its own authority,
269/// "//host/path" on the request's scheme, "/path" on its origin, else beside its path; "." and
270/// ".." taken out of the path every time (host, port and query as they are)
271fn resolve(base: &str, r: &str) -> String {
272    // a scheme: an absolute URL
273    let scheme_end = r.find(':').filter(|&i| i > 0 && !r[..i].contains(['/', '?', '#']));
274    if let Some(i) = scheme_end {
275        return match r[i + 1..].strip_prefix("//") {
276            Some(rest) => format!("{}://{}", &r[..i], authority_path(rest)),
277            None => String::from(r),
278        };
279    }
280    let Some(u) = Url::parse(base) else { return String::from(r) };
281    let scheme = base.split_once(':').map_or("https", |(s, _)| s);
282    if let Some(rest) = r.strip_prefix("//") {
283        return format!("{}://{}", scheme, authority_path(rest));
284    }
285    let path = u.target.split(['?', '#']).next().unwrap_or("");
286    if r.is_empty() || r.starts_with('#') {
287        let no_frag = u.target.split('#').next().unwrap_or("");
288        return format!("{}{}{}", u.origin(), no_frag, r);
289    }
290    if r.starts_with('?') {
291        return format!("{}{}{}", u.origin(), path, r);
292    }
293    let merged = if r.starts_with('/') { String::from(r) } else { format!("{}/{}", path.rsplit_once('/').map_or("", |(d, _)| d), r) };
294    format!("{}{}", u.origin(), remove_dots(&merged))
295}
296
297/// "authority/path?query" with the path's "." and ".." segments taken out
298fn authority_path(rest: &str) -> String {
299    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
300    let (auth, tail) = rest.split_at(end);
301    if tail.starts_with('/') { format!("{}{}", auth, remove_dots(tail)) } else { String::from(rest) }
302}
303
304/// a path without its "." and ".." segments (RFC 3986 5.2.4); the query stays as it is
305fn remove_dots(p: &str) -> String {
306    let (path, rest) = match p.find(['?', '#']) {
307        Some(i) => p.split_at(i),
308        None => (p, ""),
309    };
310    let mut out: Vec<&str> = Vec::new();
311    let segs: Vec<&str> = path.split('/').skip(1).collect();
312    for (i, seg) in segs.iter().enumerate() {
313        let last = i + 1 == segs.len();
314        match *seg {
315            "." => {
316                if last {
317                    out.push("");
318                }
319            }
320            ".." => {
321                out.pop();
322                if last {
323                    out.push("");
324                }
325            }
326            s => out.push(s),
327        }
328    }
329    format!("/{}{}", out.join("/"), rest)
330}
331
332/// an https URL of the CA (RFC 8555 6.1: every ACME URL is https)
333fn https_url(s: &str) -> Result<String, AcmeError> {
334    match Url::parse(s) {
335        Some(u) if u.is_https() => Ok(String::from(s)),
336        _ => Err(AcmeError::Protocol(format!("a URL of the CA that is not https: {}", s.chars().take(200).collect::<String>()))),
337    }
338}
339
340fn url_of(v: &Value, key: &str) -> Result<String, AcmeError> {
341    https_url(v.get(key).and_then(|x| x.as_str()).ok_or_else(|| AcmeError::Protocol(format!("no {} in the answer", key)))?)
342}
343
344fn opt_url(v: &Value, key: &str) -> Result<Option<String>, AcmeError> {
345    v.get(key).and_then(|x| x.as_str()).map(https_url).transpose()
346}
347
348fn str_of(v: &Value, key: &str) -> String {
349    v.get(key).and_then(|x| x.as_str()).unwrap_or("").to_string()
350}
351
352/// Retry-After: seconds, or an HTTP date (IMF-fixdate) -> seconds from now; at most a day
353fn retry_after(v: &str) -> Option<u64> {
354    let v = v.trim();
355    if let Ok(s) = v.parse::<u64>() {
356        return Some(s.min(86_400));
357    }
358    let t = http_date(v)?;
359    let now = plat::unix_time_ns().div_euclid(1_000_000_000);
360    Some((t - now).clamp(0, 86_400) as u64)
361}
362
363fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
364    let y = if m <= 2 { y - 1 } else { y };
365    let era = y.div_euclid(400);
366    let yoe = y - era * 400;
367    let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
368    era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
369}
370
371/// "Sun, 06 Nov 1994 08:49:37 GMT" -> Unix seconds
372fn http_date(s: &str) -> Option<i64> {
373    let p: Vec<&str> = s.split_ascii_whitespace().collect();
374    if p.len() != 6 || p[5] != "GMT" {
375        return None;
376    }
377    // IMF-fixdate (RFC 9110 5.6.7): "Sun, 06 Nov 1994 08:49:37 GMT", every number of its digits
378    let digits = |x: &str, n: usize| x.len() == n && x.bytes().all(|c| c.is_ascii_digit());
379    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
380    let m = months.iter().position(|x| *x == p[2])? as i64 + 1;
381    let hms: Vec<&str> = p[4].split(':').collect();
382    if !digits(p[1], 2) || !digits(p[3], 4) || hms.len() != 3 || !hms.iter().all(|x| digits(x, 2)) {
383        return None;
384    }
385    let d: i64 = p[1].parse().ok()?;
386    let y: i64 = p[3].parse().ok()?;
387    let hms: Vec<i64> = hms.iter().map(|x| x.parse().ok()).collect::<Option<Vec<i64>>>()?;
388    if !(1..=31).contains(&d) || hms[0] > 23 || hms[1] > 59 || hms[2] > 60 {
389        return None;
390    }
391    Some(days_from_civil(y, m, d) * 86_400 + hms[0] * 3600 + hms[1] * 60 + hms[2])
392}
393
394/// an RFC 3339 time ("2026-11-24T08:00:00Z", fractions, an offset) -> Unix seconds
395pub fn rfc3339(s: &str) -> Option<i64> {
396    let b = s.as_bytes();
397    if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || !matches!(b[10], b'T' | b't' | b' ') || b[13] != b':' || b[16] != b':' {
398        return None;
399    }
400    let n = |r: core::ops::Range<usize>| s.get(r).filter(|x| x.bytes().all(|c| c.is_ascii_digit())).and_then(|x| x.parse::<i64>().ok());
401    let (y, mo, d, h, mi, se) = (n(0..4)?, n(5..7)?, n(8..10)?, n(11..13)?, n(14..16)?, n(17..19)?);
402    if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {
403        return None;
404    }
405    let mut i = 19;
406    if b.get(i) == Some(&b'.') {
407        i += 1;
408        let start = i;
409        while b.get(i).is_some_and(|c| c.is_ascii_digit()) {
410            i += 1;
411        }
412        if i == start {
413            return None;
414        }
415    }
416    let off = match b.get(i) {
417        Some(b'Z' | b'z') if i + 1 == b.len() => 0,
418        Some(c @ (b'+' | b'-')) if i + 6 == b.len() && b[i + 3] == b':' => {
419            let (oh, om) = (n(i + 1..i + 3)?, n(i + 4..i + 6)?);
420            let o = oh * 3600 + om * 60;
421            if *c == b'+' { o } else { -o }
422        }
423        _ => return None,
424    };
425    Some(days_from_civil(y, mo, d) * 86_400 + h * 3600 + mi * 60 + se - off)
426}
427
428/// Unix seconds -> "2026-11-24T08:00:00Z"
429pub fn rfc3339_text(t: i64) -> String {
430    let z = t.div_euclid(86_400) + 719_468;
431    let era = z.div_euclid(146_097);
432    let doe = z - era * 146_097;
433    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
434    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
435    let mp = (5 * doy + 2) / 153;
436    let d = doy - (153 * mp + 2) / 5 + 1;
437    let m = if mp < 10 { mp + 3 } else { mp - 9 };
438    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
439    let s = t.rem_euclid(86_400);
440    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, m, d, s / 3600, s / 60 % 60, s % 60)
441}
442
443// ------------------------------------------------------------------ keys and JWS
444
445/// the JWS algorithm of an account key
446fn jws_alg(key: &PrivateKey) -> Result<(&'static str, SigAlg), AcmeError> {
447    match key.public_key() {
448        PubKey::Ec { curve: Curve::P256, .. } => Ok(("ES256", SigAlg::Ecdsa(HashAlg::Sha256))),
449        PubKey::Ec { curve: Curve::P384, .. } => Ok(("ES384", SigAlg::Ecdsa(HashAlg::Sha384))),
450        PubKey::Rsa { .. } => Ok(("RS256", SigAlg::RsaPkcs1(HashAlg::Sha256))),
451        PubKey::Ed25519(_) => Ok(("EdDSA", SigAlg::Ed25519)),
452        _ => Err(proto("an account key of a kind ACME does not take")),
453    }
454}
455
456/// the public JWK of a key (RFC 7517, 7518 6, RFC 8037), its members in the order of RFC 7638
457/// (the thumbprint hashes exactly this text)
458fn jwk_text(key: &PubKey) -> Result<String, AcmeError> {
459    let u = b64::encode_url;
460    match key {
461        PubKey::Ec { curve, point } => {
462            let n = curve.bytes();
463            let crv = if *curve == Curve::P256 { "P-256" } else { "P-384" };
464            // the uncompressed point: 0x04 x y
465            if point.len() != 1 + 2 * n || point[0] != 4 {
466                return Err(proto("an EC key that is not an uncompressed point"));
467            }
468            Ok(format!(r#"{{"crv":"{}","kty":"EC","x":"{}","y":"{}"}}"#, crv, u(&point[1..1 + n]), u(&point[1 + n..])))
469        }
470        PubKey::Rsa { n, e } => Ok(format!(r#"{{"e":"{}","kty":"RSA","n":"{}"}}"#, u(e), u(n))),
471        PubKey::Ed25519(k) => Ok(format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, u(k))),
472        _ => Err(proto("an account key of a kind ACME does not take")),
473    }
474}
475
476fn jwk(key: &PubKey) -> Result<Value, AcmeError> {
477    json::parse(jwk_text(key)?.as_bytes()).map_err(|_| proto("JWK"))
478}
479
480/// the JWK thumbprint (RFC 7638, SHA-256), base64url
481pub fn thumbprint(key: &PubKey) -> Option<String> {
482    jwk_text(key).ok().map(|t| b64::encode_url(&crypto::sha256(t.as_bytes())))
483}
484
485/// a flattened JWS (RFC 7515 7.2.2) of `payload` (None: the empty payload of POST-as-GET)
486fn jws(key: &PrivateKey, protected: Value, payload: Option<&Value>) -> Result<Value, AcmeError> {
487    let (_, alg) = jws_alg(key)?;
488    let p64 = b64::encode_url(json::stringify(&protected).map_err(|_| proto("JWS header"))?.as_bytes());
489    let body64 = match payload {
490        Some(v) => b64::encode_url(json::stringify(v).map_err(|_| proto("JWS payload"))?.as_bytes()),
491        None => String::new(),
492    };
493    let input = format!("{}.{}", p64, body64);
494    let random = plat::random_bytes::<32>();
495    let sig = key.sign(alg, input.as_bytes(), &random).ok_or_else(|| proto("the account key cannot sign"))?;
496    // ECDSA in JWS: r || s of the curve's size (RFC 7518 3.4), not DER
497    let sig = match key.public_key() {
498        PubKey::Ec { curve, .. } => crypto::ecdsa::p1363_from_der(curve, &sig).ok_or_else(|| proto("ECDSA signature"))?,
499        _ => sig,
500    };
501    Ok(Value::object([("protected", Value::string(p64)), ("payload", Value::string(body64)), ("signature", Value::string(b64::encode_url(&sig)))]))
502}
503
504/// an external account binding (RFC 8555 7.3.4): the key id and MAC key the CA handed out
505#[derive(Clone)]
506pub struct Eab {
507    pub kid: String,
508    pub hmac_key: Vec<u8>,
509}
510
511impl Eab {
512    /// the key id and the MAC key as the CA shows it (base64url)
513    pub fn new(kid: &str, hmac_key_b64: &str) -> Option<Eab> {
514        let k = b64::decode_url(hmac_key_b64.trim()).filter(|k| !k.is_empty())?;
515        Some(Eab { kid: String::from(kid), hmac_key: k })
516    }
517}
518
519impl core::fmt::Debug for Eab {
520    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
521        write!(f, "Eab({})", self.kid)
522    }
523}
524
525impl Drop for Eab {
526    fn drop(&mut self) {
527        crypto::zeroize(&mut self.hmac_key);
528    }
529}
530
531/// a new (or existing) account
532#[derive(Clone, Debug, Default)]
533pub struct NewAccount {
534    /// "mailto:admin@example.com" (some CAs need one; Let's Encrypt no longer writes to them)
535    pub contact: Vec<String>,
536    /// the directory's terms of service agreed to
537    pub terms_agreed: bool,
538    /// only find the account of the key, make none (RFC 8555 7.3.1)
539    pub only_existing: bool,
540    pub eab: Option<Eab>,
541}
542
543/// an order's options
544#[derive(Clone, Debug, Default)]
545pub struct OrderOptions {
546    /// the validity asked for (Unix seconds; most CAs decide it themselves)
547    pub not_before: Option<i64>,
548    pub not_after: Option<i64>,
549    /// a profile of the directory's (Directory::profiles)
550    pub profile: Option<String>,
551    /// the certificate this one replaces (its ARI id, ari_id): the CA can tell a renewal
552    pub replaces: Option<String>,
553    /// a certificate that must come with a stapled OCSP response (RFC 7633; not every CA
554    /// issues them)
555    pub must_staple: bool,
556}
557
558#[derive(Clone, Debug, PartialEq, Eq)]
559pub struct Order {
560    pub url: String,
561    /// "pending", "ready", "processing", "valid", "invalid"
562    pub status: String,
563    pub expires: Option<i64>,
564    pub identifiers: Vec<Identifier>,
565    pub authorizations: Vec<String>,
566    pub finalize: String,
567    pub certificate: Option<String>,
568    pub error: Option<Problem>,
569    pub profile: Option<String>,
570}
571
572impl Order {
573    fn from_json(url: String, v: &Value) -> Result<Order, AcmeError> {
574        let ids = v.get("identifiers").and_then(|x| x.as_array()).ok_or_else(|| proto("an order without identifiers"))?;
575        let identifiers: Vec<Identifier> = ids.iter().map(Identifier::from_json).collect::<Option<Vec<_>>>().ok_or_else(|| proto("an order's identifier"))?;
576        let authz = v.get("authorizations").and_then(|x| x.as_array()).ok_or_else(|| proto("an order without authorizations"))?;
577        if authz.len() > 256 {
578            return Err(proto("an order with too many authorizations"));
579        }
580        let authorizations = authz.iter().map(|a| a.as_str().ok_or_else(|| proto("an authorization URL")).and_then(https_url)).collect::<Result<Vec<_>, _>>()?;
581        Ok(Order {
582            url,
583            status: str_of(v, "status"),
584            expires: v.get("expires").and_then(|x| x.as_str()).and_then(rfc3339),
585            identifiers,
586            authorizations,
587            finalize: url_of(v, "finalize")?,
588            certificate: opt_url(v, "certificate")?,
589            error: v.get("error").map(|e| Problem::from_json(e, 0)),
590            profile: v.get("profile").and_then(|x| x.as_str()).map(String::from),
591        })
592    }
593}
594
595#[derive(Clone, Debug, PartialEq, Eq)]
596pub struct Challenge {
597    /// "http-01", "tls-alpn-01", "dns-01", ...
598    pub kind: String,
599    pub url: String,
600    /// "pending", "processing", "valid", "invalid"
601    pub status: String,
602    /// base64url (checked: only its alphabet, 16 to 256 characters)
603    pub token: String,
604    pub error: Option<Problem>,
605}
606
607#[derive(Clone, Debug, PartialEq, Eq)]
608pub struct Authorization {
609    pub url: String,
610    /// "pending", "valid", "invalid", "deactivated", "expired", "revoked"
611    pub status: String,
612    pub identifier: Identifier,
613    /// for "*." plus the identifier (dns-01 only)
614    pub wildcard: bool,
615    pub expires: Option<i64>,
616    pub challenges: Vec<Challenge>,
617}
618
619fn token_ok(t: &str) -> bool {
620    (16..=256).contains(&t.len()) && t.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
621}
622
623impl Authorization {
624    fn from_json(url: String, v: &Value) -> Result<Authorization, AcmeError> {
625        let identifier = v.get("identifier").and_then(Identifier::from_json).ok_or_else(|| proto("an authorization's identifier"))?;
626        let mut challenges = Vec::new();
627        for c in v.get("challenges").and_then(|x| x.as_array()).ok_or_else(|| proto("an authorization without challenges"))?.iter().take(32) {
628            let token = str_of(c, "token");
629            let kind = str_of(c, "type");
630            // a challenge of a type this client does not know may carry anything
631            if matches!(kind.as_str(), "http-01" | "tls-alpn-01" | "dns-01") && !token_ok(&token) {
632                return Err(proto("a challenge token that is not base64url"));
633            }
634            challenges.push(Challenge { kind, url: url_of(c, "url")?, status: str_of(c, "status"), token, error: c.get("error").map(|e| Problem::from_json(e, 0)) });
635        }
636        Ok(Authorization {
637            url,
638            status: str_of(v, "status"),
639            identifier,
640            wildcard: v.get("wildcard").and_then(|x| x.as_bool()).unwrap_or(false),
641            expires: v.get("expires").and_then(|x| x.as_str()).and_then(rfc3339),
642            challenges,
643        })
644    }
645
646    /// what the CA said went wrong (the first challenge's error)
647    fn problem(&self) -> Option<Problem> {
648        self.challenges.iter().find_map(|c| c.error.clone())
649    }
650}
651
652/// a certificate issued
653#[derive(Clone, Debug)]
654pub struct Issued {
655    /// DER, leaf first
656    pub chain: Vec<Vec<u8>>,
657    /// the chain as the CA sent it (PEM): for the server's certificate file
658    pub pem: String,
659    /// other chains the CA offers (Link rel="alternate"; Acme::certificate fetches them)
660    pub alternates: Vec<String>,
661    pub order: Order,
662}
663
664impl Issued {
665    /// the identity for a TLS server: the chain and the certificate key
666    pub fn identity(&self, key: &PrivateKey) -> Identity {
667        Identity::new(self.chain.clone(), key.clone())
668    }
669}
670
671/// when to renew a certificate (ARI, RFC 9773)
672#[derive(Clone, Debug, PartialEq, Eq)]
673pub struct RenewalInfo {
674    /// the window the CA suggests (Unix seconds): renew at a random time in it
675    pub start: i64,
676    pub end: i64,
677    pub explanation: Option<String>,
678    /// when to ask again (seconds, Retry-After; 6 hours when the CA does not say)
679    pub retry_after: u64,
680}
681
682impl RenewalInfo {
683    /// a time in the window to renew at: start + (end - start) * fraction (a random fraction in
684    /// [0, 1) spreads the renewals out, as RFC 9773 4.2 asks)
685    pub fn renew_at(&self, fraction: f64) -> i64 {
686        let span = (self.end - self.start).max(0) as f64;
687        self.start + (span * fraction.clamp(0.0, 1.0)) as i64
688    }
689}
690
691/// a certificate's id in renewal information and in an order's "replaces" (RFC 9773 4.1): the
692/// key identifier of its authority key identifier and its serial number; None without the
693/// former
694pub fn ari_id(cert: &Cert) -> Option<String> {
695    if cert.aki.is_empty() || cert.serial.is_empty() {
696        return None;
697    }
698    Some(format!("{}.{}", b64::encode_url(&cert.aki), b64::encode_url(&cert.serial)))
699}
700
701// ------------------------------------------------------------------ the client
702
703/// the client of one CA (cheap to clone: the clones share the nonces)
704#[derive(Clone)]
705pub struct Acme {
706    client: Client,
707    pub directory: Arc<Directory>,
708    nonces: Arc<Mutex<Vec<String>>>,
709    /// the longest wait for an authorization or the order to be decided (ms; 3 minutes)
710    pub timeout_ms: u64,
711    /// the pause between two looks at an authorization or the order when the CA sends no
712    /// Retry-After (ms; 2 seconds)
713    pub poll_ms: u32,
714    /// the longest pause taken from a Retry-After (ms; 30 s); a shorter Retry-After counts as
715    /// at least half a second (or max_poll_ms, when that is less). No pause of either kind goes
716    /// past timeout_ms: the last one ends at it
717    pub max_poll_ms: u32,
718}
719
720impl Acme {
721    /// the CA at `directory` (an https URL: LETS_ENCRYPT, ...) over `client` (with an https
722    /// connector: trust::system_connector for public CAs)
723    pub fn new(client: Client, directory: &str) -> Result<Acme, AcmeError> {
724        let url = Url::parse(&https_url(directory)?).ok_or_else(|| proto("the directory URL"))?;
725        let mut c = client;
726        c.max_body = MAX_ANSWER;
727        let r = c.request("GET", &url, &Headers::new(), &[])?;
728        let a = Answer { status: r.status, headers: r.headers.clone(), body: Vec::from(r.body_bytes()), url: String::from(directory) };
729        if a.status != 200 {
730            return Err(AcmeError::Protocol(format!("the directory answered HTTP {}", a.status)));
731        }
732        let v = a.json()?;
733        let meta = v.get("meta");
734        let ms = |k: &str| meta.and_then(|m| m.get(k)).and_then(|x| x.as_str()).map(String::from);
735        let dir = Directory {
736            new_nonce: url_of(&v, "newNonce")?,
737            new_account: url_of(&v, "newAccount")?,
738            new_order: url_of(&v, "newOrder")?,
739            revoke_cert: url_of(&v, "revokeCert")?,
740            key_change: url_of(&v, "keyChange")?,
741            new_authz: opt_url(&v, "newAuthz")?,
742            renewal_info: opt_url(&v, "renewalInfo")?,
743            terms_of_service: ms("termsOfService"),
744            website: ms("website"),
745            caa_identities: meta.and_then(|m| m.get("caaIdentities")).and_then(|x| x.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default(),
746            external_account_required: meta.and_then(|m| m.get("externalAccountRequired")).and_then(|x| x.as_bool()).unwrap_or(false),
747            profiles: meta.and_then(|m| m.get("profiles")).and_then(|x| x.as_object()).map(|o| o.iter().map(|(k, d)| (k.clone(), d.as_str().unwrap_or("").to_string())).collect()).unwrap_or_default(),
748        };
749        Ok(Acme { client: c, directory: Arc::new(dir), nonces: Arc::new(Mutex::new(Vec::new())), timeout_ms: 180_000, poll_ms: 2000, max_poll_ms: 30_000 })
750    }
751
752    fn send(&self, method: &str, url: &str, headers: &Headers, body: &[u8], max: usize) -> Result<Answer, AcmeError> {
753        let u = Url::parse(&https_url(url)?).ok_or_else(|| proto("a URL of the CA"))?;
754        let mut c = self.client.clone();
755        c.max_body = max;
756        let r = c.request(method, &u, headers, body)?;
757        Ok(Answer { status: r.status, headers: r.headers.clone(), body: Vec::from(r.body_bytes()), url: String::from(url) })
758    }
759
760    /// the nonce of an answer: base64url (RFC 8555 6.5.1)
761    fn nonce_of(a: &Answer) -> Option<String> {
762        a.headers.get("Replay-Nonce").filter(|n| !n.is_empty() && n.len() <= 256 && n.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')).map(String::from)
763    }
764
765    /// keep the nonce of an answer for the next request (of this client or a clone)
766    fn keep_nonce(&self, a: &Answer) {
767        if let Some(n) = Self::nonce_of(a) {
768            let mut v = self.nonces.lock();
769            if v.len() >= 16 {
770                v.remove(0);
771            }
772            v.push(n);
773        }
774    }
775
776    /// a nonce kept, else a new one from newNonce (that one is this request's alone)
777    fn nonce(&self) -> Result<String, AcmeError> {
778        if let Some(n) = self.nonces.lock().pop() {
779            return Ok(n);
780        }
781        let dn = self.directory.new_nonce.clone();
782        let a = self.send("HEAD", &dn, &Headers::new(), &[], 0)?;
783        if !(a.status == 200 || a.status == 204) {
784            return Err(AcmeError::Protocol(format!("newNonce answered HTTP {}", a.status)));
785        }
786        Self::nonce_of(&a).ok_or_else(|| proto("newNonce gave no Replay-Nonce"))
787    }
788
789    /// a signed POST: kid (an account's URL) or the key's JWK in the header; a badNonce is
790    /// tried again with the nonce of that answer (RFC 8555 6.5: the retry's own, not shared
791    /// with the clones); the nonces of other answers are kept for the next requests
792    fn post(&self, key: &PrivateKey, kid: Option<&str>, url: &str, payload: Option<&Value>, max: usize) -> Result<Answer, AcmeError> {
793        self.post_until(key, kid, url, payload, max, None)
794    }
795
796    /// post, but none sent once `deadline` (ms) is reached: Timeout then (checked before the
797    /// nonce, and again right before the POST goes, after a slow newNonce and the signing)
798    fn post_until(&self, key: &PrivateKey, kid: Option<&str>, url: &str, payload: Option<&Value>, max: usize, deadline: Option<u64>) -> Result<Answer, AcmeError> {
799        let (alg, _) = jws_alg(key)?;
800        let in_time = || deadline.map_or(Ok(()), Account::in_time);
801        let mut next: Option<String> = None;
802        for attempt in 0..3 {
803            in_time()?;
804            let nonce = match next.take() {
805                Some(n) => n,
806                None => self.nonce()?,
807            };
808            let mut protected = Value::object([("alg", Value::string(alg)), ("nonce", Value::string(nonce)), ("url", Value::string(url))]);
809            match kid {
810                Some(k) => protected.insert("kid", Value::string(k)),
811                None => protected.insert("jwk", jwk(&key.public_key())?),
812            };
813            let body = json::stringify(&jws(key, protected, payload)?).map_err(|_| proto("JWS"))?;
814            let mut h = Headers::new();
815            h.set("Content-Type", "application/jose+json");
816            in_time()?;
817            let a = self.send("POST", url, &h, body.as_bytes(), max)?;
818            if a.status < 400 {
819                self.keep_nonce(&a);
820                return Ok(a);
821            }
822            let p = self.problem(&a);
823            if p.is("badNonce") && attempt < 2 {
824                next = Self::nonce_of(&a);
825                continue;
826            }
827            self.keep_nonce(&a);
828            return Err(AcmeError::Problem(p));
829        }
830        Err(proto("the CA refused every nonce"))
831    }
832
833    fn problem(&self, a: &Answer) -> Problem {
834        let mut p = match a.json() {
835            Ok(v) => Problem::from_json(&v, a.status),
836            Err(_) => Problem { status: a.status, detail: String::from_utf8_lossy(&a.body[..a.body.len().min(300)]).into_owned(), ..Problem::default() },
837        };
838        p.retry_after = a.retry_after();
839        p
840    }
841
842    /// the account of `key` (made when there is none and new.only_existing is false)
843    pub fn account(&self, key: PrivateKey, new: &NewAccount) -> Result<Account, AcmeError> {
844        jws_alg(&key)?;
845        if self.directory.external_account_required && new.eab.is_none() && !new.only_existing {
846            return Err(proto("this CA needs an external account binding (NewAccount::eab)"));
847        }
848        let mut payload = Value::object([("termsOfServiceAgreed", Value::Bool(new.terms_agreed))]);
849        if !new.contact.is_empty() {
850            payload.insert("contact", Value::Array(new.contact.iter().map(|c| Value::string(c.as_str())).collect()));
851        }
852        if new.only_existing {
853            payload.insert("onlyReturnExisting", Value::Bool(true));
854        }
855        let url = self.directory.new_account.clone();
856        if let Some(eab) = &new.eab {
857            payload.insert("externalAccountBinding", eab_jws(eab, &key, &url)?);
858        }
859        let a = self.post(&key, None, &url, Some(&payload), MAX_ANSWER)?;
860        if a.status != 200 && a.status != 201 {
861            return Err(AcmeError::Protocol(format!("newAccount answered HTTP {}", a.status)));
862        }
863        let v = a.json()?;
864        let mut acc = Account { acme: self.clone(), key, url: a.location()?, status: String::new(), contact: Vec::new(), created: a.status == 201 };
865        acc.read(&v);
866        if acc.status != "valid" {
867            return Err(AcmeError::Invalid(format!("the account is {}", acc.status), None));
868        }
869        Ok(acc)
870    }
871
872    /// when the CA suggests renewing `cert` (ARI, RFC 9773); Err when the directory has no
873    /// renewalInfo or the certificate no authority key identifier
874    pub fn renewal_info(&self, cert: &Cert) -> Result<RenewalInfo, AcmeError> {
875        let base = self.directory.renewal_info.clone().ok_or_else(|| proto("the CA offers no renewal information"))?;
876        let id = ari_id(cert).ok_or_else(|| proto("the certificate has no authority key identifier"))?;
877        let url = format!("{}/{}", base.trim_end_matches('/'), id);
878        let a = self.send("GET", &url, &Headers::new(), &[], MAX_ANSWER)?;
879        if a.status != 200 {
880            return Err(AcmeError::Problem(self.problem(&a)));
881        }
882        let v = a.json()?;
883        let w = v.get("suggestedWindow").ok_or_else(|| proto("renewal information without suggestedWindow"))?;
884        let t = |k: &str| w.get(k).and_then(|x| x.as_str()).and_then(rfc3339).ok_or_else(|| proto("a renewal window's time"));
885        let (start, end) = (t("start")?, t("end")?);
886        if end < start {
887            return Err(proto("a renewal window that ends before it starts"));
888        }
889        Ok(RenewalInfo { start, end, explanation: opt_url(&v, "explanationURL")?, retry_after: a.retry_after().unwrap_or(6 * 3600).max(60) })
890    }
891
892    /// a chain of the CA (POST-as-GET to a certificate URL; for an alternate chain too), signed
893    /// with `key` and `kid` of the account
894    fn fetch_chain(&self, key: &PrivateKey, kid: &str, url: &str) -> Result<(Vec<Vec<u8>>, String, Vec<String>), AcmeError> {
895        let a = self.post(key, Some(kid), url, None, MAX_CHAIN)?;
896        if a.status != 200 {
897            return Err(AcmeError::Protocol(format!("the certificate answered HTTP {}", a.status)));
898        }
899        let pem = String::from_utf8(a.body.clone()).map_err(|_| proto("a certificate chain that is not PEM"))?;
900        let chain = crate::pem::decode_all(&pem, "CERTIFICATE");
901        if chain.is_empty() || chain.iter().any(|c| Cert::parse(c).is_none()) {
902            return Err(proto("a certificate chain that cannot be read"));
903        }
904        Ok((chain, pem, a.links("alternate")))
905    }
906}
907
908/// the binding of a new account to the CA's key id (a JWS with HS256 over the account's JWK)
909fn eab_jws(eab: &Eab, key: &PrivateKey, url: &str) -> Result<Value, AcmeError> {
910    let protected = Value::object([("alg", Value::string("HS256")), ("kid", Value::string(eab.kid.as_str())), ("url", Value::string(url))]);
911    let p64 = b64::encode_url(json::stringify(&protected).map_err(|_| proto("EAB"))?.as_bytes());
912    let body64 = b64::encode_url(jwk_text(&key.public_key())?.as_bytes());
913    let mac = crypto::hmac::hmac_sha256(&eab.hmac_key, format!("{}.{}", p64, body64).as_bytes());
914    Ok(Value::object([("protected", Value::string(p64)), ("payload", Value::string(body64)), ("signature", Value::string(b64::encode_url(&mac)))]))
915}
916
917/// an account of a CA
918#[derive(Clone)]
919pub struct Account {
920    acme: Acme,
921    key: PrivateKey,
922    /// the account's URL (its key id, "kid")
923    pub url: String,
924    /// "valid", "deactivated", "revoked"
925    pub status: String,
926    pub contact: Vec<String>,
927    /// the CA made it on this call (201)
928    pub created: bool,
929}
930
931impl core::fmt::Debug for Account {
932    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
933        write!(f, "Account({}, {})", self.url, self.status)
934    }
935}
936
937impl Account {
938    fn read(&mut self, v: &Value) {
939        self.status = str_of(v, "status");
940        self.contact = v.get("contact").and_then(|x| x.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default();
941    }
942
943    pub fn acme(&self) -> &Acme {
944        &self.acme
945    }
946
947    pub fn key(&self) -> &PrivateKey {
948        &self.key
949    }
950
951    fn post(&self, url: &str, payload: Option<&Value>) -> Result<Answer, AcmeError> {
952        self.acme.post(&self.key, Some(&self.url), url, payload, MAX_ANSWER)
953    }
954
955    /// a look (POST-as-GET) that is not sent once `deadline` is reached
956    fn look(&self, url: &str, deadline: u64) -> Result<Answer, AcmeError> {
957        self.acme.post_until(&self.key, Some(&self.url), url, None, MAX_ANSWER, Some(deadline))
958    }
959
960    /// what a challenge with this token must show (RFC 8555 8.1): token "." the thumbprint of
961    /// the account key
962    pub fn key_authorization(&self, token: &str) -> String {
963        format!("{}.{}", token, thumbprint(&self.key.public_key()).unwrap_or_default())
964    }
965
966    /// a new order for these identifiers
967    pub fn new_order(&self, ids: &[Identifier], opts: &OrderOptions) -> Result<Order, AcmeError> {
968        if ids.is_empty() {
969            return Err(proto("an order needs an identifier"));
970        }
971        let mut payload = Value::object([("identifiers", Value::Array(ids.iter().map(|i| i.to_json()).collect()))]);
972        if let Some(t) = opts.not_before {
973            payload.insert("notBefore", Value::string(rfc3339_text(t)));
974        }
975        if let Some(t) = opts.not_after {
976            payload.insert("notAfter", Value::string(rfc3339_text(t)));
977        }
978        if let Some(p) = &opts.profile {
979            payload.insert("profile", Value::string(p.as_str()));
980        }
981        if let Some(r) = &opts.replaces {
982            payload.insert("replaces", Value::string(r.as_str()));
983        }
984        let url = self.acme.directory.new_order.clone();
985        let a = self.post(&url, Some(&payload))?;
986        if a.status != 201 {
987            return Err(AcmeError::Protocol(format!("newOrder answered HTTP {}", a.status)));
988        }
989        Order::from_json(a.location()?, &a.json()?)
990    }
991
992    /// an order as it stands now
993    pub fn order(&self, url: &str) -> Result<Order, AcmeError> {
994        Order::from_json(https_url(url)?, &self.post(url, None)?.json()?)
995    }
996
997    pub fn authorization(&self, url: &str) -> Result<Authorization, AcmeError> {
998        Authorization::from_json(https_url(url)?, &self.post(url, None)?.json()?)
999    }
1000
1001    /// tell the CA a challenge is ready to be checked (RFC 8555 7.5.1)
1002    pub fn respond(&self, ch: &Challenge) -> Result<(), AcmeError> {
1003        self.post(&ch.url, Some(&Value::Object(Vec::new()))).map(|_| ())
1004    }
1005
1006    /// Timeout once the deadline is reached: no look starts then (timeout_ms 0: none at all)
1007    fn in_time(deadline: u64) -> Result<(), AcmeError> {
1008        if plat::time_us() / 1000 >= deadline {
1009            return Err(AcmeError::Timeout(String::from("the CA did not decide in time")));
1010        }
1011        Ok(())
1012    }
1013
1014    /// the pause before the next look (Retry-After: half a second to max_poll_ms; else
1015    /// poll_ms), at most to the deadline; Timeout when that is reached (no look after it)
1016    fn pause(&self, retry: Option<u64>, deadline: u64) -> Result<(), AcmeError> {
1017        let max = self.acme.max_poll_ms as u64;
1018        let want = retry.map_or(self.acme.poll_ms as u64, |s| s.saturating_mul(1000).clamp(500.min(max), max));
1019        let now = plat::time_us() / 1000;
1020        if now < deadline {
1021            plat::sleep_ms(want.min(deadline - now) as u32);
1022        }
1023        Self::in_time(deadline)
1024    }
1025
1026    /// wait until the authorization is decided: Ok when valid.  Acme::timeout_ms bounds the
1027    /// waiting: no look starts after it (0: none); a request under way runs out under the
1028    /// Client's timeouts, and what it brings counts (a valid authorization is the CA's
1029    /// decision, however late it comes)
1030    pub fn wait_authorization(&self, url: &str) -> Result<Authorization, AcmeError> {
1031        let deadline = (plat::time_us() / 1000) + self.acme.timeout_ms;
1032        loop {
1033            let a = self.look(url, deadline)?;
1034            let retry = a.retry_after();
1035            let z = Authorization::from_json(https_url(url)?, &a.json()?)?;
1036            match z.status.as_str() {
1037                "valid" => return Ok(z),
1038                "pending" => self.pause(retry, deadline)?,
1039                s => return Err(AcmeError::Invalid(format!("the authorization of {} is {}", z.identifier.value(), s), z.problem())),
1040            }
1041        }
1042    }
1043
1044    /// wait until the order is no longer pending or processing (Acme::timeout_ms as
1045    /// wait_authorization)
1046    pub fn wait_order(&self, url: &str) -> Result<Order, AcmeError> {
1047        self.wait_order_after(url, None)
1048    }
1049
1050    /// wait_order, after a pause first when an answer said "processing" (with its Retry-After)
1051    fn wait_order_after(&self, url: &str, first: Option<Option<u64>>) -> Result<Order, AcmeError> {
1052        let deadline = (plat::time_us() / 1000) + self.acme.timeout_ms;
1053        if let Some(retry) = first {
1054            self.pause(retry, deadline)?;
1055        }
1056        loop {
1057            let a = self.look(url, deadline)?;
1058            let retry = a.retry_after();
1059            let o = Order::from_json(https_url(url)?, &a.json()?)?;
1060            match o.status.as_str() {
1061                "ready" | "valid" => return Ok(o),
1062                "pending" | "processing" => self.pause(retry, deadline)?,
1063                s => return Err(AcmeError::Invalid(format!("the order is {}", s), o.error)),
1064            }
1065        }
1066    }
1067
1068    /// send the certificate request (DER) of a ready order
1069    pub fn finalize(&self, order: &Order, csr: &[u8]) -> Result<Order, AcmeError> {
1070        self.finalize_retry(order, csr).map(|(o, _)| o)
1071    }
1072
1073    /// finalize -> the order and the answer's Retry-After
1074    fn finalize_retry(&self, order: &Order, csr: &[u8]) -> Result<(Order, Option<u64>), AcmeError> {
1075        let payload = Value::object([("csr", Value::string(b64::encode_url(csr)))]);
1076        let a = self.post(&order.finalize, Some(&payload))?;
1077        Ok((Order::from_json(order.url.clone(), &a.json()?)?, a.retry_after()))
1078    }
1079
1080    /// the chain at a certificate URL (an order's, or an alternate one) -> (DER chain, PEM,
1081    /// alternates)
1082    pub fn certificate(&self, url: &str) -> Result<(Vec<Vec<u8>>, String, Vec<String>), AcmeError> {
1083        self.acme.fetch_chain(&self.key, &self.url, url)
1084    }
1085
1086    /// the whole issuance for `ids` and the key `cert_key` (not the account key): an order;
1087    /// each pending authorization proved with the first challenge type of solver.kinds() it
1088    /// offers (a wildcard only by dns-01), set up, answered, waited for and taken down; the
1089    /// certificate request; the chain, checked to be for `cert_key` and every identifier
1090    pub fn issue(&self, ids: &[Identifier], cert_key: &PrivateKey, solver: &mut dyn Solver, opts: &OrderOptions) -> Result<Issued, AcmeError> {
1091        if cert_key.spki() == self.key.spki() {
1092            return Err(proto("the certificate key must not be the account key (RFC 8555 11.1)"));
1093        }
1094        let order = self.new_order(ids, opts)?;
1095        for url in &order.authorizations {
1096            let z = self.authorization(url)?;
1097            match z.status.as_str() {
1098                "valid" => continue,
1099                "pending" => {}
1100                s => return Err(AcmeError::Invalid(format!("the authorization of {} is {}", z.identifier.value(), s), z.problem())),
1101            }
1102            let kinds = solver.kinds();
1103            let ch = kinds
1104                .iter()
1105                .filter(|k| !z.wildcard || **k == "dns-01")
1106                .find_map(|k| z.challenges.iter().find(|c| c.kind == *k))
1107                .ok_or_else(|| AcmeError::Solver(format!("no challenge for {} that the solver sets up", z.identifier.value())))?
1108                .clone();
1109            let ka = self.key_authorization(&ch.token);
1110            let id = if z.wildcard { Identifier::Dns(format!("*.{}", z.identifier.value())) } else { z.identifier.clone() };
1111            solver.present(&id, &ch, &ka).map_err(AcmeError::Solver)?;
1112            let r = self.respond(&ch).and_then(|_| self.wait_authorization(&z.url));
1113            solver.cleanup(&id, &ch);
1114            r?;
1115        }
1116        let order = self.wait_order(&order.url)?;
1117        let order = if order.status == "ready" {
1118            let mut b = CsrBuilder { must_staple: opts.must_staple, ..CsrBuilder::default() };
1119            for i in ids {
1120                match i {
1121                    Identifier::Dns(d) => b.dns.push(d.clone()),
1122                    Identifier::Ip(ip) => b.ips.push(*ip),
1123                }
1124            }
1125            b.cn = b.dns.first().filter(|d| d.len() <= 64).cloned().unwrap_or_default();
1126            let csr = b.sign(cert_key).ok_or_else(|| proto("the certificate request cannot be made (a name, the key)"))?;
1127            let (o, retry) = self.finalize_retry(&order, &csr)?;
1128            match o.status.as_str() {
1129                "valid" => o,
1130                // final (RFC 8555 7.1.6): the CA's error as it is, no look more
1131                "invalid" => return Err(AcmeError::Invalid(String::from("the order is invalid"), o.error)),
1132                _ => self.wait_order_after(&o.url, Some(retry))?,
1133            }
1134        } else {
1135            order
1136        };
1137        if order.status != "valid" {
1138            return Err(AcmeError::Invalid(format!("the order is {}", order.status), order.error));
1139        }
1140        let url = order.certificate.clone().ok_or_else(|| proto("a valid order without a certificate"))?;
1141        let (chain, pem, alternates) = self.certificate(&url)?;
1142        let leaf = Cert::parse(&chain[0]).ok_or_else(|| proto("the certificate cannot be read"))?;
1143        if leaf.key != cert_key.public_key() {
1144            return Err(proto("the certificate issued is for another key"));
1145        }
1146        for i in ids {
1147            let ok = match i {
1148                Identifier::Dns(d) => leaf.dns.iter().any(|x| x == d),
1149                Identifier::Ip(ip) => leaf.ips.contains(ip),
1150            };
1151            if !ok {
1152                return Err(AcmeError::Protocol(format!("the certificate issued does not name {}", i.value())));
1153            }
1154        }
1155        Ok(Issued { chain, pem, alternates, order })
1156    }
1157
1158    /// revoke a certificate of this account (RFC 8555 7.6); `reason`: a CRLReason (RFC 5280
1159    /// 5.3.1: 1 keyCompromise, 4 superseded, 5 cessationOfOperation, ...)
1160    pub fn revoke(&self, cert_der: &[u8], reason: Option<u8>) -> Result<(), AcmeError> {
1161        let url = self.acme.directory.revoke_cert.clone();
1162        self.post(&url, Some(&revocation(cert_der, reason))).map(|_| ())
1163    }
1164
1165    /// change the account's key (RFC 8555 7.3.5)
1166    pub fn change_key(&mut self, new_key: PrivateKey) -> Result<(), AcmeError> {
1167        jws_alg(&new_key)?;
1168        let url = self.acme.directory.key_change.clone();
1169        let (alg, _) = jws_alg(&new_key)?;
1170        let inner_protected = Value::object([("alg", Value::string(alg)), ("jwk", jwk(&new_key.public_key())?), ("url", Value::string(url.as_str()))]);
1171        let inner_payload = Value::object([("account", Value::string(self.url.as_str())), ("oldKey", jwk(&self.key.public_key())?)]);
1172        let inner = jws(&new_key, inner_protected, Some(&inner_payload))?;
1173        self.post(&url, Some(&inner))?;
1174        self.key = new_key;
1175        Ok(())
1176    }
1177
1178    /// replace the account's contact addresses
1179    pub fn update_contact(&mut self, contact: &[String]) -> Result<(), AcmeError> {
1180        let payload = Value::object([("contact", Value::Array(contact.iter().map(|c| Value::string(c.as_str())).collect()))]);
1181        let v = self.post(&self.url.clone(), Some(&payload))?.json()?;
1182        self.read(&v);
1183        Ok(())
1184    }
1185
1186    /// end the account (RFC 8555 7.3.6): it cannot be used again
1187    pub fn deactivate(&mut self) -> Result<(), AcmeError> {
1188        let payload = Value::object([("status", Value::string("deactivated"))]);
1189        let v = self.post(&self.url.clone(), Some(&payload))?.json()?;
1190        self.read(&v);
1191        Ok(())
1192    }
1193}
1194
1195fn revocation(cert_der: &[u8], reason: Option<u8>) -> Value {
1196    let mut p = Value::object([("certificate", Value::string(b64::encode_url(cert_der)))]);
1197    if let Some(r) = reason {
1198        p.insert("reason", Value::u64(r as u64));
1199    }
1200    p
1201}
1202
1203/// revoke a certificate by its own key (signed with it, no account: a lost account key, a
1204/// compromised certificate key)
1205pub fn revoke_with_key(acme: &Acme, cert_der: &[u8], cert_key: &PrivateKey, reason: Option<u8>) -> Result<(), AcmeError> {
1206    let url = acme.directory.revoke_cert.clone();
1207    acme.post(cert_key, None, &url, Some(&revocation(cert_der, reason)), MAX_ANSWER).map(|_| ())
1208}
1209
1210// ------------------------------------------------------------------ challenges
1211
1212/// what proves control of an identifier
1213pub trait Solver {
1214    /// the challenge types it sets up, the preferred first ("http-01", "tls-alpn-01",
1215    /// "dns-01")
1216    fn kinds(&self) -> Vec<&'static str>;
1217    /// set the challenge up for `id` ("*.example.com" for a wildcard): `key_auth` is what it
1218    /// must show (dns-01: dns01_value(key_auth) as TXT of dns01_name(id))
1219    fn present(&mut self, id: &Identifier, ch: &Challenge, key_auth: &str) -> Result<(), String>;
1220    /// take it down once the authorization is decided
1221    fn cleanup(&mut self, id: &Identifier, ch: &Challenge);
1222}
1223
1224/// the TXT record's name of dns-01 (RFC 8555 8.4): "_acme-challenge." and the name (a
1225/// wildcard's without "*.")
1226pub fn dns01_name(id: &Identifier) -> String {
1227    let v = id.value();
1228    format!("_acme-challenge.{}", v.strip_prefix("*.").unwrap_or(&v))
1229}
1230
1231/// the TXT record's value of dns-01: base64url of SHA-256 of the key authorization
1232pub fn dns01_value(key_auth: &str) -> String {
1233    b64::encode_url(&crypto::sha256(key_auth.as_bytes()))
1234}
1235
1236/// http-01 (RFC 8555 8.3): the key authorizations a netio HTTP server answers at
1237/// /.well-known/acme-challenge/<token> on port 80.  Clones share the tokens: one goes to the
1238/// solver, one into the server (handler or answer)
1239#[derive(Clone, Default)]
1240pub struct Http01 {
1241    tokens: Arc<Mutex<BTreeMap<String, String>>>,
1242}
1243
1244impl Http01 {
1245    pub fn new() -> Http01 {
1246        Http01::default()
1247    }
1248
1249    /// the answer to a challenge request, None for every other request
1250    pub fn answer(&self, req: &Request) -> Option<Response> {
1251        let token = req.path().strip_prefix("/.well-known/acme-challenge/")?;
1252        if req.method != "GET" && req.method != "HEAD" {
1253            return None;
1254        }
1255        let ka = self.tokens.lock().get(token).cloned()?;
1256        Some(Response::bytes(200, "application/octet-stream", ka.into_bytes()))
1257    }
1258
1259    /// a handler that answers challenges and hands every other request to `next`
1260    pub fn handler(&self, next: Handler) -> Handler {
1261        let me = self.clone();
1262        Arc::new(move |req: &Request| me.answer(req).unwrap_or_else(|| next(req)))
1263    }
1264}
1265
1266impl Solver for Http01 {
1267    fn kinds(&self) -> Vec<&'static str> {
1268        alloc::vec!["http-01"]
1269    }
1270    fn present(&mut self, _id: &Identifier, ch: &Challenge, key_auth: &str) -> Result<(), String> {
1271        self.tokens.lock().insert(ch.token.clone(), String::from(key_auth));
1272        Ok(())
1273    }
1274    fn cleanup(&mut self, _id: &Identifier, ch: &Challenge) {
1275        self.tokens.lock().remove(&ch.token);
1276    }
1277}
1278
1279/// tls-alpn-01 (RFC 8737): a certificate for the challenge, shown on port 443 to a client that
1280/// offers only "acme-tls/1".  Clones share the certificates: one goes to the solver, one into
1281/// the server's config (setup).  A name has one challenge at a time: another one for it fails
1282/// to be set up until the first is cleaned up; the same challenge set up twice (two orders the
1283/// CA gave it to) keeps its first certificate and stays until both are cleaned up
1284#[derive(Clone, Default)]
1285pub struct TlsAlpn01 {
1286    /// the server name -> the challenge's token, its certificate, how often it is set up
1287    ids: Arc<Mutex<BTreeMap<String, (String, Identity, u32)>>>,
1288}
1289
1290impl TlsAlpn01 {
1291    pub fn new() -> TlsAlpn01 {
1292        TlsAlpn01::default()
1293    }
1294
1295    /// let `cfg` answer the challenges: "acme-tls/1" among its protocols (last; to a client that
1296    /// does not offer it alone the server's list is as if it were not there, so a server without
1297    /// protocols of its own still answers without ALPN), and a select that shows the challenge
1298    /// certificate for a ClientHello offering only it (before the config's own select)
1299    pub fn setup(&self, cfg: &mut ServerConfig) {
1300        if !cfg.alpn.iter().any(|p| p == ACME_TLS_ALPN) {
1301            cfg.alpn.push(String::from(ACME_TLS_ALPN));
1302        }
1303        let me = self.clone();
1304        let next = cfg.select.take();
1305        let sel: Select = Arc::new(move |h: &Hello| {
1306            if h.alpn.len() == 1 && h.alpn[0] == ACME_TLS_ALPN.as_bytes() {
1307                if let Some((_, id, _)) = me.ids.lock().get(&h.server_name).cloned() {
1308                    return Some(id);
1309                }
1310            }
1311            next.as_ref().and_then(|f| f(h))
1312        });
1313        cfg.select = Some(sel);
1314    }
1315
1316    /// the self-signed certificate of a challenge (RFC 8737 3): the identifier as its only
1317    /// name, the critical acmeIdentifier with SHA-256 of the key authorization
1318    pub fn certificate(id: &Identifier, key_auth: &str) -> Option<Identity> {
1319        let key = PrivateKey::generate_ecdsa(Curve::P256, &mut |b: &mut [u8]| plat::fill_random(b));
1320        let now = plat::unix_time_ns().div_euclid(1_000_000_000);
1321        let mut b = CertBuilder { serial: plat::random_bytes::<16>(), cn: String::from("ACME challenge"), not_before: now - 3600, not_after: now + 7 * 86_400, spki: key.spki(), ..CertBuilder::default() };
1322        match id {
1323            Identifier::Dns(d) => b.dns.push(d.clone()),
1324            Identifier::Ip(ip) => b.ips.push(*ip),
1325        }
1326        let digest = crypto::sha256(key_auth.as_bytes());
1327        let ext = x509::extension(OID_ACME_IDENTIFIER, true, &x509::der::octets(&digest));
1328        let der = b.sign_key(None, &key, &[ext])?;
1329        Some(Identity::new(alloc::vec![der], key))
1330    }
1331}
1332
1333impl Solver for TlsAlpn01 {
1334    fn kinds(&self) -> Vec<&'static str> {
1335        alloc::vec!["tls-alpn-01"]
1336    }
1337    fn present(&mut self, id: &Identifier, ch: &Challenge, key_auth: &str) -> Result<(), String> {
1338        let identity = TlsAlpn01::certificate(id, key_auth).ok_or_else(|| String::from("the challenge certificate cannot be made"))?;
1339        let mut ids = self.ids.lock();
1340        match ids.get_mut(&id.tls_name()) {
1341            Some((token, _, _)) if *token != ch.token => Err(format!("a tls-alpn-01 challenge for {} is set up already", id.value())),
1342            Some((_, _, n)) => {
1343                *n += 1;
1344                Ok(())
1345            }
1346            None => {
1347                ids.insert(id.tls_name(), (ch.token.clone(), identity, 1));
1348                Ok(())
1349            }
1350        }
1351    }
1352    fn cleanup(&mut self, id: &Identifier, ch: &Challenge) {
1353        let mut ids = self.ids.lock();
1354        let name = id.tls_name();
1355        if let Some((token, _, n)) = ids.get_mut(&name) {
1356            if *token == ch.token {
1357                *n -= 1;
1358                if *n == 0 {
1359                    ids.remove(&name);
1360                }
1361            }
1362        }
1363    }
1364}
1365
1366/// several solvers, each for the challenge types it sets up (a DNS provider for wildcards,
1367/// http-01 for the rest): the first that sets up a type the authorization offers takes it
1368pub struct Solvers(pub Vec<Box<dyn Solver + Send>>);
1369
1370impl Solver for Solvers {
1371    fn kinds(&self) -> Vec<&'static str> {
1372        let mut v = Vec::new();
1373        for s in &self.0 {
1374            for k in s.kinds() {
1375                if !v.contains(&k) {
1376                    v.push(k);
1377                }
1378            }
1379        }
1380        v
1381    }
1382    fn present(&mut self, id: &Identifier, ch: &Challenge, key_auth: &str) -> Result<(), String> {
1383        match self.0.iter_mut().find(|s| s.kinds().contains(&ch.kind.as_str())) {
1384            Some(s) => s.present(id, ch, key_auth),
1385            None => Err(format!("no solver for {}", ch.kind)),
1386        }
1387    }
1388    fn cleanup(&mut self, id: &Identifier, ch: &Challenge) {
1389        if let Some(s) = self.0.iter_mut().find(|s| s.kinds().contains(&ch.kind.as_str())) {
1390            s.cleanup(id, ch);
1391        }
1392    }
1393}