Skip to content

Commit 9090b28

Browse files
committed
ssh: support encrypted OpenSSH private keys
DO NOT SUBMIT: need permission from Dmitry Chestnykh <[email protected]> to submit his bcrypt_pbkdf code under the CLA. Fixes golang#18692 Change-Id: I74e3ab355a8d720948d64d87adc009783a9d9732
1 parent 178fe9c commit 9090b28

File tree

5 files changed

+332
-33
lines changed

5 files changed

+332
-33
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright 2014 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Package bcrypt_pbkdf implements bcrypt_pbkdf(3) from OpenBSD.
6+
//
7+
// See https://flak.tedunangst.com/post/bcrypt-pbkdf and
8+
// https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libutil/bcrypt_pbkdf.c.
9+
package bcrypt_pbkdf
10+
11+
import (
12+
"crypto/sha512"
13+
"errors"
14+
"golang.org/x/crypto/blowfish"
15+
)
16+
17+
// Key derives a key from the password, salt and rounds count, returning a
18+
// []byte of length keyLen that can be used as cryptographic key.
19+
func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) {
20+
if rounds < 1 {
21+
return nil, errors.New("bcrypt_pbkdf: number of rounds is too small")
22+
}
23+
if len(password) == 0 {
24+
return nil, errors.New("bcrypt_pbkdf: empty password")
25+
}
26+
if len(salt) == 0 || len(salt) > 1<<20 {
27+
return nil, errors.New("bcrypt_pbkdf: bad salt length")
28+
}
29+
if keyLen > 1024 {
30+
return nil, errors.New("bcrypt_pbkdf: keyLen is too large")
31+
}
32+
var shapass, shasalt [sha512.Size]byte
33+
var out, tmp [32]byte
34+
var cnt [4]byte
35+
36+
numBlocks := (keyLen + len(out) - 1) / len(out)
37+
key := make([]byte, numBlocks*len(out))
38+
39+
h := sha512.New()
40+
h.Write(password)
41+
h.Sum(shapass[:0])
42+
43+
for block := 1; block <= numBlocks; block++ {
44+
h.Reset()
45+
h.Write(salt)
46+
cnt[0] = byte(block >> 24)
47+
cnt[1] = byte(block >> 16)
48+
cnt[2] = byte(block >> 8)
49+
cnt[3] = byte(block)
50+
h.Write(cnt[:])
51+
bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0]))
52+
copy(out[:], tmp[:])
53+
54+
for i := 2; i <= rounds; i++ {
55+
h.Reset()
56+
h.Write(tmp[:])
57+
bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0]))
58+
for j := 0; j < len(out); j++ {
59+
out[j] ^= tmp[j]
60+
}
61+
}
62+
63+
for i, v := range out {
64+
key[i*numBlocks+(block-1)] = v
65+
}
66+
}
67+
return key[:keyLen], nil
68+
}
69+
70+
var magic = []byte("OxychromaticBlowfishSwatDynamite")
71+
72+
func bcryptHash(out, shapass, shasalt []byte) {
73+
c, err := blowfish.NewSaltedCipher(shapass, shasalt)
74+
if err != nil {
75+
panic(err)
76+
}
77+
for i := 0; i < 64; i++ {
78+
blowfish.ExpandKey(shasalt, c)
79+
blowfish.ExpandKey(shapass, c)
80+
}
81+
copy(out[:], magic)
82+
for i := 0; i < 32; i += 8 {
83+
for j := 0; j < 64; j++ {
84+
c.Encrypt(out[i:i+8], out[i:i+8])
85+
}
86+
}
87+
// Swap bytes due to different endianness.
88+
for i := 0; i < 32; i += 4 {
89+
out[i+3], out[i+2], out[i+1], out[i] = out[i], out[i+1], out[i+2], out[i+3]
90+
}
91+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Copyright 2014 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package bcrypt_pbkdf
6+
7+
import (
8+
"bytes"
9+
"testing"
10+
)
11+
12+
// Test vectors generated by the reference implementation from OpenBSD.
13+
var golden = []struct {
14+
rounds int
15+
password, salt, result []byte
16+
}{
17+
{
18+
12,
19+
[]byte("password"),
20+
[]byte("salt"),
21+
[]byte{
22+
0x1a, 0xe4, 0x2c, 0x05, 0xd4, 0x87, 0xbc, 0x02, 0xf6,
23+
0x49, 0x21, 0xa4, 0xeb, 0xe4, 0xea, 0x93, 0xbc, 0xac,
24+
0xfe, 0x13, 0x5f, 0xda, 0x99, 0x97, 0x4c, 0x06, 0xb7,
25+
0xb0, 0x1f, 0xae, 0x14, 0x9a,
26+
},
27+
},
28+
{
29+
3,
30+
[]byte("passwordy\x00PASSWORD\x00"),
31+
[]byte("salty\x00SALT\x00"),
32+
[]byte{
33+
0x7f, 0x31, 0x0b, 0xd3, 0xe7, 0x8c, 0x32, 0x80, 0xc5,
34+
0x9c, 0xe4, 0x59, 0x52, 0x11, 0xa2, 0x92, 0x8e, 0x8d,
35+
0x4e, 0xc7, 0x44, 0xc1, 0xed, 0x2e, 0xfc, 0x9f, 0x76,
36+
0x4e, 0x33, 0x88, 0xe0, 0xad,
37+
},
38+
},
39+
{
40+
// See http://thread.gmane.org/gmane.os.openbsd.bugs/20542
41+
8,
42+
[]byte("секретное слово"),
43+
[]byte("посолить немножко"),
44+
[]byte{
45+
0x8d, 0xf4, 0x3f, 0xc6, 0xfe, 0x13, 0x1f, 0xc4, 0x7f,
46+
0x0c, 0x9e, 0x39, 0x22, 0x4b, 0xd9, 0x4c, 0x70, 0xb6,
47+
0xfc, 0xc8, 0xee, 0x81, 0x35, 0xfa, 0xdd, 0xf6, 0x11,
48+
0x56, 0xe6, 0xcb, 0x27, 0x33, 0xea, 0x76, 0x5f, 0x31,
49+
0x5a, 0x3e, 0x1e, 0x4a, 0xfc, 0x35, 0xbf, 0x86, 0x87,
50+
0xd1, 0x89, 0x25, 0x4c, 0x1e, 0x05, 0xa6, 0xfe, 0x80,
51+
0xc0, 0x61, 0x7f, 0x91, 0x83, 0xd6, 0x72, 0x60, 0xd6,
52+
0xa1, 0x15, 0xc6, 0xc9, 0x4e, 0x36, 0x03, 0xe2, 0x30,
53+
0x3f, 0xbb, 0x43, 0xa7, 0x6a, 0x64, 0x52, 0x3f, 0xfd,
54+
0xa6, 0x86, 0xb1, 0xd4, 0x51, 0x85, 0x43,
55+
},
56+
},
57+
}
58+
59+
func TestKey(t *testing.T) {
60+
for i, v := range golden {
61+
k, err := Key(v.password, v.salt, v.rounds, len(v.result))
62+
if err != nil {
63+
t.Errorf("%d: %s", i, err)
64+
continue
65+
}
66+
if !bytes.Equal(k, v.result) {
67+
t.Errorf("%d: expected\n%x\n, got\n%x\n", i, v.result, k)
68+
}
69+
}
70+
}
71+
72+
func TestBcryptHash(t *testing.T) {
73+
good := []byte{
74+
0x87, 0x90, 0x48, 0x70, 0xee, 0xf9, 0xde, 0xdd, 0xf8, 0xe7,
75+
0x61, 0x1a, 0x14, 0x01, 0x06, 0xe6, 0xaa, 0xf1, 0xa3, 0x63,
76+
0xd9, 0xa2, 0xc5, 0x04, 0xdb, 0x35, 0x64, 0x43, 0x72, 0x1e,
77+
0xb5, 0x55,
78+
}
79+
var pass, salt [64]byte
80+
var result [32]byte
81+
for i := 0; i < 64; i++ {
82+
pass[i] = byte(i)
83+
salt[i] = byte(i + 64)
84+
}
85+
bcryptHash(result[:], pass[:], salt[:])
86+
if !bytes.Equal(result[:], good) {
87+
t.Errorf("expected %x, got %x", good, result)
88+
}
89+
}
90+
91+
func BenchmarkKey(b *testing.B) {
92+
pass := []byte("password")
93+
salt := []byte("salt")
94+
for i := 0; i < b.N; i++ {
95+
Key(pass, salt, 10, 32)
96+
}
97+
}

ssh/keys.go

Lines changed: 97 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ package ssh
77
import (
88
"bytes"
99
"crypto"
10+
"crypto/aes"
11+
"crypto/cipher"
1012
"crypto/dsa"
1113
"crypto/ecdsa"
1214
"crypto/elliptic"
@@ -25,6 +27,7 @@ import (
2527
"strings"
2628

2729
"golang.org/x/crypto/ed25519"
30+
"golang.org/x/crypto/ssh/internal/bcrypt_pbkdf"
2831
)
2932

3033
// These constants represent the algorithm names for key types supported by this
@@ -904,21 +907,25 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
904907
case "DSA PRIVATE KEY":
905908
return ParseDSAPrivateKey(block.Bytes)
906909
case "OPENSSH PRIVATE KEY":
907-
return parseOpenSSHPrivateKey(block.Bytes)
910+
return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
908911
default:
909912
return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
910913
}
911914
}
912915

