-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathconnect.go
280 lines (228 loc) · 6.51 KB
/
connect.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
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
// Copyright (c) 2021 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package sshlib
import (
"context"
"io"
"log"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/net/proxy"
terminal "golang.org/x/term"
)
// Connect structure to store contents about ssh connection.
type Connect struct {
// Client *ssh.Client
Client *ssh.Client
// Session
Session *ssh.Session
// Session Stdin, Stdout, Stderr...
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// ProxyDialer
ProxyDialer proxy.ContextDialer
// Connect timeout second.
ConnectTimeout int
// SendKeepAliveMax and SendKeepAliveInterval
SendKeepAliveMax int
SendKeepAliveInterval int
// Session use tty flag.
// Set it before CraeteClient.
TTY bool
// Forward ssh agent flag.
// Set it before CraeteClient.
ForwardAgent bool
// Set the TTY to be used as the input and output for the Session/Cmd.
PtyRelayTty *os.File
// StdoutMutex is a mutex for use Stdout.
StdoutMutex *sync.Mutex
// CheckKnownHosts if true, check knownhosts.
// Ignored if HostKeyCallback is set.
// Set it before CraeteClient.
CheckKnownHosts bool
// HostKeyCallback is ssh.HostKeyCallback.
// This item takes precedence over `CheckKnownHosts`.
// Set it before CraeteClient.
HostKeyCallback ssh.HostKeyCallback
// OverwriteKnownHosts if true, if the knownhost is different, check whether to overwrite.
OverwriteKnownHosts bool
// KnownHostsFiles is list of knownhosts files path.
KnownHostsFiles []string
// TextAskWriteKnownHosts defines a confirmation message when writing a knownhost.
// We are using Go's template engine and have the following variables available.
// - Address ... ssh server hostname
// - RemoteAddr ... ssh server address
// - Fingerprint ... ssh PublicKey fingerprint
TextAskWriteKnownHosts string
// TextAskOverwriteKnownHosts defines a confirmation message when over-writing a knownhost.
// We are using Go's template engine and have the following variables available.
// - Address ... ssh server hostname
// - RemoteAddr ... ssh server address
// - OldKeyText ... old ssh PublicKey text.
// ex: /home/user/.ssh/known_hosts:17: ecdsa-sha2-nistp256 AAAAE2VjZHN...bJklasnFtkFSDyOjTFSv2g=
// - NewFingerprint ... new ssh PublicKey fingerprint
TextAskOverwriteKnownHosts string
// ssh-agent interface.
// agent.Agent or agent.ExtendedAgent
// Set it before CraeteClient.
Agent AgentInterface
// Forward x11 flag.
// Set it before CraeteClient.
ForwardX11 bool
// Forward X11 trusted flag.
// This flag is ssh -Y option like flag.
// Set it before CraeteClient.
ForwardX11Trusted bool
// Dynamic forward related logger
DynamicForwardLogger *log.Logger
// shell terminal log flag
logging bool
// terminal log add timestamp flag
logTimestamp bool
// terminal log path
logFile string
// remove ansi code on terminal log.
logRemoveAnsiCode bool
}
// CreateClient set c.Client.
func (c *Connect) CreateClient(host, port, user string, authMethods []ssh.AuthMethod) (err error) {
uri := net.JoinHostPort(host, port)
timeout := 20
if c.ConnectTimeout == 0 {
c.ConnectTimeout = timeout
}
// Create new ssh.ClientConfig{}
config := &ssh.ClientConfig{
User: user,
Auth: authMethods,
Timeout: time.Duration(c.ConnectTimeout) * time.Second,
}
if c.HostKeyCallback != nil {
config.HostKeyCallback = c.HostKeyCallback
} else {
if c.CheckKnownHosts {
if len(c.KnownHostsFiles) == 0 {
// append default files
c.KnownHostsFiles = append(c.KnownHostsFiles, "~/.ssh/known_hosts")
}
config.HostKeyCallback = c.VerifyAndAppendNew
} else {
config.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
}
// check Dialer
if c.ProxyDialer == nil {
c.ProxyDialer = proxy.Direct
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.ConnectTimeout)*time.Second)
defer cancel()
// Dial to host:port
netConn, cerr := c.ProxyDialer.DialContext(ctx, "tcp", uri)
if cerr != nil {
return cerr
}
// Set deadline
netConn.SetDeadline(time.Now().Add(time.Duration(c.ConnectTimeout) * time.Second))
// Create new ssh connect
sshCon, channel, req, cerr := ssh.NewClientConn(netConn, uri, config)
if cerr != nil {
return cerr
}
// Reet deadline
netConn.SetDeadline(time.Time{})
// Create *ssh.Client
c.Client = ssh.NewClient(sshCon, channel, req)
return
}
// CreateSession retrun ssh.Session
func (c *Connect) CreateSession() (session *ssh.Session, err error) {
// Create session
session, err = c.Client.NewSession()
return
}
// SendKeepAlive send packet to session.
// TODO(blacknon): Interval及びMaxを設定できるようにする(v0.1.1)
func (c *Connect) SendKeepAlive(session *ssh.Session) {
// keep alive interval (default 30 sec)
interval := 1
if c.SendKeepAliveInterval > 0 {
interval = c.SendKeepAliveInterval
}
max := 3
if c.SendKeepAliveMax > 0 {
max = c.SendKeepAliveMax
}
t := time.NewTicker(time.Duration(c.ConnectTimeout) * time.Second)
defer t.Stop()
count := 0
for {
select {
case <-t.C:
if _, err := session.SendRequest("[email protected]", true, nil); err != nil {
log.Println("Failed to send keepalive packet:", err)
count += 1
} else {
// err is nil.
time.Sleep(time.Duration(interval) * time.Second)
}
}
if count > max {
return
}
}
}
// CheckClientAlive check alive ssh.Client.
func (c *Connect) CheckClientAlive() error {
_, _, err := c.Client.SendRequest("keepalive", true, nil)
if err == nil {
return nil
}
return err
}
// RequestTty requests the association of a pty with the session on the remote
// host. Terminal size is obtained from the currently connected terminal
func RequestTty(session *ssh.Session) (err error) {
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
// Get terminal window size
fd := int(os.Stdout.Fd())
width, hight, err := terminal.GetSize(fd)
if err != nil {
return
}
// Get env `TERM`
term := os.Getenv("TERM")
if len(term) == 0 {
term = "xterm"
}
if err = session.RequestPty(term, hight, width, modes); err != nil {
session.Close()
return
}
// Terminal resize goroutine.
winch := syscall.Signal(0x1c)
signalchan := make(chan os.Signal, 1)
signal.Notify(signalchan, winch)
go func() {
for {
s := <-signalchan
switch s {
case winch:
fd := int(os.Stdout.Fd())
width, hight, _ = terminal.GetSize(fd)
session.WindowChange(hight, width)
}
}
}()
return
}