348 lines
12 KiB
Rust
348 lines
12 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::shared::{CertState, Shared};
|
|
use crate::tls::{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);
|
|
const MIN_GAP: Duration = Duration::from_secs(5);
|
|
|
|
/// 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 shared: Arc<Shared>,
|
|
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.shared.current().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.shared.certs.insert(host, ck);
|
|
self.ok(host, expiry);
|
|
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.shared.certs.insert(host, ck);
|
|
self.ok(host, expiry);
|
|
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.
|
|
fn ok(&self, host: &str, expiry: i64) {
|
|
self.shared.set_cert_state(
|
|
host,
|
|
CertState {
|
|
state: "ok",
|
|
not_after: Some(expiry),
|
|
error: None,
|
|
},
|
|
);
|
|
}
|
|
|
|
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
|
|
let rt = self.shared.current();
|
|
let Some(acme) = &rt.cfg.acme else {
|
|
return true;
|
|
};
|
|
let due: Vec<String> = 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;
|
|
}
|
|
for h in &due {
|
|
if !expiries.contains_key(h) {
|
|
self.shared.set_cert_state(
|
|
h,
|
|
CertState {
|
|
state: "pending",
|
|
not_after: None,
|
|
error: None,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
|
|
Ok(a) => a,
|
|
Err(e) => {
|
|
log::error!(target: "ianitor::acme", "{e}");
|
|
for h in &due {
|
|
self.failed(h, expiries.get(h).copied(), &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}");
|
|
self.failed(&host, expiries.get(&host).copied(), &e);
|
|
ok = false;
|
|
}
|
|
}
|
|
}
|
|
ok
|
|
}
|
|
|
|
/// A host that still has a valid certificate stays `ok` while renewal retries.
|
|
fn failed(&self, host: &str, expiry: Option<i64>, error: &str) {
|
|
let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs());
|
|
self.shared.set_cert_state(
|
|
host,
|
|
CertState {
|
|
state: if still_valid { "ok" } else { "failed" },
|
|
not_after: expiry,
|
|
error: Some(error.chars().take(300).collect()),
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl BackgroundService for AcmeService {
|
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
|
let mut expiries = HashMap::new();
|
|
let mut retry = FIRST_RETRY;
|
|
let mut last: Option<std::time::Instant> = None;
|
|
loop {
|
|
// Reloads can come many times a second; ACME rounds at most every 5 s.
|
|
if let Some(l) = last
|
|
&& l.elapsed() < MIN_GAP
|
|
{
|
|
tokio::select! {
|
|
_ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {}
|
|
_ = shutdown.changed() => return,
|
|
}
|
|
}
|
|
last = Some(std::time::Instant::now());
|
|
let hosts = self.shared.current().acme_hosts();
|
|
let mut wait = CHECK_EVERY;
|
|
if !hosts.is_empty() {
|
|
let dir = self.dir();
|
|
if let Err(e) = std::fs::create_dir_all(&dir) {
|
|
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
|
|
} else {
|
|
for h in hosts {
|
|
if !expiries.contains_key(&h)
|
|
&& let Some(e) = self.load_stored(&h)
|
|
{
|
|
expiries.insert(h, e);
|
|
}
|
|
}
|
|
wait = if self.round(&mut expiries).await {
|
|
retry = FIRST_RETRY;
|
|
CHECK_EVERY
|
|
} else {
|
|
let w = retry;
|
|
retry = (retry * 2).min(MAX_RETRY);
|
|
w
|
|
};
|
|
}
|
|
}
|
|
// Woken early by a reload (new hosts) or a "try again" from control.
|
|
tokio::select! {
|
|
_ = tokio::time::sleep(wait) => {}
|
|
_ = self.shared.acme_wake.notified() => {}
|
|
_ = shutdown.changed() => return,
|
|
}
|
|
}
|
|
}
|
|
}
|