Просмотр исходного кода

feat(https): serve a certificate set in Settings (#1759)

A homelab that already runs its own CA had no way to hand NetPulse a certificate from the UI. The environment accepted `NETPULSE_TLS_CERT` and `NETPULSE_TLS_KEY`, but nothing in Settings pointed at it, and with those variables set the HTTPS card just stayed locked. This adds the setting (#1756).

Settings > HTTPS > Certificate takes absolute paths to a full chain and its key, or switches back to the private CA. The pair is loaded before anything changes, so a typo leaves the running listener untouched, and it is read on every handshake through the existing reloader, so a renewal is picked up without a restart as long as the files keep their names.

With a certificate from disk there is no root of ours to download and nothing to reissue, so the card hides the root box and Renew says where to go instead. The pin agents get is the key of that certificate. Switching to one with a different key asks for the same acknowledgement as turning HTTPS off, because the agents pinned to the old key would stop reporting; a renewal that keeps the key (`certbot --reuse-key`) goes through without a warning.

The environment still wins: with `NETPULSE_TLS_CERT` set, the setting stays locked.

Tests cover the pair replacing the CA and coming back, a bad pair leaving the pin and the listener as they were, the pin and the missing root in `AgentTrust`, Renew refusing a file, the pair surviving a restart, and the setting through `POST /api/settings/https`.

Closes #1756
Nacho 1 месяц назад
Родитель
Сommit
febed3b4ee

+ 11 - 0
app/public/locales/en/translation.json

@@ -2136,6 +2136,17 @@
     },
     "https": {
       "title": "HTTPS",
+      "certTitle": "Certificate",
+      "certHint": "NetPulse can serve its own private CA, or a certificate you already have on this machine.",
+      "certModeCa": "NetPulse CA",
+      "certModeCustom": "My own certificate",
+      "certPathLabel": "Certificate (full chain, PEM)",
+      "keyPathLabel": "Private key (PEM)",
+      "certApply": "Use this certificate",
+      "certUseCa": "Use the NetPulse CA",
+      "certCurrentCa": "Serving the NetPulse CA.",
+      "certCurrentCustom": "Serving {{path}}.",
+      "certRenewHint": "This certificate is renewed wherever it was issued. If the new one uses a different key, the agents pinned to the old one stop reporting until you reinstall them, so renew with the same key (certbot --reuse-key).",
       "loadError": "Could not load the HTTPS settings.",
       "unavailable": "HTTPS is managed outside this page: {{reason}}.",
       "enabled": "HTTPS",

+ 11 - 0
app/public/locales/es/translation.json

@@ -2136,6 +2136,17 @@
     },
     "https": {
       "title": "HTTPS",
+      "certTitle": "Certificado",
+      "certHint": "NetPulse puede servir su propia CA privada o un certificado que ya tengas en esta máquina.",
+      "certModeCa": "CA de NetPulse",
+      "certModeCustom": "Mi certificado",
+      "certPathLabel": "Certificado (cadena completa, PEM)",
+      "keyPathLabel": "Clave privada (PEM)",
+      "certApply": "Usar este certificado",
+      "certUseCa": "Usar la CA de NetPulse",
+      "certCurrentCa": "Sirviendo la CA de NetPulse.",
+      "certCurrentCustom": "Sirviendo {{path}}.",
+      "certRenewHint": "Este certificado se renueva donde se emitió. Si el nuevo usa otra clave, los agentes anclados a la anterior dejan de reportar hasta que los reinstales, así que renueva con la misma clave (certbot --reuse-key).",
       "loadError": "No se pudieron cargar los ajustes de HTTPS.",
       "unavailable": "HTTPS se gestiona fuera de esta página: {{reason}}.",
       "enabled": "HTTPS",

+ 99 - 3
app/src/components/HttpsCard.tsx

@@ -1,7 +1,7 @@
 import { useState, useEffect, useCallback, useRef } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useSearchParams } from 'react-router'
-import { Loader2, Check, Lock, Download, Copy, ShieldCheck, TriangleAlert, ExternalLink, RefreshCw, Send } from 'lucide-react'
+import { Loader2, Check, Lock, Download, Copy, ShieldCheck, TriangleAlert, ExternalLink, RefreshCw, Send, KeyRound } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
 import { InfoTip } from '@/components/InfoTip'
 
@@ -24,6 +24,11 @@ interface HttpsStatus {
   port: number
   portLocked?: boolean
   rootSha256?: string
+  // #1756: "custom" when the listener serves the pair below instead of the
+  // private CA, so there is no root to download and nothing to renew here.
+  certSource?: 'ca' | 'custom'
+  certPath?: string
+  keyPath?: string
   fingerprint?: string
   names?: string[]
   uncovered?: string[]
@@ -34,7 +39,7 @@ interface HttpsStatus {
   agentsOnHttp?: { slug: string; lastSeen: string }[] | null
 }
 
-type Change = { enabled?: boolean; mode?: Mode; port?: number; force?: boolean }
+type Change = { enabled?: boolean; mode?: Mode; port?: number; cert?: string; key?: string; force?: boolean }
 
 const MODES: Mode[] = ['full', 'migrate', 'redirect']
 
@@ -57,6 +62,11 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
   const [reemitError, setReemitError] = useState('')
   const [renewNote, setRenewNote] = useState('')
   const [portDraft, setPortDraft] = useState(0)
+  // #1756: the pair set in Settings. The draft only reaches the server when
+  // the admin confirms it with the password.
+  const [certMode, setCertMode] = useState<'ca' | 'custom'>('ca')
+  const [certDraft, setCertDraft] = useState('')
+  const [keyDraft, setKeyDraft] = useState('')
   const confirming = useRef(false)
   const changeRef = useRef(change)
   changeRef.current = change
@@ -72,6 +82,9 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
       setSt({ ...d, agentsOnHttp: d.agentsOnHttp ?? [], names: d.names ?? [] })
       // No pisar el borrador si hay un cambio de puerto pendiente (#978).
       if (!changeRef.current?.port) setPortDraft(d.port)
+      setCertMode(d.certSource === 'custom' ? 'custom' : 'ca')
+      setCertDraft(d.certPath ?? '')
+      setKeyDraft(d.keyPath ?? '')
     } catch {
       setLoadError(t('settings.https.loadError'))
     }
@@ -258,9 +271,91 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
       {(st.enabledLocked || st.portLocked) && <p className="text-[11px] text-text-muted">{t('settings.https.locked')}</p>}
       {st.error && <p className="text-xs text-danger">{st.error}</p>}
 
+      {/* #1756: where the certificate comes from */}
+      <div className="rounded-lg border border-border bg-elevated p-3">
+        <div className="mb-1 flex flex-wrap items-center justify-between gap-2">
+          <div className="flex items-center gap-2 text-sm font-medium text-text-primary">
+            <KeyRound className="h-4 w-4 text-accent" strokeWidth={2} />
+            {t('settings.https.certTitle')}
+            <InfoTip text={t('settings.https.certHint')} />
+          </div>
+          <div className="flex gap-1">
+            {(['ca', 'custom'] as const).map((mode) => (
+              <button
+                key={mode}
+                type="button"
+                aria-pressed={certMode === mode}
+                onClick={() => setCertMode(mode)}
+                disabled={busy}
+                className={
+                  'inline-flex h-7 items-center rounded-lg border px-2 text-[11px] font-medium disabled:opacity-50 ' +
+                  (certMode === mode
+                    ? 'border-accent bg-accent/10 text-text-primary'
+                    : 'border-border bg-surface text-text-muted hover:bg-hover')
+                }
+              >
+                {t(mode === 'ca' ? 'settings.https.certModeCa' : 'settings.https.certModeCustom')}
+              </button>
+            ))}
+          </div>
+        </div>
+        {certMode === 'custom' && (
+          <div className="mt-2 space-y-2">
+            <label className="block text-[11px] text-text-muted">
+              {t('settings.https.certPathLabel')}
+              <input
+                className={`${inputCls} mt-1 w-full font-mono`}
+                value={certDraft}
+                onChange={(e) => setCertDraft(e.target.value)}
+                placeholder="/etc/letsencrypt/live/host/fullchain.pem"
+                spellCheck={false}
+                autoComplete="off"
+              />
+            </label>
+            <label className="block text-[11px] text-text-muted">
+              {t('settings.https.keyPathLabel')}
+              <input
+                className={`${inputCls} mt-1 w-full font-mono`}
+                value={keyDraft}
+                onChange={(e) => setKeyDraft(e.target.value)}
+                placeholder="/etc/letsencrypt/live/host/privkey.pem"
+                spellCheck={false}
+                autoComplete="off"
+              />
+            </label>
+            {st.certSource === 'custom' && (
+              <p className="text-[11px] leading-relaxed text-warn">{t('settings.https.certRenewHint')}</p>
+            )}
+          </div>
+        )}
+        <div className="mt-2 flex flex-wrap items-center gap-2">
+          <button
+            type="button"
+            disabled={busy || (certMode === 'custom' && (!certDraft.trim() || !keyDraft.trim()))}
+            onClick={() =>
+              setChange((c) => ({
+                ...c,
+                cert: certMode === 'custom' ? certDraft.trim() : '',
+                key: certMode === 'custom' ? keyDraft.trim() : '',
+              }))
+            }
+            className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 text-xs font-medium text-text-primary hover:bg-hover disabled:opacity-50"
+          >
+            {t(certMode === 'custom' ? 'settings.https.certApply' : 'settings.https.certUseCa')}
+          </button>
+          <span className="text-[11px] text-text-muted">
+            {st.certSource === 'custom'
+              ? t('settings.https.certCurrentCustom', { path: st.certPath ?? '' })
+              : t('settings.https.certCurrentCa')}
+          </span>
+        </div>
+      </div>
+
       {st.enabled && (
         <>
-          {/* The root, for devices to install */}
+          {/* The root, for devices to install. A certificate from disk has
+              no root of ours to hand out (#1756). */}
+          {st.certSource !== 'custom' && (
           <div className="rounded-lg border border-border bg-elevated p-3">
             <div className="mb-1 flex items-center gap-2 text-sm font-medium text-text-primary">
               <ShieldCheck className="h-4 w-4 text-accent" strokeWidth={2} />
@@ -311,6 +406,7 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
               {renewNote && <span className="text-[11px] text-text-muted">{renewNote}</span>}
             </div>
           </div>
+          )}
 
           {/* The pin for agents */}
           <div>

+ 17 - 4
docs/https.md

@@ -195,13 +195,26 @@ To create a new CA, for example to cover a new name:
 Removing only one of `ca.pem` and `ca-key.pem` is refused: a lost half is
 restored from a backup, never silently replaced.
 
+## A certificate of your own
+
+Settings > HTTPS > Certificate serves a pair that is already on the server
+instead of the private CA. Give the absolute paths to the full chain and its
+key. They are read on every handshake, so a renewal is picked up without a
+restart as long as the files keep their names. Nothing changes until the pair
+loads: a typo leaves the running listener as it was.
+
+With a certificate from disk there is no root of ours to download and nothing
+to renew from this page. The pin agents are given is the key of that
+certificate, so renew it with the same key (for example `certbot --reuse-key`)
+or reinstall the agents afterwards.
+
 ## Other HTTPS set-ups
 
 - **On-box** (`NETPULSE_ONBOX=1`) keeps its own HTTPS on the server's port.
-- **A certificate of your own** (`NETPULSE_TLS_CERT` / `NETPULSE_TLS_KEY`)
-  keeps working as before. If agents pin its key, renew it keeping the same
-  key (for example `certbot --reuse-key`). Agents pinning a CA need that CA's
-  certificate in the chain the server sends.
+- **A certificate of your own** can also come from the environment
+  (`NETPULSE_TLS_CERT` / `NETPULSE_TLS_KEY`), which wins over the setting
+  above. Agents pinning a CA need that CA's certificate in the chain the
+  server sends.
 - **Behind a TLS-terminating proxy**, agents see the proxy's certificate. Set
   `NETPULSE_SERVER_FP` on them by hand; pairing cannot prove a key the server
   does not hold.

+ 93 - 0
server-go/internal/httpapi/https_customcert_test.go

@@ -0,0 +1,93 @@
+package httpapi_test
+
+// FORK: #1756 - setting a certificate from disk through Settings.
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/pem"
+	"fmt"
+	"math/big"
+	"net"
+	"net/http"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+)
+
+func writeTestPair(t *testing.T, dir, name string) (string, string) {
+	t.Helper()
+	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	tmpl := &x509.Certificate{
+		SerialNumber: big.NewInt(9),
+		Subject:      pkix.Name{CommonName: name},
+		DNSNames:     []string{name},
+		IPAddresses:  []net.IP{net.ParseIP("192.168.50.2")},
+		NotBefore:    time.Now().Add(-time.Hour),
+		NotAfter:     time.Now().Add(24 * time.Hour),
+		KeyUsage:     x509.KeyUsageDigitalSignature,
+		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+	}
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+	if err != nil {
+		t.Fatal(err)
+	}
+	kb, err := x509.MarshalECPrivateKey(key)
+	if err != nil {
+		t.Fatal(err)
+	}
+	certPath := filepath.Join(dir, name+".crt")
+	keyPath := filepath.Join(dir, name+".key")
+	if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb}), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	return certPath, keyPath
+}
+
+func TestACertificateCanBeSetFromSettings(t *testing.T) {
+	ts, mgr := makeHTTPSTestServer(t)
+	certPath, keyPath := writeTestPair(t, t.TempDir(), "monitor-box")
+
+	st, body := httpsCall(t, ts, "POST", "/api/settings/https",
+		fmt.Sprintf(`{"cert":%q,"key":%q,"password":"test123456"}`, certPath, keyPath), true)
+	if st != http.StatusOK {
+		t.Fatalf("status %d: %v", st, body)
+	}
+	status, _ := body["status"].(map[string]any)
+	if status["certSource"] != "custom" {
+		t.Fatalf("status after setting the pair: %v", body)
+	}
+	if got := mgr.Status(); got.CertPath != certPath || got.KeyPath != keyPath {
+		t.Fatalf("the manager kept %+v", got)
+	}
+
+	// A pair that does not load is rejected and the current one stays.
+	st, body = httpsCall(t, ts, "POST", "/api/settings/https",
+		fmt.Sprintf(`{"cert":%q,"key":%q,"password":"test123456"}`,
+			filepath.Join(t.TempDir(), "nope.crt"), filepath.Join(t.TempDir(), "nope.key")), true)
+	if st != http.StatusBadRequest {
+		t.Fatalf("a bad pair: status %d: %v", st, body)
+	}
+	if got := mgr.Status(); got.CertPath != certPath {
+		t.Fatalf("a rejected pair changed the setting: %+v", got)
+	}
+
+	// Empty paths go back to the private CA.
+	st, body = httpsCall(t, ts, "POST", "/api/settings/https", `{"cert":"","key":"","password":"test123456"}`, true)
+	if st != http.StatusOK {
+		t.Fatalf("back to the CA: status %d: %v", st, body)
+	}
+	if got := mgr.Status(); got.CertSource != "ca" {
+		t.Fatalf("back to the CA: %+v", got)
+	}
+}

