-
Notifications
You must be signed in to change notification settings - Fork 162
/
client.go
162 lines (124 loc) · 3.72 KB
/
client.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
package ssh
import (
"fmt"
"net"
"strings"
"time"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshhttp "github.com/cloudfoundry/bosh-utils/httpclient"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
"github.com/pivotal-golang/clock"
"golang.org/x/crypto/ssh"
)
type Client interface {
Start() error
Stop() error
Dial(net, addr string) (net.Conn, error)
Listen(net, addr string) (net.Listener, error)
}
type ClientImpl struct {
opts ClientOpts
connectionRefusedTimeout time.Duration
authFailureTimeout time.Duration
timeService clock.Clock
startDialDelay time.Duration
client *ssh.Client
logTag string
logger boshlog.Logger
}
func (s *ClientImpl) Start() error {
authMethods := []ssh.AuthMethod{}
if s.opts.PrivateKey != "" {
signer, err := ssh.ParsePrivateKey([]byte(s.opts.PrivateKey))
if err != nil {
return bosherr.WrapErrorf(err, "Parsing private key '%s'", s.opts.PrivateKey)
}
authMethods = append(authMethods, ssh.PublicKeys(signer))
}
if s.opts.Password != "" {
s.logger.Debug(s.logTag, "Adding password auth method to ssh tunnel config")
keyboardInteractiveChallenge := func(_, _ string, questions []string, _ []bool) ([]string, error) {
if len(questions) == 0 {
return []string{}, nil
}
return []string{s.opts.Password}, nil
}
authMethods = append(authMethods, ssh.KeyboardInteractive(keyboardInteractiveChallenge))
authMethods = append(authMethods, ssh.Password(s.opts.Password))
}
sshConfig := &ssh.ClientConfig{
User: s.opts.User,
Auth: authMethods,
}
s.logger.Debug(s.logTag, "Dialing remote server at %s:%d", s.opts.Host, s.opts.Port)
retryStrategy := &ClientConnectRetryStrategy{
TimeService: s.timeService,
ConnectionRefusedTimeout: s.connectionRefusedTimeout,
AuthFailureTimeout: s.authFailureTimeout,
}
var err error
for i := 0; ; i++ {
s.logger.Debug(s.logTag, "Making attempt #%d", i)
s.client, err = s.newClient("tcp", fmt.Sprintf("%s:%d", s.opts.Host, s.opts.Port), sshConfig)
if err == nil {
break
}
if !retryStrategy.IsRetryable(err) {
return bosherr.WrapError(err, "Failed to connect to remote server")
}
s.logger.Debug(s.logTag, "Attempt failed #%d: Dialing remote server: %s", i, err.Error())
time.Sleep(s.startDialDelay)
}
return nil
}
func (s *ClientImpl) Dial(n, addr string) (net.Conn, error) {
return s.client.Dial(n, addr)
}
func (s *ClientImpl) Listen(n, addr string) (net.Listener, error) {
return s.client.Listen(n, addr)
}
func (s *ClientImpl) Stop() error {
if s.client != nil {
return s.client.Close()
}
return nil
}
func (s *ClientImpl) newClient(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
dialFunc := net.Dial
if !s.opts.DisableSOCKS {
dialFunc = boshhttp.SOCKS5DialFuncFromEnvironment(net.Dial)
}
conn, err := dialFunc(network, addr)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
type ClientConnectRetryStrategy struct {
ConnectionRefusedTimeout time.Duration
AuthFailureTimeout time.Duration
TimeService clock.Clock
initialized bool
startTime time.Time
authStartTime time.Time
}
func (s *ClientConnectRetryStrategy) 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))
}