forked from ginuerzh/gost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socks.go
2079 lines (1775 loc) · 50.4 KB
/
socks.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gost
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/url"
"strconv"
"sync"
"time"
"github.com/ginuerzh/gosocks4"
"github.com/ginuerzh/gosocks5"
"github.com/go-log/log"
smux "gopkg.in/xtaci/smux.v1"
)
const (
// MethodTLS is an extended SOCKS5 method with tls encryption support.
MethodTLS uint8 = 0x80
// MethodTLSAuth is an extended SOCKS5 method with tls encryption and authentication support.
MethodTLSAuth uint8 = 0x82
// MethodMux is an extended SOCKS5 method for stream multiplexing.
MethodMux = 0x88
)
const (
// CmdMuxBind is an extended SOCKS5 request CMD for
// multiplexing transport with the binding server.
CmdMuxBind uint8 = 0xF2
// CmdUDPTun is an extended SOCKS5 request CMD for UDP over TCP.
CmdUDPTun uint8 = 0xF3
)
var (
_ net.PacketConn = (*socks5UDPTunnelConn)(nil)
)
type clientSelector struct {
methods []uint8
User *url.Userinfo
TLSConfig *tls.Config
}
func (selector *clientSelector) Methods() []uint8 {
if Debug {
log.Log("[socks5] methods:", selector.methods)
}
return selector.methods
}
func (selector *clientSelector) AddMethod(methods ...uint8) {
selector.methods = append(selector.methods, methods...)
}
func (selector *clientSelector) Select(methods ...uint8) (method uint8) {
return
}
func (selector *clientSelector) OnSelected(method uint8, conn net.Conn) (net.Conn, error) {
if Debug {
log.Log("[socks5] method selected:", method)
}
switch method {
case MethodTLS:
conn = tls.Client(conn, selector.TLSConfig)
case gosocks5.MethodUserPass, MethodTLSAuth:
if method == MethodTLSAuth {
conn = tls.Client(conn, selector.TLSConfig)
}
var username, password string
if selector.User != nil {
username = selector.User.Username()
password, _ = selector.User.Password()
}
req := gosocks5.NewUserPassRequest(gosocks5.UserPassVer, username, password)
if err := req.Write(conn); err != nil {
log.Log("[socks5]", err)
return nil, err
}
if Debug {
log.Log("[socks5]", req)
}
resp, err := gosocks5.ReadUserPassResponse(conn)
if err != nil {
log.Log("[socks5]", err)
return nil, err
}
if Debug {
log.Log("[socks5]", resp)
}
if resp.Status != gosocks5.Succeeded {
return nil, gosocks5.ErrAuthFailure
}
case gosocks5.MethodNoAcceptable:
return nil, gosocks5.ErrBadMethod
}
return conn, nil
}
type serverSelector struct {
methods []uint8
// Users []*url.Userinfo
Authenticator Authenticator
TLSConfig *tls.Config
}
func (selector *serverSelector) Methods() []uint8 {
return selector.methods
}
func (selector *serverSelector) AddMethod(methods ...uint8) {
selector.methods = append(selector.methods, methods...)
}
func (selector *serverSelector) Select(methods ...uint8) (method uint8) {
if Debug {
log.Logf("[socks5] %d %d %v", gosocks5.Ver5, len(methods), methods)
}
method = gosocks5.MethodNoAuth
for _, m := range methods {
if m == MethodTLS {
method = m
break
}
}
// when Authenticator is set, auth is mandatory
if selector.Authenticator != nil {
if method == gosocks5.MethodNoAuth {
method = gosocks5.MethodUserPass
}
if method == MethodTLS {
method = MethodTLSAuth
}
}
return
}
func (selector *serverSelector) OnSelected(method uint8, conn net.Conn) (net.Conn, error) {
if Debug {
log.Logf("[socks5] %d %d", gosocks5.Ver5, method)
}
switch method {
case MethodTLS:
conn = tls.Server(conn, selector.TLSConfig)
case gosocks5.MethodUserPass, MethodTLSAuth:
if method == MethodTLSAuth {
conn = tls.Server(conn, selector.TLSConfig)
}
req, err := gosocks5.ReadUserPassRequest(conn)
if err != nil {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), err)
return nil, err
}
if Debug {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), req.String())
}
if selector.Authenticator != nil && !selector.Authenticator.Authenticate(req.Username, req.Password) {
resp := gosocks5.NewUserPassResponse(gosocks5.UserPassVer, gosocks5.Failure)
if err := resp.Write(conn); err != nil {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), err)
return nil, err
}
if Debug {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), resp)
}
log.Logf("[socks5] %s - %s: proxy authentication required", conn.RemoteAddr(), conn.LocalAddr())
return nil, gosocks5.ErrAuthFailure
}
resp := gosocks5.NewUserPassResponse(gosocks5.UserPassVer, gosocks5.Succeeded)
if err := resp.Write(conn); err != nil {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), err)
return nil, err
}
if Debug {
log.Logf("[socks5] %s - %s: %s", conn.RemoteAddr(), conn.LocalAddr(), resp)
}
case gosocks5.MethodNoAcceptable:
return nil, gosocks5.ErrBadMethod
}
return conn, nil
}
type socks5Connector struct {
User *url.Userinfo
}
// SOCKS5Connector creates a connector for SOCKS5 proxy client.
// It accepts an optional auth info for SOCKS5 Username/Password Authentication.
func SOCKS5Connector(user *url.Userinfo) Connector {
return &socks5Connector{User: user}
}
func (c *socks5Connector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
func (c *socks5Connector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "udp", "udp4", "udp6":
cnr := &socks5UDPTunConnector{User: c.User}
return cnr.ConnectContext(ctx, conn, network, address, options...)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
user := opts.User
if user == nil {
user = c.User
}
cc, err := socks5Handshake(conn,
selectorSocks5HandshakeOption(opts.Selector),
userSocks5HandshakeOption(user),
noTLSSocks5HandshakeOption(opts.NoTLS),
)
if err != nil {
return nil, err
}
conn = cc
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
p, _ := strconv.Atoi(port)
req := gosocks5.NewRequest(gosocks5.CmdConnect, &gosocks5.Addr{
Type: gosocks5.AddrDomain,
Host: host,
Port: uint16(p),
})
if err := req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Log("[socks5]", req)
}
reply, err := gosocks5.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Log("[socks5]", reply)
}
if reply.Rep != gosocks5.Succeeded {
return nil, errors.New("Service unavailable")
}
return conn, nil
}
type socks5BindConnector struct {
User *url.Userinfo
}
// SOCKS5BindConnector creates a connector for SOCKS5 bind.
// It accepts an optional auth info for SOCKS5 Username/Password Authentication.
func SOCKS5BindConnector(user *url.Userinfo) Connector {
return &socks5BindConnector{User: user}
}
func (c *socks5BindConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
func (c *socks5BindConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "udp", "udp4", "udp6":
return nil, fmt.Errorf("%s unsupported", network)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
user := opts.User
if user == nil {
user = c.User
}
cc, err := socks5Handshake(conn,
selectorSocks5HandshakeOption(opts.Selector),
userSocks5HandshakeOption(user),
noTLSSocks5HandshakeOption(opts.NoTLS),
)
if err != nil {
return nil, err
}
conn = cc
laddr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
log.Log(err)
return nil, err
}
req := gosocks5.NewRequest(gosocks5.CmdBind, &gosocks5.Addr{
Type: gosocks5.AddrIPv4,
Host: laddr.IP.String(),
Port: uint16(laddr.Port),
})
if err := req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] bind\n", req)
}
reply, err := gosocks5.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] bind\n", reply)
}
if reply.Rep != gosocks5.Succeeded {
log.Logf("[socks5] bind on %s failure", address)
return nil, fmt.Errorf("SOCKS5 bind on %s failure", address)
}
baddr, err := net.ResolveTCPAddr("tcp", reply.Addr.String())
if err != nil {
return nil, err
}
log.Logf("[socks5] bind on %s OK", baddr)
return &socks5BindConn{Conn: conn, laddr: baddr}, nil
}
type socks5MuxBindConnector struct{}
// Socks5MuxBindConnector creates a Connector for SOCKS5 multiplex bind client.
func Socks5MuxBindConnector() Connector {
return &socks5MuxBindConnector{}
}
func (c *socks5MuxBindConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
// NOTE: the conn must be *muxBindClientConn.
func (c *socks5MuxBindConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "udp", "udp4", "udp6":
return nil, fmt.Errorf("%s unsupported", network)
}
accepter, ok := conn.(Accepter)
if !ok {
return nil, errors.New("wrong connection type")
}
return accepter.Accept()
}
type socks5MuxBindTransporter struct {
bindAddr string
sessions map[string]*muxSession // server addr to session mapping
sessionMutex sync.Mutex
}
// SOCKS5MuxBindTransporter creates a Transporter for SOCKS5 multiplex bind client.
func SOCKS5MuxBindTransporter(bindAddr string) Transporter {
return &socks5MuxBindTransporter{
bindAddr: bindAddr,
sessions: make(map[string]*muxSession),
}
}
func (tr *socks5MuxBindTransporter) Dial(addr string, options ...DialOption) (conn net.Conn, err error) {
opts := &DialOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = DialTimeout
}
tr.sessionMutex.Lock()
defer tr.sessionMutex.Unlock()
session, ok := tr.sessions[addr]
if session != nil && session.IsClosed() {
delete(tr.sessions, addr)
ok = false
}
if !ok {
if opts.Chain == nil {
conn, err = net.DialTimeout("tcp", addr, timeout)
} else {
conn, err = opts.Chain.Dial(addr)
}
if err != nil {
return
}
session = &muxSession{conn: conn}
tr.sessions[addr] = session
}
return session.conn, nil
}
func (tr *socks5MuxBindTransporter) Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error) {
opts := &HandshakeOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = HandshakeTimeout
}
tr.sessionMutex.Lock()
defer tr.sessionMutex.Unlock()
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
session, ok := tr.sessions[opts.Addr]
if !ok || session.session == nil {
s, err := tr.initSession(conn, tr.bindAddr, opts)
if err != nil {
conn.Close()
delete(tr.sessions, opts.Addr)
return nil, err
}
session = s
tr.sessions[opts.Addr] = session
}
return &muxBindClientConn{session: session}, nil
}
func (tr *socks5MuxBindTransporter) initSession(conn net.Conn, addr string, opts *HandshakeOptions) (*muxSession, error) {
if opts == nil {
opts = &HandshakeOptions{}
}
cc, err := socks5Handshake(conn,
userSocks5HandshakeOption(opts.User),
)
if err != nil {
return nil, err
}
conn = cc
bindAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return nil, err
}
req := gosocks5.NewRequest(CmdMuxBind, &gosocks5.Addr{
Type: gosocks5.AddrIPv4,
Host: bindAddr.IP.String(),
Port: uint16(bindAddr.Port),
})
if err = req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] mbind\n", req)
}
reply, err := gosocks5.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] mbind\n", reply)
}
if reply.Rep != gosocks5.Succeeded {
log.Logf("[socks5] mbind on %s failure", addr)
return nil, fmt.Errorf("SOCKS5 mbind on %s failure", addr)
}
baddr, err := net.ResolveTCPAddr("tcp", reply.Addr.String())
if err != nil {
return nil, err
}
log.Logf("[socks5] mbind on %s OK", baddr)
// Upgrade connection to multiplex stream.
session, err := smux.Server(conn, smux.DefaultConfig())
if err != nil {
return nil, err
}
return &muxSession{conn: conn, session: session}, nil
}
func (tr *socks5MuxBindTransporter) Multiplex() bool {
return true
}
type socks5UDPConnector struct {
User *url.Userinfo
}
// SOCKS5UDPConnector creates a connector for SOCKS5 UDP relay.
// It accepts an optional auth info for SOCKS5 Username/Password Authentication.
func SOCKS5UDPConnector(user *url.Userinfo) Connector {
return &socks5UDPConnector{User: user}
}
func (c *socks5UDPConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "udp", address, options...)
}
func (c *socks5UDPConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "tcp", "tcp4", "tcp6":
return nil, fmt.Errorf("%s unsupported", network)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
user := opts.User
if user == nil {
user = c.User
}
cc, err := socks5Handshake(conn,
selectorSocks5HandshakeOption(opts.Selector),
userSocks5HandshakeOption(user),
noTLSSocks5HandshakeOption(opts.NoTLS),
)
if err != nil {
return nil, err
}
conn = cc
taddr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return nil, err
}
req := gosocks5.NewRequest(gosocks5.CmdUdp, &gosocks5.Addr{
Type: gosocks5.AddrIPv4,
})
if err := req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] udp\n", req)
}
reply, err := gosocks5.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Log("[socks5] udp\n", reply)
}
if reply.Rep != gosocks5.Succeeded {
log.Logf("[socks5] udp relay failure")
return nil, fmt.Errorf("SOCKS5 udp relay failure")
}
baddr, err := net.ResolveUDPAddr("udp", reply.Addr.String())
if err != nil {
return nil, err
}
log.Logf("[socks5] udp associate on %s OK", baddr)
uc, err := net.DialUDP("udp", nil, baddr)
if err != nil {
return nil, err
}
// log.Logf("udp laddr:%s, raddr:%s", uc.LocalAddr(), uc.RemoteAddr())
return &socks5UDPConn{UDPConn: uc, taddr: taddr}, nil
}
type socks5UDPTunConnector struct {
User *url.Userinfo
}
// SOCKS5UDPTunConnector creates a connector for SOCKS5 UDP-over-TCP relay.
// It accepts an optional auth info for SOCKS5 Username/Password Authentication.
func SOCKS5UDPTunConnector(user *url.Userinfo) Connector {
return &socks5UDPTunConnector{User: user}
}
func (c *socks5UDPTunConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "udp", address, options...)
}
func (c *socks5UDPTunConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "tcp", "tcp4", "tcp6":
return nil, fmt.Errorf("%s unsupported", network)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
user := opts.User
if user == nil {
user = c.User
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
taddr, _ := net.ResolveUDPAddr("udp", address)
return newSocks5UDPTunnelConn(conn,
nil, taddr,
selectorSocks5HandshakeOption(opts.Selector),
userSocks5HandshakeOption(user),
noTLSSocks5HandshakeOption(opts.NoTLS),
)
}
type socks4Connector struct{}
// SOCKS4Connector creates a Connector for SOCKS4 proxy client.
func SOCKS4Connector() Connector {
return &socks4Connector{}
}
func (c *socks4Connector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
func (c *socks4Connector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "udp", "udp4", "udp6":
return nil, fmt.Errorf("%s unsupported", network)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
taddr, err := net.ResolveTCPAddr("tcp4", address)
if err != nil {
return nil, err
}
if len(taddr.IP) == 0 {
taddr.IP = net.IPv4zero
}
req := gosocks4.NewRequest(gosocks4.CmdConnect,
&gosocks4.Addr{
Type: gosocks4.AddrIPv4,
Host: taddr.IP.String(),
Port: uint16(taddr.Port),
}, nil,
)
if err := req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Logf("[socks4] %s", req)
}
reply, err := gosocks4.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Logf("[socks4] %s", reply)
}
if reply.Code != gosocks4.Granted {
return nil, fmt.Errorf("[socks4] %d", reply.Code)
}
return conn, nil
}
type socks4aConnector struct{}
// SOCKS4AConnector creates a Connector for SOCKS4A proxy client.
func SOCKS4AConnector() Connector {
return &socks4aConnector{}
}
func (c *socks4aConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
func (c *socks4aConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
switch network {
case "udp", "udp4", "udp6":
return nil, fmt.Errorf("%s unsupported", network)
}
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
p, _ := strconv.Atoi(port)
req := gosocks4.NewRequest(gosocks4.CmdConnect,
&gosocks4.Addr{Type: gosocks4.AddrDomain, Host: host, Port: uint16(p)}, nil)
if err := req.Write(conn); err != nil {
return nil, err
}
if Debug {
log.Logf("[socks4a] %s", req)
}
reply, err := gosocks4.ReadReply(conn)
if err != nil {
return nil, err
}
if Debug {
log.Logf("[socks4a] %s", reply)
}
if reply.Code != gosocks4.Granted {
return nil, fmt.Errorf("[socks4a] %d", reply.Code)
}
return conn, nil
}
type socks5Handler struct {
selector *serverSelector
options *HandlerOptions
}
// SOCKS5Handler creates a server Handler for SOCKS5 proxy server.
func SOCKS5Handler(opts ...HandlerOption) Handler {
h := &socks5Handler{}
h.Init(opts...)
return h
}
func (h *socks5Handler) Init(options ...HandlerOption) {
if h.options == nil {
h.options = &HandlerOptions{}
}
for _, opt := range options {
opt(h.options)
}
tlsConfig := h.options.TLSConfig
if tlsConfig == nil {
tlsConfig = DefaultTLSConfig
}
h.selector = &serverSelector{ // socks5 server selector
// Users: h.options.Users,
Authenticator: h.options.Authenticator,
TLSConfig: tlsConfig,
}
// methods that socks5 server supported
h.selector.AddMethod(
gosocks5.MethodNoAuth,
gosocks5.MethodUserPass,
MethodTLS,
MethodTLSAuth,
)
}
func (h *socks5Handler) Handle(conn net.Conn) {
defer conn.Close()
conn = gosocks5.ServerConn(conn, h.selector)
req, err := gosocks5.ReadRequest(conn)
if err != nil {
log.Logf("[socks5] %s -> %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
return
}
if Debug {
log.Logf("[socks5] %s -> %s\n%s",
conn.RemoteAddr(), conn.LocalAddr(), req)
}
switch req.Cmd {
case gosocks5.CmdConnect:
h.handleConnect(conn, req)
case gosocks5.CmdBind:
h.handleBind(conn, req)
case gosocks5.CmdUdp:
h.handleUDPRelay(conn, req)
case CmdMuxBind:
h.handleMuxBind(conn, req)
case CmdUDPTun:
h.handleUDPTunnel(conn, req)
default:
log.Logf("[socks5] %s - %s : Unrecognized request: %d",
conn.RemoteAddr(), conn.LocalAddr(), req.Cmd)
}
}
func (h *socks5Handler) handleConnect(conn net.Conn, req *gosocks5.Request) {
host := req.Addr.String()
log.Logf("[socks5] %s -> %s -> %s",
conn.RemoteAddr(), h.options.Node.String(), host)
if !Can("tcp", host, h.options.Whitelist, h.options.Blacklist) {
log.Logf("[socks5] %s - %s : Unauthorized to tcp connect to %s",
conn.RemoteAddr(), conn.LocalAddr(), host)
rep := gosocks5.NewReply(gosocks5.NotAllowed, nil)
rep.Write(conn)
if Debug {
log.Logf("[socks5] %s <- %s\n%s",
conn.RemoteAddr(), conn.LocalAddr(), rep)
}
return
}
if h.options.Bypass.Contains(host) {
log.Logf("[socks5] %s - %s : Bypass %s",
conn.RemoteAddr(), conn.LocalAddr(), host)
rep := gosocks5.NewReply(gosocks5.NotAllowed, nil)
rep.Write(conn)
if Debug {
log.Logf("[socks5] %s <- %s\n%s",
conn.RemoteAddr(), conn.LocalAddr(), rep)
}
return
}
retries := 1
if h.options.Chain != nil && h.options.Chain.Retries > 0 {
retries = h.options.Chain.Retries
}
if h.options.Retries > 0 {
retries = h.options.Retries
}
var err error
var cc net.Conn
var route *Chain
for i := 0; i < retries; i++ {
route, err = h.options.Chain.selectRouteFor(host)
if err != nil {
log.Logf("[socks5] %s -> %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
continue
}
buf := bytes.Buffer{}
fmt.Fprintf(&buf, "%s -> %s -> ",
conn.RemoteAddr(), h.options.Node.String())
for _, nd := range route.route {
fmt.Fprintf(&buf, "%d@%s -> ", nd.ID, nd.String())
}
fmt.Fprintf(&buf, "%s", host)
log.Log("[route]", buf.String())
cc, err = route.Dial(host,
TimeoutChainOption(h.options.Timeout),
HostsChainOption(h.options.Hosts),
ResolverChainOption(h.options.Resolver),
)
if err == nil {
break
}
log.Logf("[socks5] %s -> %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
}
if err != nil {
rep := gosocks5.NewReply(gosocks5.HostUnreachable, nil)
rep.Write(conn)
if Debug {
log.Logf("[socks5] %s <- %s\n%s",
conn.RemoteAddr(), conn.LocalAddr(), rep)
}
return
}
defer cc.Close()
rep := gosocks5.NewReply(gosocks5.Succeeded, nil)
if err := rep.Write(conn); err != nil {
log.Logf("[socks5] %s <- %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
return
}
if Debug {
log.Logf("[socks5] %s <- %s\n%s",
conn.RemoteAddr(), conn.LocalAddr(), rep)
}
log.Logf("[socks5] %s <-> %s", conn.RemoteAddr(), host)
transport(conn, cc)
log.Logf("[socks5] %s >-< %s", conn.RemoteAddr(), host)
}
func (h *socks5Handler) handleBind(conn net.Conn, req *gosocks5.Request) {
addr := req.Addr.String()
log.Logf("[socks5-bind] %s -> %s -> %s",
conn.RemoteAddr(), h.options.Node.String(), addr)
if h.options.Chain.IsEmpty() {
if !Can("rtcp", addr, h.options.Whitelist, h.options.Blacklist) {
log.Logf("[socks5-bind] %s - %s : Unauthorized to tcp bind to %s",
conn.RemoteAddr(), conn.LocalAddr(), addr)
return
}
h.bindOn(conn, addr)
return
}
cc, err := h.options.Chain.Conn()
if err != nil {
log.Logf("[socks5-bind] %s <- %s : %s",
conn.RemoteAddr(), conn.LocalAddr(), err)
reply := gosocks5.NewReply(gosocks5.Failure, nil)