+ 34 - 2
server-go/internal/httpapi/https_settings.go

@@ -4,7 +4,7 @@ package httpapi
 // still do, and handing out the private CA's root. See internal/tlsmode.
 //
 //	GET  /api/settings/https          (admin) state, and the agents still on HTTP
-//	POST /api/settings/https          (admin, password) {enabled?, mode?, force?}
+//	POST /api/settings/https          (admin, password) {enabled?, mode?, port?, cert?, key?, force?}
 //	POST /api/settings/https/confirm  (admin, over HTTPS) {code}
 //	GET  /netpulse-ca.crt | .pem      (anyone) the root, for devices to install
 
@@ -19,6 +19,7 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/security"
+	"github.com/gnacho/netpulse/server-go/internal/tlscert"
 	"github.com/gnacho/netpulse/server-go/internal/tlsmode"
 )
 
@@ -177,11 +178,13 @@ func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
 		Enabled  *bool   `json:"enabled"`
 		Mode     *string `json:"mode"`
 		Port     *int    `json:"port"`
+		Cert     *string `json:"cert"`
+		Key      *string `json:"key"`
 		Force    bool    `json:"force"`
 		Password string  `json:"password"`
 	}
 	if st := readJSONBody(w, r, &body); st != 0 {
-		writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "port"?, "password" }`)
+		writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "port"?, "cert"?, "key"?, "password" }`)
 		return
 	}
 	// Counted as sign-in attempts: a stolen session must not be a way to
