forked from cloudfoundry/cli
/
ssh.go
409 lines (341 loc) · 9.5 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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package clissh
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"
"code.cloudfoundry.org/cli/cf/ssh/sigwinch"
"code.cloudfoundry.org/cli/util/clissh/ssherror"
"github.com/moby/moby/pkg/term"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
const (
md5FingerprintLength = 47 // inclusive of space between bytes
hexSha1FingerprintLength = 59 // inclusive of space between bytes
base64Sha256FingerprintLength = 43
DefaultKeepAliveInterval = 30 * time.Second
)
type LocalPortForward struct {
LocalAddress string
RemoteAddress string
}
type SecureShell struct {
secureDialer SecureDialer
secureClient SecureClient
terminalHelper TerminalHelper
listenerFactory ListenerFactory
localListeners []net.Listener
keepAliveInterval time.Duration
}
func NewDefaultSecureShell() *SecureShell {
defaultSecureDialer := DefaultSecureDialer()
defaultTerminalHelper := DefaultTerminalHelper()
defaultListenerFactory := DefaultListenerFactory()
return &SecureShell{
secureDialer: defaultSecureDialer,
terminalHelper: defaultTerminalHelper,
listenerFactory: defaultListenerFactory,
keepAliveInterval: DefaultKeepAliveInterval,
localListeners: []net.Listener{},
}
}
func NewSecureShell(
secureDialer SecureDialer,
terminalHelper TerminalHelper,
listenerFactory ListenerFactory,
keepAliveInterval time.Duration,
) *SecureShell {
return &SecureShell{
secureDialer: secureDialer,
terminalHelper: terminalHelper,
listenerFactory: listenerFactory,
keepAliveInterval: keepAliveInterval,
localListeners: []net.Listener{},
}
}
func (c *SecureShell) Close() error {
for _, listener := range c.localListeners {
listener.Close()
}
return c.secureClient.Close()
}
func (c *SecureShell) Connect(username string, passcode string, appSSHEndpoint string, appSSHHostKeyFingerprint string, skipHostValidation bool) error {
hostKeyCallbackFunction := fingerprintCallback(skipHostValidation, appSSHHostKeyFingerprint)
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{ssh.Password(passcode)},
HostKeyCallback: hostKeyCallbackFunction,
}
secureClient, err := c.secureDialer.Dial("tcp", appSSHEndpoint, clientConfig)
if err != nil {
if strings.Contains(err.Error(), "ssh: unable to authenticate") {
return ssherror.UnableToAuthenticateError{Err: err}
}
return err
}
c.secureClient = secureClient
return nil
}
func (c *SecureShell) InteractiveSession(commands []string, terminalRequest TTYRequest) error {
session, err := c.secureClient.NewSession()
if err != nil {
return fmt.Errorf("SSH session allocation failed: %s", err.Error())
}
defer session.Close()
stdin, stdout, stderr := c.terminalHelper.StdStreams()
inPipe, err := session.StdinPipe()
if err != nil {
return err
}
outPipe, err := session.StdoutPipe()
if err != nil {
return err
}
errPipe, err := session.StderrPipe()
if err != nil {
return err
}
stdinFd, stdinIsTerminal := c.terminalHelper.GetFdInfo(stdin)
stdoutFd, stdoutIsTerminal := c.terminalHelper.GetFdInfo(stdout)
if c.shouldAllocateTerminal(commands, terminalRequest, stdinIsTerminal) {
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 115200,
ssh.TTY_OP_OSPEED: 115200,
}
width, height := c.getWindowDimensions(stdoutFd)
err = session.RequestPty(c.terminalType(), height, width, modes)
if err != nil {
return err
}
var state *term.State
state, err = c.terminalHelper.SetRawTerminal(stdinFd)
if err == nil {
defer func() {
err := c.terminalHelper.RestoreTerminal(stdinFd, state)
log.Errorln("restore terminal", err)
}()
}
}
if len(commands) > 0 {
cmd := strings.Join(commands, " ")
err = session.Start(cmd)
if err != nil {
return err
}
} else {
err = session.Shell()
if err != nil {
return err
}
}
wg := &sync.WaitGroup{}
wg.Add(2)
go copyAndClose(nil, inPipe, stdin)
go copyAndDone(wg, stdout, outPipe)
go copyAndDone(wg, stderr, errPipe)
if stdoutIsTerminal {
resized := make(chan os.Signal, 16)
if runtime.GOOS == "windows" {
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
go func() {
for range ticker.C {
resized <- syscall.Signal(-1)
}
close(resized)
}()
} else {
signal.Notify(resized, sigwinch.SIGWINCH())
defer func() { signal.Stop(resized); close(resized) }()
}
go c.resize(resized, session, stdoutFd)
}
keepaliveStopCh := make(chan struct{})
defer close(keepaliveStopCh)
go keepalive(c.secureClient.Conn(), time.NewTicker(c.keepAliveInterval), keepaliveStopCh)
result := session.Wait()
wg.Wait()
return result
}
func (c *SecureShell) LocalPortForward(localPortForwardSpecs []LocalPortForward) error {
for _, spec := range localPortForwardSpecs {
listener, err := c.listenerFactory.Listen("tcp", spec.LocalAddress)
if err != nil {
return err
}
c.localListeners = append(c.localListeners, listener)
go c.localForwardAcceptLoop(listener, spec.RemoteAddress)
}
return nil
}
func (c *SecureShell) Wait() error {
keepaliveStopCh := make(chan struct{})
defer close(keepaliveStopCh)
go keepalive(c.secureClient.Conn(), time.NewTicker(c.keepAliveInterval), keepaliveStopCh)
return c.secureClient.Wait()
}
func (c *SecureShell) getWindowDimensions(terminalFd uintptr) (width int, height int) {
winSize, err := c.terminalHelper.GetWinsize(terminalFd)
if err != nil {
winSize = &term.Winsize{
Width: 80,
Height: 43,
}
}
return int(winSize.Width), int(winSize.Height)
}
func (c *SecureShell) handleForwardConnection(conn net.Conn, targetAddr string) {
defer conn.Close()
target, err := c.secureClient.Dial("tcp", targetAddr)
if err != nil {
fmt.Printf("connect to %s failed: %s\n", targetAddr, err.Error())
return
}
defer target.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
go copyAndClose(wg, conn, target)
go copyAndClose(wg, target, conn)
wg.Wait()
}
func (c *SecureShell) localForwardAcceptLoop(listener net.Listener, addr string) {
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
time.Sleep(100 * time.Millisecond)
continue
}
return
}
go c.handleForwardConnection(conn, addr)
}
}
func (c *SecureShell) resize(resized <-chan os.Signal, session SecureSession, terminalFd uintptr) {
type resizeMessage struct {
Width uint32
Height uint32
PixelWidth uint32
PixelHeight uint32
}
var previousWidth, previousHeight int
for range resized {
width, height := c.getWindowDimensions(terminalFd)
if width == previousWidth && height == previousHeight {
continue
}
message := resizeMessage{
Width: uint32(width),
Height: uint32(height),
}
_, err := session.SendRequest("window-change", false, ssh.Marshal(message))
if err != nil {
log.Errorln("window-change:", err)
}
previousWidth = width
previousHeight = height
}
}
func (c *SecureShell) shouldAllocateTerminal(commands []string, terminalRequest TTYRequest, stdinIsTerminal bool) bool {
switch terminalRequest {
case RequestTTYForce:
return true
case RequestTTYNo:
return false
case RequestTTYYes:
return stdinIsTerminal
case RequestTTYAuto:
return len(commands) == 0 && stdinIsTerminal
default:
return false
}
}
func (c *SecureShell) terminalType() string {
term := os.Getenv("TERM")
if term == "" {
term = "xterm"
}
return term
}
func base64Sha256Fingerprint(key ssh.PublicKey) string {
sum := sha256.Sum256(key.Marshal())
return base64.RawStdEncoding.EncodeToString(sum[:])
}
func copyAndClose(wg *sync.WaitGroup, dest io.WriteCloser, src io.Reader) {
_, err := io.Copy(dest, src)
if err != nil {
log.Errorln("copy and close:", err)
}
_ = dest.Close()
if wg != nil {
wg.Done()
}
}
func copyAndDone(wg *sync.WaitGroup, dest io.Writer, src io.Reader) {
_, err := io.Copy(dest, src)
if err != nil {
log.Errorln("copy and done:", err)
}
wg.Done()
}
func fingerprintCallback(skipHostValidation bool, expectedFingerprint string) ssh.HostKeyCallback {
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
if skipHostValidation {
return nil
}
var fingerprint string
switch len(expectedFingerprint) {
case base64Sha256FingerprintLength:
fingerprint = base64Sha256Fingerprint(key)
case hexSha1FingerprintLength:
fingerprint = hexSha1Fingerprint(key)
case md5FingerprintLength:
fingerprint = md5Fingerprint(key)
case 0:
fingerprint = md5Fingerprint(key)
return fmt.Errorf("Unable to verify identity of host.\n\nThe fingerprint of the received key was %q.", fingerprint)
default:
return errors.New("Unsupported host key fingerprint format")
}
if fingerprint != expectedFingerprint {
return fmt.Errorf("Host key verification failed.\n\nThe fingerprint of the received key was %q.", fingerprint)
}
return nil
}
}
func hexSha1Fingerprint(key ssh.PublicKey) string {
sum := sha1.Sum(key.Marshal())
return strings.Replace(fmt.Sprintf("% x", sum), " ", ":", -1)
}
func keepalive(conn ssh.Conn, ticker *time.Ticker, stopCh chan struct{}) {
for {
select {
case <-ticker.C:
_, _, err := conn.SendRequest("keepalive@cloudfoundry.org", true, nil)
if err != nil {
log.Errorln("err sending keep alive:", err)
}
case <-stopCh:
ticker.Stop()
return
}
}
}
func md5Fingerprint(key ssh.PublicKey) string {
sum := md5.Sum(key.Marshal())
return strings.Replace(fmt.Sprintf("% x", sum), " ", ":", -1)
}