-
Notifications
You must be signed in to change notification settings - Fork 231
/
ssh.go
156 lines (135 loc) · 3.78 KB
/
ssh.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package util
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/alibaba/kt-connect/pkg/common"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/ssh"
)
// SSHCredential ssh info
type SSHCredential struct {
RemoteHost string
Port string
PrivateKeyPath string
}
// SSHGenerator ssh key pair generator
type SSHGenerator struct {
PrivateKey, PublicKey []byte
PrivateKeyPath string
}
// NewSSHGenerator create ssh generator
func NewSSHGenerator(privateKey string, publicKey string, privateKeyPath string) *SSHGenerator {
return &SSHGenerator{
PrivateKey: []byte(privateKey),
PublicKey: []byte(publicKey),
PrivateKeyPath: privateKeyPath,
}
}
// NewDefaultSSHCredential ...
func NewDefaultSSHCredential() *SSHCredential {
return &SSHCredential{
Port: "2222",
RemoteHost: "127.0.0.1",
}
}
// Generate generate SSHGenerator
func Generate(privateKeyPath string) (*SSHGenerator, error) {
privateKey, err := generatePrivateKey(common.SSHBitSize)
if err != nil {
return nil, err
}
publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
if err != nil {
return nil, err
}
privateKeyBytes := encodePrivateKeyToPEM(privateKey)
ssh := &SSHGenerator{
PrivateKey: privateKeyBytes,
PrivateKeyPath: privateKeyPath,
PublicKey: publicKeyBytes,
}
err = WritePrivateKey(ssh.PrivateKeyPath, ssh.PrivateKey)
return ssh, err
}
// PrivateKeyPath ...
func PrivateKeyPath(component, identifier string) string {
return fmt.Sprintf("%s/%s/"+common.SSHPrivateKeyName, KtHome, component, identifier)
}
// CleanRsaKeys ...
func CleanRsaKeys() {
for _, c := range common.AllKtComponents {
dir := fmt.Sprintf("%s/%s/", KtHome, c)
files, _ := ioutil.ReadDir(dir)
for _, f := range files {
if strings.HasSuffix(f.Name(), common.PostfixRsaKey) {
rsaKey := fmt.Sprintf("%s/%s", dir, f.Name())
err := os.Remove(rsaKey)
if err != nil {
log.Debug().Msgf("Failed to remove rsa key file: %s", rsaKey)
}
}
}
}
}
// generatePrivateKey creates a RSA Private Key of specified byte size
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
// Private Key generation
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, err
}
// Validate Private Key
err = privateKey.Validate()
if err != nil {
return nil, err
}
log.Info().Msg("Private Key generated")
return privateKey, nil
}
// encodePrivateKeyToPEM encodes Private Key from RSA to PEM format
func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
// pem.Block
privBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
return privatePEM
}
// generatePublicKey take a rsa.PublicKey and return bytes suitable for writing to .pub file
// returns in the format "ssh-rsa ..."
func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
publicRsaKey, err := ssh.NewPublicKey(privatekey)
if err != nil {
return nil, err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
log.Info().Msg("Public key generated")
return pubKeyBytes, nil
}
// WritePrivateKey write ssh private key to privateKeyPath
func WritePrivateKey(privateKeyPath string, data []byte) error {
dir := filepath.Dir(privateKeyPath)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0700); err != nil {
log.Error().Err(err).Str("dir", dir).Msg("Can't create dir")
return err
}
}
if err := ioutil.WriteFile(privateKeyPath, data, 0400); err != nil {
log.Error().Err(err).Str("file", privateKeyPath).Msg("Write ssh private key failed")
return err
}
return nil
}