@@ -228,6 +231,35 @@ func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
 			return
 		}
 	}
+	if body.Cert != nil || body.Key != nil {
+		cert, key := "", ""
+		if body.Cert != nil {
+			cert = strings.TrimSpace(*body.Cert)
+		}
+		if body.Key != nil {
+			key = strings.TrimSpace(*body.Key)
+		}
+		// #1756: agents on HTTPS pin the key they were given. Switching to
+		// a certificate with a different key leaves them unable to verify,
+		// so it needs the same acknowledgement as turning HTTPS off. A
+		// renewal that keeps the key (certbot --reuse-key) does not.
+		if !body.Force && s.tlsMgr.Enabled() && cert != "" {
+			if moved := s.agentsByTransport(true); len(moved) > 0 {
+				if r, err := tlscert.NewReloader(cert, key); err == nil && r.Fingerprint() != s.tlsMgr.Fingerprint() {
+					writeJSON(w, http.StatusConflict, map[string]any{
+						"error":   "agents_on_https",
+						"message": "this certificate has a different key, so the agents pinned to the current one would stop reporting",
+						"agents":  moved,
+					})
+					return
+				}
+			}
+		}
+		if err := s.tlsMgr.SetCertificate(cert, key, by); err != nil {
+			writeHTTPSError(w, err)
+			return
+		}
+	}
 	if body.Enabled != nil {
 		if err := s.tlsMgr.SetEnabled(*body.Enabled, by); err != nil {
 			writeHTTPSError(w, err)

+ 18 - 8
server-go/internal/tlscert/reloader.go

@@ -72,18 +72,28 @@ func (r *Reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error
 // --reuse-key), and a value captured at start-up would hand agents a pin
 // the server no longer matches. Empty if the served pair cannot be parsed.
 func (r *Reloader) Fingerprint() string {
+	if leaf := r.Leaf(); leaf != nil {
+		return Fingerprint(leaf)
+	}
+	return ""
+}
+
+// Leaf devuelve la hoja que se está sirviendo ahora (#1756), para que el
+// estado de HTTPS pueda mostrar sus nombres y su caducidad. Pasa por
+// GetCertificate, así que también recarga si el par cambió en disco.
+func (r *Reloader) Leaf() *x509.Certificate {
 	cert, _ := r.GetCertificate(nil)
 	if cert == nil || len(cert.Certificate) == 0 {
-		return ""
+		return nil
 	}
-	leaf := cert.Leaf
-	if leaf == nil {
-		var err error
-		if leaf, err = x509.ParseCertificate(cert.Certificate[0]); err != nil {
-			return ""
-		}
+	if cert.Leaf != nil {
+		return cert.Leaf
+	}
+	leaf, err := x509.ParseCertificate(cert.Certificate[0])
+	if err != nil {
+		return nil
 	}
-	return Fingerprint(leaf)
+	return leaf
 }
 
 // reload repuebla la caché desde disco. Debe llamarse con r.mu tomado.

+ 195 - 0
server-go/internal/tlsmode/customcert_test.go

@@ -0,0 +1,195 @@
+package tlsmode
+
+// FORK: #1756 - a certificate from disk replaces the private CA. Names and
+// paths are invented.
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/pem"
+	"math/big"
+	"net"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+)
+
+// writePair leaves a self-signed certificate and its key in dir.
+func writePair(t *testing.T, dir, name string) (string, string) {
+	t.Helper()
+	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	tmpl := &x509.Certificate{
+		SerialNumber:          big.NewInt(7),
+		Subject:               pkix.Name{CommonName: name},
+		DNSNames:              []string{name},
+		IPAddresses:           []net.IP{net.ParseIP("192.168.50.2")},
+		NotBefore:             time.Now().Add(-time.Hour),
+		NotAfter:              time.Now().Add(24 * time.Hour),
+		KeyUsage:              x509.KeyUsageDigitalSignature,
+		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		BasicConstraintsValid: true,
+	}
+	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+	if err != nil {
+		t.Fatal(err)
+	}
+	kb, err := x509.MarshalECPrivateKey(key)
+	if err != nil {
+		t.Fatal(err)
+	}
+	certPath := filepath.Join(dir, name+".crt")
+	keyPath := filepath.Join(dir, name+".key")
+	if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb}), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	return certPath, keyPath
+}
+
+func TestACertificateFromDiskReplacesTheCA(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
+	if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
+		t.Fatal(err)
+	}
+	st := r.m.Status()
+	if st.CertSource != "custom" || st.CertPath != certPath || st.KeyPath != keyPath {
+		t.Fatalf("status does not point at the pair: %+v", st)
+	}
+	if st.RootSHA256 != "" || len(st.Uncovered) != 0 {
+		t.Errorf("a certificate from disk has no root of ours to hand out: %+v", st)
+	}
+	if len(st.Names) != 2 || st.Names[0] != "monitor-box" || st.Names[1] != "192.168.50.2" {
+		t.Errorf("names of the served leaf: %v", st.Names)
+	}
+	if st.Fingerprint == "" || st.Fingerprint != r.m.Fingerprint() {
+		t.Errorf("pin: status %q, manager %q", st.Fingerprint, r.m.Fingerprint())
+	}
+	// The listener serves it: the rig pins whatever the manager reports, so
+	// a handshake only succeeds if the served leaf is the one on disk.
+	if body, err := r.getTLS("/"); err != nil {
+		t.Fatalf("the listener does not serve the new pair: %v", err)
+	} else if body != "tls=true" {
+		t.Fatalf("body %q", body)
+	}
+	// Going back to the CA brings its root back.
+	if err := r.m.SetCertificate("", "", "test"); err != nil {
+		t.Fatal(err)
+	}
+	if st := r.m.Status(); st.CertSource != "ca" || st.RootSHA256 == "" {
+		t.Fatalf("back to the CA: %+v", st)
+	}
+	if _, err := r.getTLS("/"); err != nil {
+		t.Fatalf("the CA listener did not come back: %v", err)
+	}
+}
+
+func TestABadPairLeavesTheListenerAlone(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	before, beforeStatus := r.m.Fingerprint(), r.m.Status()
+
+	for name, err := range map[string]error{
+		"missing file":    r.m.SetCertificate(filepath.Join(t.TempDir(), "nope.crt"), filepath.Join(t.TempDir(), "nope.key"), "test"),
+		"relative path":   r.m.SetCertificate("cert.pem", "key.pem", "test"),
+		"only one of two": r.m.SetCertificate(filepath.Join(t.TempDir(), "nope.crt"), "", "test"),
+	} {
+		if err == nil {
+			t.Errorf("%s: no error", name)
+		}
+	}
+	if got := r.m.Fingerprint(); got != before {
+		t.Errorf("the pin changed after a rejected pair: %q -> %q", before, got)
+	}
+	if st := r.m.Status(); st.CertSource != beforeStatus.CertSource {
+		t.Errorf("the source changed after a rejected pair: %q", st.CertSource)
+	}
+	if _, err := r.getTLS("/"); err != nil {
+		t.Fatalf("the listener stopped serving: %v", err)
+	}
+}
+
+func TestAgentTrustWithACertificateFromDisk(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
+	if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
+		t.Fatal(err)
+	}
+	tr := AgentTrust(r.m, func() string { return "legacy-pin" }, "http://192.168.50.2:3000")
+	if tr.ServerURL == "" {
+		t.Fatal("no HTTPS URL with a certificate from disk")
+	}
+	if tr.ServerFP != r.m.Fingerprint() {
+		t.Errorf("pin %q, want the served leaf %q", tr.ServerFP, r.m.Fingerprint())
+	}
+	if len(tr.CAPEM) != 0 {
+		t.Errorf("there is no root to hand out, got %d bytes", len(tr.CAPEM))
+	}
+}
+
+func TestRenewRefusesACertificateFromDisk(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
+	if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := r.m.Renew("test"); err == nil || !strings.Contains(err.Error(), "file") {
+		t.Fatalf("renew: %v", err)
+	}
+}
+
+// The pair survives a restart: a new manager on the same database serves it
+// without going through the UI again.
+func TestACertificateFromDiskSurvivesARestart(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "test"); err != nil {
+		t.Fatal(err)
+	}
+	certPath, keyPath := writePair(t, t.TempDir(), "monitor-box")
+	if err := r.m.SetCertificate(certPath, keyPath, "test"); err != nil {
+		t.Fatal(err)
+	}
+	want := r.m.Fingerprint()
+	r.m.Close()
+
+	opts := Options{
+		DB: r.db, DataDir: r.dir, Port: r.port,
+		NewServer: func(addr string, h http.Handler) *http.Server {
+			return &http.Server{Addr: addr, Handler: h, ReadHeaderTimeout: 5 * time.Second}
+		},
+		Now: func() time.Time { return r.now },
+	}
+	m := New(opts)
+	if err := m.Start(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(m.Close)
+	if st := m.Status(); st.CertSource != "custom" || st.CertPath != certPath {
+		t.Fatalf("after a restart: %+v", st)
+	}
+	if got := m.Fingerprint(); got != want {
+		t.Errorf("pin after a restart: %q, want %q", got, want)
+	}
+}

