-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsocks5.go
347 lines (278 loc) Β· 8.55 KB
/
socks5.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
// Package socks5 a fully featured implementation of the SOCKS 5 protocol in golang.
package socks5
import (
"context"
"net"
"golang.org/x/sync/errgroup"
)
const (
version5 byte = 0x05
noAuthenticationRequired byte = 0x00
usernamePasswordAuthentication byte = 0x02
noAcceptableMethods byte = 0xff
usernamePasswordVersion byte = 0x01
usernamePasswordSuccess byte = 0x00
usernamePasswordFailure byte = 0x01
addressTypeIPv4 byte = 0x01
addressTypeFQDN byte = 0x03
addressTypeIPv6 byte = 0x04
connect byte = 0x01
bind byte = 0x02
udpAssociate byte = 0x03
connectionSuccessful byte = 0x00
generalSOCKSserverFailure byte = 0x01
connectionNotAllowedByRuleSet byte = 0x02
networkUnreachable byte = 0x03
hostUnreachable byte = 0x04
connectionRefused byte = 0x05
commandNotSupported byte = 0x07
addressTypeNotSupported byte = 0x08
)
func (s *Server) handshake(ctx context.Context, conn *connection) {
version, err := conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read protocol version: "+err.Error())
return
}
if version != version5 {
return
}
numMethods, err := conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read number of authentication methods: "+err.Error())
return
}
methods := make([]byte, numMethods)
if _, err := conn.read(methods); err != nil {
s.logger.Error(ctx, "failed to read authentication methods: "+err.Error())
return
}
method := s.choiceAuthenticationMethod(methods)
switch method {
case noAuthenticationRequired:
s.response(ctx, conn, version5, noAuthenticationRequired)
s.acceptRequest(ctx, conn)
case usernamePasswordAuthentication:
s.response(ctx, conn, version5, usernamePasswordAuthentication)
s.usernamePasswordAuthenticate(ctx, conn)
default:
s.response(ctx, conn, version5, noAcceptableMethods)
}
}
func (s *Server) acceptRequest(ctx context.Context, conn *connection) {
version, err := conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read protocol version: "+err.Error())
return
}
if version != version5 {
return
}
command, err := conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read command: "+err.Error())
return
}
// Reserved byte: 0x00
if _, err := conn.readByte(); err != nil {
s.logger.Error(ctx, "failed to read reserved byte: "+err.Error())
return
}
var addr address
addr.Type, err = conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read address type: "+err.Error())
return
}
switch addr.Type {
case addressTypeIPv4:
addr.IP = make(net.IP, net.IPv4len)
if _, err := conn.read(addr.IP); err != nil {
s.logger.Error(ctx, "failed to read IPv4 address: "+err.Error())
return
}
case addressTypeFQDN:
addr.DomainLen, err = conn.readByte()
if err != nil {
s.logger.Error(ctx, "failed to read domain length: "+err.Error())
return
}
addr.Domain = make([]byte, addr.DomainLen)
if _, err := conn.read(addr.Domain); err != nil {
s.logger.Error(ctx, "failed to read domain: "+err.Error())
return
}
case addressTypeIPv6:
addr.IP = make(net.IP, net.IPv6len)
if _, err := conn.read(addr.IP); err != nil {
s.logger.Error(ctx, "failed to read IPv6 address: "+err.Error())
return
}
default:
s.replyRequest(ctx, conn, addressTypeNotSupported, &addr)
return
}
addr.Port = make([]byte, 2)
if _, err := conn.read(addr.Port); err != nil {
s.logger.Error(ctx, "failed to read port: "+err.Error())
return
}
if !s.rules.IsAllowDestination(ctx, addr.getDomainOrIP()) {
s.replyRequest(ctx, conn, connectionNotAllowedByRuleSet, &addr)
return
}
switch command {
case connect:
if !s.rules.IsAllowCommand(ctx, connect) {
s.replyRequest(ctx, conn, connectionNotAllowedByRuleSet, &addr)
return
}
s.connect(ctx, conn, &addr)
case udpAssociate:
if !s.rules.IsAllowCommand(ctx, udpAssociate) {
s.replyRequest(ctx, conn, connectionNotAllowedByRuleSet, &addr)
return
}
s.udpAssociate(ctx, conn, &addr)
default:
s.replyRequest(ctx, conn, commandNotSupported, &addr)
}
}
func (s *Server) connect(ctx context.Context, conn *connection, addr *address) {
target, err := s.driver.Dial("tcp", addr.String())
if err != nil {
s.replyRequestWithError(ctx, conn, err, addr)
s.logger.Error(ctx, "dial "+addr.String()+": "+err.Error())
return
}
defer target.Close()
s.replyRequest(ctx, conn, connectionSuccessful, addr)
s.logger.Info(ctx, "dial "+addr.String())
var g errgroup.Group
g.Go(func() error {
n, err := relay(target, conn)
s.metrics.UploadBytes(ctx, n)
return err
})
g.Go(func() error {
n, err := relay(conn, target)
s.metrics.DownloadBytes(ctx, n)
return err
})
if err = g.Wait(); err != nil {
s.logger.Error(ctx, "error sync wait group: "+err.Error())
}
}
func (s *Server) udpAssociate(ctx context.Context, conn *connection, addr *address) {
packetConn, err := s.driver.ListenPacket("udp", net.JoinHostPort(s.config.host, addr.Port.String()))
if err != nil {
s.replyRequestWithError(ctx, conn, err, addr)
s.logger.Error(ctx, "error listen udp: "+err.Error())
return
}
conn.onClose(func() {
if err := packetConn.Close(); err != nil {
s.logger.Error(ctx, "error close udp listener: "+err.Error())
}
})
go conn.keepAlive()
var port port
port.fromAddress(packetConn.LocalAddr())
s.replyRequest(ctx, conn, connectionSuccessful, &address{
Type: addressTypeIPv4,
IP: s.config.publicIP,
Port: port,
})
buff := s.bytePool.get()
defer s.bytePool.put(buff)
natTable := newNatTable()
stop := natTable.cleanup(s.config.natCleanupPeriod, s.config.ttlPacket)
defer stop()
s.logger.Info(ctx, "start of udp datagram forwarding")
for conn.isActive() {
n, clientAddress, err := packetConn.ReadFrom(buff)
if err != nil {
if !isClosedListenerError(err) {
s.logger.Error(ctx, "failed to read from packet connection: "+err.Error())
}
continue
}
if sourceAddress, packet, ok := natTable.get(clientAddress); ok {
packet.encode(buff[:n])
s.metrics.DownloadBytes(ctx, packet.payload.len())
packetConn.SetWriteDeadline(newDeadline(s.config.packetWriteTimeout))
if _, err := packetConn.WriteTo(packet.payload, sourceAddress); err != nil {
if !isClosedListenerError(err) {
s.logger.Error(ctx, "failed writing to packet connection: "+err.Error())
}
}
natTable.delete(clientAddress)
continue
}
if conn.equalAddresses(clientAddress) {
var packet packet
if err := packet.decode(buff[:n]); err != nil {
s.logger.Error(ctx, "failed to unpack packet: "+err.Error())
continue
}
if !s.rules.IsAllowDestination(ctx, packet.address.getDomainOrIP()) {
continue
}
destAddress, err := s.driver.Resolve("udp", packet.address.String())
if err != nil {
s.logger.Error(ctx, "failed to resolve target UDP address: "+err.Error())
continue
}
s.metrics.UploadBytes(ctx, packet.payload.len())
packetConn.SetWriteDeadline(newDeadline(s.config.packetWriteTimeout))
if _, err := packetConn.WriteTo(packet.payload, destAddress); err != nil {
if !isClosedListenerError(err) {
s.logger.Error(ctx, "failed writing to packet connection: "+err.Error())
}
continue
}
packet.payload.reset()
natTable.set(clientAddress, destAddress, &packet)
}
}
s.logger.Info(ctx, "udp datagram forwarding complete")
}
func (s *Server) replyRequestWithError(ctx context.Context, conn *connection, err error, addr *address) {
switch {
case isNetworkUnreachableError(err):
s.replyRequest(ctx, conn, networkUnreachable, addr)
case isNoSuchHostError(err):
s.replyRequest(ctx, conn, hostUnreachable, addr)
case isConnectionRefusedError(err):
s.replyRequest(ctx, conn, connectionRefused, addr)
default:
s.replyRequest(ctx, conn, generalSOCKSserverFailure, addr)
}
}
func (s *Server) replyRequest(ctx context.Context, conn *connection, status byte, addr *address) {
fields := []byte{
0x00, // Reserved byte
addr.Type,
}
switch addr.Type {
case addressTypeIPv4:
fields = append(fields, addr.IP.To4()...)
case addressTypeFQDN:
fields = append(fields, addr.DomainLen)
fields = append(fields, addr.Domain...)
case addressTypeIPv6:
fields = append(fields, addr.IP.To16()...)
}
fields = append(fields, addr.Port...)
s.response(ctx, conn, version5, status, fields...)
}
func (s *Server) response(ctx context.Context, conn *connection, version, status byte, fields ...byte) {
res := []byte{
version,
status,
}
res = append(res, fields...)
if _, err := conn.write(res); err != nil {
s.logger.Error(ctx, "failed to send a response to the client: "+err.Error())
}
}