public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Shannon Sterz <s.sterz@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH datacenter-manager 08/10] api/auth/bin: add certificate renewal logic
Date: Tue,  7 Apr 2026 15:57:12 +0200	[thread overview]
Message-ID: <20260407135714.490747-9-s.sterz@proxmox.com> (raw)
In-Reply-To: <20260407135714.490747-1-s.sterz@proxmox.com>

the daily-update service is used to check whether a self-signed
certificate is in use and renews it if it would expire within the next
15 days.

a self-signed certificate is detected by parsing the issuer field of
the certificate. if it aligns with how self-signed certificates are
created by this instance of proxmox datacenter manager, it will be
deemed self-signed.

15 days was chosen as that should give a reasonable trade-off between
not failing if the daily-update service can't run on the specific day
that the certificate would expire and not refreshing the certificate
too often. note that 15 days before expiry corresponds to let's
encrypt's recommendation for when to update new certificates that are
valid for 45 days:

> Acceptable behavior includes renewing certificates at approximately
> two thirds of the way through the current certificate’s lifetime.
>
> -  https://letsencrypt.org/2025/12/02/from-90-to-45#action-required

15 days before expiry is about two thirds of the lifetime of a
certificate that lasts for 45 days.

Signed-off-by: Shannon Sterz <s.sterz@proxmox.com>
---
 server/Cargo.toml                             |  1 +
 server/src/api/nodes/certificates.rs          | 48 +++++++++++++++++++
 server/src/auth/certs.rs                      |  3 +-
 ...proxmox-datacenter-manager-daily-update.rs | 26 ++++++++++
 4 files changed, 77 insertions(+), 1 deletion(-)

diff --git a/server/Cargo.toml b/server/Cargo.toml
index 6969549..0874acd 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -25,6 +25,7 @@ nix.workspace = true
 once_cell.workspace = true
 openssl.workspace = true
 percent-encoding.workspace = true
+regex.workspace = true
 serde.workspace = true
 serde_json.workspace = true
 serde_plain.workspace = true
diff --git a/server/src/api/nodes/certificates.rs b/server/src/api/nodes/certificates.rs
index 47aef7a..3b43f2e 100644
--- a/server/src/api/nodes/certificates.rs
+++ b/server/src/api/nodes/certificates.rs
@@ -1,7 +1,10 @@
 use anyhow::{bail, format_err, Context, Error};
+use const_format::concatcp;
+use openssl::asn1::Asn1Time;
 use openssl::pkey::PKey;
 use openssl::x509::X509;
 
+use proxmox_dns_api::read_etc_resolv_conf;
 use proxmox_log::info;
 use proxmox_router::list_subdirs_api_method;
 use proxmox_router::SubdirMap;
@@ -17,6 +20,14 @@ use pdm_api_types::PRIV_SYS_MODIFY;
 
 use crate::auth::certs::{API_CERT_FN, API_KEY_FN};
 
+proxmox_schema::const_regex! {
+    pub SELF_SIGNED_REGEX = concatcp!(
+        r#"^O\s?=\s?"#,
+        crate::auth::certs::PRODUCT_NAME,
+        r#", OU\s?=\s?[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}, CN\s?=\s?(?<fqdn>.*)$"#
+    );
+}
+
 pub const ROUTER: Router = Router::new()
     .get(&list_subdirs_api_method!(SUBDIRS))
     .subdirs(SUBDIRS);
@@ -247,6 +258,43 @@ pub fn cert_expires_soon() -> Result<bool, Error> {
         .map_err(|err| format_err!("Failed to check certificate expiration date: {}", err))
 }
 