+ 178 - 30
server-go/internal/tlsmode/manager.go

@@ -26,6 +26,7 @@ import (
 	"context"
 	"crypto/rand"
 	"crypto/subtle"
+	"crypto/x509"
 	"database/sql"
 	"encoding/hex"
 	"errors"
@@ -68,6 +69,10 @@ const (
 	kvEnabled = "settings.https.enabled"
 	kvMode    = "settings.https.mode"
 	kvPort    = "settings.https.port" // #978: UI-chosen HTTPS port
+	// kvCert and kvKey (#1756) point at a certificate on disk that replaces
+	// the private CA. Both set, or both empty.
+	kvCert = "settings.https.cert"
+	kvKey  = "settings.https.key"
 	// kvPortMigrated (FORK) marks that the pre-#978 port was decided once.
 	kvPortMigrated = "settings.https.port_migrated"
 
@@ -129,6 +134,9 @@ type Manager struct {
 	pending  *pendingMode
 	mode     atomic.Value // Mode
 	caLoaded atomic.Pointer[tlscert.CA]
+	// reloader serves a certificate set in Settings instead of the CA
+	// (#1756). Nil when the CA is the source.
+	reloader *tlscert.Reloader
 
 	sniff *sniffServer
 }
@@ -269,7 +277,18 @@ func (m *Manager) openCALocked() error {
 }
 
 func (m *Manager) startLocked() error {
-	if err := m.openCALocked(); err != nil {
+	// #1756: a certificate set in Settings wins over the private CA, so a
+	// homelab that already has its own PKI serves that. A pair that no
+	// longer loads fails here, before the listener is bound.
+	certPath, keyPath := m.savedCert()
+	var reloader *tlscert.Reloader
+	if certPath != "" {
+		r, err := tlscert.NewReloader(certPath, keyPath)
+		if err != nil {
+			return fmt.Errorf("the certificate from Settings: %w", err)
+		}
+		reloader = r
+	} else if err := m.openCALocked(); err != nil {
 		return err
 	}
 	addr := fmt.Sprintf(":%d", m.port)
@@ -287,7 +306,12 @@ func (m *Manager) startLocked() error {
 		return fmt.Errorf("HTTPS listener on %s: %w", addr, err)
 	}
 	srv := m.opts.NewServer(addr, m.handler)
-	srv.TLSConfig = m.ca.TLSConfig()
+	m.reloader = reloader
+	if reloader != nil {
+		srv.TLSConfig = reloader.Config()
+	} else {
+		srv.TLSConfig = m.ca.TLSConfig()
+	}
 	m.srv = srv
 	go func() {
 		if err := srv.ServeTLS(ln, "", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
@@ -295,13 +319,18 @@ func (m *Manager) startLocked() error {
 		}
 	}()
 	m.lastErr = ""
-	m.opts.Logf("[netpulse] HTTPS on :%d (private CA)", m.port)
+	source := "private CA"
+	if reloader != nil {
+		source = "certificate from Settings"
+	}
+	m.opts.Logf("[netpulse] HTTPS on :%d (%s)", m.port, source)
 	return nil
 }
 
 func (m *Manager) stopLocked() {
 	if srv := m.srv; srv != nil {
 		m.srv = nil
+		m.reloader = nil
 		// Shutdown closes the listener at once - the port is free to be
 		// opened again - and lets requests in flight finish, including the
 		// one that turned HTTPS off, whose answer would otherwise be lost.
@@ -484,12 +513,73 @@ func (m *Manager) Enabled() bool {
 	return m.enabled
 }
 
-// Fingerprint is the pin agents should use: the root's SPKI, or "" while
-// HTTPS is off.
+// SetCertificate makes the HTTPS listener serve a certificate from disk
+// instead of the private CA (#1756), which is what a homelab with its own PKI
+// wants. Empty paths go back to the CA. The pair is loaded before anything
+// changes, so a typo leaves the running listener untouched.
+func (m *Manager) SetCertificate(certPath, keyPath, by string) error {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.opts.Unavailable != "" {
+		return ErrLocked
+	}
+	certPath, keyPath = strings.TrimSpace(certPath), strings.TrimSpace(keyPath)
+	if (certPath == "") != (keyPath == "") {
+		return errors.New("give both the certificate and its key, or neither")
+	}
+	if certPath != "" {
+		if !filepath.IsAbs(certPath) || !filepath.IsAbs(keyPath) {
+			return errors.New("the certificate and key paths must be absolute")
+		}
+		if _, err := tlscert.NewReloader(certPath, keyPath); err != nil {
+			return fmt.Errorf("the certificate cannot be used: %w", err)
+		}
+	}
+	oldCert, oldKey := m.savedCert()
+	if certPath == oldCert && keyPath == oldKey {
+		return nil
+	}
+	m.kvSet(kvCert, certPath)
+	m.kvSet(kvKey, keyPath)
+	if m.enabled {
+		m.stopLocked()
+		if err := m.startLocked(); err != nil {
+			// Put back what was serving so a bad pair does not leave the
+			// port closed.
+			m.kvSet(kvCert, oldCert)
+			m.kvSet(kvKey, oldKey)
+			if back := m.startLocked(); back != nil {
+				m.lastErr = back.Error()
+				return fmt.Errorf("%w (and the previous certificate did not come back: %v)", err, back)
+			}
+			m.lastErr = ""
+			return err
+		}
+	}
+	source := "the private CA"
+	if certPath != "" {
+		source = "the certificate set in Settings"
+	}
+	m.opts.Logf("[netpulse] TLS: HTTPS now serves %s (%s)", source, by)
+	return nil
+}
+
+// Fingerprint is the pin agents should use: the SPKI of the certificate the
+// listener serves now (the CA's leaf, or the one set in Settings, #1756), or
+// "" while HTTPS is off.
 func (m *Manager) Fingerprint() string {
-	if !m.Enabled() {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.fingerprintLocked()
+}
+
+func (m *Manager) fingerprintLocked() string {
+	if !m.enabled {
 		return ""
 	}
+	if m.reloader != nil {
+		return m.reloader.Fingerprint()
+	}
 	if ca := m.caLoaded.Load(); ca != nil {
 		return ca.Fingerprint()
 	}
@@ -499,24 +589,58 @@ func (m *Manager) Fingerprint() string {
 // CA is the private CA once it has been opened, for serving its root.
 func (m *Manager) CA() *tlscert.CA { return m.caLoaded.Load() }
 
+// CertSource says where the served certificate comes from: "custom" when a
+// pair was set in Settings (#1756), "ca" otherwise.
+func (m *Manager) CertSource() string {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if cert, _ := m.savedCert(); cert != "" {
+		return "custom"
+	}
+	return "ca"
+}
+
+// Leaf is the certificate the HTTPS listener serves now, nil while HTTPS is
+// off. The trust helpers use it to know which names the server answers to.
+func (m *Manager) Leaf() *x509.Certificate {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if !m.enabled {
+		return nil
+	}
+	if m.reloader != nil {
+		return m.reloader.Leaf()
+	}
+	if ca := m.caLoaded.Load(); ca != nil {
+		return ca.Leaf()
+	}
+	return nil
+}
+
 // Status is what the settings page shows.
 type Status struct {
-	Available     bool      `json:"available"`
-	Unavailable   string    `json:"unavailable,omitempty"`
-	Enabled       bool      `json:"enabled"`
-	EnabledLocked bool      `json:"enabledLocked"`
-	Mode          Mode      `json:"mode"`
-	ModeLocked    bool      `json:"modeLocked"`
-	Port          int       `json:"port"`
-	PortLocked    bool      `json:"portLocked"`
-	RootSHA256    string    `json:"rootSha256,omitempty"`
-	Fingerprint   string    `json:"fingerprint,omitempty"`
-	Names         []string  `json:"names,omitempty"`
-	Uncovered     []string  `json:"uncovered,omitempty"`
-	ValidUntil    time.Time `json:"validUntil,omitzero"`
-	Pending       Mode      `json:"pending,omitempty"`
-	PendingUntil  time.Time `json:"pendingUntil,omitzero"`
-	Error         string    `json:"error,omitempty"`
+	Available     bool   `json:"available"`
+	Unavailable   string `json:"unavailable,omitempty"`
+	Enabled       bool   `json:"enabled"`
+	EnabledLocked bool   `json:"enabledLocked"`
+	Mode          Mode   `json:"mode"`
+	ModeLocked    bool   `json:"modeLocked"`
+	Port          int    `json:"port"`
+	PortLocked    bool   `json:"portLocked"`
+	RootSHA256    string `json:"rootSha256,omitempty"`
+	Fingerprint   string `json:"fingerprint,omitempty"`
+	// #1756: where the served certificate comes from. "custom" means the
+	// paths below, so there is no root to download and nothing to renew
+	// from here.
+	CertSource   string    `json:"certSource"`
+	CertPath     string    `json:"certPath,omitempty"`
+	KeyPath      string    `json:"keyPath,omitempty"`
+	Names        []string  `json:"names,omitempty"`
+	Uncovered    []string  `json:"uncovered,omitempty"`
+	ValidUntil   time.Time `json:"validUntil,omitzero"`
+	Pending      Mode      `json:"pending,omitempty"`
+	PendingUntil time.Time `json:"pendingUntil,omitzero"`
+	Error        string    `json:"error,omitempty"`
 }
 
 // Status reports the current state.
@@ -537,13 +661,27 @@ func (m *Manager) Status() Status {
 	if p := m.pending; p != nil && m.opts.Now().Before(p.expires) {
 		st.Pending, st.PendingUntil = p.mode, p.expires
 	}
-	if m.ca != nil && m.enabled {
-		st.RootSHA256 = m.ca.RootSHA256()
-		st.Fingerprint = m.ca.Fingerprint()
-		st.Uncovered = m.ca.Uncovered()
-		if leaf := m.ca.Leaf(); leaf != nil {
-			st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
-			st.ValidUntil = leaf.NotAfter
+	certPath, keyPath := m.savedCert()
+	st.CertSource = "ca"
+	if certPath != "" {
+		st.CertSource, st.CertPath, st.KeyPath = "custom", certPath, keyPath
+	}
+	if m.enabled {
+		switch {
+		case m.reloader != nil:
+			st.Fingerprint = m.reloader.Fingerprint()
+			if leaf := m.reloader.Leaf(); leaf != nil {
+				st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
+				st.ValidUntil = leaf.NotAfter
+			}
+		case m.ca != nil:
+			st.RootSHA256 = m.ca.RootSHA256()
+			st.Fingerprint = m.ca.Fingerprint()
+			st.Uncovered = m.ca.Uncovered()
+			if leaf := m.ca.Leaf(); leaf != nil {
+				st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
+				st.ValidUntil = leaf.NotAfter
+			}
 		}
 	}
 	return st
@@ -554,8 +692,12 @@ func (m *Manager) Status() Status {
 // whether it issued one. The root, and so every pin, stays the same.
 func (m *Manager) Renew(by string) (bool, error) {
 	m.mu.Lock()
-	ca, on := m.ca, m.enabled
+	ca, on, custom := m.ca, m.enabled, m.reloader != nil
 	m.mu.Unlock()
+	if custom {
+		// #1756: nothing to reissue, the file is someone else's.
+		return false, errors.New("this certificate comes from a file, renew it where it is issued")
+	}
 	if ca == nil || !on {
 		return false, errors.New("turn HTTPS on first")
 	}
@@ -647,6 +789,12 @@ func (m *Manager) savedMode() Mode {
 }
 
 // savedPort (#978): the UI-chosen port, 0 when absent or invalid.
+// savedCert is the certificate pair set in Settings, empty when the private
+// CA is the source (#1756).
+func (m *Manager) savedCert() (string, string) {
+	return m.kvGet(kvCert), m.kvGet(kvKey)
+}
+
 func (m *Manager) savedPort() int {
 	v := m.kvGet(kvPort)
 	if v == "" {

+ 7 - 6
server-go/internal/tlsmode/trust.go

@@ -13,14 +13,10 @@ import (
 // whatever address routers were given (NETPULSE_PUBLIC_URL, or the one the
 // admin browsed to).
 func (m *Manager) HTTPSURL(base string) string {
-	if !m.Enabled() {
+	leaf := m.Leaf()
+	if leaf == nil {
 		return ""
 	}
-	ca := m.CA()
-	if ca == nil || ca.Leaf() == nil {
-		return ""
-	}
-	leaf := ca.Leaf()
 	host := urlHost(base)
 	if host == "" {
 		host = hostOnly(base)
@@ -44,6 +40,11 @@ func (m *Manager) HTTPSURL(base string) string {
 func AgentTrust(m *Manager, legacyFP func() string, base string) reinstall.Trust {
 	if m != nil {
 		if url := m.HTTPSURL(base); url != "" {
+			if m.CertSource() == "custom" {
+				// #1756: a certificate from disk has no root of ours to
+				// hand out, so the agent pins the leaf itself.
+				return reinstall.Trust{ServerURL: url, ServerFP: m.Fingerprint()}
+			}
 			ca := m.CA()
 			return reinstall.Trust{ServerURL: url, ServerFP: ca.Fingerprint(), CAPEM: ca.RootPEM()}
 		}