-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgohpts.go
More file actions
1862 lines (1807 loc) · 55.3 KB
/
gohpts.go
File metadata and controls
1862 lines (1807 loc) · 55.3 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
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 gohpts transform SOCKS5 proxy into HTTP(S) proxy with support for Transparent Proxy (Redirect and TProxy), Proxychains and Traffic Sniffing
package gohpts
import (
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"maps"
"math/rand"
"net"
"net/http"
"net/http/pprof"
"net/netip"
"os"
"os/exec"
"os/signal"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/goccy/go-yaml"
"github.com/rs/zerolog"
"github.com/shadowy-pycoder/arpspoof"
"github.com/shadowy-pycoder/mshark/layers"
"github.com/shadowy-pycoder/mshark/network"
"github.com/shadowy-pycoder/ndpspoof"
"github.com/wzshiming/socks5"
)
const (
readTimeout time.Duration = 30 * time.Second
writeTimeout time.Duration = 30 * time.Second
timeout time.Duration = 10 * time.Second
shutdownTimeout time.Duration = 30 * time.Second
hopTimeout time.Duration = 3 * time.Second
flushTimeout time.Duration = 10 * time.Millisecond
availProxyUpdateInterval time.Duration = 30 * time.Second
rrIndexMax uint32 = 1_000_000
maxBodySize int64 = 2 << 15
)
var (
supportedChainTypes = []string{"strict", "dynamic", "random", "round_robin"}
SupportedTProxyModes = []string{"redirect", "tproxy"}
SupportedTProxyOS = []string{"linux", "android"}
errInvalidWrite = errors.New("invalid write result")
)
type Config struct {
AddrHTTP string
AddrSOCKS string
AddrPprof string
User string
Pass string
ServerUser string
ServerPass string
CertFile string
KeyFile string
Interface string
ServerConfPath string
IPv6Enabled bool
TProxy string
TProxyOnly string
TProxyUDP string
TProxyMode string
TProxyWorkers uint
TProxyUDPWorkers uint
Auto bool
Dump bool
Mark uint
ARPSpoof string
NDPSpoof string
IgnoredPorts string
LogFilePath string
Debug bool
JSON bool
Sniff bool
SniffLogFile string
NoColor bool
Body bool
}
type logWriter struct {
file *os.File
}
func (writer logWriter) Write(bytes []byte) (int, error) {
return fmt.Fprintf(writer.file, "%s ERR %s", time.Now().Format(time.RFC3339), string(bytes))
}
type jsonLogWriter struct {
file *os.File
}
func (writer jsonLogWriter) Write(bytes []byte) (int, error) {
return fmt.Fprintf(writer.file, "{\"level\":\"error\",\"time\":\"%s\",\"message\":\"%s\"}\n",
time.Now().Format(time.RFC3339), strings.TrimRight(string(bytes), "\n"))
}
type proxyEntry struct {
Address string `yaml:"address"`
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
}
func (pe proxyEntry) String() string {
return pe.Address
}
type server struct {
Address string `yaml:"address"`
Interface string `yaml:"interface,omitempty"`
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
CertFile string `yaml:"cert_file,omitempty"`
KeyFile string `yaml:"key_file,omitempty"`
}
type chain struct {
Type string `yaml:"type"`
Length int `yaml:"length"`
}
type serverConfig struct {
Chain chain `yaml:"chain"`
ProxyList []proxyEntry `yaml:"proxy_list"`
Server server `yaml:"server"`
}
type proxyapp struct {
httpServer *http.Server
sockClient *http.Client
httpClient *http.Client
sockDialer *socks5.Dialer
logger *zerolog.Logger
snifflogger *zerolog.Logger
certFile string
keyFile string
httpServerAddr string
pprofAddr string
iface *net.Interface
tcp string
udp string
ipv6enabled bool
tproxyAddr string
tproxyAddrUDP string
tproxyMode string
tproxyWorkers uint
tproxyUDPWorkers uint
auto bool
mark uint
arpspoofer *arpspoof.ARPSpoofer
ndpspoofer *ndpspoof.NDPSpoofer
raEnabled bool
hostIPGlobal netip.Addr
ignoredPorts string
user string
pass string
proxychain chain
proxylist []proxyEntry
rrIndex uint32
rrIndexReset uint32
sniff bool
nocolor bool
body bool
json bool
debug bool
dumpRules bool
dump strings.Builder
closeConn chan bool
mu sync.RWMutex
availProxyList []proxyEntry
}
func New(conf *Config) *proxyapp {
var logger, snifflogger zerolog.Logger
var p proxyapp
logfile := os.Stdout
var snifflog *os.File
var err error
p.sniff = conf.Sniff
p.body = conf.Body
p.json = conf.JSON
if conf.LogFilePath != "" {
f, err := os.OpenFile(conf.LogFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
log.Fatalf("Failed to open log file: %v", err)
}
logfile = f
}
if conf.SniffLogFile != "" && conf.SniffLogFile != conf.LogFilePath {
f, err := os.OpenFile(conf.SniffLogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
log.Fatalf("Failed to open sniff log file: %v", err)
}
snifflog = f
} else {
snifflog = logfile
}
p.nocolor = conf.JSON || conf.NoColor
if conf.JSON {
log.SetFlags(0)
jsonWriter := jsonLogWriter{file: logfile}
log.SetOutput(jsonWriter)
logger = zerolog.New(logfile).With().Timestamp().Logger()
snifflogger = zerolog.New(snifflog).With().Timestamp().Logger()
} else {
log.SetFlags(0)
logWriter := logWriter{file: logfile}
log.SetOutput(logWriter)
output := zerolog.ConsoleWriter{Out: logfile, NoColor: p.nocolor}
output.FormatTimestamp = func(i any) string {
ts, _ := time.Parse(time.RFC3339, i.(string))
return colorizeTimestamp(ts, p.nocolor)
}
output.FormatMessage = func(i any) string {
if i == nil || i == "" {
return ""
}
return colorizeLogMessage(i.(string), p.nocolor)
}
output.FormatErrFieldName = func(i any) string {
return fmt.Sprintf("%s", i)
}
output.FormatErrFieldValue = func(i any) string {
s := i.(string)
return colorizeErrMessage(s, p.nocolor)
}
logger = zerolog.New(output).With().Timestamp().Logger()
sniffoutput := zerolog.ConsoleWriter{Out: snifflog, TimeFormat: time.RFC3339, NoColor: p.nocolor, PartsExclude: []string{"level"}}
sniffoutput.FormatTimestamp = func(i any) string {
ts, _ := time.Parse(time.RFC3339, i.(string))
return colorizeTimestamp(ts, p.nocolor)
}
sniffoutput.FormatMessage = func(i any) string {
if i == nil || i == "" {
return ""
}
return fmt.Sprintf("%s", i)
}
sniffoutput.FormatErrFieldName = func(i any) string {
return fmt.Sprintf("%s", i)
}
sniffoutput.FormatErrFieldValue = func(i any) string {
return colorizeErrMessage(i.(string), p.nocolor)
}
snifflogger = zerolog.New(sniffoutput).With().Timestamp().Logger()
}
zerolog.SetGlobalLevel(zerolog.DebugLevel)
lvl := zerolog.InfoLevel
if conf.Debug {
lvl = zerolog.DebugLevel
}
p.debug = conf.Debug
if conf.AddrPprof != "" {
var pprofAddr netip.AddrPort
pprofAddr, err = network.ParseAddrPort(conf.AddrPprof, "127.0.0.1")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
p.pprofAddr = pprofAddr.String()
}
// the only way I found to make debug level independent between loggers
l := logger.Level(lvl)
sl := snifflogger.Level(lvl)
p.logger = &l
p.snifflogger = &sl
if conf.IPv6Enabled {
p.tcp = "tcp"
p.udp = "udp"
p.ipv6enabled = true
} else {
p.tcp = "tcp4"
p.udp = "udp4"
p.ipv6enabled = false
}
if slices.Contains(SupportedTProxyOS, runtime.GOOS) && conf.TProxy != "" && conf.TProxyOnly != "" {
p.logger.Fatal().Msg("Cannot specify TPRoxy and TProxyOnly at the same time")
} else if slices.Contains(SupportedTProxyOS, runtime.GOOS) && conf.TProxyMode != "" && !slices.Contains(SupportedTProxyModes, conf.TProxyMode) {
p.logger.Fatal().Msg("Incorrect TProxyMode provided")
} else if !slices.Contains(SupportedTProxyOS, runtime.GOOS) && (conf.TProxy != "" || conf.TProxyOnly != "" || conf.TProxyMode != "" || conf.TProxyUDP != "") {
conf.TProxy = ""
conf.TProxyOnly = ""
conf.TProxyMode = ""
conf.TProxyUDP = ""
p.logger.Warn().Msgf("[%s] functionality only available on linux or android systems", conf.TProxyMode)
}
p.tproxyMode = conf.TProxyMode
tproxyonly := conf.TProxyOnly != ""
var tAddr string
if tproxyonly {
tAddr = conf.TProxyOnly
} else {
tAddr = conf.TProxy
}
if p.tproxyMode != "" {
var tproxyAddr netip.AddrPort
tproxyAddr, err = network.ParseAddrPort(tAddr, "0.0.0.0")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
p.tproxyAddr = tproxyAddr.String()
if conf.TProxyUDP != "" {
if p.tproxyMode != "tproxy" {
p.logger.Warn().Msgf("[%s] transparent UDP server only supports tproxy mode", conf.TProxyMode)
}
var tproxyAddrUDP netip.AddrPort
tproxyAddrUDP, err = network.ParseAddrPort(conf.TProxyUDP, "0.0.0.0")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
p.tproxyAddrUDP = tproxyAddrUDP.String()
}
} else {
p.tproxyAddr = ""
}
if network.AddrEqual(p.tproxyAddr, p.tproxyAddrUDP) {
p.logger.Fatal().Msgf("%s: address already in use", p.tproxyAddrUDP)
}
p.tproxyWorkers = conf.TProxyWorkers
if p.tproxyWorkers > 0 && !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("Setting the number of instances of transparent proxy is available only on linux/android systems")
} else if p.tproxyWorkers == 0 && slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.tproxyWorkers = uint(runtime.NumCPU())
}
p.tproxyUDPWorkers = conf.TProxyUDPWorkers
if p.tproxyUDPWorkers > 0 && !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("Setting the number of instances of transparent proxy is available only on linux/android systems")
} else if p.tproxyUDPWorkers == 0 && slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.tproxyUDPWorkers = uint(runtime.NumCPU())
}
p.auto = conf.Auto
if p.auto && !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("Auto setup is available only on linux/android systems")
}
p.dumpRules = conf.Dump
if p.dumpRules && !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("Dump is available only on linux/android systems")
}
p.dump.WriteString("#!/usr/bin/env bash\n\nset -ex\n")
p.mark = conf.Mark
if p.mark > 0 && !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("SO_MARK is available only on linux/android systems")
}
if p.mark > 0xFFFFFFFF {
p.logger.Fatal().Msg("SO_MARK is out of range")
}
if p.mark == 0 && p.tproxyMode == "tproxy" {
p.mark = 100
}
if conf.IgnoredPorts != "" {
if !p.auto {
p.logger.Fatal().Msg("Ignoring ports is only possible in auto configuration")
}
if !portsPattern.MatchString(conf.IgnoredPorts) {
p.logger.Fatal().Msg("Ignored ports must be a comma separated list of port numbers")
}
p.ignoredPorts = conf.IgnoredPorts
}
var addrHTTP, addrSOCKS, certFile, keyFile string
if conf.ServerConfPath != "" {
var sconf serverConfig
yamlFile, err := os.ReadFile(expandPath(conf.ServerConfPath))
if err != nil {
p.logger.Fatal().Err(err).Msg("[yaml config] Parsing failed")
}
err = yaml.Unmarshal(yamlFile, &sconf)
if err != nil {
p.logger.Fatal().Err(err).Msg("[yaml config] Parsing failed")
}
if !tproxyonly {
if sconf.Server.Address == "" {
p.logger.Fatal().Err(err).Msg("[yaml config] Server address is empty")
}
if sconf.Server.Interface != "" {
p.iface, err = net.InterfaceByName(sconf.Server.Interface)
if err != nil {
if ifIdx, err := strconv.Atoi(sconf.Server.Interface); err == nil {
p.iface, err = net.InterfaceByIndex(ifIdx)
if err != nil {
p.logger.Warn().Err(err).Msgf("Failed binding to %s, using default interface", sconf.Server.Interface)
}
} else {
p.logger.Warn().Msgf("Failed binding to %s, using default interface", sconf.Server.Interface)
}
}
}
iAddr, err := getAddressFromInterface(p.iface)
if err != nil {
p.iface = nil
p.logger.Warn().Err(err).Msgf("Failed binding to %s, using default interface", sconf.Server.Interface)
}
var hostPortHTTP netip.AddrPort
if iAddr == "" {
hostPortHTTP, err = network.ParseAddrPort(conf.AddrHTTP, "127.0.0.1")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
} else {
parsedAddrHTTP, err := network.ParseAddrPort(conf.AddrHTTP, iAddr)
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
hostPortHTTP = netip.AddrPortFrom(netip.MustParseAddr(iAddr), parsedAddrHTTP.Port())
}
addrHTTP = hostPortHTTP.String()
p.httpServerAddr = addrHTTP
certFile = expandPath(sconf.Server.CertFile)
keyFile = expandPath(sconf.Server.KeyFile)
p.user = sconf.Server.Username
p.pass = sconf.Server.Password
}
p.proxychain = sconf.Chain
p.proxylist = sconf.ProxyList
p.availProxyList = make([]proxyEntry, 0, len(p.proxylist))
if len(p.proxylist) == 0 {
p.logger.Fatal().Msg("[yaml config] Proxy list is empty")
}
seen := make(map[string]struct{})
for idx, pr := range p.proxylist {
hpAddr, err := network.ParseAddrPort(pr.Address, "127.0.0.1")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
addr := hpAddr.String()
if _, ok := seen[addr]; !ok {
seen[addr] = struct{}{}
p.proxylist[idx].Address = addr
} else {
p.logger.Fatal().Msgf("[yaml config] Duplicate entry `%s`", addr)
}
}
addrSOCKS = p.printProxyChain(p.proxylist)
chainType := p.proxychain.Type
if !slices.Contains(supportedChainTypes, chainType) {
p.logger.Fatal().Msgf("[yaml config] Chain type `%s` is not supported", chainType)
}
p.rrIndexReset = rrIndexMax
} else {
if !tproxyonly {
if conf.Interface != "" {
p.iface, err = net.InterfaceByName(conf.Interface)
if err != nil {
if ifIdx, err := strconv.Atoi(conf.Interface); err == nil {
p.iface, err = net.InterfaceByIndex(ifIdx)
if err != nil {
p.logger.Warn().Err(err).Msgf("Failed binding to %s, using default interface", conf.Interface)
}
} else {
p.logger.Warn().Msgf("Failed binding to %s, using default interface", conf.Interface)
}
}
}
iAddr, err := getAddressFromInterface(p.iface)
if err != nil {
p.logger.Warn().Err(err).Msgf("Failed binding to %s, using default interface", conf.Interface)
p.iface = nil
}
var hostPortHTTP netip.AddrPort
if iAddr == "" {
hostPortHTTP, err = network.ParseAddrPort(conf.AddrHTTP, "127.0.0.1")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
} else {
parsedAddrHTTP, err := network.ParseAddrPort(conf.AddrHTTP, iAddr)
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
hostPortHTTP = netip.AddrPortFrom(netip.MustParseAddr(iAddr), parsedAddrHTTP.Port())
}
addrHTTP = hostPortHTTP.String()
p.httpServerAddr = addrHTTP
certFile = expandPath(conf.CertFile)
keyFile = expandPath(conf.KeyFile)
p.user = conf.ServerUser
p.pass = conf.ServerPass
}
var hostPortSOCKS netip.AddrPort
hostPortSOCKS, err = network.ParseAddrPort(conf.AddrSOCKS, "127.0.0.1")
if err != nil {
p.logger.Fatal().Err(err).Msg("")
}
addrSOCKS = hostPortSOCKS.String()
auth := auth{
User: conf.User,
Password: conf.Pass,
}
dialer, err := newSOCKS5Dialer(addrSOCKS, &auth, getBaseDialer(timeout, p.mark), p.tcp)
if err != nil {
p.logger.Fatal().Err(err).Msg("Unable to create SOCKS5 dialer")
}
p.sockDialer = dialer
if !tproxyonly {
p.sockClient = &http.Client{
Transport: &http.Transport{
DialContext: dialer.DialContext,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
}
if !tproxyonly {
hs := &http.Server{
Addr: addrHTTP,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: 1 << 20,
Protocols: new(http.Protocols),
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
},
}
hs.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
hs.Protocols.SetHTTP1(true)
p.httpServer = hs
p.httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DialContext: getBaseDialer(timeout, p.mark).DialContext,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: timeout,
}
}
if conf.ARPSpoof != "" {
if !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("ARP spoof setup is available only on linux/android systems")
}
if !p.auto {
p.logger.Warn().Msg("ARP spoof setup requires iptables configuration")
}
asc, err := arpspoof.NewARPSpoofConfig(conf.ARPSpoof, p.logger)
if err != nil {
p.logger.Fatal().Err(err).Msg("Failed creating arp spoofer")
}
asc.Interface = ""
asc.Gateway = nil
if p.iface != nil {
asc.Interface = p.iface.Name
}
p.arpspoofer, err = arpspoof.NewARPSpoofer(asc)
if err != nil {
p.logger.Fatal().Err(err).Msg("Failed creating arp spoofer")
}
}
if conf.NDPSpoof != "" {
if !p.ipv6enabled {
p.logger.Fatal().Msg("NDP spoof requires IPv6 enabled")
}
if !slices.Contains(SupportedTProxyOS, runtime.GOOS) {
p.logger.Fatal().Msg("NDP spoof setup is available only on linux/android systems")
}
if !p.auto {
p.logger.Warn().Msg("NDP spoof setup requires iptables configuration")
}
nsc, err := ndpspoof.NewNDPSpoofConfig(conf.NDPSpoof, p.logger)
if err != nil {
p.logger.Fatal().Err(err).Msg("Failed creating ndp spoofer")
}
nsc.Interface = ""
nsc.Gateway = nil
if p.iface != nil {
nsc.Interface = p.iface.Name
}
nsc.RDNSS = ""
nsc.Auto = false
if nsc.RA {
hostIP, err := network.GetHostIPv6GlobalUnicastFromRoute()
if err == nil {
nsc.RDNSS = hostIP.String() // use host ip as DNS server
p.raEnabled = true
p.hostIPGlobal = hostIP
}
}
p.ndpspoofer, err = ndpspoof.NewNDPSpoofer(nsc)
if err != nil {
p.logger.Fatal().Err(err).Msg("Failed creating ndp spoofer")
}
}
if conf.ServerConfPath != "" {
p.logger.Info().Msgf("SOCKS5 Proxy [%s] chain: %s", p.proxychain.Type, addrSOCKS)
} else {
p.logger.Info().Msgf("SOCKS5 Proxy: %s", addrSOCKS)
}
if !tproxyonly {
if certFile != "" && keyFile != "" {
p.certFile = certFile
p.keyFile = keyFile
p.logger.Info().Msgf("HTTPS Proxy: %s", p.httpServerAddr)
} else {
p.logger.Info().Msgf("HTTP Proxy: %s", p.httpServerAddr)
}
}
if p.tproxyAddr != "" {
suffix := ""
if p.tproxyWorkers != 1 {
suffix = "s"
}
if p.tproxyMode == "tproxy" {
p.logger.Info().Msgf("TPROXY: %s (%d instance%s)", p.tproxyAddr, p.tproxyWorkers, suffix)
} else {
p.logger.Info().Msgf("REDIRECT: %s (%d instance%s)", p.tproxyAddr, p.tproxyWorkers, suffix)
}
}
if p.tproxyAddrUDP != "" {
suffix := ""
if p.tproxyUDPWorkers != 1 {
suffix = "s"
}
p.logger.Info().Msgf("TPROXY (UDP): %s (%d instanse%s)", p.tproxyAddrUDP, p.tproxyUDPWorkers, suffix)
}
if p.pprofAddr != "" {
p.logger.Info().Msgf("PPROF: %s", p.pprofAddr)
}
return &p
}
func (p *proxyapp) Run() {
done := make(chan bool)
quit := make(chan os.Signal, 1)
p.closeConn = make(chan bool)
signal.Notify(quit, os.Interrupt)
if p.pprofAddr != "" {
sm := http.NewServeMux()
sm.HandleFunc("/debug/pprof/", pprof.Index)
sm.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
sm.HandleFunc("/debug/pprof/profile", pprof.Profile)
sm.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
sm.HandleFunc("/debug/pprof/trace", pprof.Trace)
go http.ListenAndServe(p.pprofAddr, sm)
}
if p.arpspoofer != nil {
go p.arpspoofer.Start()
}
if p.ndpspoofer != nil {
go p.ndpspoofer.Start()
}
tproxyEnabled := p.tproxyAddr != ""
tproxyServers := make([]*tproxyServer, p.tproxyWorkers)
opts := make(map[string]string, 20)
if p.auto {
p.applyCommonRedirectRules(opts)
}
if tproxyEnabled {
for i := range tproxyServers {
tproxyServers[i] = newTproxyServer(p)
}
if p.auto {
tproxyServers[0].ApplyRedirectRules(opts) // NOTE: probably stupid, need to move TCP settings in a separate function
}
}
tproxyUDPEnabled := p.tproxyAddrUDP != ""
tproxyUDPServers := make([]*tproxyServerUDP, p.tproxyUDPWorkers)
if tproxyUDPEnabled {
for i := range tproxyUDPServers {
tproxyUDPServers[i] = newTproxyServerUDP(p)
}
if p.auto {
tproxyUDPServers[0].ApplyRedirectRules(opts)
}
}
if p.proxylist != nil {
chainType := p.proxychain.Type
ctl := colorizeChainType(chainType, p.nocolor)
go func() {
for {
p.logger.Debug().Msgf("%s Updating available proxy", ctl)
p.updateSocksList()
time.Sleep(availProxyUpdateInterval)
}
}()
}
if p.httpServer != nil {
go func() {
<-quit
if p.arpspoofer != nil {
err := p.arpspoofer.Stop()
if err != nil {
p.logger.Error().Err(err).Msg("Failed stopping arp spoofer")
}
}
if p.ndpspoofer != nil {
err := p.ndpspoofer.Stop()
if err != nil {
p.logger.Error().Err(err).Msg("Failed stopping ndp spoofer")
}
}
close(p.closeConn)
var wg sync.WaitGroup
if tproxyEnabled {
p.logger.Info().Msgf("[tcp %s] Server is shutting down...", p.tproxyMode)
if p.auto {
err := tproxyServers[0].ClearRedirectRules()
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
wg.Add(int(p.tproxyWorkers))
for i, tproxyServer := range tproxyServers {
go func() {
p.logger.Info().Msgf("[tcp %s] Server %d is shutting down...", p.tproxyMode, i)
tproxyServer.Shutdown()
p.logger.Info().Msgf("[tcp %s] Server %d gracefully shutdown", p.tproxyMode, i)
wg.Done()
}()
}
}
if tproxyUDPEnabled {
p.logger.Info().Msgf("[udp %s] Server is shutting down...", p.tproxyMode)
if p.auto {
err := tproxyUDPServers[0].ClearRedirectRules()
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
wg.Add(int(p.tproxyUDPWorkers))
for i, tproxyServerUDP := range tproxyUDPServers {
go func() {
p.logger.Info().Msgf("[udp %s] Server %d is shutting down...", p.tproxyMode, i)
tproxyServerUDP.Shutdown()
p.logger.Info().Msgf("[udp %s] Server %d gracefully shutdown", p.tproxyMode, i)
wg.Done()
}()
}
}
wg.Wait()
if p.auto {
err := p.clearCommonRedirectRules(opts)
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
p.logger.Info().Msg("Server is shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
p.httpServer.SetKeepAlivesEnabled(false)
if err := p.httpServer.Shutdown(ctx); err != nil {
p.logger.Fatal().Err(err).Msg("Could not gracefully shutdown the server")
}
close(done)
}()
if tproxyEnabled {
for _, tproxyServer := range tproxyServers {
go tproxyServer.ListenAndServe()
}
}
if tproxyUDPEnabled {
for _, tproxyServerUDP := range tproxyUDPServers {
go tproxyServerUDP.ListenAndServe()
}
}
if p.user != "" && p.pass != "" {
p.httpServer.Handler = p.proxyAuth(p.handler())
} else {
p.httpServer.Handler = p.handler()
}
if p.certFile != "" && p.keyFile != "" {
if err := p.httpServer.ListenAndServeTLS(p.certFile, p.keyFile); err != nil && err != http.ErrServerClosed {
p.logger.Fatal().Err(err).Msg("Unable to start HTTPS server")
}
} else {
if err := p.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
p.logger.Fatal().Err(err).Msg("Unable to start HTTP server")
}
}
} else {
go func() {
<-quit
if p.arpspoofer != nil {
err := p.arpspoofer.Stop()
if err != nil {
p.logger.Error().Err(err).Msg("Failed stopping arp spoofer")
}
}
if p.ndpspoofer != nil {
err := p.ndpspoofer.Stop()
if err != nil {
p.logger.Error().Err(err).Msg("Failed stopping ndp spoofer")
}
}
close(p.closeConn)
var wg sync.WaitGroup
if tproxyEnabled {
if p.auto {
err := tproxyServers[0].ClearRedirectRules()
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
wg.Add(int(p.tproxyWorkers))
for i, tproxyServer := range tproxyServers {
go func() {
p.logger.Info().Msgf("[tcp %s] Server %d is shutting down...", p.tproxyMode, i)
tproxyServer.Shutdown()
p.logger.Info().Msgf("[tcp %s] Server %d gracefully shutdown", p.tproxyMode, i)
wg.Done()
}()
}
}
if tproxyUDPEnabled {
if p.auto {
err := tproxyUDPServers[0].ClearRedirectRules()
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
wg.Add(int(p.tproxyUDPWorkers))
for i, tproxyServerUDP := range tproxyUDPServers {
go func() {
p.logger.Info().Msgf("[udp %s] Server %d is shutting down...", p.tproxyMode, i)
tproxyServerUDP.Shutdown()
p.logger.Info().Msgf("[udp %s] Server %d gracefully shutdown", p.tproxyMode, i)
wg.Done()
}()
}
}
wg.Wait()
if p.auto {
err := p.clearCommonRedirectRules(opts)
if err != nil {
p.logger.Error().Err(err).Msg("Failed clearing iptables rules")
}
}
close(done)
}()
if tproxyEnabled && tproxyUDPEnabled {
for _, tproxyServerUDP := range tproxyUDPServers {
go tproxyServerUDP.ListenAndServe()
}
for i, tproxyServer := range tproxyServers {
if i < len(tproxyServers)-1 {
go tproxyServer.ListenAndServe()
} else {
tproxyServer.ListenAndServe()
}
}
} else if tproxyEnabled {
for i, tproxyServer := range tproxyServers {
if i < len(tproxyServers)-1 {
go tproxyServer.ListenAndServe()
} else {
tproxyServer.ListenAndServe()
}
}
} else {
for i, tproxyServerUDP := range tproxyUDPServers {
if i < len(tproxyUDPServers)-1 {
go tproxyServerUDP.ListenAndServe()
} else {
tproxyServerUDP.ListenAndServe()
}
}
}
}
<-done
if p.dumpRules {
err := os.WriteFile("rules.sh", []byte(p.dump.String()), 0o755)
if err != nil {
p.logger.Error().Err(err).Msg("Failed dumping rules")
}
}
p.logger.Info().Msg("Proxy stopped")
}
func (p *proxyapp) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
p.handleTunnel(w, r)
} else {
p.handleForward(w, r)
}
}
}
func (p *proxyapp) handleForward(w http.ResponseWriter, r *http.Request) {
var reqBodySaved []byte
if p.sniff && p.body {
reqBodySaved, _ = io.ReadAll(io.LimitReader(r.Body, maxBodySize))
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(reqBodySaved), r.Body))
}
req, err := http.NewRequest(r.Method, r.URL.String(), r.Body)
if err != nil {
p.logger.Error().Err(err).Msgf("Error during NewRequest() %s: %s", r.URL.String(), err)
w.WriteHeader(http.StatusInternalServerError)
return
}
req.RequestURI = ""
copyHeader(req.Header, r.Header)
delConnectionHeaders(req.Header)
delHopHeaders(req.Header)
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
appendHostToXForwardHeader(req.Header, clientIP)
}
var resp *http.Response
var chunked bool
var respBodySaved []byte
if network.IsLocalAddress(r.Host) {
resp = p.doReq(w, req, nil)
} else {
_, sockClient, err := p.getSocks()
if err != nil {
p.logger.Error().Err(err).Msg("Failed getting SOCKS5 client")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
resp = p.doReq(w, req, sockClient)
}
if resp == nil {
return
}
chunked = slices.Contains(resp.TransferEncoding, "chunked")
if p.sniff {
if p.body {
if chunked {
buf := make([]byte, maxBodySize)
n, _ := resp.Body.Read(buf)
respBodySaved = buf[:n]
resp.Body = io.NopCloser(io.MultiReader(bytes.NewReader(buf[:n]), resp.Body))
} else {
respBodySaved, _ = io.ReadAll(io.LimitReader(resp.Body, maxBodySize))
resp.Body = io.NopCloser(io.MultiReader(bytes.NewReader(respBodySaved), resp.Body))
}
if resp.Header.Get("Content-Encoding") == "gzip" {
gzr, err := gzip.NewReader(bytes.NewReader(respBodySaved))
if err == nil {
respBodySaved, _ = io.ReadAll(gzr)
}
}
reqBodySaved = bytes.Trim(reqBodySaved, "\r\n\t ")
respBodySaved = bytes.Trim(respBodySaved, "\r\n\t ")
}
if p.json {
sniffdata := make([]string, 0, 4)
j, err := json.Marshal(&layers.HTTPMessage{Request: r})
if err == nil {
sniffdata = append(sniffdata, string(j))
}
j, err = json.Marshal(&layers.HTTPMessage{Response: resp})
if err == nil {
sniffdata = append(sniffdata, string(j))
}
if p.body && len(reqBodySaved) > 0 {
sniffdata = append(sniffdata, fmt.Sprintf("{\"req_body\":%s}", reqBodySaved))
}
if p.body && len(respBodySaved) > 0 {
sniffdata = append(sniffdata, fmt.Sprintf("{\"resp_body\":%s}", respBodySaved))
}
p.snifflogger.Log().Msg(fmt.Sprintf("[%s]", strings.Join(sniffdata, ",")))
} else {
id := getID(p.nocolor)
p.snifflogger.Log().Msg(colorizeHTTP(req, resp, &reqBodySaved, &respBodySaved, id, false, p.body, p.nocolor))
}
}
defer resp.Body.Close()
done := make(chan bool)
if chunked {
rc := http.NewResponseController(w)
go func() {
for {
select {
case <-time.Tick(flushTimeout):
err := rc.Flush()
if err != nil {
p.logger.Error().Err(err).Msg("Failed flushing buffer")
return
}
err = rc.SetReadDeadline(time.Now().Add(readTimeout))
if err != nil {
p.logger.Error().Err(err).Msg("Failed setting read deadline")
return