+/// Check whether the current certificate is self-signed and returns the remaining days the
+/// certificate is valid for.
+pub fn self_signed_cert_expires_in() -> Result<Option<i32>, Error> {
+    let cert = get_certificate_info()?;
+
+    let Some(captures) = (SELF_SIGNED_REGEX.regex_obj)().captures(&cert.issuer) else {
+        return Ok(None);
+    };
+
+    let mut fqdn = proxmox_sys::nodename().to_owned();
+    let resolv_conf = read_etc_resolv_conf(None)?.config;
+
+    if let Some(domain) = resolv_conf.search {
+        fqdn.push('.');
+        fqdn.push_str(&domain);
+    }
+
+    if captures["fqdn"] != fqdn {
+        return Ok(None);
+    }
+
+    let now = Asn1Time::from_unix(proxmox_time::epoch_i64())?;
+    let not_after = Asn1Time::from_unix(cert.notafter.ok_or_else(|| {
+        format_err!("Could not get \"not after\" epoch for current certificate.")
+    })?)?;
+
+    let diff = now.diff(&not_after)?;
+    Ok(Some(diff.days))
+}
+
+/// Renews the self signed certificate. The caller needs to make sure the current certificate is
+/// really a self-signed certificate and not an ACME or custom certificate.
+pub async fn renew_self_signed_cert() -> Result<(), Error> {
+    crate::auth::certs::update_self_signed_cert(true)?;
+    crate::reload_api_certificate().await
+}
+
 fn spawn_certificate_worker(
     name: &'static str,
     force: bool,
diff --git a/server/src/auth/certs.rs b/server/src/auth/certs.rs
index c310593..ea561d0 100644
--- a/server/src/auth/certs.rs
+++ b/server/src/auth/certs.rs
@@ -7,6 +7,7 @@ use pdm_buildcfg::configdir;
 
 pub const API_KEY_FN: &str = configdir!("/auth/api.key");
 pub const API_CERT_FN: &str = configdir!("/auth/api.pem");
+pub const PRODUCT_NAME: &str = "Proxmox Datacenter Manager";
 
 /// Update self signed node certificate.
 pub fn update_self_signed_cert(force: bool) -> Result<(), Error> {
@@ -20,7 +21,7 @@ pub fn update_self_signed_cert(force: bool) -> Result<(), Error> {
     let resolv_conf = read_etc_resolv_conf(None)?.config;
 
     let (priv_key, cert) = proxmox_acme_api::create_self_signed_cert(
-        "Proxmox Datacenter Manager",
+        PRODUCT_NAME,
         proxmox_sys::nodename(),
         resolv_conf.search.as_deref(),
         None,
diff --git a/server/src/bin/proxmox-datacenter-manager-daily-update.rs b/server/src/bin/proxmox-datacenter-manager-daily-update.rs
index 8b6641c..deed0be 100644
--- a/server/src/bin/proxmox-datacenter-manager-daily-update.rs
+++ b/server/src/bin/proxmox-datacenter-manager-daily-update.rs
@@ -59,6 +59,11 @@ async fn do_update(rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> {
         log::error!("error checking certificates: {err}");
     }
 
+    println!("check if self-signed certificate requires renewal");
+    if let Err(err) = renew_self_signed_certificate().await {
+        log::error!("error checking self-signed certificate renewal: {err:#}");
+    }
+
     // TODO: cleanup tasks like in PVE?
 
     Ok(())
@@ -87,6 +92,27 @@ async fn check_acme_certificates(rpcenv: &mut dyn RpcEnvironment) -> Result<(),
     Ok(())
 }
 
+async fn renew_self_signed_certificate() -> Result<(), Error> {
+    let days = match api::nodes::certificates::self_signed_cert_expires_in()? {
+        None => {
+            log::debug!("Certificate is not self-signed, nothing to do.");
+            return Ok(());
+        }
+        Some(days) => days,
+    };
+
+    if days <= 15 {
+        log::info!("Certificate expires within 15 days, renewing certificate...");
+        let _err = &api::nodes::certificates::renew_self_signed_cert().await;
+        // fixme: send_self_signed_renewal_notification(&err)?;
+    } else if days <= 30 {
+        log::info!("Certificate expires within 30 days.");
+        // fixme: send_upcoming_self_signed_renewal_notification()?;
+    }
+
+    Ok(())
+}
+
 async fn run(rpcenv: &mut dyn RpcEnvironment) -> Result<(), Error> {
     let api_user = pdm_config::api_user()?;
     let file_opts = CreateOptions::new().owner(api_user.uid).group(api_user.gid);
-- 
2.47.3





  parent reply	other threads:[~2026-04-07 13:56 UTC|newest]

Thread overview: 12+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-04-07 13:57 [RFC datacenter-manager/proxmox{,-backup} 00/10] TLS Certificate Rotation Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox 01/10] acme-api: make self-signed certificate expiry configurable Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox-backup 02/10] config: use proxmox_acme_api for generating self-signed certificates Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox-backup 03/10] config: adapt to api change in proxmox_acme_api, add expiry paramter Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox-backup 04/10] config/server/api: add certificate renewal logic including notifications Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox-backup 05/10] daily-update/docs: warn on excessive self-signed certificate lifetime Shannon Sterz
2026-04-07 13:57 ` [PATCH proxmox-backup 06/10] backup-manager cli: `cert update` can create auth and csrf key Shannon Sterz
2026-04-07 13:57 ` [PATCH datacenter-manager 07/10] certs: adapt to api change in proxmox_acme_api, add expiry paramter Shannon Sterz
2026-04-07 13:57 ` Shannon Sterz [this message]
2026-04-07 13:57 ` [PATCH datacenter-manager 09/10] cli: expose certificate management endpoints via the cli Shannon Sterz
2026-04-07 13:57 ` [PATCH datacenter-manager 10/10] daily-update/docs: warn on excessive tls certificate validity periods Shannon Sterz
2026-04-07 15:29   ` Shannon Sterz

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260407135714.490747-9-s.sterz@proxmox.com \
    --to=s.sterz@proxmox.com \
    --cc=pbs-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal