-
Notifications
You must be signed in to change notification settings - Fork 162
/
ssh_opts.go
69 lines (55 loc) · 1.42 KB
/
ssh_opts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package director
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshuuid "github.com/cloudfoundry/bosh-utils/uuid"
"golang.org/x/crypto/ssh"
)
type SSHOpts struct {
Username string
Password string
PublicKey string
}
func NewSSHOpts(uuidGen boshuuid.Generator) (SSHOpts, string, error) {
privKey, pubKey, err := makeSSHKeyPair()
if err != nil {
return SSHOpts{}, "", bosherr.WrapErrorf(err, "Generating SSH key pair")
}
nameSuffix, err := uuidGen.Generate()
if err != nil {
return SSHOpts{}, "", bosherr.WrapErrorf(err, "Generating unique SSH user suffix")
}
// username cannot be >32
nameSuffix = strings.Replace(nameSuffix, "-", "", -1)[0:16]
sshOpts := SSHOpts{
Username: "bosh_" + nameSuffix,
Password: "p",
PublicKey: string(pubKey),
}
return sshOpts, string(privKey), nil
}
func makeSSHKeyPair() ([]byte, []byte, error) {
privKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
privKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privKey),
}
privKeyBuf := bytes.NewBufferString("")
err = pem.Encode(privKeyBuf, privKeyPEM)
if err != nil {
return nil, nil, err
}
pub, err := ssh.NewPublicKey(&privKey.PublicKey)
if err != nil {
return nil, nil, err
}
return privKeyBuf.Bytes(), ssh.MarshalAuthorizedKey(pub), nil
}