Skip to content

Commit

Permalink
Return errors on failed key loads, update pkcs11 init and error handling
Browse files Browse the repository at this point in the history
Modified the execution flow in hsm.go to return errors immediately when RSA or EC key loads fail. Also, updated the initialization of pkcs11 digest and improved the error handling in the sanity check of the key pair.
  • Loading branch information
arkavo-com committed May 12, 2024
1 parent eab99a4 commit 35fbbf8
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions service/internal/security/hsm.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,15 @@ func (h *HSMSession) loadKeys(keys map[string]KeyInfo) error {
pair, err := h.LoadRSAKey(info)
if err != nil {
slog.Error("pkcs11 error unable to load RSA key", "err", err)
return err
} else {
h.RSA = pair
}
case "ec":
pair, err := h.LoadECKey(info)
if err != nil {
slog.Error("pkcs11 error unable to load EC key", "err", err)
return err
} else {
h.EC = pair
}
Expand Down Expand Up @@ -498,14 +500,19 @@ func (h *HSMSession) LoadECKey(info KeyInfo) (*ECKeyPair, error) {
pair.PublicKey = ecPublicKey

// Do a sanity check of the key pair
mechanism := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}
err = h.ctx.SignInit(h.sh, mechanism, keyHandleEC)
err = h.ctx.DigestInit(h.sh, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_SHA256, nil)})
if err != nil {
slog.Error("pkcs11 SignInit", "err", err)
return nil, err
}
digest, err := h.ctx.Digest(h.sh, []byte("sanity now"))
if err != nil {
slog.Error("pkcs11 Digest", "err", err)
return nil, err
}
err = h.ctx.SignInit(h.sh, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}, keyHandleEC)
if err != nil {
slog.Error("pkcs11 SignInit", "err", err)
return nil, err
}
sig, err := h.ctx.Sign(h.sh, digest)
Expand All @@ -528,7 +535,7 @@ func (h *HSMSession) LoadECKey(info KeyInfo) (*ECKeyPair, error) {
"hash", hex.EncodeToString(digest),
"sig", hex.EncodeToString(sig),
"ecPublicKey", pemData)
return nil, err
return nil, fmt.Errorf("pkcs11 VerifyASN1 signature failed")
}
return &pair, nil
}
Expand Down

0 comments on commit 35fbbf8

Please sign in to comment.