From 7f9d7eadc9e9c8647df0d3b0836296885348d3cf Mon Sep 17 00:00:00 2001 From: Mariano Cano Date: Fri, 29 Jan 2021 13:31:07 -0800 Subject: [PATCH] Attempt to delete key and certificate with the same name. Nitrokey will override the label of the key with the certificate one. If they are stored with the same id. --- cmd/step-pkcs11-init/main.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/cmd/step-pkcs11-init/main.go b/cmd/step-pkcs11-init/main.go index 225557d4..e7643265 100644 --- a/cmd/step-pkcs11-init/main.go +++ b/cmd/step-pkcs11-init/main.go @@ -149,6 +149,7 @@ func main() { for _, u := range certUris { if u != "" && !c.NoCerts { checkObject(k, u) + checkCertificate(k, u) } } for _, u := range keyUris { @@ -164,6 +165,11 @@ func main() { if ok { for _, u := range certUris { if u != "" && !c.NoCerts { + // Some HSMs like Nitrokey will overwrite the key with the + // certificate label. + if err := deleter.DeleteKey(u); err != nil { + fatal(err) + } if err := deleter.DeleteCertificate(u); err != nil { fatal(err) } @@ -215,6 +221,18 @@ COPYRIGHT os.Exit(1) } +func checkCertificate(k kms.KeyManager, rawuri string) { + if cm, ok := k.(kms.CertificateManager); ok { + if _, err := cm.LoadCertificate(&apiv1.LoadCertificateRequest{ + Name: rawuri, + }); err == nil { + fmt.Fprintf(os.Stderr, "⚠️ Your PKCS #11 module already has a certificate on %s.\n", rawuri) + fmt.Fprintln(os.Stderr, " If you want to delete it and start fresh, use `--force`.") + os.Exit(1) + } + } +} + func checkObject(k kms.KeyManager, rawuri string) { if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{ Name: rawuri,