Skip to content

Commit

Permalink
ssh: signal incorrect private key passwords with x509.IncorrectPasswo…
Browse files Browse the repository at this point in the history
…rdError

Fixes golang/go#20781

Change-Id: Iae42fff3c9b0b9984509e44a92f9bc99a1a12470
Reviewed-on: https://go-review.googlesource.com/46439
Reviewed-by: Han-Wen Nienhuys <[email protected]>
Run-TryBot: Han-Wen Nienhuys <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
  • Loading branch information
mattn authored and hanwen committed Jun 28, 2017
1 parent adbae1b commit 84f24df
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ssh/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,9 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
}
}

// ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
// passphrase from a PEM encoded private key. If wrong passphrase, return
// x509.IncorrectPasswordError.
func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
Expand All @@ -814,6 +817,9 @@ func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{},
var err error
buf, err = x509.DecryptPEMBlock(block, passPhrase)
if err != nil {
if err == x509.IncorrectPasswordError {
return nil, err
}
return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
}
}
Expand Down
7 changes: 7 additions & 0 deletions ssh/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"reflect"
Expand Down Expand Up @@ -165,6 +166,12 @@ func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) {
t.Errorf("Verify failed: %v", err)
}
}

tt := testdata.PEMEncryptedKeys[0]
_, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte("incorrect"))
if err != x509.IncorrectPasswordError {
t.Fatalf("got %v want IncorrectPasswordError", err)
}
}

func TestParseDSA(t *testing.T) {
Expand Down

0 comments on commit 84f24df

Please sign in to comment.