Files
ianitor/crates/edge/src/acme.rs
T

290 lines
10 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Let's Encrypt (any RFC 8555 directory) through `instant-acme`, HTTP-01 challenges answered
//! on the plain-HTTP listener. Certificates and the account live in `<state_dir>/acme`
//! (key files mode 0600) and are swapped into the SNI store without a restart. A certificate
//! is renewed when it has less than 30 days left; failures are retried with backoff.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use instant_acme::{
Account, AccountCredentials, AuthorizationStatus, ChallengeType, Identifier, NewAccount,
NewOrder, OrderStatus, RetryPolicy,
};
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use crate::logging::now_secs;
use crate::runtime::Runtime;
use crate::tls::{CertStore, certified_key, not_after};
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
const FIRST_RETRY: Duration = Duration::from_secs(30);
const MAX_RETRY: Duration = Duration::from_secs(3600);
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
#[derive(Default)]
pub struct Challenges(RwLock<HashMap<String, String>>);
impl Challenges {
pub fn get(&self, token: &str) -> Option<String> {
self.0.read().ok()?.get(token).cloned()
}
fn insert(&self, token: String, key_auth: String) {
if let Ok(mut m) = self.0.write() {
m.insert(token, key_auth);
}
}
fn remove(&self, token: &str) {
if let Ok(mut m) = self.0.write() {
m.remove(token);
}
}
}
pub struct AcmeService {
pub rt: Arc<Runtime>,
pub certs: Arc<CertStore>,
pub challenges: Arc<Challenges>,
/// Extra trust root for the ACME directory (tests against Pebble only).
pub ca_root: Option<PathBuf>,
}
fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
let tmp = path.with_extension("tmp");
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
let mut f = opts
.open(&tmp)
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
std::io::Write::write_all(&mut f, data)
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("cannot replace {}: {e}", path.display()))
}
fn fnv(data: &[u8]) -> String {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in data {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
format!("{h:016x}")
}
impl AcmeService {
fn dir(&self) -> PathBuf {
self.rt.acme_dir()
}
fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
(
self.dir().join(format!("{host}.crt")),
self.dir().join(format!("{host}.key")),
)
}
/// Load a stored certificate into the SNI store; returns its expiry.
fn load_stored(&self, host: &str) -> Option<i64> {
let (crt, key) = self.paths(host);
let cert_pem = std::fs::read(&crt).ok()?;
let key_pem = std::fs::read(&key).ok()?;
let expiry = not_after(&cert_pem)?;
match certified_key(&cert_pem, &key_pem) {
Ok(ck) => {
self.certs.insert(host, ck);
Some(expiry)
}
Err(e) => {
log::warn!(target: "ianitor::acme", "{host}: stored certificate is not usable ({e}); ordering a new one");
None
}
}
}
fn builder(&self) -> Result<instant_acme::AccountBuilder, String> {
match &self.ca_root {
Some(p) => Account::builder_with_root(p),
None => Account::builder(),
}
.map_err(|e| format!("cannot set up the ACME client: {e}"))
}
async fn account(&self, directory: &str, email: Option<&str>) -> Result<Account, String> {
let file = self
.dir()
.join(format!("account-{}.json", fnv(directory.as_bytes())));
if let Ok(text) = std::fs::read_to_string(&file) {
let creds: AccountCredentials = serde_json::from_str(&text)
.map_err(|e| format!("{} is damaged: {e}", file.display()))?;
return self
.builder()?
.from_credentials(creds)
.await
.map_err(|e| format!("cannot restore the ACME account: {e}"));
}
let contact = email.map(|e| format!("mailto:{e}"));
let contacts: Vec<&str> = contact.iter().map(String::as_str).collect();
let (account, creds) = self
.builder()?
.create(
&NewAccount {
contact: &contacts,
terms_of_service_agreed: true,
only_return_existing: false,
},
directory.to_owned(),
None,
)
.await
.map_err(|e| format!("cannot create the ACME account: {e}"))?;
let text = serde_json::to_vec(&creds)
.map_err(|e| format!("cannot store the ACME account: {e}"))?;
write_private(&file, &text)?;
log::info!(target: "ianitor::acme", "created ACME account at {directory}");
Ok(account)
}
async fn issue(&self, account: &Account, host: &str) -> Result<i64, String> {
let ids = [Identifier::Dns(host.to_owned())];
let mut order = account
.new_order(&NewOrder::new(&ids))
.await
.map_err(|e| format!("new order: {e}"))?;
let mut tokens = Vec::new();
let mut auths = order.authorizations();
while let Some(result) = auths.next().await {
let mut authz = result.map_err(|e| format!("authorization: {e}"))?;
if authz.status == AuthorizationStatus::Valid {
continue;
}
if authz.status != AuthorizationStatus::Pending {
return Err(format!("authorization is {:?}", authz.status));
}
let mut ch = authz
.challenge(ChallengeType::Http01)
.ok_or("the server offers no HTTP-01 challenge")?;
self.challenges
.insert(ch.token.clone(), ch.key_authorization().as_str().to_owned());
tokens.push(ch.token.clone());
ch.set_ready()
.await
.map_err(|e| format!("challenge ready: {e}"))?;
}
let policy = RetryPolicy::new().timeout(Duration::from_secs(90));
let status = order
.poll_ready(&policy)
.await
.map_err(|e| format!("order: {e}"));
for t in &tokens {
self.challenges.remove(t);
}
match status? {
OrderStatus::Ready => {}
other => return Err(format!("order ended as {other:?}")),
}
let key_pem = order
.finalize()
.await
.map_err(|e| format!("finalize: {e}"))?;
let chain_pem = order
.poll_certificate(&policy)
.await
.map_err(|e| format!("certificate: {e}"))?;
let ck = certified_key(chain_pem.as_bytes(), key_pem.as_bytes())?;
let expiry =
not_after(chain_pem.as_bytes()).ok_or("cannot read the new certificate's expiry")?;
let (crt, key) = self.paths(host);
write_private(&key, key_pem.as_bytes())?;
write_private(&crt, chain_pem.as_bytes())?;
self.certs.insert(host, ck);
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
Ok(expiry)
}
/// One pass over every ACME host. Returns false if any host failed.
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
let Some(acme) = &self.rt.cfg.acme else {
return true;
};
let due: Vec<String> = self
.rt
.acme_hosts()
.into_iter()
.filter(|h| {
expiries
.get(h)
.is_none_or(|e| (*e as f64) - now_secs() < RENEW_BEFORE_SECS)
})
.collect();
if due.is_empty() {
return true;
}
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
Ok(a) => a,
Err(e) => {
log::error!(target: "ianitor::acme", "{e}");
return false;
}
};
let mut ok = true;
for host in due {
match self.issue(&account, &host).await {
Ok(exp) => {
expiries.insert(host, exp);
}
Err(e) => {
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
ok = false;
}
}
}
ok
}
}
#[async_trait]
impl BackgroundService for AcmeService {
async fn start(&self, mut shutdown: ShutdownWatch) {
if self.rt.acme_hosts().is_empty() {
return;
}
let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
return;
}
let mut expiries = HashMap::new();
for h in self.rt.acme_hosts() {
if let Some(e) = self.load_stored(&h) {
expiries.insert(h, e);
}
}
let mut retry = FIRST_RETRY;
loop {
let wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY;
CHECK_EVERY
} else {
let w = retry;
retry = (retry * 2).min(MAX_RETRY);
w
};
tokio::select! {
_ = tokio::time::sleep(wait) => {}
_ = shutdown.changed() => return,
}
}
}
}