Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/clustering.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ the ML-DSA CA, so a node that hasn't learned the new anchor keeps verifying the
ECDSA one. Either way the connection's key exchange is the X25519MLKEM768
hybrid. ACME and imported certificates stay classical.

A cluster made before ML-DSA certificates has the ECDSA chain only. Once every
node runs a release with ML-DSA support, the primary's **Cluster** page offers
**Upgrade to Post-Quantum** in the **Post-Quantum Certificates** card. Each node
then adds the ML-DSA CA and certificate to its own Sable Private CA within a
minute, without a restart, and the card shows each node's state. The ECDSA
chain stays, so nothing changes for browsers. A node with an ACME or imported
certificate is left as it is. Don't downgrade a node below this release once
it is upgraded: older releases can't read the ML-DSA CA in its trust anchor.

## Create the primary

1. Open **Cluster → Initialize Primary**.
Expand Down
17 changes: 17 additions & 0 deletions internal/app/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,7 @@ func (process *process) startWeb(ctx context.Context) error {
if err := process.clusterService.SetUpdateController(process.updateManager, requestRestart); err != nil {
process.logger.Error("restore cluster update progress", "error", err)
}
process.clusterService.SetPQCertificateUpgrader(process.upgradePQClusterCertificates)
initial := process.initial
if err := webServer.Start(initial.Server.HTTPListen); err != nil {
return err
Expand All @@ -652,6 +653,22 @@ func (process *process) startWeb(ctx context.Context) error {
return nil
}

// upgradePQClusterCertificates adds ML-DSA certificates to this node's
// generated cluster PKI and has the HTTPS listener serve them to peers that
// ask. A node with an imported or ACME certificate is left as it is.
func (process *process) upgradePQClusterCertificates(ctx context.Context) error {
current := process.current()
anchor := current.ClusterTrustAnchorPath(process.configurationDirectory)
if anchor == "" || current.EncryptedDNS.CertificateMode != "manual" || current.Server.HTTPSListen == "" {
return certificates.ErrNotGeneratedClusterPKI
}
certificate, privateKey := current.EncryptedDNSCertificatePaths(process.configurationDirectory)
if err := process.certificateManager.AddClusterPQ(ctx, anchor, certificate, privateKey); err != nil {
return err
}
return process.webServer.ReplaceCertificate(certificate, privateKey)
}

func (process *process) newWebServer() error {
var webAuthentication web.Authenticator
if process.authentication != nil {
Expand Down
90 changes: 89 additions & 1 deletion internal/certificates/cluster_pq.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package certificates

import (
"bytes"
"context"
"crypto/mldsa"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"net"
"os"
Expand Down Expand Up @@ -125,6 +127,13 @@ func (pq clusterPQ) commit(caKey *mldsa.PrivateKey, caDER []byte, nodeKey *mldsa
if err := writeAtomic(pq.caKeyFile, caKeyPEM, 0o600); err != nil {
return fmt.Errorf("write ML-DSA cluster CA private key: %w", err)
}
// The node certificate goes first and the trust anchor last. Peers ask
// for the ML-DSA certificate only once the anchor carries its CA, so an
// upgrade cut short leaves nothing that a peer would reach for, and the
// next attempt starts again from a classical anchor.
if err := commitKeyPair(pq.certificateFile, pq.keyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: nodeDER}), nodeKeyPEM); err != nil {
return err
}
anchor, err := os.ReadFile(pq.caFile)
if err != nil {
return fmt.Errorf("read cluster CA certificate: %w", err)
Expand All @@ -136,5 +145,84 @@ func (pq clusterPQ) commit(caKey *mldsa.PrivateKey, caDER []byte, nodeKey *mldsa
if err := writeAtomic(pq.caFile, anchor, 0o600); err != nil {
return fmt.Errorf("write cluster CA certificate: %w", err)
}
return commitKeyPair(pq.certificateFile, pq.keyFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: nodeDER}), nodeKeyPEM)
return nil
}

// ErrNotGeneratedClusterPKI means a node's HTTPS certificate doesn't come
// from a cluster CA that Sable generated and holds the key for, so Sable
// can't add ML-DSA certificates beside it.
var ErrNotGeneratedClusterPKI = errors.New("the HTTPS certificate is not from a Sable-generated cluster CA")

// AddClusterPQ adds the ML-DSA half to a cluster PKI that GenerateClusterPKI
// made before it made one itself: an ML-DSA CA appended to caFile, and an
// ML-DSA node certificate beside certificateFile with the same names and
// expiry. The classical CA and certificate stay as they are, so browsers and
// older peers see no change. It does nothing when caFile already has an
// ML-DSA CA.
func (manager *Manager) AddClusterPQ(_ context.Context, caFile, certificateFile, privateKeyFile string) error {
directory := filepath.Dir(caFile)
if _, err := os.Stat(filepath.Join(directory, "cluster-ca-private-key.pem")); err != nil {
return ErrNotGeneratedClusterPKI
}
anchor, err := os.ReadFile(caFile)
if err != nil {
return fmt.Errorf("read cluster CA certificate: %w", err)
}
if ContainsMLDSA(anchor) {
return nil
}
leaf, err := readLeaf(certificateFile)
if err != nil {
return err
}
if !signedByAnchor(leaf, anchor) {
return ErrNotGeneratedClusterPKI
}
now := manager.now().UTC()
if !leaf.NotAfter.After(now) {
return errors.New("the cluster node certificate has expired; generate a new one first")
}
pqCertificateFile, pqKeyFile := PQCompanionPaths(certificateFile, privateKeyFile)
pq := clusterPQ{
caFile: caFile, caKeyFile: filepath.Join(directory, "cluster-ca-mldsa-private-key.pem"),
certificateFile: pqCertificateFile, keyFile: pqKeyFile,
nodeName: leaf.Subject.CommonName, dnsNames: leaf.DNSNames, ipAddresses: leaf.IPAddresses,
now: now, validFor: leaf.NotAfter.Sub(now),
}
if err := pq.write(); err != nil {
return err
}
manager.logger.Info("ML-DSA certificates added to the private cluster PKI", "node", leaf.Subject.CommonName, "node_expires", leaf.NotAfter)
return nil
}

func readLeaf(certificateFile string) (*x509.Certificate, error) {
contents, err := os.ReadFile(certificateFile)
if err != nil {
return nil, fmt.Errorf("read cluster node certificate: %w", err)
}
block, _ := pem.Decode(contents)
if block == nil || block.Type != "CERTIFICATE" {
return nil, errors.New("cluster node certificate is not PEM encoded")
}
leaf, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parse cluster node certificate: %w", err)
}
return leaf, nil
}

func signedByAnchor(leaf *x509.Certificate, anchor []byte) bool {
for rest := anchor; len(rest) > 0; {
block, remaining := pem.Decode(rest)
if block == nil {
return false
}
rest = remaining
ca, err := x509.ParseCertificate(block.Bytes)
if err == nil && ca.IsCA && leaf.CheckSignatureFrom(ca) == nil {
return true
}
}
return false
}
114 changes: 114 additions & 0 deletions internal/certificates/cluster_pq_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package certificates

import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
"testing"
"time"
)

// classicalClusterPKI generates a cluster PKI and strips its ML-DSA half, as
// a release before ML-DSA certificates left it.
func classicalClusterPKI(t *testing.T) (*Manager, string, string, string) {
t.Helper()
directory := t.TempDir()
manager := New(&memoryVault{}, slog.New(slog.NewTextHandler(io.Discard, nil)), directory)
result, err := manager.GenerateClusterPKI(context.Background(), ClusterPKIOptions{
NodeName: "dns-1", Names: []string{"dns-1.example.test", "192.0.2.10"}, ValidFor: 365 * 24 * time.Hour,
})
if err != nil {
t.Fatal(err)
}
caFile := filepath.Join(directory, result.CAFile)
certificateFile := filepath.Join(directory, result.CertificateFile)
keyFile := filepath.Join(directory, result.PrivateKeyFile)
anchor, err := os.ReadFile(caFile)
if err != nil {
t.Fatal(err)
}
block, _ := pem.Decode(anchor)
if err := os.WriteFile(caFile, pem.EncodeToMemory(block), 0o600); err != nil {
t.Fatal(err)
}
pqCertificate, pqKey := PQCompanionPaths(certificateFile, keyFile)
for _, file := range []string{pqCertificate, pqKey, filepath.Join(filepath.Dir(caFile), "cluster-ca-mldsa-private-key.pem")} {
if err := os.Remove(file); err != nil {
t.Fatal(err)
}
}
return manager, caFile, certificateFile, keyFile
}

func TestAddClusterPQUpgradesAClassicalClusterPKI(t *testing.T) {
manager, caFile, certificateFile, keyFile := classicalClusterPKI(t)
before, _ := os.ReadFile(caFile)
classicalBefore, _ := os.ReadFile(certificateFile)
if err := manager.AddClusterPQ(context.Background(), caFile, certificateFile, keyFile); err != nil {
t.Fatal(err)
}
after, err := os.ReadFile(caFile)
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(after, before) || !ContainsMLDSA(after) {
t.Fatal("the trust anchor should keep its classical CA and gain an ML-DSA one")
}
if classicalAfter, _ := os.ReadFile(certificateFile); !bytes.Equal(classicalAfter, classicalBefore) {
t.Fatal("the classical node certificate changed")
}
classical, err := readLeaf(certificateFile)
if err != nil {
t.Fatal(err)
}
pqCertificate, pqKey := PQCompanionPaths(certificateFile, keyFile)
pair, err := tls.LoadX509KeyPair(pqCertificate, pqKey)
if err != nil {
t.Fatal(err)
}
leaf := pair.Leaf
if leaf.PublicKeyAlgorithm != x509.MLDSA {
t.Fatalf("companion key is %v, want ML-DSA", leaf.PublicKeyAlgorithm)
}
if !slices.Equal(leaf.DNSNames, classical.DNSNames) || len(leaf.IPAddresses) != len(classical.IPAddresses) ||
leaf.Subject.CommonName != classical.Subject.CommonName || leaf.NotAfter.After(classical.NotAfter) {
t.Fatalf("companion certificate names or lifetime differ: %v %v %v", leaf.DNSNames, leaf.IPAddresses, leaf.NotAfter)
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(after)
if _, err := leaf.Verify(x509.VerifyOptions{Roots: pool, DNSName: "dns-1.example.test"}); err != nil {
t.Fatal(err)
}

if err := manager.AddClusterPQ(context.Background(), caFile, certificateFile, keyFile); err != nil {
t.Fatal(err)
}
if again, _ := os.ReadFile(caFile); !bytes.Equal(again, after) {
t.Fatal("a second upgrade changed an anchor that already has an ML-DSA CA")
}
}

func TestAddClusterPQRefusesCertificatesSableDidNotIssue(t *testing.T) {
manager, caFile, _, _ := classicalClusterPKI(t)
directory := t.TempDir()
other := New(&memoryVault{}, slog.New(slog.NewTextHandler(io.Discard, nil)), directory)
foreign, err := other.GenerateSelfSigned(context.Background(), ManualCertificateOptions{Names: []string{"dns-1.example.test"}})
if err != nil {
t.Fatal(err)
}
err = manager.AddClusterPQ(context.Background(), caFile, filepath.Join(directory, foreign.CertificateFile), filepath.Join(directory, foreign.PrivateKeyFile))
if !errors.Is(err, ErrNotGeneratedClusterPKI) {
t.Fatalf("err = %v, want ErrNotGeneratedClusterPKI", err)
}
if err := manager.AddClusterPQ(context.Background(), filepath.Join(directory, foreign.CertificateFile), filepath.Join(directory, foreign.CertificateFile), filepath.Join(directory, foreign.PrivateKeyFile)); !errors.Is(err, ErrNotGeneratedClusterPKI) {
t.Fatalf("err = %v, want ErrNotGeneratedClusterPKI without a CA key", err)
}
}
7 changes: 5 additions & 2 deletions internal/cluster/enrollment.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ type JoinConfiguration struct {
Members []Member `json:"members"`
UpdateCommand *UpdateCommand `json:"update_command,omitempty"`
UpdateProtocol int `json:"update_protocol,omitempty"`
// PQCertificates carries the manifest's flag of the same name.
PQCertificates bool `json:"pq_certificates,omitempty"`
// AlertProtocol is set only on synchronization, by a primary that takes
// replicas' own alerts in their heartbeats.
AlertProtocol int `json:"alert_protocol,omitempty"`
Expand Down Expand Up @@ -454,7 +456,7 @@ func joinConfiguration(source *manifest, stateSnapshot []byte) JoinConfiguration
FormatVersion: source.FormatVersion, ClusterID: source.ClusterID, ClusterDomain: source.ClusterDomain,
Generation: source.Generation, Term: source.Term, UpdatedAt: source.UpdatedAt, PrimaryID: source.PrimaryID,
StatusKey: source.StatusKey, StateDigest: source.StateDigest, StateSnapshot: stateSnapshot,
Members: make([]Member, 0, len(source.Nodes)),
PQCertificates: source.PQCertificates, Members: make([]Member, 0, len(source.Nodes)),
}
for _, node := range source.Nodes {
configuration.Members = append(configuration.Members, Member{
Expand All @@ -471,7 +473,8 @@ func manifestFromJoinConfiguration(source JoinConfiguration) *manifest {
result := &manifest{
FormatVersion: source.FormatVersion, ClusterID: source.ClusterID, ClusterDomain: source.ClusterDomain,
Generation: source.Generation, Term: source.Term, UpdatedAt: source.UpdatedAt, PrimaryID: source.PrimaryID,
StatusKey: source.StatusKey, StateDigest: source.StateDigest, Nodes: make([]member, 0, len(source.Members)),
StatusKey: source.StatusKey, StateDigest: source.StateDigest, PQCertificates: source.PQCertificates,
Nodes: make([]member, 0, len(source.Members)),
}
for _, node := range source.Members {
result.Nodes = append(result.Nodes, member{
Expand Down
2 changes: 2 additions & 0 deletions internal/cluster/heartbeat.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ type SyncConfiguration struct {
Members []Member `json:"members"`
UpdateCommand *UpdateCommand `json:"update_command,omitempty"`
UpdateProtocol int `json:"update_protocol,omitempty"`
PQCertificates bool `json:"pq_certificates,omitempty"`
AlertProtocol int `json:"alert_protocol,omitempty"`
LookupProtocol int `json:"lookup_protocol,omitempty"`
// ClientIdentities is a batch of the lead's client identities as a JSON
Expand Down Expand Up @@ -118,6 +119,7 @@ func (service *Service) StartMonitoring(ctx context.Context) {
gathering.Go(func() { service.gatherLocalLookups(monitorContext) })
gathering.Go(func() { service.gatherClientIdentities(monitorContext) })
gathering.Go(func() { service.probePeers(monitorContext) })
gathering.Go(func() { service.maintainPQCertificates(monitorContext) })
service.monitorPrimary(monitorContext)
gathering.Wait()
}()
Expand Down
Loading