-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
542 lines (504 loc) · 16.9 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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package socks5
import (
"errors"
"fmt"
"io"
"log"
"net"
"strconv"
"time"
)
// Client defines parameters for running socks client.
type Client struct {
// ProxyAddr in the form "host:port". It not be empty.
ProxyAddr string
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, reading the response body.
//
// A Timeout of zero means no timeout.
//
// The Client cancels requests to the underlying Transport
// as if the Request's Context ended.
Timeout time.Duration
// method mapping to the authenticator
Auth map[METHOD]Authenticator
// ErrorLog specifics an options logger for errors accepting
// If nil, logging is done via log package's standard logger.
ErrorLog *log.Logger
// DisableSocks4A client disable socks4a client, default enable socks4a extension.
DisableSocks4A bool
}
// UserPasswd provide socks5 Client Username/Password Authenticator.
type UserPasswd struct {
Username string
Password string
}
// Authenticate socks5 Client Username/Password Authentication.
func (c *UserPasswd) Authenticate(in io.Reader, out io.Writer) error {
//This begins with the client producing a Username/Password request:
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
_, err := out.Write(append(append(append([]byte{0x01, byte(len(c.Username))}, []byte(c.Username)...), byte(len(c.Password))), []byte(c.Password)...))
if err != nil {
return err
}
//Get reply, the following response:
// +----+--------+
// |VER | STATUS |
// +----+--------+
// | 1 | 1 |
// +----+--------+
tmp, err := ReadNBytes(in, 2)
if err != nil {
return err
}
if tmp[0] != 0x01 {
return errors.New("not support method")
}
if tmp[1] != SUCCESSED {
return errors.New("user authentication failed")
}
return nil
}
// handshake socks TCP connect,get a tcp connect and reply addr
func (clt *Client) handshake(request *Request) (conn *net.TCPConn, replyAddr *Address, err error) {
// get Socks server Address
proxyTCPAddr, err := net.ResolveTCPAddr("tcp", clt.ProxyAddr)
if err != nil {
return nil, nil, err
}
// dial to Socks server.
proxyTCPConn, err := net.DialTCP("tcp", nil, proxyTCPAddr)
if err != nil {
return nil, nil, err
}
if clt.Timeout != 0 {
err = proxyTCPConn.SetDeadline(time.Now().Add(clt.Timeout))
if err != nil {
return nil, nil, err
}
defer proxyTCPConn.SetDeadline(time.Time{})
}
// process handshake by version
if request.VER == Version5 {
replyAddr, err = clt.handShake5(request, proxyTCPConn)
} else if request.VER == Version4 {
if request.ATYPE == DOMAINNAME && clt.DisableSocks4A {
return nil, nil, errors.New("socks4a client had been disabled")
}
replyAddr, err = clt.handshake4(request, proxyTCPConn)
}
// handshake wrong.
if err != nil {
proxyTCPConn.Close()
return nil, nil, err
}
return proxyTCPConn, replyAddr, nil
}
// handShake5 Socks 5 version of the connection handshake
func (clt *Client) handShake5(request *Request, proxyTCPConn net.Conn) (*Address, error) {
err := clt.authentication(proxyTCPConn)
if err != nil {
return nil, err
}
destAddrByte, err := request.Address.Bytes(Version5)
if err != nil {
return nil, err
}
// The SOCKS request is formed as follows:
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
if _, err := proxyTCPConn.Write(append([]byte{request.VER, request.CMD, request.RSV}, destAddrByte...)); err != nil {
return nil, err
}
// reply formed as follows:
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
reply := &Reply{}
tmp, err := ReadNBytes(proxyTCPConn, 3)
if err != nil {
return nil, fmt.Errorf("failed to get reply version and command and reserved, %v", err)
}
reply.VER, reply.REP, reply.RSV = tmp[0], tmp[1], tmp[2]
if reply.VER != Version5 {
return nil, fmt.Errorf("unrecognized SOCKS version[%d]", reply.VER)
}
// read address
serverBoundAddr, _, err := readAddress(proxyTCPConn, request.VER)
if err != nil {
return nil, fmt.Errorf("failed to get reply address, %v", err)
}
reply.Address = serverBoundAddr
if reply.REP != SUCCESSED {
return nil, fmt.Errorf("server refuse client request, %s", rep2Str[reply.REP])
}
return reply.Address, nil
}
// authentication
func (clt *Client) authentication(proxyConn net.Conn) error {
var methods []byte
for method := range clt.Auth {
methods = append(methods, method)
}
// The client connects to the server, and sends a version identifier/method selection message:
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
_, err := proxyConn.Write(append([]byte{Version5, byte(len(methods))}, methods...))
if err != nil {
return nil
}
//Get reply, a METHOD selection message:
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
reply, err := ReadNBytes(proxyConn, 2)
if err != nil {
return err
}
if reply[0] != Version5 {
return &VersionError{reply[0]}
}
// Is client has this method?
if _, ok := clt.Auth[reply[1]]; !ok {
return &MethodError{reply[1]}
}
// process authentication sub negotiation
err = clt.Auth[reply[1]].Authenticate(proxyConn, proxyConn)
if err != nil {
return err
}
return nil
}
// handShake4 Socks 4 version of the connection handshake
func (clt *Client) handshake4(request *Request, proxyConn net.Conn) (*Address, error) {
destAddrByte, err := request.Address.Bytes(Version4)
if err != nil {
return nil, err
}
// The client connects to the SOCKS server and sends a CONNECT request when it wants to establish a connection to an application server.
// The client includes in the request packet the IP address and the port number of the destination host, and userid, in the following format.
// +----+----+----+----+----+----+----+----+----+----+....+----+
// | VN | CD | DSTPORT | DSTIP | USERID |NULL|
// +----+----+----+----+----+----+----+----+----+----+....+----+
// 1 1 2 4 variable 1
if _, err := proxyConn.Write(append([]byte{request.VER, request.CMD}, destAddrByte...)); err != nil {
return nil, err
}
// A reply packet is sent to the client when this connection is established,or when the request is rejected or the operation fails.
// +----+----+----+----+----+----+----+----+
// | VN | CD | DSTPORT | DSTIP |
// +----+----+----+----+----+----+----+----+
// 1 1 2 4
tmp, err := ReadNBytes(proxyConn, 2)
if err != nil {
return nil, fmt.Errorf("failed to get reply version and command, %v", err)
}
if tmp[0] != 0 {
return nil, fmt.Errorf("response VN wrong[%d]", tmp[0])
}
if tmp[1] != Granted {
return nil, errors.New("server refuse client request")
}
// Read address
replyAddr, _, err := readSocks4ReplyAddress(proxyConn, request.VER)
if err != nil {
return nil, fmt.Errorf("failed to get reply address, %v", err)
}
return replyAddr, nil
}
// Connect send CONNECT Request. Returned a connected proxy connection.
func (clt *Client) Connect(ver VER, dest string) (*net.TCPConn, error) {
if ver != Version4 && ver != Version5 {
return nil, &VersionError{ver}
}
destAddr, err := ParseAddress(dest)
if err != nil {
return nil, err
}
req := &Request{
VER: ver,
CMD: CONNECT,
RSV: 0,
Address: destAddr,
}
conn, _, err := clt.handshake(req)
if err != nil {
return nil, err
}
return conn, nil
}
// UDPForward send UDP_ASSOCIATE Request.
// The laddr Param specific Client address to send udp datagram.
// If laddr is empty string, a local address (127.0.0.1:port) is automatically chosen.
// If port is occupied will return error.
func (clt *Client) UDPForward(laddr string) (*UDPConn, error) {
if laddr == "" {
laddr = "127.0.0.1:0"
}
// split laddr to host/port
host, portStr, err := net.SplitHostPort(laddr)
p, err := strconv.Atoi(portStr)
if err != nil {
return nil, err
}
port := uint16(p)
// zero port, will automatically chosen.
if port == 0 {
err, port = GetRandomPort("udp")
if err != nil {
return nil, errors.New("automatically chosen port fail")
}
laddr = net.JoinHostPort(host, strconv.Itoa(int(port)))
}
// get addr
addr, err := ParseAddress(laddr)
if err != nil {
return nil, err
}
req := &Request{
VER: Version5,
CMD: UDP_ASSOCIATE,
RSV: 0,
Address: addr,
}
// Handshake base on TCP connection
proxyTCPConn, UDPRelayAddr, err := clt.handshake(req)
if err != nil {
return nil, err
}
// Get local UDP addr
localUDPAddr, err := addr.UDPAddr()
if err != nil {
return nil, err
}
// Get udp relay server bind addr.
serverListenUDPAddr, err := UDPRelayAddr.UDPAddr()
if err != nil {
return nil, err
}
// Dial UDP relay Server
err = IsFreePort("udp", port)
if err != nil {
proxyTCPConn.Close()
return nil, fmt.Errorf("port %d is occupied", port)
}
proxyUDPConn, err := net.DialUDP("udp", localUDPAddr, serverListenUDPAddr)
if err != nil {
proxyTCPConn.Close()
return nil, err
}
return NewUDPConn(proxyUDPConn, proxyTCPConn), nil
}
// Bind send BIND Request. return 4 params:
// 1. Server bind address.
// 2. a readable chan to recv second reply from socks server.
// 3. A connection that is not immediately available, until read a nil from err chan.
// 4. An error, indicate the first reply result. If nil, successes.
func (clt *Client) Bind(ver VER, destAddr string) (*Address, <-chan error, net.Conn, error) {
dest, err := ParseAddress(destAddr)
if err != nil {
return nil, nil, nil, err
}
request := &Request{
Address: dest,
CMD: BIND,
VER: ver,
}
proxyConn, err := net.Dial("tcp", clt.ProxyAddr)
if err != nil {
clt.logf()(err.Error())
return nil, nil, nil, err
}
if clt.Timeout != 0 {
err = proxyConn.SetDeadline(time.Now().Add(clt.Timeout))
if err != nil {
clt.logf()(err.Error())
return nil, nil, nil, err
}
defer proxyConn.SetDeadline(time.Time{})
}
switch request.VER {
case Version4:
serverBindAddr, secondReply, err := clt.bind4(request, proxyConn)
if err != nil {
proxyConn.Close()
clt.logf()(err.Error())
return nil, nil, nil, err
}
return serverBindAddr, secondReply, proxyConn, nil
case Version5:
serverBindAddr, secondReply, err := clt.bind5(request, proxyConn)
if err != nil {
proxyConn.Close()
clt.logf()(err.Error())
return nil, nil, nil, err
}
return serverBindAddr, secondReply, proxyConn, nil
default:
proxyConn.Close()
return nil, nil, nil, &VersionError{request.VER}
}
}
// bind5 socks5 bind
func (clt *Client) bind5(request *Request, proxyBindConn net.Conn) (*Address, <-chan error, error) {
err := clt.authentication(proxyBindConn)
if err != nil {
return nil, nil, err
}
destAddrByte, err := request.Address.Bytes(Version5)
if err != nil {
return nil, nil, err
}
// The SOCKS request is formed as follows:
// +----+-----+-------+------+----------+----------+
// // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// // +----+-----+-------+------+----------+----------+
// // | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
if _, err := proxyBindConn.Write(append([]byte{request.VER, request.CMD, request.RSV}, destAddrByte...)); err != nil {
return nil, nil, err
}
// reply formed as follows:
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
reply := &Reply{}
tmp, err := ReadNBytes(proxyBindConn, 3)
if err != nil {
return nil, nil, fmt.Errorf("failed to get reply version and command and reserved, %v", err)
}
reply.VER, reply.REP, reply.RSV = tmp[0], tmp[1], tmp[2]
if reply.VER != Version5 {
return nil, nil, fmt.Errorf("unrecognized SOCKS version[%d]", reply.VER)
}
// read address
serverBoundAddr, _, err := readAddress(proxyBindConn, request.VER)
if err != nil {
return nil, nil, fmt.Errorf("failed to get reply address, %v", err)
}
reply.Address = serverBoundAddr
if reply.REP != SUCCESSED {
return nil, nil, fmt.Errorf("server refuse client request, %s,when first time reply", rep2Str[reply.REP])
}
errorChan := make(chan error)
go func() {
reply2 := &Reply{}
// The second time reply formed as follows:
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
tmp, err := ReadNBytes(proxyBindConn, 3)
if err != nil {
errorChan <- fmt.Errorf("failed to get reply version and command and reserved, %v", err)
proxyBindConn.Close()
}
reply2.VER, reply2.REP, reply2.RSV = tmp[0], tmp[1], tmp[2]
if reply2.VER != Version5 {
errorChan <- fmt.Errorf("unrecognized SOCKS version[%d]", reply.VER)
proxyBindConn.Close()
}
// read address
serverBoundAddr, _, err := readAddress(proxyBindConn, request.VER)
if err != nil {
errorChan <- fmt.Errorf("failed to get reply address, %v", err)
proxyBindConn.Close()
}
reply2.Address = serverBoundAddr
if reply2.REP != SUCCESSED {
errorChan <- errors.New("server refuse client request,when second time reply")
proxyBindConn.Close()
}
errorChan <- nil
}()
return serverBoundAddr, errorChan, nil
}
// bind4 socks4 bind
func (clt *Client) bind4(request *Request, proxyBindConn net.Conn) (*Address, <-chan error, error) {
destAddrByte, err := request.Address.Bytes(Version4)
if err != nil {
return nil, nil, err
}
// The client connects to the SOCKS server and sends a CONNECT request when it wants to establish a connection to an application server.
// The client includes in the request packet the IP address and the port number of the destination host, and userid, in the following format.
// +----+----+----+----+----+----+----+----+----+----+....+----+
// | VN | CD | DSTPORT | DSTIP | USERID |NULL|
// +----+----+----+----+----+----+----+----+----+----+....+----+
// 1 1 2 4 variable 1
if _, err := proxyBindConn.Write(append([]byte{request.VER, request.CMD}, destAddrByte...)); err != nil {
return nil, nil, err
}
// A reply packet is sent to the client when this connection is established,or when the request is rejected or the operation fails.
// +----+----+----+----+----+----+----+----+
// | VN | CD | DSTPORT | DSTIP |
// +----+----+----+----+----+----+----+----+
// 1 1 2 4
tmp, err := ReadNBytes(proxyBindConn, 2)
if err != nil {
return nil, nil, fmt.Errorf("failed to get reply version and command, %v", err)
}
if tmp[0] != 0 {
return nil, nil, fmt.Errorf("response VN wrong[%d]", tmp[0])
}
// Read address
serverBoundAddr, _, err := readSocks4ReplyAddress(proxyBindConn, request.VER)
if err != nil {
return nil, nil, fmt.Errorf("failed to get reply address, %v", err)
}
if tmp[1] != Granted {
return nil, nil, errors.New("server refuse client request,when first time reply")
}
errorChan := make(chan error)
go func() {
// A reply packet is sent to the client,or when the request is rejected or the operation fails.
// +----+----+----+----+----+----+----+----+
// | VN | CD | DSTPORT | DSTIP |
// +----+----+----+----+----+----+----+----+
// 1 1 2 4
tmp, err := ReadNBytes(proxyBindConn, 2)
if err != nil {
errorChan <- fmt.Errorf("failed to get reply version and command, %v", err)
proxyBindConn.Close()
}
if tmp[0] != 0 {
errorChan <- fmt.Errorf("response VN wrong[%d]", tmp[0])
proxyBindConn.Close()
}
// read address
_, _, err = readSocks4ReplyAddress(proxyBindConn, request.VER)
if err != nil {
errorChan <- fmt.Errorf("failed to get reply address, %v", err)
proxyBindConn.Close()
}
if tmp[1] != Granted {
errorChan <- errors.New("server refuse client request,when second time reply")
proxyBindConn.Close()
}
errorChan <- nil
}()
return serverBoundAddr, errorChan, nil
}
// logf Logging is done using the client's errorlog
func (clt *Client) logf() func(format string, args ...interface{}) {
if clt.ErrorLog == nil {
return log.Printf
}
return clt.ErrorLog.Printf
}