Skip to content

Commit d181620

Browse files
FiloSottilehanwen
authored andcommitted
ssh: support encrypted OpenSSH private keys
Includes the bcrypt_pbkdf package by Dmitry Chestnykh, submitted with permission on his behalf under the CLA: https://go-review.googlesource.com/c/crypto/+/207600/2#message-6a035dd62ff76f6c9367299b911076a1be237fb8 Fixes golang/go#18692 Change-Id: I74e3ab355a8d720948d64d87adc009783a9d9732 Reviewed-on: https://go-review.googlesource.com/c/crypto/+/207600 Run-TryBot: Filippo Valsorda <[email protected]> Run-TryBot: Han-Wen Nienhuys <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Han-Wen Nienhuys <[email protected]>
1 parent 32be728 commit d181620

File tree

4 files changed

+302
-22
lines changed

4 files changed

+302
-22
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
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+
const blockSize = 32
18+
19+
// Key derives a key from the password, salt and rounds count, returning a
20+
// []byte of length keyLen that can be used as cryptographic key.
21+
func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) {
22+
if rounds < 1 {
23+
return nil, errors.New("bcrypt_pbkdf: number of rounds is too small")
24+
}
25+
if len(password) == 0 {
26+
return nil, errors.New("bcrypt_pbkdf: empty password")
27+
}
28+
if len(salt) == 0 || len(salt) > 1<<20 {
29+
return nil, errors.New("bcrypt_pbkdf: bad salt length")
30+
}
31+
if keyLen > 1024 {
32+
return nil, errors.New("bcrypt_pbkdf: keyLen is too large")
33+
}
34+
35+
numBlocks := (keyLen + blockSize - 1) / blockSize
36+
key := make([]byte, numBlocks*blockSize)
37+
38+
h := sha512.New()
39+
h.Write(password)
40+
shapass := h.Sum(nil)
41+
42+
shasalt := make([]byte, 0, sha512.Size)
43+
cnt, tmp := make([]byte, 4), make([]byte, blockSize)
44+
for block := 1; block <= numBlocks; block++ {
45+
h.Reset()
46+
h.Write(salt)
47+
cnt[0] = byte(block >> 24)
48+
cnt[1] = byte(block >> 16)
49+
cnt[2] = byte(block >> 8)
50+
cnt[3] = byte(block)
51+
h.Write(cnt)
52+
bcryptHash(tmp, shapass, h.Sum(shasalt))
53+
54+
out := make([]byte, blockSize)
55+
copy(out, tmp)
56+
for i := 2; i <= rounds; i++ {
57+
h.Reset()
58+
h.Write(tmp)
59+
bcryptHash(tmp, shapass, h.Sum(shasalt))
60+
for j := 0; j < len(out); j++ {
61+
out[j] ^= tmp[j]
62+
}
63+
}
64+
65+
for i, v := range out {
66+
key[i*numBlocks+(block-1)] = v
67+
}
68+
}
69+
return key[:keyLen], nil
70+
}
71+
72+
var magic = []byte("OxychromaticBlowfishSwatDynamite")
73+
74+
func bcryptHash(out, shapass, shasalt []byte) {
75+
c, err := blowfish.NewSaltedCipher(shapass, shasalt)
76+
if err != nil {
77+
panic(err)
78+
}
79+
for i := 0; i < 64; i++ {
80+
blowfish.ExpandKey(shasalt, c)
81+
blowfish.ExpandKey(shapass, c)
82+
}
83+
copy(out, magic)
84+
for i := 0; i < 32; i += 8 {
85+
for j := 0; j < 64; j++ {
86+
c.Encrypt(out[i:i+8], out[i:i+8])
87+
}
88+
}
89+
// Swap bytes due to different endianness.
90+
for i := 0; i < 32; i += 4 {
91+
out[i+3], out[i+2], out[i+1], out[i] = out[i], out[i+1], out[i+2], out[i+3]
92+
}
93+
}
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
@@ -1122,21 +1125,25 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
11221125
case "DSA PRIVATE KEY":
11231126
return ParseDSAPrivateKey(block.Bytes)
11241127
case "OPENSSH PRIVATE KEY":
1125-
return parseOpenSSHPrivateKey(block.Bytes)
1128+
return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
11261129
default:
11271130
return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
11281131
}
11291132
}
11301133

11311134
// ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
1132-
// passphrase from a PEM encoded private key. If wrong passphrase, return
1133-
// x509.IncorrectPasswordError.
1135+
// passphrase from a PEM encoded private key. If the passphrase is wrong, it
1136+
// will return x509.IncorrectPasswordError.
11341137
func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
11351138
block, _ := pem.Decode(pemBytes)
11361139
if block == nil {
11371140
return nil, errors.New("ssh: no key found")
11381141
}
11391142

1143+
if block.Type == "OPENSSH PRIVATE KEY" {
1144+
return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
1145+
}
1146+
11401147
if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
11411148
return nil, errors.New("ssh: not an encrypted key")
11421149
}
@@ -1193,9 +1200,60 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
11931200
}, nil
11941201
}
11951202

