forked from cloudfoundry-attic/bosh-init
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_tunnel.go
200 lines (168 loc) · 5.48 KB
/
ssh_tunnel.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
package sshtunnel
import (
"fmt"
"io"
"io/ioutil"
"net"
"strings"
"time"
"github.com/cloudfoundry/bosh-init/internal/golang.org/x/crypto/ssh"
bosherr "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-init/internal/github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-init/internal/github.com/pivotal-golang/clock"
)
type SSHTunnel interface {
Start(chan<- error, chan<- error)
Stop() error
}
type sshTunnel struct {
connectionRefusedTimeout time.Duration
authFailureTimeout time.Duration
timeService clock.Clock
startDialDelay time.Duration
options Options
remoteListener net.Listener
logger boshlog.Logger
logTag string
}
func (s *sshTunnel) Start(readyErrCh chan<- error, errCh chan<- error) {
authMethods := []ssh.AuthMethod{}
if s.options.PrivateKey != "" {
s.logger.Debug(s.logTag, "Reading private key file '%s'", s.options.PrivateKey)
keyContents, err := ioutil.ReadFile(s.options.PrivateKey)
if err != nil {
readyErrCh <- bosherr.WrapErrorf(err, "Reading private key file '%s'", s.options.PrivateKey)
return
}
s.logger.Debug(s.logTag, "Parsing private key file '%s'", s.options.PrivateKey)
signer, err := ssh.ParsePrivateKey(keyContents)
if err != nil {
readyErrCh <- bosherr.WrapErrorf(err, "Parsing private key file '%s'", s.options.PrivateKey)
return
}
authMethods = append(authMethods, ssh.PublicKeys(signer))
}
if s.options.Password != "" {
s.logger.Debug(s.logTag, "Adding password auth method to ssh tunnel config")
keyboardInteractiveChallenge := func(
user,
instruction string,
questions []string,
echos []bool,
) (answers []string, err error) {
if len(questions) == 0 {
return []string{}, nil
}
return []string{s.options.Password}, nil
}
authMethods = append(authMethods, ssh.KeyboardInteractive(keyboardInteractiveChallenge))
authMethods = append(authMethods, ssh.Password(s.options.Password))
}
sshConfig := &ssh.ClientConfig{
User: s.options.User,
Auth: authMethods,
}
s.logger.Debug(s.logTag, "Dialing remote server at %s:%d", s.options.Host, s.options.Port)
remoteAddr := fmt.Sprintf("%s:%d", s.options.Host, s.options.Port)
retryStrategy := &SSHRetryStrategy{
TimeService: s.timeService,
ConnectionRefusedTimeout: s.connectionRefusedTimeout,
AuthFailureTimeout: s.authFailureTimeout,
}
var conn *ssh.Client
var err error
for i := 0; ; i++ {
s.logger.Debug(s.logTag, "Making attempt #%d", i)
conn, err = ssh.Dial("tcp", remoteAddr, sshConfig)
if err == nil {
break
}
if !retryStrategy.IsRetryable(err) {
readyErrCh <- bosherr.WrapError(err, "Failed to connect to remote server")
return
}
s.logger.Debug(s.logTag, "Attempt failed #%d: Dialing remote server: %s", i, err.Error())
time.Sleep(s.startDialDelay)
}
remoteListenAddr := fmt.Sprintf("127.0.0.1:%d", s.options.RemoteForwardPort)
s.logger.Debug(s.logTag, "Listening on remote server %s", remoteListenAddr)
s.remoteListener, err = conn.Listen("tcp", remoteListenAddr)
if err != nil {
readyErrCh <- bosherr.WrapError(err, "Listening on remote server")
return
}
readyErrCh <- nil
for {
remoteConn, err := s.remoteListener.Accept()
s.logger.Debug(s.logTag, "Received connection")
if err != nil {
errCh <- bosherr.WrapError(err, "Accepting connection on remote server")
}
defer func() {
if err = remoteConn.Close(); err != nil {
s.logger.Warn(s.logTag, "Failed to close remote listener connection: %s", err.Error())
}
}()
s.logger.Debug(s.logTag, "Dialing local server")
localDialAddr := fmt.Sprintf("127.0.0.1:%d", s.options.LocalForwardPort)
localConn, err := net.Dial("tcp", localDialAddr)
if err != nil {
errCh <- bosherr.WrapError(err, "Dialing local server")
return
}
go func() {
bytesNum, err := io.Copy(remoteConn, localConn)
defer func() {
if err = localConn.Close(); err != nil {
s.logger.Warn(s.logTag, "Failed to close local dial connection: %s", err.Error())
}
}()
s.logger.Debug(s.logTag, "Copying bytes from local to remote %d", bytesNum)
if err != nil {
errCh <- bosherr.WrapError(err, "Copying bytes from local to remote")
}
}()
go func() {
bytesNum, err := io.Copy(localConn, remoteConn)
defer func() {
if err = localConn.Close(); err != nil {
s.logger.Warn(s.logTag, "Failed to close local dial connection: %s", err.Error())
}
}()
s.logger.Debug(s.logTag, "Copying bytes from remote to local %d", bytesNum)
if err != nil {
errCh <- bosherr.WrapError(err, "Copying bytes from remote to local")
}
}()
}
}
func (s *sshTunnel) Stop() error {
if s.remoteListener == nil {
return nil
}
return s.remoteListener.Close()
}
type SSHRetryStrategy struct {
ConnectionRefusedTimeout time.Duration
AuthFailureTimeout time.Duration
TimeService clock.Clock
initialized bool
startTime time.Time
authStartTime time.Time
}
func (s *SSHRetryStrategy) IsRetryable(err error) bool {
now := s.TimeService.Now()
if !s.initialized {
s.startTime = now
s.authStartTime = now
s.initialized = true
}
if strings.Contains(err.Error(), "no common algorithms") {
return false
}
if strings.Contains(err.Error(), "unable to authenticate") {
return now.Before(s.authStartTime.Add(s.AuthFailureTimeout))
}
s.authStartTime = now
return now.Before(s.startTime.Add(s.ConnectionRefusedTimeout))
}