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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package srvconn
import (
"errors"
"fmt"
"net"
"strconv"
"strings"
"sync"
"time"
gossh "golang.org/x/crypto/ssh"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/service"
)
var (
sshClients = make(map[string]*SSHClient)
clientLock = new(sync.RWMutex)
)
var (
supportedCiphers = []string{
"aes128-ctr", "aes192-ctr", "aes256-ctr",
"aes128-gcm@openssh.com",
"chacha20-poly1305@openssh.com",
"arcfour256", "arcfour128", "arcfour",
"aes128-cbc",
"3des-cbc"}
)
type SSHClient struct {
client *gossh.Client
proxyConn gossh.Conn
username string
ref int
key string
mu *sync.RWMutex
closed chan struct{}
}
func (s *SSHClient) RefCount() int {
if s.isClosed() {
return 0
}
s.mu.RLock()
defer s.mu.RUnlock()
return s.ref
}
func (s *SSHClient) increaseRef() {
if s.isClosed() {
return
}
s.mu.Lock()
defer s.mu.Unlock()
s.ref++
}
func (s *SSHClient) decreaseRef() {
if s.isClosed() {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.ref == 0 {
return
}
s.ref--
}
func (s *SSHClient) NewSession() (*gossh.Session, error) {
return s.client.NewSession()
}
func (s *SSHClient) Close() error {
select {
case <-s.closed:
return nil
default:
close(s.closed)
}
if s.proxyConn != nil {
_ = s.proxyConn.Close()
}
s.mu.Lock()
s.ref = 0
s.mu.Unlock()
return s.client.Close()
}
func (s *SSHClient) isClosed() bool {
select {
case <-s.closed:
return true
default:
return false
}
}
func KeepAlive(c *SSHClient, closed <-chan struct{}, keepInterval time.Duration) {
t := time.NewTicker(keepInterval * time.Second)
defer t.Stop()
logger.Infof("SSH client %p keep alive start", c)
defer logger.Infof("SSH client %p keep alive stop", c)
for {
select {
case <-closed:
return
case <-t.C:
_, _, err := c.client.SendRequest("keepalive@openssh.com", true, nil)
if err != nil {
logger.Errorf("SSH client %p keep alive err: %s", c, err.Error())
_ = c.Close()
RecycleClient(c)
return
}
}
}
}
type SSHClientConfig struct {
Host string `json:"host"`
Port string `json:"port"`
User string `json:"user"`
Password string `json:"password"`
PrivateKey string `json:"private_key"`
PrivateKeyPath string `json:"private_key_path"`
Timeout time.Duration `json:"timeout"`
Proxy []*SSHClientConfig
proxyConn gossh.Conn
}
func (sc *SSHClientConfig) Config() (config *gossh.ClientConfig, err error) {
authMethods := make([]gossh.AuthMethod, 0)
if sc.Password != "" {
authMethods = append(authMethods, gossh.Password(sc.Password))
}
if sc.PrivateKeyPath != "" {
if pubkey, err := GetPubKeyFromFile(sc.PrivateKeyPath); err != nil {
err = fmt.Errorf("parse private key from file error: %s", err)
return config, err
} else {
authMethods = append(authMethods, gossh.PublicKeys(pubkey))
}
}
if sc.PrivateKey != "" {
if signer, err := gossh.ParsePrivateKeyWithPassphrase([]byte(sc.PrivateKey), []byte(sc.Password)); err != nil {
err = fmt.Errorf("parse private key error: %s", err)
logger.Error(err.Error())
} else {
authMethods = append(authMethods, gossh.PublicKeys(signer))
}
}
config = &gossh.ClientConfig{
User: sc.User,
Auth: authMethods,
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Config: gossh.Config{Ciphers: supportedCiphers},
Timeout: sc.Timeout,
}
return config, nil
}
func (sc *SSHClientConfig) DialProxy() (client *gossh.Client, err error) {
for _, p := range sc.Proxy {
client, err = p.Dial()
if err == nil {
logger.Debugf("Connect proxy host %s:%s success", p.Host, p.Port)
return
} else {
logger.Errorf("Connect proxy host %s:%s error: %s", p.Host, p.Port, err)
}
}
return
}
func (sc *SSHClientConfig) Dial() (client *gossh.Client, err error) {
cfg, err := sc.Config()
if err != nil {
return
}
if len(sc.Proxy) > 0 {
logger.Debugf("Dial host proxy first")
proxyClient, err := sc.DialProxy()
if err != nil {
err = errors.New("connect proxy host error 1: " + err.Error())
logger.Error("Connect proxy host error 1: ", err.Error())
return client, err
}
proxySock, err := proxyClient.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port))
if err != nil {
err = errors.New(fmt.Sprintf("tcp connect host %s:%s error 2: %s", sc.Host, sc.Port, err.Error()))
logger.Errorf("Tcp connect host %s:%s error 2: %s", sc.Host, sc.Port, err.Error())
return client, err
}
proxyConn, chans, reqs, err := gossh.NewClientConn(proxySock, net.JoinHostPort(sc.Host, sc.Port), cfg)
if err != nil {
err = errors.New(fmt.Sprintf("ssh connect host %s:%s error 3: %s", sc.Host, sc.Port, err.Error()))
logger.Errorf("SSH Connect host %s:%s error 3: %s", sc.Host, sc.Port, err.Error())
return client, err
}
sc.proxyConn = proxyConn
client = gossh.NewClient(proxyConn, chans, reqs)
} else {
logger.Debugf("Dial host %s:%s", sc.Host, sc.Port)
client, err = gossh.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port), cfg)
if err != nil {
return
}
}
return client, nil
}
func (sc *SSHClientConfig) String() string {
return fmt.Sprintf("%s@%s:%s", sc.User, sc.Host, sc.Port)
}
func MakeConfig(asset *model.Asset, systemUser *model.SystemUser, timeout time.Duration) (conf *SSHClientConfig) {
proxyConfigs := make([]*SSHClientConfig, 0)
// 如果有网关则从网关中连接
if asset.Domain != "" {
domain := service.GetDomainWithGateway(asset.Domain)
if domain.ID != "" && len(domain.Gateways) > 0 {
for _, gateway := range domain.Gateways {
proxyConfigs = append(proxyConfigs, &SSHClientConfig{
Host: gateway.IP,
Port: strconv.Itoa(gateway.Port),
User: gateway.Username,
Password: gateway.Password,
PrivateKey: gateway.PrivateKey,
Timeout: timeout,
})
}
}
}
if systemUser.Password == "" && systemUser.PrivateKey == "" && systemUser.LoginMode != model.LoginModeManual {
info := service.GetSystemUserAssetAuthInfo(systemUser.ID, asset.ID)
systemUser.Password = info.Password
systemUser.PrivateKey = info.PrivateKey
}
conf = &SSHClientConfig{
Host: asset.IP,
Port: strconv.Itoa(asset.ProtocolPort("ssh")),
User: systemUser.Username,
Password: systemUser.Password,
PrivateKey: systemUser.PrivateKey,
Timeout: timeout,
Proxy: proxyConfigs,
}
return
}
func newClient(asset *model.Asset, systemUser *model.SystemUser, timeout time.Duration) (client *SSHClient, err error) {
sshConfig := MakeConfig(asset, systemUser, timeout)
conn, err := sshConfig.Dial()
if err != nil {
return nil, err
}
closed := make(chan struct{})
client = &SSHClient{client: conn, proxyConn: sshConfig.proxyConn,
username: systemUser.Username,
mu: new(sync.RWMutex),
ref: 1,
closed: closed}
go KeepAlive(client, closed, 60)
return client, nil
}
func NewClient(user *model.User, asset *model.Asset, systemUser *model.SystemUser, timeout time.Duration,
useCache bool) (client *SSHClient, err error) {
client, err = newClient(asset, systemUser, timeout)
if err == nil && useCache {
key := MakeReuseSSHClientKey(user, asset, systemUser)
setClientCache(key, client)
}
return
}
func searchSSHClientFromCache(prefixKey string) (client *SSHClient, ok bool) {
clientLock.Lock()
defer clientLock.Unlock()
for key, cacheClient := range sshClients {
if strings.HasPrefix(key, prefixKey) {
cacheClient.increaseRef()
return cacheClient, true
}
}
return
}
func GetClientFromCache(key string) (client *SSHClient, ok bool) {
clientLock.Lock()
defer clientLock.Unlock()
client, ok = sshClients[key]
if ok {
client.increaseRef()
}
return
}
func setClientCache(key string, client *SSHClient) {
clientLock.Lock()
sshClients[key] = client
client.key = key
clientLock.Unlock()
}
func RecycleClient(client *SSHClient) {
// decrease client ref; if ref==0, delete Cache, close client.
if client == nil {
return
}
client.decreaseRef()
if client.RefCount() == 0 {
clientLock.Lock()
delete(sshClients, client.key)
clientLock.Unlock()
err := client.Close()
if err != nil {
logger.Errorf("Close SSH client %p err: %s ", client, err.Error())
} else {
logger.Infof("Success to close SSH client %p", client)
}
} else {
logger.Debugf("SSH client %p ref -1. current ref: %d", client, client.RefCount())
}
}
func MakeReuseSSHClientKey(user *model.User, asset *model.Asset, systemUser *model.SystemUser) string {
return fmt.Sprintf("%s_%s_%s_%s", user.ID, asset.ID, systemUser.ID, systemUser.Username)
}