forked from jpillora/chisel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
284 lines (267 loc) · 6.65 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
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
package chclient
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/jpillora/backoff"
"github.com/jpillora/chisel/share"
"golang.org/x/crypto/ssh"
)
//Config represents a client configuration
type Config struct {
shared *chshare.Config
Fingerprint string
Auth string
KeepAlive time.Duration
MaxRetryCount int
MaxRetryInterval time.Duration
Server string
HTTPProxy string
Remotes []string
HostHeader string
}
//Client represents a client instance
type Client struct {
*chshare.Logger
config *Config
sshConfig *ssh.ClientConfig
sshConn ssh.Conn
httpProxyURL *url.URL
server string
running bool
runningc chan error
connStats chshare.ConnStats
}
//NewClient creates a new client instance
func NewClient(config *Config) (*Client, error) {
//apply default scheme
if !strings.HasPrefix(config.Server, "http") {
config.Server = "http://" + config.Server
}
if config.MaxRetryInterval < time.Second {
config.MaxRetryInterval = 5 * time.Minute
}
u, err := url.Parse(config.Server)
if err != nil {
return nil, err
}
//apply default port
if !regexp.MustCompile(`:\d+$`).MatchString(u.Host) {
if u.Scheme == "https" || u.Scheme == "wss" {
u.Host = u.Host + ":443"
} else {
u.Host = u.Host + ":80"
}
}
//swap to websockets scheme
u.Scheme = strings.Replace(u.Scheme, "http", "ws", 1)
shared := &chshare.Config{}
for _, s := range config.Remotes {
r, err := chshare.DecodeRemote(s)
if err != nil {
return nil, fmt.Errorf("Failed to decode remote '%s': %s", s, err)
}
shared.Remotes = append(shared.Remotes, r)
}
config.shared = shared
client := &Client{
Logger: chshare.NewLogger("client"),
config: config,
server: u.String(),
running: true,
runningc: make(chan error, 1),
}
client.Info = true
if p := config.HTTPProxy; p != "" {
client.httpProxyURL, err = url.Parse(p)
if err != nil {
return nil, fmt.Errorf("Invalid proxy URL (%s)", err)
}
}
user, pass := chshare.ParseAuth(config.Auth)
client.sshConfig = &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(pass)},
ClientVersion: "SSH-" + chshare.ProtocolVersion + "-client",
HostKeyCallback: client.verifyServer,
Timeout: 30 * time.Second,
}
return client, nil
}
//Run starts client and blocks while connected
func (c *Client) Run() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := c.Start(ctx); err != nil {
return err
}
return c.Wait()
}
func (c *Client) verifyServer(hostname string, remote net.Addr, key ssh.PublicKey) error {
expect := c.config.Fingerprint
got := chshare.FingerprintKey(key)
if expect != "" && !strings.HasPrefix(got, expect) {
return fmt.Errorf("Invalid fingerprint (%s)", got)
}
//overwrite with complete fingerprint
c.Infof("Fingerprint %s", got)
return nil
}
//Start client and does not block
func (c *Client) Start(ctx context.Context) error {
via := ""
if c.httpProxyURL != nil {
via = " via " + c.httpProxyURL.String()
}
//prepare non-reverse proxies
for i, r := range c.config.shared.Remotes {
if !r.Reverse {
proxy := chshare.NewTCPProxy(c.Logger, func() ssh.Conn { return c.sshConn }, i, r)
if err := proxy.Start(ctx); err != nil {
return err
}
}
}
c.Infof("Connecting to %s%s\n", c.server, via)
//optional keepalive loop
if c.config.KeepAlive > 0 {
go c.keepAliveLoop()
}
//connection loop
go c.connectionLoop()
return nil
}
func (c *Client) keepAliveLoop() {
for c.running {
time.Sleep(c.config.KeepAlive)
if c.sshConn != nil {
c.sshConn.SendRequest("ping", true, nil)
}
}
}
func (c *Client) connectionLoop() {
//connection loop!
var connerr error
b := &backoff.Backoff{Max: c.config.MaxRetryInterval}
for c.running {
if connerr != nil {
attempt := int(b.Attempt())
maxAttempt := c.config.MaxRetryCount
d := b.Duration()
//show error and attempt counts
msg := fmt.Sprintf("Connection error: %s", connerr)
if attempt > 0 {
msg += fmt.Sprintf(" (Attempt: %d", attempt)
if maxAttempt > 0 {
msg += fmt.Sprintf("/%d", maxAttempt)
}
msg += ")"
}
c.Debugf(msg)
//give up?
if maxAttempt >= 0 && attempt >= maxAttempt {
break
}
c.Infof("Retrying in %s...", d)
connerr = nil
chshare.SleepSignal(d)
}
d := websocket.Dialer{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
HandshakeTimeout: 45 * time.Second,
Subprotocols: []string{chshare.ProtocolVersion},
}
//optionally CONNECT proxy
if c.httpProxyURL != nil {
d.Proxy = func(*http.Request) (*url.URL, error) {
return c.httpProxyURL, nil
}
}
wsHeaders := http.Header{}
if c.config.HostHeader != "" {
wsHeaders = http.Header{
"Host": {c.config.HostHeader},
}
}
wsConn, _, err := d.Dial(c.server, wsHeaders)
if err != nil {
connerr = err
continue
}
conn := chshare.NewWebSocketConn(wsConn)
// perform SSH handshake on net.Conn
c.Debugf("Handshaking...")
sshConn, chans, reqs, err := ssh.NewClientConn(conn, "", c.sshConfig)
if err != nil {
if strings.Contains(err.Error(), "unable to authenticate") {
c.Infof("Authentication failed")
c.Debugf(err.Error())
} else {
c.Infof(err.Error())
}
break
}
c.config.shared.Version = chshare.BuildVersion
conf, _ := chshare.EncodeConfig(c.config.shared)
c.Debugf("Sending config")
t0 := time.Now()
_, configerr, err := sshConn.SendRequest("config", true, conf)
if err != nil {
c.Infof("Config verification failed")
break
}
if len(configerr) > 0 {
c.Infof(string(configerr))
break
}
c.Infof("Connected (Latency %s)", time.Since(t0))
//connected
b.Reset()
c.sshConn = sshConn
go ssh.DiscardRequests(reqs)
go c.connectStreams(chans)
err = sshConn.Wait()
//disconnected
c.sshConn = nil
if err != nil && err != io.EOF {
connerr = err
continue
}
c.Infof("Disconnected\n")
}
close(c.runningc)
}
//Wait blocks while the client is running.
//Can only be called once.
func (c *Client) Wait() error {
return <-c.runningc
}
//Close manually stops the client
func (c *Client) Close() error {
c.running = false
if c.sshConn == nil {
return nil
}
return c.sshConn.Close()
}
func (c *Client) connectStreams(chans <-chan ssh.NewChannel) {
for ch := range chans {
remote := string(ch.ExtraData())
stream, reqs, err := ch.Accept()
if err != nil {
c.Debugf("Failed to accept stream: %s", err)
continue
}
go ssh.DiscardRequests(reqs)
l := c.Logger.Fork("conn#%d", c.connStats.New())
go chshare.HandleTCPStream(l, &c.connStats, stream, remote)
}
}