From 227c341f6bb3ca5d88e8a36a2f2bda82474a4687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=C3=ABl=20Cluseau?= Date: Fri, 27 Jan 2023 06:25:51 +0100 Subject: [PATCH] renew: hande more error cases --- cmd/dkl-local-server/secrets.go | 51 +++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/cmd/dkl-local-server/secrets.go b/cmd/dkl-local-server/secrets.go index 490ea5e..fb1987e 100644 --- a/cmd/dkl-local-server/secrets.go +++ b/cmd/dkl-local-server/secrets.go @@ -3,7 +3,6 @@ package main import ( "crypto" "crypto/rand" - "crypto/x509" "encoding/base32" "encoding/json" "errors" @@ -221,19 +220,25 @@ func (sd *SecretData) RenewCACert(cluster, name string) (err error) { ca := cs.CAs[name] - var cert *x509.Certificate - cert, err = helpers.ParseCertificatePEM(ca.Cert) - if err != nil { - return - } - var signer crypto.Signer signer, err = helpers.ParsePrivateKeyPEM(ca.Key) if err != nil { return } - newCert, err := initca.RenewFromSigner(cert, signer) + var newCert []byte + + cert, err := helpers.ParseCertificatePEM(ca.Cert) + if err == nil { + newCert, err = initca.RenewFromSigner(cert, signer) + } + + if err != nil { + // failed to load or renew, create a new cert from the existing key + req := newCACertReq() + newCert, _, err = initca.NewFromSigner(req, signer) + } + if err != nil { return } @@ -247,6 +252,22 @@ func (sd *SecretData) RenewCACert(cluster, name string) (err error) { return } +func newCACertReq() *csr.CertificateRequest { + return &csr.CertificateRequest{ + CN: "Direktil Local Server", + KeyRequest: &csr.KeyRequest{ + A: "ecdsa", + S: 521, // 256, 384, 521 + }, + Names: []csr.Name{ + { + C: "NC", + O: "novit.nc", + }, + }, + } +} + func (sd *SecretData) CA(cluster, name string) (ca *CA, err error) { defer func() { @@ -277,19 +298,7 @@ func (sd *SecretData) CA(cluster, name string) (ca *CA, err error) { log.Info("secret-data: new CA in cluster ", cluster, ": ", name) - req := &csr.CertificateRequest{ - CN: "Direktil Local Server", - KeyRequest: &csr.KeyRequest{ - A: "ecdsa", - S: 521, // 256, 384, 521 - }, - Names: []csr.Name{ - { - C: "NC", - O: "novit.nc", - }, - }, - } + req := newCACertReq() cert, _, key, err := initca.New(req) if err != nil {