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 28, 2023
1 parent 149f22e commit 2dfbda2
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions x/cert/utils/key_pair_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ 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
Expand All @@ -272,21 +273,26 @@ func (kpm *keyPairManager) readImpl(fin io.Reader) ([]byte, []byte, []byte, erro
} else if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
// nolint: staticcheck
privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordBytes)

Check failure on line 275 in x/cert/utils/key_pair_manager.go

View workflow job for this annotation

GitHub Actions / lint

ineffectual assignment to err (ineffassign)

Check failure on line 275 in x/cert/utils/key_pair_manager.go

View workflow job for this annotation

GitHub Actions / lint

ineffectual assignment to err (ineffassign)
if errors.Is(err, x509.IncorrectPasswordError) {

// 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 281 in x/cert/utils/key_pair_manager.go

View check run for this annotation

Codecov / codecov/patch

x/cert/utils/key_pair_manager.go#L276-L281

Added lines #L276 - L281 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 295 in x/cert/utils/key_pair_manager.go

View check run for this annotation

Codecov / codecov/patch

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

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

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

0 comments on commit 2dfbda2

Please sign in to comment.