913916
// ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
914-
// passphrase from a PEM encoded private key. If wrong passphrase, return
915-
// x509.IncorrectPasswordError.
917+
// passphrase from a PEM encoded private key. If the passphrase is wrong, it
918+
// will return x509.IncorrectPasswordError.
916919
func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
917920
block, _ := pem.Decode(pemBytes)
918921
if block == nil {
919922
return nil, errors.New("ssh: no key found")
920923
}
921924

925+
if block.Type == "OPENSSH PRIVATE KEY" {
926+
return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
927+
}
928+
922929
if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
923930
return nil, errors.New("ssh: not an encrypted key")
924931
}
@@ -975,9 +982,60 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
975982
}, nil
976983
}
977984

978-
// Implemented based on the documentation at
979-
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
980-
func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
985+
func unencryptedOpenSSHKey(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error) {
986+
if KdfName != "none" || CipherName != "none" {
987+
return nil, &PassphraseNeededError{}
988+
}
989+
if KdfOpts != "" {
990+
return nil, errors.New("ssh: invalid openssh private key")
991+
}
992+
return PrivKeyBlock, nil
993+
}
994+
995+
func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
996+
return func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error) {
997+
if KdfName == "none" || CipherName == "none" {
998+
return nil, errors.New("ssh: key is not password protected")
999+
}
1000+
if KdfName != "bcrypt" {
1001+
return nil, errors.New("ssh: unknown KDF: " + KdfName)
1002+
}
1003+
1004+
var kdfOpts struct {
1005+
Salt string
1006+
Rounds uint32
1007+
}
1008+
if err := Unmarshal([]byte(KdfOpts), &kdfOpts); err != nil {
1009+
return nil, err
1010+
}
1011+
1012+
k, err := bcrypt_pbkdf.Key(passphrase, []byte(kdfOpts.Salt), int(kdfOpts.Rounds), 32+16)
1013+
if err != nil {
1014+
return nil, err
1015+
}
1016+
key, iv := k[:32], k[32:]
1017+
1018+
if CipherName != "aes256-ctr" {
1019+
return nil, errors.New("ssh: unknown cipher: " + CipherName)
1020+
}
1021+
c, err := aes.NewCipher(key)
1022+
if err != nil {
1023+
return nil, err
1024+
}
1025+
ctr := cipher.NewCTR(c, iv)
1026+
ctr.XORKeyStream(PrivKeyBlock, PrivKeyBlock)
1027+
1028+
return PrivKeyBlock, nil
1029+
}
1030+
}
1031+
1032+
type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
1033+
1034+
// parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
1035+
// function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
1036+
// as the decrypt function to parse an unencrypted private key. See
1037+
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
1038+
func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
9811039
const magic = "openssh-key-v1\x00"
9821040
if len(key) < len(magic) || string(key[:len(magic)]) != magic {
9831041
return nil, errors.New("ssh: invalid openssh private key format")
@@ -996,9 +1054,22 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
9961054
if err := Unmarshal(remaining, &w); err != nil {
9971055
return nil, err
9981056
}
1057+
if w.NumKeys != 1 {
1058+
// We only support single key files, and so does OpenSSH.
1059+
// https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
1060+
return nil, errors.New("ssh: multi-key files are not supported")
1061+
}
9991062

1000-
if w.KdfName != "none" || w.CipherName != "none" {
1001-
return nil, errors.New("ssh: cannot decode encrypted private keys")
1063+
privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
1064+
if err != nil {
1065+
if err, ok := err.(*PassphraseNeededError); ok {
1066+
pub, errPub := ParsePublicKey(w.PubKey)
1067+
if errPub != nil {
1068+
return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
1069+
}
1070+
err.PublicKey = pub
1071+
}
1072+
return nil, err
10021073
}
10031074

10041075
pk1 := struct {
@@ -1008,12 +1079,11 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
10081079
Rest []byte `ssh:"rest"`
10091080
}{}
10101081

1011-
if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil {
1012-
return nil, err
1013-
}
1014-
1015-
if pk1.Check1 != pk1.Check2 {
1016-
return nil, errors.New("ssh: checkint mismatch")
1082+
if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
1083+
if w.CipherName != "none" {
1084+
return nil, x509.IncorrectPasswordError
1085+
}
1086+
return nil, errors.New("ssh: malformed OpenSSH key")
10171087
}
10181088

10191089
// we only handle ed25519 and rsa keys currently
@@ -1035,10 +1105,8 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
10351105
return nil, err
10361106
}
10371107

1038-
for i, b := range key.Pad {
1039-
if int(b) != i+1 {
1040-
return nil, errors.New("ssh: padding not as expected")
1041-
}
1108+
if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
1109+
return nil, err
10421110
}
10431111

10441112
pk := &rsa.PrivateKey{
@@ -1073,10 +1141,8 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
10731141
return nil, errors.New("ssh: private key unexpected length")
10741142
}
10751143

1076-
for i, b := range key.Pad {
1077-
if int(b) != i+1 {
1078-
return nil, errors.New("ssh: padding not as expected")
1079-
}
1144+
if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
1145+
return nil, err
10801146
}
10811147

10821148
pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
@@ -1087,6 +1153,15 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
10871153
}
10881154
}
10891155

1156+
func checkOpenSSHKeyPadding(pad []byte) error {
1157+
for i, b := range pad {
1158+
if int(b) != i+1 {
1159+
return errors.New("ssh: padding not as expected")
1160+
}
1161+
}
1162+
return nil
1163+
}
1164+
10901165
// FingerprintLegacyMD5 returns the user presentation of the key's
10911166
// fingerprint as described by RFC 4716 section 4.
10921167
func FingerprintLegacyMD5(pubKey PublicKey) string {

0 commit comments

Comments
 (0)