-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtproxy_linux.go
More file actions
794 lines (756 loc) · 23.7 KB
/
Copy pathtproxy_linux.go
File metadata and controls
794 lines (756 loc) · 23.7 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
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
//go:build linux || (android && arm)
package gohpts
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"os/exec"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/shadowy-pycoder/mshark/layers"
"github.com/shadowy-pycoder/mshark/network"
"golang.org/x/sys/unix"
)
type tproxyServer struct {
listener net.Listener
quit chan struct{}
wg sync.WaitGroup
p *Proxy
startingFlag atomic.Bool
closingFlag atomic.Bool
}
func newTproxyServer(p *Proxy) (*tproxyServer, error) {
ts := &tproxyServer{
quit: make(chan struct{}),
p: p,
}
// https://iximiuz.com/en/posts/go-net-http-setsockopt-example/
lc := net.ListenConfig{
Control: func(network, address string, conn syscall.RawConn) error {
var operr error
size := 2 * 1024 * 1024
if err := conn.Control(func(fd uintptr) {
setopt := func(level, opt, val int) {
if operr != nil {
return
}
if e := unix.SetsockoptInt(int(fd), level, opt, val); e != nil {
operr = fmt.Errorf("setsockopt(%d,%d): %w", level, opt, e)
}
}
setopt(unix.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout.Milliseconds()))
setopt(unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
setopt(unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
setopt(unix.SOL_SOCKET, unix.SO_SNDBUF, size)
setopt(unix.SOL_SOCKET, unix.SO_RCVBUF, size)
if ts.p.tproxyMode == "tproxy" || ts.p.tproxyMode == "tlocal" {
setopt(unix.SOL_IP, unix.IP_TRANSPARENT, 1)
if ts.p.ipv6enabled {
setopt(unix.SOL_IPV6, unix.IPV6_TRANSPARENT, 1)
}
}
}); err != nil {
return err
}
return operr
},
}
ln, err := lc.Listen(context.Background(), ts.p.tcp, ts.p.tproxyAddr)
if err != nil {
if errors.Is(err, os.ErrPermission) {
return nil, fmt.Errorf("permission denied (try setting CAP_NET_ADMIN capability): %v", err)
}
return nil, err
}
ts.listener = ln
return ts, nil
}
func (ts *tproxyServer) Serve() {
ts.startingFlag.Store(true)
ts.wg.Add(1)
go ts.serve()
ts.startingFlag.Store(false)
}
func (ts *tproxyServer) serve() {
defer ts.wg.Done()
for {
conn, err := ts.listener.Accept()
if err != nil {
select {
case <-ts.quit:
return
default:
ts.p.logger.Error().Err(err).Msg("Failed accepting connection")
}
} else {
if ts.closingFlag.Load() {
return
}
ts.wg.Add(1)
err := conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
ts.p.logger.Error().Err(err).Msg("")
}
go func() {
ts.handleConnection(conn)
ts.wg.Done()
}()
}
}
}
func getsockopt(s int, level int, optname int, optval unsafe.Pointer, optlen *uint32) (err error) {
_, _, e := unix.Syscall6(
unix.SYS_GETSOCKOPT,
uintptr(s),
uintptr(level),
uintptr(optname),
uintptr(optval),
uintptr(unsafe.Pointer(optlen)),
0,
)
if e != 0 {
return e
}
return nil
}
func (ts *tproxyServer) getOriginalDst(rawConn syscall.RawConn, addr *net.TCPAddr) (string, error) {
var dstHost netip.Addr
var dstPort uint16
err := rawConn.Control(func(fd uintptr) {
if addr.IP.To4() != nil {
var originalDst unix.RawSockaddrInet4
optlen := uint32(unsafe.Sizeof(originalDst))
err := getsockopt(int(fd), unix.SOL_IP, unix.SO_ORIGINAL_DST, unsafe.Pointer(&originalDst), &optlen)
if err != nil {
ts.p.logger.Error().Err(err).Msgf("")
return
}
dstHost = netip.AddrFrom4(originalDst.Addr)
dstPort = uint16(originalDst.Port<<8) | originalDst.Port>>8
} else {
var originalDst unix.RawSockaddrInet6
optlen := uint32(unsafe.Sizeof(originalDst))
err := getsockopt(int(fd), unix.SOL_IPV6, unix.SO_ORIGINAL_DST, unsafe.Pointer(&originalDst), &optlen)
if err != nil {
ts.p.logger.Error().Err(err).Msgf("")
return
}
dstHost = netip.AddrFrom16(originalDst.Addr)
dstPort = uint16(originalDst.Port<<8) | originalDst.Port>>8
}
})
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed invoking control connection", ts.p.tcp, ts.p.tproxyMode)
return "", err
}
if !dstHost.IsValid() || dstPort == 0 {
return "", fmt.Errorf("[%s %s] getsockopt SO_ORIGINAL_DST failed", ts.p.tcp, ts.p.tproxyMode)
}
return netip.AddrPortFrom(dstHost, dstPort).String(), nil
}
func (ts *tproxyServer) handleConnection(srcConn net.Conn) {
var (
dstConn net.Conn
dst string
err error
)
defer srcConn.Close()
switch ts.p.tproxyMode {
case "redirect":
rawConn, err := srcConn.(*net.TCPConn).SyscallConn()
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed to get raw connection", ts.p.tcp, ts.p.tproxyMode)
return
}
addr := srcConn.RemoteAddr().(*net.TCPAddr)
dst, err = ts.getOriginalDst(rawConn, addr)
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed to get destination address", ts.p.tcp, ts.p.tproxyMode)
return
}
case "tproxy", "tlocal":
dst = srcConn.LocalAddr().String()
default:
ts.p.logger.Fatal().Msg("Unknown tproxyMode")
}
if !ts.p.socksEnabled || network.IsLocalAddress(dst) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
dstConn, err = ts.p.baseDialer.DialContext(ctx, ts.p.tcp, dst)
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed connecting to %s", ts.p.tcp, ts.p.tproxyMode, dst)
return
}
} else {
sockDialer, err := ts.p.getSockDialer()
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed getting %s client", ts.p.tcp, ts.p.tproxyMode, ts.p.socksProto)
return
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
dstConn, err = sockDialer.DialContext(ctx, ts.p.tcp, dst)
if err != nil {
ts.p.logger.Error().Err(err).Msgf("[%s %s] Failed connecting to %s", ts.p.tcp, ts.p.tproxyMode, dst)
return
}
}
defer dstConn.Close()
arrow := "→ "
if ts.p.nocolor {
arrow = "->"
}
dstConnStr := fmt.Sprintf("%s%s%s%s%s", dstConn.LocalAddr().String(), arrow, dstConn.RemoteAddr().String(), arrow, dst)
srcConnStr := fmt.Sprintf("%s%s%s", srcConn.RemoteAddr().String(), arrow, srcConn.LocalAddr().String())
ts.p.logger.Debug().Msgf("[%s %s] src: %s - dst: %s", ts.p.tcp, ts.p.tproxyMode, srcConnStr, dstConnStr)
reqChan := make(chan layers.Layer)
respChan := make(chan layers.Layer)
var wg sync.WaitGroup
wg.Add(2)
go ts.p.transfer(&wg, dstConn, srcConn, dstConnStr, srcConnStr, reqChan)
go ts.p.transfer(&wg, srcConn, dstConn, srcConnStr, dstConnStr, respChan)
if ts.p.sniff {
wg.Add(1)
sniffheader := make([]string, 0, 6)
id := getID(ts.p.nocolor)
if ts.p.json {
sniffheader = append(
sniffheader,
fmt.Sprintf(
"{\"connection\":{\"tproxy_mode\":%q,\"src_remote\":%q,\"src_local\":%q,\"dst_local\":%q,\"dst_remote\":%q,\"original_dst\":%q}}",
ts.p.tproxyMode,
srcConn.RemoteAddr(),
srcConn.LocalAddr(),
dstConn.LocalAddr(),
dstConn.RemoteAddr(),
dst,
),
)
} else {
connections := colorizeConnectionsTransparent(
srcConn.RemoteAddr(),
srcConn.LocalAddr(),
dstConn.LocalAddr(),
dstConn.RemoteAddr(),
dst, id, ts.p.nocolor,
)
sniffheader = append(sniffheader, connections)
}
go ts.p.sniffreporter(&wg, &sniffheader, reqChan, respChan, id)
}
wg.Wait()
}
func (ts *tproxyServer) Shutdown() {
for ts.startingFlag.Load() {
time.Sleep(50 * time.Millisecond)
}
close(ts.quit)
ts.closingFlag.Store(true)
ts.listener.Close()
done := make(chan struct{})
go func() {
ts.wg.Wait()
close(done)
}()
select {
case <-done:
return
case <-time.After(shutdownTimeout):
ts.p.logger.Error().Msgf("[%s %s] Server timed out waiting for connections to finish", ts.p.tcp, ts.p.tproxyMode)
return
}
}
func (ts *tproxyServer) ApplyRedirectRules(opts map[string]string) {
_, tproxyPort, _ := net.SplitHostPort(ts.p.tproxyAddr)
var setex string
if ts.p.dumpRules {
setex = "set -ex"
}
cmdCheckBBR := exec.Command("bash", "-c", fmt.Sprintf(`
%s
if command -v lsmod >/dev/null 2>&1 && command -v modprobe >/dev/null 2>&1
then
lsmod | grep -q '^tcp_bbr' || modprobe tcp_bbr
fi
`, setex))
cmdCheckBBR.Stdout = os.Stdout
cmdCheckBBR.Stderr = os.Stderr
if !ts.p.dumpRules {
cmdCheckBBR.Stdout = nil
}
if err := cmdCheckBBR.Run(); err == nil {
_ = runSysctlOptCmd("net.ipv4.tcp_congestion_control", "bbr", setex, opts, ts.p.dumpRules, &ts.p.dump)
}
_ = runSysctlOptCmd("net.core.default_qdisc", "fq", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.ipv4.tcp_tw_reuse", "1", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.ipv4.tcp_fin_timeout", "15", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.ipv4.tcp_rmem", "4096 65536 4194304", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.ipv4.tcp_wmem", "4096 65536 4194304", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.ipv4.tcp_window_scaling", "1", setex, opts, ts.p.dumpRules, &ts.p.dump)
_ = runSysctlOptCmd("net.core.somaxconn", "65535", setex, opts, ts.p.dumpRules, &ts.p.dump)
switch ts.p.tproxyMode {
case "redirect":
// ipv4
if ts.p.ipv4enabled {
cmdClear0 := `
iptables -t nat -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
iptables -t nat -D OUTPUT -p tcp -j GOHPTS 2>/dev/null || true
iptables -t nat -F GOHPTS 2>/dev/null || true
iptables -t nat -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear0)
cmdInit0 := `
iptables -t nat -N GOHPTS 2>/dev/null
iptables -t nat -F GOHPTS
iptables -t nat -A GOHPTS -p tcp -d 127.0.0.0/8 -j RETURN
iptables -t nat -A GOHPTS -p tcp -d 224.0.0.0/4 -j RETURN
iptables -t nat -A GOHPTS -p tcp -d 255.255.255.255/32 -j RETURN
iptables -t nat -A GOHPTS -p tcp --dport 22 -j RETURN
`
ts.p.runRuleCmd(cmdInit0)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd1 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd1)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix != nil {
cmdInit00 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp -s %s -d %s -j RETURN
`, ts.p.prefix.Masked(), ts.p.prefix.Masked())
ts.p.runRuleCmd(cmdInit00)
}
if ts.p.ignoredPorts != "" {
cmdInit1 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp -m multiport --dports %s -j RETURN
iptables -t nat -A GOHPTS -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit1)
}
if ts.p.httpServerAddr != "" {
_, httpPort, _ := net.SplitHostPort(ts.p.httpServerAddr)
cmdHTTP0 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, httpPort)
ts.p.runRuleCmd(cmdHTTP0)
}
if ts.p.mark > 0 {
cmdMark0 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp -m mark --mark %d -j RETURN
`, ts.p.mark)
ts.p.runRuleCmd(cmdMark0)
} else {
cmd0 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, tproxyPort)
ts.p.runRuleCmd(cmd0)
}
cmdDocker4 := `
if command -v docker >/dev/null 2>&1
then
for subnet in $(docker network inspect $(docker network ls -q) --format '{{range .IPAM.Config}}{{println .Subnet}}{{end}}'); do
if [[ "$subnet" == *:* ]]; then
continue
else
iptables -t nat -A GOHPTS -p tcp -d "$subnet" -j RETURN
fi
done
fi
`
ts.p.runRuleCmd(cmdDocker4)
cmdNat0 := fmt.Sprintf(`
iptables -t nat -A GOHPTS -p tcp -j REDIRECT --to-ports %s
iptables -t nat -C PREROUTING -p tcp -j GOHPTS 2>/dev/null || \
iptables -t nat -A PREROUTING -p tcp -j GOHPTS
iptables -t nat -C OUTPUT -p tcp -j GOHPTS 2>/dev/null || \
iptables -t nat -A OUTPUT -p tcp -j GOHPTS
`, tproxyPort)
ts.p.runRuleCmd(cmdNat0)
}
// ipv6
if ts.p.ipv6enabled {
cmdClear1 := `
ip6tables -t nat -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t nat -D OUTPUT -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t nat -F GOHPTS 2>/dev/null || true
ip6tables -t nat -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear1)
cmdInit2 := `
ip6tables -t nat -N GOHPTS 2>/dev/null
ip6tables -t nat -F GOHPTS
ip6tables -t nat -A GOHPTS -p tcp -d ::/128 -j RETURN
ip6tables -t nat -A GOHPTS -p tcp -d ::1/128 -j RETURN
ip6tables -t nat -A GOHPTS -p tcp -d ff00::/8 -j RETURN
ip6tables -t nat -A GOHPTS -p tcp -d fe80::/10 -j RETURN
ip6tables -t nat -A GOHPTS -p tcp -d fc00::/7 -j RETURN
ip6tables -t nat -A GOHPTS -p tcp --dport 22 -j RETURN
`
ts.p.runRuleCmd(cmdInit2)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd11 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd11)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix6 != nil {
cmdInit02 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp -s %s -d %s -j RETURN
`, ts.p.prefix6.Masked(), ts.p.prefix6.Masked())
ts.p.runRuleCmd(cmdInit02)
}
if ts.p.ignoredPorts != "" {
cmdInit3 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp -m multiport --dports %s -j RETURN
ip6tables -t nat -A GOHPTS -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit3)
}
if ts.p.httpServerAddr != "" {
_, httpPort, _ := net.SplitHostPort(ts.p.httpServerAddr)
cmdHTTP1 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, httpPort)
ts.p.runRuleCmd(cmdHTTP1)
}
if ts.p.mark > 0 {
cmdMark1 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp -m mark --mark %d -j RETURN
`, ts.p.mark)
ts.p.runRuleCmd(cmdMark1)
} else {
cmd01 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp --dport %s -j RETURN
`, tproxyPort)
ts.p.runRuleCmd(cmd01)
}
cmdDocker6 := `
if command -v docker >/dev/null 2>&1
then
for subnet in $(docker network inspect $(docker network ls -q) --format '{{range .IPAM.Config}}{{println .Subnet}}{{end}}'); do
if [[ "$subnet" == *:* ]]; then
ip6tables -t nat -A GOHPTS -p tcp -d "$subnet" -j RETURN
fi
done
fi
`
ts.p.runRuleCmd(cmdDocker6)
cmdNat1 := fmt.Sprintf(`
ip6tables -t nat -A GOHPTS -p tcp -j REDIRECT --to-ports %s
ip6tables -t nat -C PREROUTING -p tcp -j GOHPTS 2>/dev/null || \
ip6tables -t nat -A PREROUTING -p tcp -j GOHPTS
ip6tables -t nat -C OUTPUT -p tcp -j GOHPTS 2>/dev/null || \
ip6tables -t nat -A OUTPUT -p tcp -j GOHPTS
`, tproxyPort)
ts.p.runRuleCmd(cmdNat1)
}
case "tlocal":
// ipv4
if ts.p.ipv4enabled {
cmdClear0 := `
iptables -t mangle -D OUTPUT -p tcp -j GOHPTS_OUT 2>/dev/null || true
iptables -t mangle -F GOHPTS_OUT 2>/dev/null || true
iptables -t mangle -X GOHPTS_OUT 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear0)
cmdInit0 := `
iptables -t mangle -N GOHPTS_OUT 2>/dev/null || true
iptables -t mangle -F GOHPTS_OUT
iptables -t mangle -A GOHPTS_OUT -p tcp -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A GOHPTS_OUT -p tcp -d 224.0.0.0/4 -j RETURN
iptables -t mangle -A GOHPTS_OUT -p tcp -d 255.255.255.255/32 -j RETURN
`
ts.p.runRuleCmd(cmdInit0)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd1 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS_OUT -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd1)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix != nil {
cmdInit00 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS_OUT -p tcp -d %s -j RETURN
`, ts.p.prefix.Masked())
ts.p.runRuleCmd(cmdInit00)
}
if ts.p.ignoredPorts != "" {
cmdInit1 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS_OUT -p tcp -m multiport --dports %s -j RETURN
iptables -t mangle -A GOHPTS_OUT -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit1)
}
cmdInit2 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS_OUT -p tcp -m mark --mark %d -j RETURN
iptables -t mangle -A GOHPTS_OUT -p tcp -j MARK --set-mark 2
iptables -t mangle -A OUTPUT -p tcp -j GOHPTS_OUT
`, ts.p.mark)
ts.p.runRuleCmd(cmdInit2)
}
// ipv6
if ts.p.ipv6enabled {
cmdClear1 := `
ip6tables -t mangle -D OUTPUT -p tcp -j GOHPTS_OUT 2>/dev/null || true
ip6tables -t mangle -F GOHPTS_OUT 2>/dev/null || true
ip6tables -t mangle -X GOHPTS_OUT 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear1)
cmdInit01 := `
ip6tables -t mangle -N GOHPTS_OUT 2>/dev/null || true
ip6tables -t mangle -F GOHPTS_OUT
ip6tables -t mangle -A GOHPTS_OUT -p tcp -d ::/128 -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -d ::1/128 -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -d ff00::/8 -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -d fe80::/10 -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -d fc00::/7 -j RETURN
`
ts.p.runRuleCmd(cmdInit01)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd11 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS_OUT -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd11)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix6 != nil {
cmdInit02 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS_OUT -p tcp -s %s -d %s -j RETURN
`, ts.p.prefix6.Masked(), ts.p.prefix6.Masked())
ts.p.runRuleCmd(cmdInit02)
}
if ts.p.ignoredPorts != "" {
cmdInit11 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS_OUT -p tcp -m multiport --dports %s -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit11)
}
cmdInit21 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS_OUT -p tcp -m mark --mark %d -j RETURN
ip6tables -t mangle -A GOHPTS_OUT -p tcp -j MARK --set-mark 2
ip6tables -t mangle -A OUTPUT -p tcp -j GOHPTS_OUT
`, ts.p.mark)
ts.p.runRuleCmd(cmdInit21)
}
fallthrough
case "tproxy":
// ipv4
if ts.p.ipv4enabled {
cmdClear0 := `
iptables -t mangle -D PREROUTING -p tcp -m socket -j DIVERT 2>/dev/null || true
iptables -t mangle -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
iptables -t mangle -F GOHPTS 2>/dev/null || true
iptables -t mangle -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear0)
cmdInit0 := `
iptables -t mangle -N GOHPTS 2>/dev/null || true
iptables -t mangle -F GOHPTS
iptables -t mangle -A GOHPTS -p tcp -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A GOHPTS -p tcp -d 224.0.0.0/4 -j RETURN
iptables -t mangle -A GOHPTS -p tcp -d 255.255.255.255/32 -j RETURN
`
ts.p.runRuleCmd(cmdInit0)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd1 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd1)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix != nil {
cmdInit00 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS -p tcp -d %s -j RETURN
`, ts.p.prefix.Masked())
ts.p.runRuleCmd(cmdInit00)
}
if ts.p.ignoredPorts != "" {
cmdInit1 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS -p tcp -m multiport --dports %s -j RETURN
iptables -t mangle -A GOHPTS -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit1)
}
cmdDocker4 := `
if command -v docker >/dev/null 2>&1
then
for subnet in $(docker network inspect $(docker network ls -q) --format '{{range .IPAM.Config}}{{println .Subnet}}{{end}}'); do
if [[ "$subnet" == *:* ]]; then
continue
else
iptables -t mangle -A GOHPTS -p tcp -d "$subnet" -j RETURN
fi
done
fi
`
ts.p.runRuleCmd(cmdDocker4)
cmdInit2 := fmt.Sprintf(`
iptables -t mangle -A GOHPTS -p tcp -m mark --mark %d -j RETURN
iptables -t mangle -A GOHPTS -p tcp -j TPROXY --on-port %s --tproxy-mark 0x1/0x1
iptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
iptables -t mangle -A PREROUTING -p tcp -j GOHPTS
`, ts.p.mark, tproxyPort)
ts.p.runRuleCmd(cmdInit2)
}
// ipv6
if ts.p.ipv6enabled {
cmdClear1 := `
ip6tables -t mangle -D PREROUTING -p tcp -m socket -j DIVERT 2>/dev/null || true
ip6tables -t mangle -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t mangle -F GOHPTS 2>/dev/null || true
ip6tables -t mangle -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmdClear1)
cmdInit01 := `
ip6tables -t mangle -N GOHPTS 2>/dev/null || true
ip6tables -t mangle -F GOHPTS
ip6tables -t mangle -A GOHPTS -p tcp -d ::/128 -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -d ::1/128 -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -d ff00::/8 -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -d fe80::/10 -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -d fc00::/7 -j RETURN
`
ts.p.runRuleCmd(cmdInit01)
if ts.p.socksEnabled {
for _, pr := range ts.p.proxylist {
_, port, _ := net.SplitHostPort(pr.Address)
cmd11 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS -p tcp --dport %s -j RETURN
`, port)
ts.p.runRuleCmd(cmd11)
if ts.p.proxychain.Type == "strict" {
break
}
}
}
if ts.p.prefix6 != nil {
cmdInit02 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS -p tcp -s %s -d %s -j RETURN
`, ts.p.prefix6.Masked(), ts.p.prefix6.Masked())
ts.p.runRuleCmd(cmdInit02)
}
if ts.p.ignoredPorts != "" {
cmdInit11 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS -p tcp -m multiport --dports %s -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -m multiport --sports %s -j RETURN
`, ts.p.ignoredPorts, ts.p.ignoredPorts)
ts.p.runRuleCmd(cmdInit11)
}
cmdDocker6 := `
if command -v docker >/dev/null 2>&1
then
for subnet in $(docker network inspect $(docker network ls -q) --format '{{range .IPAM.Config}}{{println .Subnet}}{{end}}'); do
if [[ "$subnet" == *:* ]]; then
ip6tables -t mangle -A GOHPTS -p tcp -d "$subnet" -j RETURN
fi
done
fi
`
ts.p.runRuleCmd(cmdDocker6)
cmdInit21 := fmt.Sprintf(`
ip6tables -t mangle -A GOHPTS -p tcp -m mark --mark %d -j RETURN
ip6tables -t mangle -A GOHPTS -p tcp -j TPROXY --on-port %s --tproxy-mark 0x1/0x1
ip6tables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT
ip6tables -t mangle -A PREROUTING -p tcp -j GOHPTS
`, ts.p.mark, tproxyPort)
ts.p.runRuleCmd(cmdInit21)
}
default:
ts.p.logger.Fatal().Msgf("Unreachable, unknown mode: %s", ts.p.tproxyMode)
}
}
func (ts *tproxyServer) ClearRedirectRules() error {
switch ts.p.tproxyMode {
case "redirect":
if ts.p.ipv4enabled {
cmd0 := `
iptables -t nat -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
iptables -t nat -D OUTPUT -p tcp -j GOHPTS 2>/dev/null || true
iptables -t nat -F GOHPTS 2>/dev/null || true
iptables -t nat -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmd0)
}
if ts.p.ipv6enabled {
cmd1 := `
ip6tables -t nat -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t nat -D OUTPUT -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t nat -F GOHPTS 2>/dev/null || true
ip6tables -t nat -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmd1)
}
case "tlocal":
if ts.p.ipv4enabled {
cmd0 := `
iptables -t mangle -D OUTPUT -p tcp -j GOHPTS_OUT 2>/dev/null || true
iptables -t mangle -F GOHPTS_OUT 2>/dev/null || true
iptables -t mangle -X GOHPTS_OUT 2>/dev/null || true
`
ts.p.runRuleCmd(cmd0)
}
if ts.p.ipv6enabled {
cmd1 := `
ip6tables -t mangle -D OUTPUT -p tcp -j GOHPTS_OUT 2>/dev/null || true
ip6tables -t mangle -F GOHPTS_OUT 2>/dev/null || true
ip6tables -t mangle -X GOHPTS_OUT 2>/dev/null || true
`
ts.p.runRuleCmd(cmd1)
}
fallthrough
case "tproxy":
if ts.p.ipv4enabled {
cmd0 := `
iptables -t mangle -D PREROUTING -p tcp -m socket -j DIVERT 2>/dev/null || true
iptables -t mangle -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
iptables -t mangle -F GOHPTS 2>/dev/null || true
iptables -t mangle -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmd0)
}
if ts.p.ipv6enabled {
cmd1 := `
ip6tables -t mangle -D PREROUTING -p tcp -m socket -j DIVERT 2>/dev/null || true
ip6tables -t mangle -D PREROUTING -p tcp -j GOHPTS 2>/dev/null || true
ip6tables -t mangle -F GOHPTS 2>/dev/null || true
ip6tables -t mangle -X GOHPTS 2>/dev/null || true
`
ts.p.runRuleCmd(cmd1)
}
}
return nil
}