Skip to content

Commit

Permalink
fix: try parse private key instead of checking for error
Browse files Browse the repository at this point in the history
DecryptPEMBlock may not return error due to format quirks
Try parse key instead, and if fail use legacy passowrd to open it

Signed-off-by: Artur Troian <troian.ap@gmail.com>
  • Loading branch information
troian committed Aug 29, 2023
1 parent 149f22e commit eda7bb1
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions x/cert/utils/key_pair_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,29 +264,34 @@ func (kpm *keyPairManager) readImpl(fin io.Reader) ([]byte, []byte, []byte, erro
}

var privKeyPlaintext []byte
var privKeyI interface{}

// PKCS#8 header defined in RFC7468 section 11
// nolint: gocritic
if block.Type == "ENCRYPTED PRIVATE KEY" {
privKeyPlaintext, err = pemutil.DecryptPKCS8PrivateKey(block.Bytes, kpm.passwordBytes)
} else if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
// nolint: staticcheck
privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordBytes)
if errors.Is(err, x509.IncorrectPasswordError) {
privKeyPlaintext, _ = x509.DecryptPEMBlock(block, kpm.passwordBytes)

// DecryptPEMBlock may not return IncorrectPasswordError.
// Try parse private key instead and if it fails give another try with legacy password
privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext)
if err != nil {

Check warning on line 280 in x/cert/utils/key_pair_manager.go

View check run for this annotation

Codecov / codecov/patch

x/cert/utils/key_pair_manager.go#L275-L280

Added lines #L275 - L280 were not covered by tests
// nolint: staticcheck
privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordLegacy)
}
} else {
return nil, nil, nil, errUnsupportedEncryptedPEM
}

if err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed decrypting x509 block with private key", err)
}

var privKeyI interface{}
if privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext); err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed parsing private key data", err)
if privKeyI == nil {
if privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext); err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed parsing private key data", err)
}

Check warning on line 294 in x/cert/utils/key_pair_manager.go

View check run for this annotation

Codecov / codecov/patch

x/cert/utils/key_pair_manager.go#L293-L294

Added lines #L293 - L294 were not covered by tests
}

eckey, valid := privKeyI.(*ecdsa.PrivateKey)
Expand Down

0 comments on commit eda7bb1

Please sign in to comment.