This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
441 lines (401 loc) · 10.7 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"io"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
"gopkg.in/yaml.v2"
)
var ForwardPort = 443
var cfg configModel
var (
cfgfile = flag.String("c", "config.yaml", "config file")
FileLogPath = flag.String("l", "", "log to file")
EnableDebug = flag.Bool("d", false, "Enable debug")
ValEnableDebug = false
)
func main() {
flag.Parse()
ValEnableDebug = *EnableDebug
data, err := os.ReadFile(*cfgfile)
if err != nil {
serviceLogger(fmt.Sprintf("Yaml file read failed: %v", err), 31)
os.Exit(1)
}
if err := yaml.Unmarshal(data, &cfg); err != nil {
serviceLogger(fmt.Sprintf("Yaml file unmarshal failed: %v", err), 31)
os.Exit(1)
}
if len(cfg.ForwardRules) <= 0 && !cfg.AllowAllHosts {
serviceLogger("No rules found in yaml!", 31)
os.Exit(1)
}
for _, rule := range cfg.ForwardRules {
serviceLogger(fmt.Sprintf("Loaded rule: %v", rule), 32)
}
serviceLogger(fmt.Sprintf("Debug: %v", ValEnableDebug), 32)
serviceLogger(fmt.Sprintf("Socks: %v", cfg.EnableSocks), 32)
serviceLogger(fmt.Sprintf("All Hosts: %v", cfg.AllowAllHosts), 32)
startSniProxy()
}
func startSniProxy() {
_, cancel := context.WithCancel(context.Background())
defer cancel()
listener, err := net.Listen("tcp", cfg.ListenAddr)
if err != nil {
serviceLogger(fmt.Sprintf("Listened failed: %v", err), 31)
os.Exit(1)
}
serviceLogger(fmt.Sprintf("Start listening: %v", listener.Addr()), 0)
go func(listener net.Listener) {
defer listener.Close()
for {
connection, err := listener.Accept()
if err != nil {
serviceLogger(fmt.Sprintf("SNI Proxy Accept failed: %v", err), 31)
}
raddr := connection.RemoteAddr().(*net.TCPAddr)
serviceLogger(fmt.Sprintf("Connection From %s", fmt.Sprintf("%s", raddr)), 32)
go serve(connection, fmt.Sprintf("%s", raddr))
}
}(listener)
ch := make(chan os.Signal, 2)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
select {
case s := <-ch:
cancel()
fmt.Printf("\nreceived signal %s, exit.\n", s)
}
}
func serve(c net.Conn, raddr string) {
defer c.Close()
buf := make([]byte, 1024)
n, err := c.Read(buf)
if err != nil && fmt.Sprintf("%v", err) != "EOF" {
serviceLogger(fmt.Sprintf("SNI Proxy Serve failed: %v", err), 31)
return
}
servername := getSNIServerName(buf[:n])
if servername == "" {
serviceDebugger("No SNI server name found, ignore it", 31)
return
}
if cfg.AllowAllHosts {
serviceDebugger(fmt.Sprintf("Found %v, forwarding to %s:%d", servername, servername, ForwardPort), 32)
forward(c, buf[:n], fmt.Sprintf("%s:%d", servername, ForwardPort), raddr)
return
}
for _, rule := range cfg.ForwardRules {
if strings.Contains(servername, rule) {
serviceDebugger(fmt.Sprintf("Found %v, forwarding to %s:%d", servername, servername, ForwardPort), 32)
forward(c, buf[:n], fmt.Sprintf("%s:%d", servername, ForwardPort), raddr)
}
}
}
func getSNIServerName(buf []byte) string {
n := len(buf)
if n < 5 {
serviceDebugger("Not tls handshake", 31)
return ""
}
// tls record type
if recordType(buf[0]) != recordTypeHandshake {
serviceDebugger("Not tls", 31)
return ""
}
// tls major version
if buf[1] != 3 {
serviceDebugger("TLS version < 3 not supported", 31)
return ""
}
// payload length
//l := int(buf[3])<<16 + int(buf[4])
//log.Printf("length: %d, got: %d", l, n)
// handshake message type
if buf[5] != typeClientHello {
serviceDebugger("Not client hello", 31)
return ""
}
// parse client hello message
msg := &clientHelloMsg{}
// client hello message not include tls header, 5 bytes
ret := msg.unmarshal(buf[5:n])
if !ret {
serviceDebugger("Parse hello message return false", 31)
return ""
}
return msg.serverName
}
func forward(conn net.Conn, data []byte, dst string, raddr string) {
backend, err := GetDialer(cfg.EnableSocks).Dial("tcp", dst)
if err != nil {
serviceLogger(fmt.Sprintf("Couldn't connect to backend, %v", err), 31)
return
}
defer backend.Close()
if _, err = backend.Write(data); err != nil {
serviceLogger(fmt.Sprintf("Couldn't write to backend, %v", err), 31)
return
}
conChk := make(chan int)
go ioReflector(backend, conn, false, conChk, raddr, dst)
go ioReflector(conn, backend, true, conChk, raddr, dst)
<-conChk
}
func ioReflector(dst io.WriteCloser, src io.Reader, isToClient bool, conChk chan int, raddr string, dsts string) {
// Reflect IO stream to another.
defer onDisconnect(dst, conChk)
written, _ := io.Copy(dst, src)
if isToClient {
serviceDebugger(fmt.Sprintf("[%v] -> [%v], Written %d bytes", dsts, raddr, written), 33)
} else {
serviceDebugger(fmt.Sprintf("[%v] -> [%v], Written %d bytes", raddr, dsts, written), 33)
}
dst.Close()
conChk <- 1
}
func onDisconnect(dst io.WriteCloser, conChk chan int) {
// On Close-> Force Disconnect another pair of connection.
dst.Close()
conChk <- 1
}
func (m *clientHelloMsg) unmarshal(data []byte) bool {
if len(data) < 42 {
return false
}
m.raw = data
m.vers = uint16(data[4])<<8 | uint16(data[5])
m.random = data[6:38]
sessionIDLen := int(data[38])
if sessionIDLen > 32 || len(data) < 39+sessionIDLen {
return false
}
m.sessionID = data[39 : 39+sessionIDLen]
data = data[39+sessionIDLen:]
if len(data) < 2 {
return false
}
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
// they are uint16s, the number must be even.
cipherSuiteLen := int(data[0])<<8 | int(data[1])
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
return false
}
numCipherSuites := cipherSuiteLen / 2
m.cipherSuites = make([]uint16, numCipherSuites)
for i := 0; i < numCipherSuites; i++ {
m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i])
if m.cipherSuites[i] == scsvRenegotiation {
m.secureRenegotiationSupported = true
}
}
data = data[2+cipherSuiteLen:]
if len(data) < 1 {
return false
}
compressionMethodsLen := int(data[0])
if len(data) < 1+compressionMethodsLen {
return false
}
m.compressionMethods = data[1 : 1+compressionMethodsLen]
data = data[1+compressionMethodsLen:]
m.nextProtoNeg = false
m.serverName = ""
m.ocspStapling = false
m.ticketSupported = false
m.sessionTicket = nil
m.signatureAndHashes = nil
m.alpnProtocols = nil
m.scts = false
if len(data) == 0 {
// ClientHello is optionally followed by extension data
return true
}
if len(data) < 2 {
return false
}
extensionsLength := int(data[0])<<8 | int(data[1])
data = data[2:]
if extensionsLength != len(data) {
return false
}
for len(data) != 0 {
if len(data) < 4 {
return false
}
extension := uint16(data[0])<<8 | uint16(data[1])
length := int(data[2])<<8 | int(data[3])
data = data[4:]
if len(data) < length {
return false
}
switch extension {
case extensionServerName:
d := data[:length]
if len(d) < 2 {
return false
}
namesLen := int(d[0])<<8 | int(d[1])
d = d[2:]
if len(d) != namesLen {
return false
}
for len(d) > 0 {
if len(d) < 3 {
return false
}
nameType := d[0]
nameLen := int(d[1])<<8 | int(d[2])
d = d[3:]
if len(d) < nameLen {
return false
}
if nameType == 0 {
m.serverName = string(d[:nameLen])
// An SNI value may not include a
// trailing dot. See
// https://tools.ietf.org/html/rfc6066#section-3.
if strings.HasSuffix(m.serverName, ".") {
return false
}
break
}
d = d[nameLen:]
}
case extensionNextProtoNeg:
if length > 0 {
return false
}
m.nextProtoNeg = true
case extensionStatusRequest:
m.ocspStapling = length > 0 && data[0] == statusTypeOCSP
case extensionSupportedCurves:
// http://tools.ietf.org/html/rfc4492#section-5.5.1
if length < 2 {
return false
}
l := int(data[0])<<8 | int(data[1])
if l%2 == 1 || length != l+2 {
return false
}
numCurves := l / 2
m.supportedCurves = make([]CurveID, numCurves)
d := data[2:]
for i := 0; i < numCurves; i++ {
m.supportedCurves[i] = CurveID(d[0])<<8 | CurveID(d[1])
d = d[2:]
}
case extensionSupportedPoints:
// http://tools.ietf.org/html/rfc4492#section-5.5.2
if length < 1 {
return false
}
l := int(data[0])
if length != l+1 {
return false
}
m.supportedPoints = make([]uint8, l)
copy(m.supportedPoints, data[1:])
case extensionSessionTicket:
// http://tools.ietf.org/html/rfc5077#section-3.2
m.ticketSupported = true
m.sessionTicket = data[:length]
case extensionSignatureAlgorithms:
// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
if length < 2 || length&1 != 0 {
return false
}
l := int(data[0])<<8 | int(data[1])
if l != length-2 {
return false
}
n := l / 2
d := data[2:]
m.signatureAndHashes = make([]signatureAndHash, n)
for i := range m.signatureAndHashes {
m.signatureAndHashes[i].hash = d[0]
m.signatureAndHashes[i].signature = d[1]
d = d[2:]
}
case extensionRenegotiationInfo:
if length == 0 {
return false
}
d := data[:length]
l := int(d[0])
d = d[1:]
if l != len(d) {
return false
}
m.secureRenegotiation = d
m.secureRenegotiationSupported = true
case extensionALPN:
if length < 2 {
return false
}
l := int(data[0])<<8 | int(data[1])
if l != length-2 {
return false
}
d := data[2:length]
for len(d) != 0 {
stringLen := int(d[0])
d = d[1:]
if stringLen == 0 || stringLen > len(d) {
return false
}
m.alpnProtocols = append(m.alpnProtocols, string(d[:stringLen]))
d = d[stringLen:]
}
case extensionSCT:
m.scts = true
if length != 0 {
return false
}
}
data = data[length:]
}
return true
}
func serviceLogger(log string, color int) {
log = strings.Replace(log, "\n", "", -1)
log = strings.Join([]string{time.Now().Format("2006/01/02 15:04:05"), " ", log}, "")
if color == 0 {
fmt.Printf("%s\n", log)
} else {
fmt.Printf("%c[1;0;%dm%s%c[0m\n", 0x1B, color, log, 0x1B)
}
if *FileLogPath != "" {
fd, _ := os.OpenFile(*FileLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fdTime := time.Now().Format("2006/01/02-15:04:05")
fdContent := strings.Join([]string{fdTime, " ", log, "\n"}, "")
buf := []byte(fdContent)
fd.Write(buf)
fd.Close()
}
}
func serviceDebugger(log string, color int) {
if ValEnableDebug {
log = strings.Replace(log, "\n", "", -1)
log = strings.Join([]string{time.Now().Format("2006/01/02 15:04:05"), " [Debug] ", log}, "")
if color == 0 {
fmt.Printf("%s\n", log)
} else {
fmt.Printf("%c[1;0;%dm%s%c[0m\n", 0x1B, color, log, 0x1B)
}
if *FileLogPath != "" {
fd, _ := os.OpenFile(*FileLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fdTime := time.Now().Format("2006/01/02-15:04:05")
fdContent := strings.Join([]string{fdTime, " ", log, "\n"}, "")
buf := []byte(fdContent)
fd.Write(buf)
fd.Close()
}
}
}