1196-
// Implemented based on the documentation at
1197-
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
1198-
func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
1203+
func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
1204+
if kdfName != "none" || cipherName != "none" {
1205+
return nil, &PassphraseMissingError{}
1206+
}
1207+
if kdfOpts != "" {
1208+
return nil, errors.New("ssh: invalid openssh private key")
1209+
}
1210+
return privKeyBlock, nil
1211+
}
1212+
1213+
func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
1214+
return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
1215+
if kdfName == "none" || cipherName == "none" {
1216+
return nil, errors.New("ssh: key is not password protected")
1217+
}
1218+
if kdfName != "bcrypt" {
1219+
return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt")
1220+
}
1221+
1222+
var opts struct {
1223+
Salt string
1224+
Rounds uint32
1225+
}
1226+
if err := Unmarshal([]byte(kdfOpts), &opts); err != nil {
1227+
return nil, err
1228+
}
1229+
1230+
k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
1231+
if err != nil {
1232+
return nil, err
1233+
}
1234+
key, iv := k[:32], k[32:]
1235+
1236+
if cipherName != "aes256-ctr" {
1237+
return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q", cipherName, "aes256-ctr")
1238+
}
1239+
c, err := aes.NewCipher(key)
1240+
if err != nil {
1241+
return nil, err
1242+
}
1243+
ctr := cipher.NewCTR(c, iv)
1244+
ctr.XORKeyStream(privKeyBlock, privKeyBlock)
1245+
1246+
return privKeyBlock, nil
1247+
}
1248+
}
1249+
1250+
type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
1251+
1252+
// parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
1253+
// function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
1254+
// as the decrypt function to parse an unencrypted private key. See
1255+
// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
1256+
func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
11991257
const magic = "openssh-key-v1\x00"
12001258
if len(key) < len(magic) || string(key[:len(magic)]) != magic {
12011259
return nil, errors.New("ssh: invalid openssh private key format")
@@ -1214,9 +1272,22 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
12141272
if err := Unmarshal(remaining, &w); err != nil {
12151273
return nil, err
12161274
}
1275+
if w.NumKeys != 1 {
1276+
// We only support single key files, and so does OpenSSH.
1277+
// https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
1278+
return nil, errors.New("ssh: multi-key files are not supported")
1279+
}
12171280

1218-
if w.KdfName != "none" || w.CipherName != "none" {
1219-
return nil, errors.New("ssh: cannot decode encrypted private keys")
1281+
privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
1282+
if err != nil {
1283+
if err, ok := err.(*PassphraseMissingError); ok {
1284+
pub, errPub := ParsePublicKey(w.PubKey)
1285+
if errPub != nil {
1286+
return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
1287+
}
1288+
err.PublicKey = pub
1289+
}
1290+
return nil, err
12201291
}
12211292

12221293
pk1 := struct {
@@ -1226,12 +1297,11 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
12261297
Rest []byte `ssh:"rest"`
12271298
}{}
12281299

1229-
if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil {
1230-
return nil, err
1231-
}
1232-
1233-
if pk1.Check1 != pk1.Check2 {
1234-
return nil, errors.New("ssh: checkint mismatch")
1300+
if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
1301+
if w.CipherName != "none" {
1302+
return nil, x509.IncorrectPasswordError
1303+
}
1304+
return nil, errors.New("ssh: malformed OpenSSH key")
12351305
}
12361306

12371307
// we only handle ed25519 and rsa keys currently
@@ -1253,10 +1323,8 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
12531323
return nil, err
12541324
}
12551325

1256-
for i, b := range key.Pad {
1257-
if int(b) != i+1 {
1258-
return nil, errors.New("ssh: padding not as expected")
1259-
}
1326+
if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
1327+
return nil, err
12601328
}
12611329

12621330
pk := &rsa.PrivateKey{
@@ -1291,10 +1359,8 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
12911359
return nil, errors.New("ssh: private key unexpected length")
12921360
}
12931361

1294-
for i, b := range key.Pad {
1295-
if int(b) != i+1 {
1296-
return nil, errors.New("ssh: padding not as expected")
1297-
}
1362+
if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
1363+
return nil, err
12981364
}
12991365

13001366
pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
@@ -1305,6 +1371,15 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
13051371
}
13061372
}
13071373

1374+
func checkOpenSSHKeyPadding(pad []byte) error {
1375+
for i, b := range pad {
1376+
if int(b) != i+1 {
1377+
return errors.New("ssh: padding not as expected")
1378+
}
1379+
}
1380+
return nil
1381+
}
1382+
13081383
// FingerprintLegacyMD5 returns the user presentation of the key's
13091384
// fingerprint as described by RFC 4716 section 4.
13101385
func FingerprintLegacyMD5(pubKey PublicKey) string {

0 commit comments

Comments
 (0)