Repository navigation
Expand file tree
/
Copy pathv2ray-core.patch
More file actions
646 lines (637 loc) · 19.1 KB
/
Copy pathv2ray-core.patch
File metadata and controls
646 lines (637 loc) · 19.1 KB
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
app/tun/packetparse/udp.go | 3 +
app/tun/packetparse/udp_stub.go | 25 ++
common/protofilter/filter.go | 9 +-
domain2ip.go | 40 ++++
envoy/v2ray.go | 430 +++++++++++++++++++++++++++++++++
transport/internet/http/dialer.go | 23 +-
transport/internet/websocket/dialer.go | 21 +-
7 files changed, 544 insertions(+), 7 deletions(-)
diff --git a/app/tun/packetparse/udp.go b/app/tun/packetparse/udp.go
index 8e5cdd19..4f3f258f 100644
--- a/app/tun/packetparse/udp.go
+++ b/app/tun/packetparse/udp.go
@@ -1,3 +1,6 @@
+//go:build with_packetparse
+// +build with_packetparse
+
package packetparse
import (
diff --git a/app/tun/packetparse/udp_stub.go b/app/tun/packetparse/udp_stub.go
new file mode 100644
index 00000000..d8677a37
--- /dev/null
+++ b/app/tun/packetparse/udp_stub.go
@@ -0,0 +1,25 @@
+//go:build !with_packetparse
+// +build !with_packetparse
+
+package packetparse
+
+import (
+ "github.com/v2fly/v2ray-core/v5/common/net"
+)
+
+var (
+ errNotIPPacket = newError("not an IP packet")
+ errNotUDPPacket = newError("not a UDP packet")
+)
+
+var nullDestination = net.UnixDestination(net.DomainAddress("null"))
+
+// TryParseAsUDPPacket provides a stub implementation when packet parsing is disabled
+func TryParseAsUDPPacket(packet []byte) (src, dst net.Destination, data []byte, err error) {
+ return nullDestination, nullDestination, nil, newError("packet parsing disabled - build with 'with_packetparse' tag to enable")
+}
+
+// TryConstructUDPPacket provides a stub implementation when packet parsing is disabled
+func TryConstructUDPPacket(src, dst net.Destination, data []byte) ([]byte, error) {
+ return nil, newError("packet parsing disabled - build with 'with_packetparse' tag to enable")
+}
diff --git a/common/protofilter/filter.go b/common/protofilter/filter.go
index 521d0d1c..718ed0ea 100644
--- a/common/protofilter/filter.go
+++ b/common/protofilter/filter.go
@@ -39,9 +39,12 @@ func filterMessage(ctx context.Context, message protoreflect.Message) error {
v2extension, ferr := protoext.GetFieldOptions(descriptor)
if ferr == nil {
if v2extension.Forbidden {
- if value.Bool() {
- err = newError("a forbidden value is set ", descriptor.FullName())
- return false
+ // Skip forbidden check for allow_insecure field to restore functionality
+ if descriptor.FullName() != "v2ray.core.transport.internet.tls.Config.allow_insecure" {
+ if value.Bool() {
+ err = newError("a forbidden value is set ", descriptor.FullName())
+ return false
+ }
}
}
diff --git a/domain2ip.go b/domain2ip.go
new file mode 100644
index 00000000..da1ad5c6
--- /dev/null
+++ b/domain2ip.go
@@ -0,0 +1,40 @@
+package core
+
+import (
+ "sync"
+)
+
+// DomainToIPs is a map of domain names to IP addresses
+// Note: there may be multiple IP addresses for a given domain
+var DomainToIPs = map[string][]string{}
+var domainMutex sync.RWMutex
+
+// GetDomainIPs returns IP addresses for a given domain
+func GetDomainIPs(domain string) ([]string, bool) {
+ domainMutex.RLock()
+ defer domainMutex.RUnlock()
+ ips, ok := DomainToIPs[domain]
+ return ips, ok
+}
+
+// SetDomainIPs sets IP addresses for a given domain
+func SetDomainIPs(domain string, ips []string) {
+ domainMutex.Lock()
+ defer domainMutex.Unlock()
+ DomainToIPs[domain] = ips
+}
+
+// DropDomainIPs drops specific IP address for a given domain from the cache
+func DropDomainIPs(domain string, ip string) {
+ domainMutex.Lock()
+ defer domainMutex.Unlock()
+ for i, existingIP := range DomainToIPs[domain] {
+ if existingIP == ip {
+ DomainToIPs[domain] = append(DomainToIPs[domain][:i], DomainToIPs[domain][i+1:]...)
+ if len(DomainToIPs[domain]) == 0 {
+ delete(DomainToIPs, domain)
+ }
+ break
+ }
+ }
+}
diff --git a/envoy/v2ray.go b/envoy/v2ray.go
new file mode 100644
index 0000000..34a5a18
--- /dev/null
+++ b/envoy/v2ray.go
@@ -0,0 +1,430 @@
+package v2ray
+
+// copied and modified from main/commands/run.go
+
+// feeding core.LoadConfig with a string reader containing the config
+// JSON seems the simplest way to run v2ray as a library
+//
+// Golang's JSON support seems a little cumbersome for a couple
+// string substitutions in a complex JSON snippet, so we just
+// use fmt.Sprintf to assemble the config
+//
+// The JSON file we build should look similar to the client example config
+// (that will be) documented here:
+// https://gitlab.com/stevenmcdonald/envoy-proxy-examples/v2ray/
+
+// We provide functions for starting and stopping several client services
+// independently. Unfortunately you can't start them all and tell v2ray to
+// use the one that works... but that's what Envoy is good at.
+
+import (
+ "fmt"
+ "strings"
+ "sync"
+
+ core "github.com/v2fly/v2ray-core/v5"
+ _ "github.com/v2fly/v2ray-core/v5/main/distro/all"
+)
+
+const jsonV5 = "jsonv5"
+
+var wsServers sync.Map
+var httpServers sync.Map
+var wechatServers sync.Map
+var srtpServers sync.Map
+
+// getInbound
+//
+// @param port - port to listen for SOCKS5 connections
+func getInbound(clientPort int) string {
+ return fmt.Sprintf(`
+ {
+ "port": %d,
+ "protocol": "socks",
+ "sniffing": {
+ "enabled": true,
+ "destOverride": ["http", "tls"]
+ },
+ "settings": {}
+ }`, clientPort)
+}
+
+func getWsConfig(clientPort int, serverAddress, serverWsPort, wsPath, id string, allowInsecure bool, serverName string, hostName string, utlsFingerprint string) string {
+ return fmt.Sprintf(`
+ {
+ "log": {
+ "error": {
+ "type": "Console",
+ "level": "Error"
+ }
+ },
+ "inbounds": [%s
+ ],
+ "outbounds": [
+ {
+ "protocol": "vmess",
+ "settings": {
+ "address": "%s",
+ "port": %s,
+ "uuid": "%s"
+ },
+ "streamSettings": {
+ "transport": "ws",
+ "transportSettings": {
+ "path": "%s",
+ "header": [
+ {
+ "key": "Host",
+ "value": "%s"
+ }
+ ]
+ },
+ "security": "utls",
+ "securitySettings": {
+ "tlsConfig": {
+ "serverName": "%s",
+ "allowInsecure": %t,
+ "nextProtocol": ["http/1.1"]
+ },
+ "imitate": "%s",
+ "forceAlpn": "TRANSPORT_PREFERENCE_TAKE_PRIORITY"
+ }
+ }
+ }
+ ]
+ }`, getInbound(clientPort), serverAddress, serverWsPort, id, wsPath, hostName, serverName, allowInsecure, utlsFingerprint)
+}
+
+func getHttpConfig(clientPort int, serverAddress, serverHttpPort, httpPath, id string, allowInsecure bool, serverName string, hostName string, utlsFingerprint string) string {
+ return fmt.Sprintf(`
+ {
+ "log": {
+ "error": {
+ "type": "Console",
+ "level": "Error"
+ }
+ },
+ "inbounds": [%s
+ ],
+ "outbounds": [
+ {
+ "protocol": "vmess",
+ "settings": {
+ "address": "%s",
+ "port": %s,
+ "uuid": "%s"
+ },
+ "streamSettings": {
+ "transport": "h2",
+ "transportSettings": {
+ "path": "%s",
+ "host": ["%s"],
+ "method": "POST"
+ },
+ "security": "utls",
+ "securitySettings": {
+ "tlsConfig": {
+ "serverName": "%s",
+ "allowInsecure": %t,
+ "nextProtocol": ["h2", "http/1.1"]
+ },
+ "imitate": "%s",
+ "forceAlpn": "TRANSPORT_PREFERENCE_TAKE_PRIORITY"
+ }
+ }
+ }
+ ]
+ }`, getInbound(clientPort), serverAddress, serverHttpPort, id, httpPath, hostName, serverName, allowInsecure, utlsFingerprint)
+}
+
+// getQUICConfig
+//
+// @param clientPort - port to listen on for SOCKS5 connections
+//
+// @param serverAddress - server address to connect to
+//
+// @param serverPort - server port to connect to
+//
+// @oaram type - type of QUIC obfuscation, should be "srtp" or "wechat-video"
+func getQuicConfig(clientPort int, serverAddress, serverPort, quicType, id string) string {
+ // Determine the @type for the header based on quicType
+ var headerType string
+ switch quicType {
+ case "srtp":
+ headerType = "type.googleapis.com/v2ray.core.transport.internet.headers.srtp.Config"
+ case "wechat-video":
+ headerType = "type.googleapis.com/v2ray.core.transport.internet.headers.wechat.VideoConfig"
+ default:
+ headerType = "type.googleapis.com/v2ray.core.transport.internet.headers.noop.Config"
+ }
+
+ return fmt.Sprintf(`
+ {
+ "log": {
+ "error": {
+ "type": "Console",
+ "level": "Error"
+ }
+ },
+ "inbounds": [%s
+ ],
+ "outbounds": [
+ {
+ "protocol": "vmess",
+ "settings": {
+ "address": "%s",
+ "port": %s,
+ "uuid": "%s"
+ },
+ "streamSettings": {
+ "transport": "quic",
+ "transportSettings": {
+ "security": {
+ "type": "AES128_GCM"
+ },
+ "header": {
+ "@type": "%s"
+ },
+ "key": "0"
+ }
+ }
+ }
+ ]
+ }`, getInbound(clientPort), serverAddress, serverPort, id, headerType)
+}
+
+func startServer(jsonConfig string) (*core.Instance, error) {
+ reader := strings.NewReader(jsonConfig)
+
+ config, err := core.LoadConfig(jsonV5, reader)
+ if err != nil {
+ fmt.Printf("error reading config: %s\n", err)
+ return nil, err
+ }
+
+ server, err := core.New(config)
+ if err != nil {
+ fmt.Printf("error creating server: %s\n", err)
+ return nil, err
+ }
+
+ if err := server.Start(); err != nil {
+ fmt.Printf("failed to start %s\n", err)
+
+ _ = server.Close()
+
+ return nil, err
+ }
+
+ return server, nil
+}
+
+// WsConfigOptional holds optional configuration for WebSocket connections
+type WsConfigOptional struct {
+ AllowInsecure bool
+ ServerName string
+ Hostname string
+ UtlsFingerprint string
+}
+
+// HttpConfigOptional - optional configuration for HTTP/2 transport
+type HttpConfigOptional struct {
+ AllowInsecure bool
+ ServerName string
+ Hostname string
+ UtlsFingerprint string
+}
+
+// StartWs - start v2ray, websocket transport
+//
+// @param clientPort - client SOCKS port routed to the WS server
+//
+// @param serverAddress - IP or hostname of the server
+//
+// @param serverPort - port of the websocket server (probably 443)
+//
+// @param wsPath - path to the websocket on the server
+//
+// @param id - UUID used to authenticate with the server
+//
+// @param config - optional configuration (allowInsecure defaults to false,
+// serverName defaults to serverAddress, hostname defaults to serverAddress,
+// utlsFingerprint defaults to chrome_auto)
+//
+// @returns error, if transport could not be started, or `nil` on success.
+func StartWs(clientPort int, serverAddress, serverPort, wsPath, id string, config ...WsConfigOptional) error {
+ // Set defaults for optional config
+ allowInsecure := false
+ serverName := serverAddress
+ hostName := serverAddress
+ utlsFingerprint := "chrome_auto"
+
+ // Override with provided config if any
+ if len(config) > 0 {
+ cfg := config[0]
+ allowInsecure = cfg.AllowInsecure
+ if cfg.ServerName != "" {
+ serverName = cfg.ServerName
+ }
+ if cfg.Hostname != "" {
+ hostName = cfg.Hostname
+ }
+ if cfg.UtlsFingerprint != "" {
+ utlsFingerprint = cfg.UtlsFingerprint
+ }
+ }
+
+ server, err := startServer(getWsConfig(clientPort, serverAddress, serverPort, wsPath, id, allowInsecure, serverName, hostName, utlsFingerprint))
+ if err != nil {
+ return err
+ }
+
+ wsServers.Store(clientPort, server)
+ return nil
+}
+
+func StopWsByPort(clientPort int) {
+ if val, ok := wsServers.LoadAndDelete(clientPort); ok {
+ _ = val.(*core.Instance).Close()
+ }
+}
+
+func StopWs() {
+ wsServers.Range(func(key, value any) bool {
+ wsServers.Delete(key)
+ _ = value.(*core.Instance).Close()
+ return true
+ })
+}
+
+// StartHttp - start v2ray, HTTP/2 transport
+//
+// @param clientPort - client SOCKS port routed to the HTTP/2 server
+//
+// @param serverAddress - IP or hostname of the server
+//
+// @param serverPort - port of the HTTP/2 server (probably 443)
+//
+// @param httpPath - path to the HTTP/2 endpoint on the server
+//
+// @param id - UUID used to authenticate with the server
+//
+// @param config - optional configuration (allowInsecure defaults to false,
+// serverName defaults to serverAddress, hostname defaults to serverAddress,
+// utlsFingerprint defaults to chrome_auto)
+//
+// @returns error, if transport could not be started, or `nil` on success.
+func StartHttp(clientPort int, serverAddress, serverPort, httpPath, id string, config ...HttpConfigOptional) error {
+ // Set defaults for optional config
+ allowInsecure := false
+ serverName := serverAddress
+ hostName := serverAddress
+ utlsFingerprint := "chrome_auto"
+
+ // Override with provided config if any
+ if len(config) > 0 {
+ cfg := config[0]
+ allowInsecure = cfg.AllowInsecure
+ if cfg.ServerName != "" {
+ serverName = cfg.ServerName
+ }
+ if cfg.Hostname != "" {
+ hostName = cfg.Hostname
+ }
+ if cfg.UtlsFingerprint != "" {
+ utlsFingerprint = cfg.UtlsFingerprint
+ }
+ }
+
+ server, err := startServer(getHttpConfig(clientPort, serverAddress, serverPort, httpPath, id, allowInsecure, serverName, hostName, utlsFingerprint))
+ if err != nil {
+ return err
+ }
+
+ httpServers.Store(clientPort, server)
+ return nil
+}
+
+func StopHttpByPort(clientPort int) {
+ if val, ok := httpServers.LoadAndDelete(clientPort); ok {
+ _ = val.(*core.Instance).Close()
+ }
+}
+
+func StopHttp() {
+ httpServers.Range(func(key, value any) bool {
+ httpServers.Delete(key)
+ _ = value.(*core.Instance).Close()
+ return true
+ })
+}
+
+// StartSrtp - start v2ray, QUIC/SRTP transport
+//
+// @param clientPort - client SOCKS port routed to the WS server
+//
+// @param serverAddress - IP or hostname of the server
+//
+// @param serverPort - port of the websocket server (probably 443)
+//
+// @param id - UUID used to authenticate with the server
+//
+// @returns error, if transport could not be started, or `nil` on success.
+func StartSrtp(clientPort int, serverAddress, serverPort, id string) error {
+ server, err := startServer(getQuicConfig(clientPort, serverAddress, serverPort, "srtp", id))
+ if err != nil {
+ return err
+ }
+
+ srtpServers.Store(clientPort, server)
+ return nil
+}
+
+func StopSrtpByPort(clientPort int) {
+ if val, ok := srtpServers.LoadAndDelete(clientPort); ok {
+ _ = val.(*core.Instance).Close()
+ }
+}
+
+func StopSrtp() {
+ srtpServers.Range(func(key, value any) bool {
+ srtpServers.Delete(key)
+ _ = value.(*core.Instance).Close()
+ return true
+ })
+}
+
+// StartWechat - start v2ray, QUIC/Wechat-video transport
+//
+// @param clientPort - client SOCKS port routed to the WS server
+//
+// @param serverAddress - IP or hostname of the server
+//
+// @param serverPort - port of the websocket server (probably 443)
+//
+// @param id - UUID used to authenticate with the server
+//
+// @returns error, if transport could not be started, or `nil` on success.
+func StartWechat(clientPort int, serverAddress, serverPort, id string) error {
+ server, err := startServer(getQuicConfig(clientPort, serverAddress, serverPort, "wechat-video", id))
+ if err != nil {
+ return err
+ }
+
+ wechatServers.Store(clientPort, server)
+ return nil
+}
+
+func StopWechatByPort(clientPort int) {
+ if val, ok := wechatServers.LoadAndDelete(clientPort); ok {
+ _ = val.(*core.Instance).Close()
+ }
+}
+
+func StopWechat() {
+ wechatServers.Range(func(key, value any) bool {
+ wechatServers.Delete(key)
+ _ = value.(*core.Instance).Close()
+ return true
+ })
+}
diff --git a/transport/internet/http/dialer.go b/transport/internet/http/dialer.go
index 8a9da0e4..c957e408 100644
--- a/transport/internet/http/dialer.go
+++ b/transport/internet/http/dialer.go
@@ -59,6 +59,23 @@ func getHTTPClient(ctx context.Context, dest net.Destination, securityEngine *se
}
address := net.ParseAddress(rawHost)
+ // // Store original domain before potentially replacing with IP
+ // originalDomain := rawHost
+ // if ips, ok := core.GetDomainIPs(originalDomain); ok {
+ // address = net.ParseAddress(ips[0])
+ // }
+ // Only try to resolve using GetDomainIPs if the address is a domain, not an IP
+ var originalDomain string
+ if address.Family().IsDomain() {
+ originalDomain = rawHost
+ if ips, ok := core.GetDomainIPs(originalDomain); ok {
+ address = net.ParseAddress(ips[0])
+ }
+ } else {
+ originalDomain = address.String()
+ }
+ // fmt.Printf("http2.Transport DialTLSContext to resolved address: %s\n", address)
+
detachedContext := core.ToBackgroundDetachedContext(ctx)
pconn, err := internet.DialSystem(detachedContext, net.TCPDestination(address, port), streamSettings.SocketSettings)
if err != nil {
@@ -66,7 +83,11 @@ func getHTTPClient(ctx context.Context, dest net.Destination, securityEngine *se
}
cn, err := (*securityEngine).Client(pconn,
- security.OptionWithDestination{Dest: dest})
+ security.OptionWithDestination{Dest: net.Destination{
+ Network: dest.Network,
+ Address: net.ParseAddress(originalDomain),
+ Port: dest.Port,
+ }})
if err != nil {
return nil, err
}
diff --git a/transport/internet/websocket/dialer.go b/transport/internet/websocket/dialer.go
index 3fb229f..9deea95 100644
--- a/transport/internet/websocket/dialer.go
+++ b/transport/internet/websocket/dialer.go
@@ -38,13 +38,24 @@ func init() {
func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (net.Conn, error) {
wsSettings := streamSettings.ProtocolSettings.(*Config)
+ // Only try to resolve using GetDomainIPs if the address is a domain, not an IP
+ var originalDomain string
+ if dest.Address.Family().IsDomain() {
+ originalDomain = dest.Address.Domain()
+ if ips, ok := core.GetDomainIPs(originalDomain); ok {
+ dest.Address = net.ParseAddress(ips[0])
+ }
+ } else {
+ originalDomain = dest.Address.String()
+ }
+
dialer := &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
return internet.DialSystem(ctx, dest, streamSettings.SocketSettings)
},
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
- HandshakeTimeout: time.Second * 8,
+ HandshakeTimeout: time.Second * 15,
}
protocol := "ws"
@@ -63,7 +74,11 @@ func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *in
return nil, newError("dial TLS connection failed").Base(err)
}
conn, err = securityEngine.Client(conn,
- security.OptionWithDestination{Dest: dest},
+ security.OptionWithDestination{Dest: net.Destination{
+ Network: dest.Network,
+ Address: net.ParseAddress(originalDomain),
+ Port: dest.Port,
+ }},
security.OptionWithALPN{ALPNs: []string{"http/1.1"}})
if err != nil {
return nil, newError("unable to create security protocol client from security engine").Base(err)
@@ -74,7 +89,7 @@ func dialWebsocket(ctx context.Context, dest net.Destination, streamSettings *in
host := dest.NetAddr()
if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
- host = dest.Address.String()
+ host = originalDomain
}
uri := protocol + "://" + host + wsSettings.GetNormalizedPath()