forked from SenseUnit/dumbproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1122 lines (1044 loc) · 33.9 KB
/
main.go
File metadata and controls
1122 lines (1044 loc) · 33.9 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 main
import (
"bytes"
"context"
"crypto/tls"
"encoding/csv"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/http"
"net/http/pprof"
"net/netip"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/coreos/go-systemd/v22/activation"
"github.com/libp2p/go-reuseport"
"github.com/things-go/go-socks5"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/crypto/bcrypt"
"github.com/SenseUnit/dumbproxy/access"
"github.com/SenseUnit/dumbproxy/auth"
"github.com/SenseUnit/dumbproxy/certcache"
"github.com/SenseUnit/dumbproxy/dialer"
"github.com/SenseUnit/dumbproxy/forward"
"github.com/SenseUnit/dumbproxy/handler"
clog "github.com/SenseUnit/dumbproxy/log"
"github.com/SenseUnit/dumbproxy/resolver"
"github.com/SenseUnit/dumbproxy/tlsutil"
proxyproto "github.com/pires/go-proxyproto"
_ "golang.org/x/crypto/x509roots/fallback"
)
var home, _ = os.UserHomeDir()
func perror(msg string) {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, msg)
}
func arg_fail(msg string) {
perror(msg)
perror("Usage:")
flag.PrintDefaults()
os.Exit(2)
}
type CSVArg struct {
values []string
}
func (a *CSVArg) String() string {
if len(a.values) == 0 {
return ""
}
buf := new(bytes.Buffer)
wr := csv.NewWriter(buf)
wr.Write(a.values)
wr.Flush()
return strings.TrimRight(buf.String(), "\n")
}
func (a *CSVArg) Set(line string) error {
if line == "" {
a.values = nil
return nil
}
rd := csv.NewReader(strings.NewReader(line))
rd.FieldsPerRecord = -1
rd.TrimLeadingSpace = true
rd.ReuseRecord = true
values, err := rd.Read()
if err == io.EOF {
a.values = nil
return nil
}
if err != nil {
return fmt.Errorf("unable to parse comma-separated argument: %w", err)
}
a.values = values
return nil
}
type PrefixList []netip.Prefix
func (l *PrefixList) Set(s string) error {
var pfxList []netip.Prefix
parts := strings.Split(s, ",")
for i, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
continue
}
pfx, err := netip.ParsePrefix(part)
if err != nil {
return fmt.Errorf("unable to parse prefix list element %d (%q): %w", i, part, err)
}
pfxList = append(pfxList, pfx)
}
*l = PrefixList(pfxList)
return nil
}
func (l *PrefixList) String() string {
if l == nil || *l == nil {
return ""
}
parts := make([]string, 0, len([]netip.Prefix(*l)))
for _, part := range []netip.Prefix(*l) {
parts = append(parts, part.String())
}
return strings.Join(parts, ", ")
}
func (l *PrefixList) Value() []netip.Prefix {
return []netip.Prefix(*l)
}
type TLSVersionArg uint16
func (a *TLSVersionArg) Set(s string) error {
ver, err := tlsutil.ParseVersion(s)
if err != nil {
return err
}
*a = TLSVersionArg(ver)
return nil
}
func (a *TLSVersionArg) String() string {
return tlsutil.FormatVersion(uint16(*a))
}
type proxyArg struct {
literal bool
value string
}
type hexArg struct {
value []byte
}
func (a *hexArg) String() string {
return hex.EncodeToString(a.value)
}
func (a *hexArg) Set(s string) error {
b, err := hex.DecodeString(s)
if err != nil {
return err
}
a.value = b
return nil
}
func (a *hexArg) Value() []byte {
return a.value
}
type modeArg fs.FileMode
func (a *modeArg) String() string {
return fmt.Sprintf("%#o", uint32(*a))
}
func (a *modeArg) Set(s string) error {
p, err := strconv.ParseUint(s, 8, 32)
if err != nil {
return err
}
*a = modeArg(p)
return nil
}
func (a *modeArg) Value() fs.FileMode {
return fs.FileMode(*a)
}
type cacheKind int
const (
cacheKindDir cacheKind = iota
cacheKindRedis
cacheKindRedisCluster
)
type autocertCache struct {
kind cacheKind
value string
}
type proxyMode int
const (
_ proxyMode = iota
proxyModeHTTP
proxyModeSOCKS5
proxyModeStdIO
proxyModePortForward
)
type proxyModeArg struct {
value proxyMode
}
func (a *proxyModeArg) Set(arg string) error {
var val proxyMode
switch s := strings.ToLower(arg); s {
case "http", "https":
val = proxyModeHTTP
case "socks", "socks5":
val = proxyModeSOCKS5
case "stdio":
val = proxyModeStdIO
case "port-forward":
val = proxyModePortForward
default:
return fmt.Errorf("unrecognized proxy mode %q", arg)
}
a.value = val
return nil
}
func (a *proxyModeArg) String() string {
switch a.value {
case proxyModeHTTP:
return "http"
case proxyModeSOCKS5:
return "socks5"
case proxyModeStdIO:
return "stdio"
case proxyModePortForward:
return "port-forward"
default:
return fmt.Sprintf("proxyMode(%d)", int(a.value))
}
}
const envCacheEncKey = "DUMBPROXY_CACHE_ENC_KEY"
type dnsPreferenceArg resolver.Preference
func (a *dnsPreferenceArg) String() string {
return resolver.Preference(*a).String()
}
func (a *dnsPreferenceArg) Set(s string) error {
p, err := resolver.ParsePreference(s)
if err != nil {
return nil
}
*a = dnsPreferenceArg(p)
return nil
}
func (a *dnsPreferenceArg) Value() resolver.Preference {
return resolver.Preference(*a)
}
type bindSpec struct {
af string
address string
}
type CLIArgs struct {
bind bindSpec
bindReusePort bool
bindPprof bindSpec
unixSockUnlink bool
unixSockMode modeArg
mode proxyModeArg
auth string
verbosity int
cert, key, cafile string
list_ciphers bool
list_curves bool
ciphers string
curves string
disableHTTP2 bool
showVersion bool
autocert bool
autocertWhitelist CSVArg
autocertCache autocertCache
autocertCacheRedisPrefix string
autocertACME string
autocertEmail string
autocertHTTP string
autocertLocalCacheTTL time.Duration
autocertCacheEncKey hexArg
passwd string
passwdCost int
hmacSign bool
hmacGenKey bool
positionalArgs []string
proxy []proxyArg
sourceIPHints string
userIPHints bool
minTLSVersion TLSVersionArg
maxTLSVersion TLSVersionArg
tlsALPNEnabled bool
tlsSessionKeys [][32]byte
tlsCookies bool
tlsSessionCacheDB string
bwLimit forward.LimitSpec
bwBurst int64
bwSeparate bool
dnsServers []string
dnsPreferAddress dnsPreferenceArg
dnsCacheTTL time.Duration
dnsCacheNegTTL time.Duration
dnsCacheTimeout time.Duration
reqHeaderTimeout time.Duration
denyDstAddr PrefixList
jsAccessFilter string
jsAccessFilterInstances int
jsProxyRouterInstances int
jsBWLimitInstances int
proxyproto bool
tt bool
shutdownTimeout time.Duration
}
func parse_args() *CLIArgs {
args := &CLIArgs{
minTLSVersion: TLSVersionArg(tls.VersionTLS12),
maxTLSVersion: TLSVersionArg(tls.VersionTLS13),
denyDstAddr: PrefixList{
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("0.0.0.0/32"),
netip.MustParsePrefix("10.0.0.0/8"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("169.254.0.0/16"),
netip.MustParsePrefix("::1/128"),
netip.MustParsePrefix("::/128"),
netip.MustParsePrefix("fe80::/10"),
},
autocertCache: autocertCache{
kind: cacheKindDir,
value: filepath.Join(home, ".dumbproxy", "autocert"),
},
bind: bindSpec{
address: ":8080",
af: "tcp",
},
mode: proxyModeArg{proxyModeHTTP},
dnsPreferAddress: dnsPreferenceArg(resolver.PreferenceIPv4),
}
args.autocertCacheEncKey.Set(os.Getenv(envCacheEncKey))
flag.Func("bind-address", "HTTP proxy listen address. Set empty value to use systemd socket activation. (default \":8080\")", func(p string) error {
args.bind.address = p
args.bind.af = "tcp"
return nil
})
flag.Func("bind-unix-socket", "Unix domain socket to listen to, overrides bind-address if set.", func(p string) error {
args.bind.address = p
args.bind.af = "unix"
return nil
})
flag.BoolVar(&args.bindReusePort, "bind-reuseport", false, "allow multiple server instances on the same port")
flag.Func("bind-pprof", "enables pprof debug endpoints", func(p string) error {
args.bindPprof.address = p
args.bindPprof.af = "tcp"
return nil
})
flag.Func("bind-pprof-unix-socket", "enables pprof debug endpoints listening on Unix domain socket", func(p string) error {
args.bindPprof.address = p
args.bindPprof.af = "unix"
return nil
})
flag.BoolVar(&args.unixSockUnlink, "unix-sock-unlink", true, "delete file object located at Unix domain socket bind path before binding")
flag.Var(&args.unixSockMode, "unix-sock-mode", "set file mode for bound unix socket")
flag.Var(&args.mode, "mode", "proxy operation mode (http/socks5/stdio/port-forward)")
flag.StringVar(&args.auth, "auth", "none://", "auth parameters")
flag.IntVar(&args.verbosity, "verbosity", 20, "logging verbosity "+
"(10 - debug, 20 - info, 30 - warning, 40 - error, 50 - critical)")
flag.StringVar(&args.cert, "cert", "", "enable TLS and use certificate")
flag.StringVar(&args.key, "key", "", "key for TLS certificate")
flag.StringVar(&args.cafile, "cafile", "", "CA file to authenticate clients with certificates")
flag.BoolVar(&args.list_ciphers, "list-ciphers", false, "list ciphersuites")
flag.BoolVar(&args.list_curves, "list-curves", false, "list key exchange curves")
flag.StringVar(&args.ciphers, "ciphers", "", "colon-separated list of enabled ciphers")
flag.StringVar(&args.curves, "curves", "", "colon-separated list of enabled key exchange curves")
flag.BoolVar(&args.disableHTTP2, "disable-http2", false, "disable HTTP2")
flag.BoolVar(&args.showVersion, "version", false, "show program version and exit")
flag.BoolVar(&args.autocert, "autocert", false, "issue TLS certificates automatically")
flag.Var(&args.autocertWhitelist, "autocert-whitelist", "restrict autocert domains to this comma-separated list")
flag.Func("autocert-dir", "use directory path for autocert cache", func(p string) error {
args.autocertCache = autocertCache{
kind: cacheKindDir,
value: p,
}
return nil
})
flag.Func("autocert-cache-redis", "use Redis URL for autocert cache", func(p string) error {
args.autocertCache = autocertCache{
kind: cacheKindRedis,
value: p,
}
return nil
})
flag.Func("autocert-cache-redis-cluster", "use Redis Cluster URL for autocert cache", func(p string) error {
args.autocertCache = autocertCache{
kind: cacheKindRedisCluster,
value: p,
}
return nil
})
flag.StringVar(&args.autocertCacheRedisPrefix, "autocert-cache-redis-prefix", "", "prefix to use for keys in Redis or Redis Cluster cache")
flag.Var(&args.autocertCacheEncKey, "autocert-cache-enc-key", "hex-encoded encryption key for cert cache entries. Can be also set with "+envCacheEncKey+" environment variable")
flag.StringVar(&args.autocertACME, "autocert-acme", autocert.DefaultACMEDirectory, "custom ACME endpoint")
flag.StringVar(&args.autocertEmail, "autocert-email", "", "email used for ACME registration")
flag.StringVar(&args.autocertHTTP, "autocert-http", "", "listen address for HTTP-01 challenges handler of ACME")
flag.DurationVar(&args.autocertLocalCacheTTL, "autocert-local-cache-ttl", 0, "enables in-memory cache for certificates")
flag.StringVar(&args.passwd, "passwd", "", "update given htpasswd file and add/set password for username. "+
"Username and password can be passed as positional arguments or requested interactively")
flag.IntVar(&args.passwdCost, "passwd-cost", bcrypt.MinCost, "bcrypt password cost (for -passwd mode)")
flag.BoolVar(&args.hmacSign, "hmac-sign", false, "sign username with specified key for given validity period. "+
"Positional arguments are: hex-encoded HMAC key, username, validity duration.")
flag.BoolVar(&args.hmacGenKey, "hmac-genkey", false, "generate hex-encoded HMAC signing key of optimal length")
flag.Func("proxy", "upstream proxy URL. Can be repeated multiple times to chain proxies. Examples: socks5h://127.0.0.1:9050; https://user:password@example.com:443", func(p string) error {
args.proxy = append(args.proxy, proxyArg{true, p})
return nil
})
flag.StringVar(&args.sourceIPHints, "ip-hints", "", "a comma-separated list of source addresses to use on dial attempts. \"$lAddr\" gets expanded to local address of connection. Example: \"10.0.0.1,fe80::2,$lAddr,0.0.0.0,::\"")
flag.BoolVar(&args.userIPHints, "user-ip-hints", false, "allow IP hints to be specified by user in X-Src-IP-Hints header")
flag.Var(&args.minTLSVersion, "min-tls-version", "minimum TLS version accepted by server")
flag.Var(&args.maxTLSVersion, "max-tls-version", "maximum TLS version accepted by server")
flag.BoolVar(&args.tlsALPNEnabled, "tls-alpn-enabled", true, "enable application protocol negotiation with TLS ALPN extension")
flag.Func("bw-limit", "per-user bandwidth limit in bytes per second", func(p string) error {
num, err := strconv.ParseUint(p, 10, 64)
if err != nil {
return err
}
args.bwLimit = forward.LimitSpec{
Kind: forward.LimitKindStatic,
Spec: forward.StaticLimitSpec{
BPS: num,
},
}
return nil
})
flag.Func("js-bw-limit", "path to JS script with \"bwLimit\" function. Overrides every other BW limit option", func(p string) error {
args.bwLimit = forward.LimitSpec{
Kind: forward.LimitKindJS,
Spec: forward.JSLimitSpec{
Filename: p,
},
}
return nil
})
flag.Int64Var(&args.bwBurst, "bw-limit-burst", 0, "allowed burst size for bandwidth limit, how many \"tokens\" can fit into leaky bucket")
flag.BoolVar(&args.bwSeparate, "bw-limit-separate", false, "separate upload and download bandwidth limits")
flag.Func("dns-server", "nameserver specification (udp://..., tcp://..., https://..., tls://..., doh://..., dot://..., default://). Option can be used multiple times for parallel use of multiple nameservers. Empty string resets the list", func(p string) error {
if p == "" {
args.dnsServers = nil
} else {
args.dnsServers = append(args.dnsServers, p)
}
return nil
})
flag.Var(&args.dnsPreferAddress, "dns-prefer-address", "address resolution preference (none/ipv4/ipv6)")
flag.DurationVar(&args.dnsCacheTTL, "dns-cache-ttl", 0, "enable DNS cache with specified fixed TTL")
flag.DurationVar(&args.dnsCacheNegTTL, "dns-cache-neg-ttl", time.Second, "TTL for negative responses of DNS cache")
flag.DurationVar(&args.dnsCacheTimeout, "dns-cache-timeout", 5*time.Second, "timeout for shared resolves of DNS cache")
flag.DurationVar(&args.reqHeaderTimeout, "req-header-timeout", 30*time.Second, "amount of time allowed to read request headers")
flag.Var(&args.denyDstAddr, "deny-dst-addr", "comma-separated list of CIDR prefixes of forbidden IP addresses")
flag.StringVar(&args.jsAccessFilter, "js-access-filter", "", "path to JS script file with the \"access\" filter function")
flag.IntVar(&args.jsAccessFilterInstances, "js-access-filter-instances", runtime.GOMAXPROCS(0), "number of JS VM instances to handle access filter requests")
flag.IntVar(&args.jsProxyRouterInstances, "js-proxy-router-instances", runtime.GOMAXPROCS(0), "number of JS VM instances to handle proxy router requests")
flag.IntVar(&args.jsProxyRouterInstances, "js-bw-limit-instances", runtime.GOMAXPROCS(0), "number of JS VM instances to handle requests for BW limit parameters")
flag.Func("js-proxy-router", "path to JS script file with the \"getProxy\" function", func(p string) error {
args.proxy = append(args.proxy, proxyArg{false, p})
return nil
})
flag.BoolVar(&args.proxyproto, "proxyproto", false, "listen proxy protocol")
flag.BoolVar(&args.tt, "trusttunnel", true, "enable TrustTunnel protocol extensions")
flag.DurationVar(&args.shutdownTimeout, "shutdown-timeout", 1*time.Second, "grace period during server shutdown")
flag.Func("tls-session-key", "override TLS server session keys. Key must be provided as hex-encoded 32-byte string. "+
"This option can be repeated multiple times, first key will be used to create session tickets. Empty value resets the list.", func(p string) error {
if len(p) == 0 {
args.tlsSessionKeys = nil
return nil
}
key, err := hex.DecodeString(p)
if err != nil {
return fmt.Errorf("unable to hex-decode TLS session key: %w", err)
}
if len(key) != 32 {
return fmt.Errorf("provided session key has length %d instead of 32", len(key))
}
args.tlsSessionKeys = append(args.tlsSessionKeys, [32]byte(key))
return nil
})
flag.BoolVar(&args.tlsCookies, "tls-cookies", true, "mark TLS sessions with cookie-like unique session IDs")
flag.StringVar(&args.tlsSessionCacheDB, "tls-session-cache-db", "", "location of TLS client session cache DB")
flag.Func("config", "read configuration from file with space-separated keys and values", readConfig)
flag.Parse()
// pull up remaining parameters from other BW-related arguments
switch args.bwLimit.Kind {
case forward.LimitKindNone:
case forward.LimitKindStatic:
o := args.bwLimit.Spec.(forward.StaticLimitSpec)
args.bwLimit.Spec = forward.StaticLimitSpec{
BPS: o.BPS,
Burst: args.bwBurst,
Separate: args.bwSeparate,
}
case forward.LimitKindJS:
o := args.bwLimit.Spec.(forward.JSLimitSpec)
args.bwLimit.Spec = forward.JSLimitSpec{
Filename: o.Filename,
Instances: args.jsBWLimitInstances,
}
default:
panic("unexpected BW limit kind in arg parse")
}
args.positionalArgs = flag.Args()
return args
}
func run() int {
args := parse_args()
// handle special invocation modes
if args.showVersion {
fmt.Println(version())
return 0
}
if args.list_ciphers {
list_ciphers()
return 0
}
if args.list_curves {
list_curves()
return 0
}
if args.passwd != "" {
if err := passwd(args.passwd, args.passwdCost, args.positionalArgs...); err != nil {
log.Fatalf("can't set password: %v", err)
}
return 0
}
if args.hmacSign {
if err := hmacSign(args.positionalArgs...); err != nil {
log.Fatalf("can't sign: %v", err)
}
return 0
}
if args.hmacGenKey {
if err := hmacGenKey(); err != nil {
log.Fatalf("can't generate key: %v", err)
}
return 0
}
switch args.mode.value {
case proxyModeStdIO, proxyModePortForward:
// expect exactly two positional arguments
if len(args.positionalArgs) != 2 {
arg_fail("Exactly two positional arguments are expected in this mode: host and port")
}
default:
// we don't expect positional arguments in the main operation mode
if len(args.positionalArgs) > 0 {
arg_fail("Unexpected positional arguments! Check your command line.")
}
}
// setup logging
logWriter := clog.NewLogWriter(os.Stderr, 128)
defer func() {
ctx, cl := context.WithTimeout(context.Background(), 1*time.Second)
defer cl()
logWriter.Close(ctx)
}()
mainLogger := clog.NewCondLogger(log.New(logWriter, "MAIN : ",
log.LstdFlags|log.Lshortfile),
args.verbosity)
proxyLogger := clog.NewCondLogger(log.New(logWriter, "PROXY : ",
log.LstdFlags|log.Lshortfile),
args.verbosity)
authLogger := clog.NewCondLogger(log.New(logWriter, "AUTH : ",
log.LstdFlags|log.Lshortfile),
args.verbosity)
jsAccessLogger := clog.NewCondLogger(log.New(logWriter, "JSACCESS: ",
log.LstdFlags|log.Lshortfile),
args.verbosity)
jsRouterLogger := clog.NewCondLogger(log.New(logWriter, "JSROUTER: ",
log.LstdFlags|log.Lshortfile),
args.verbosity)
jsLimitLogger := clog.NewCondLogger(log.New(logWriter, "JSLIMIT :",
log.LstdFlags|log.Lshortfile),
args.verbosity)
ttDemuxLogger := clog.NewCondLogger(log.New(logWriter, "TTDEMUX :",
log.LstdFlags|log.Lshortfile),
args.verbosity)
tlsSessionLogger := clog.NewCondLogger(log.New(logWriter, "TLSSESS :",
log.LstdFlags|log.Lshortfile),
args.verbosity)
tlsCacheLogger := clog.NewCondLogger(log.New(logWriter, "TLSCACHE:",
log.LstdFlags|log.Lshortfile),
args.verbosity)
// setup TLS session cache
if args.tlsSessionCacheDB != "" {
cache, err := tlsutil.NewPersistentClientSessionCache(args.tlsSessionCacheDB, tlsCacheLogger)
if err != nil {
mainLogger.Critical("Failed to instantiate TLS session cache: %v", err)
return 3
}
tlsutil.SessionCache = cache
}
// setup auth provider
authProvider, err := auth.NewAuth(args.auth, authLogger)
if err != nil {
mainLogger.Critical("Failed to instantiate auth provider: %v", err)
return 3
}
defer authProvider.Close()
// setup access filters
var filterRoot access.Filter = access.AlwaysAllow{}
if args.jsAccessFilter != "" {
j, err := access.NewJSFilter(
args.jsAccessFilter,
args.jsAccessFilterInstances,
jsAccessLogger,
filterRoot,
)
if err != nil {
mainLogger.Critical("Failed to run JS filter: %v", err)
return 3
}
filterRoot = j
}
if len(args.denyDstAddr.Value()) > 0 {
filterRoot = access.NewDstAddrFilter(args.denyDstAddr.Value(), filterRoot)
}
// construct dialers
var dialerRoot dialer.Dialer = dialer.NewBoundDialer(new(net.Dialer), args.sourceIPHints)
if len(args.proxy) > 0 {
for _, proxy := range args.proxy {
if proxy.literal {
newDialer, err := dialer.ProxyDialerFromURL(proxy.value, dialerRoot)
if err != nil {
mainLogger.Critical("Failed to create dialer for proxy %q: %v", proxy.value, err)
return 3
}
dialerRoot = newDialer
} else {
newDialer, err := dialer.NewJSRouter(
proxy.value,
args.jsProxyRouterInstances,
func(root dialer.Dialer) func(url string) (dialer.Dialer, error) {
return func(url string) (dialer.Dialer, error) {
return dialer.ProxyDialerFromURL(url, root)
}
}(dialerRoot),
jsRouterLogger,
dialerRoot,
)
if err != nil {
mainLogger.Critical("Failed to create JS proxy router: %v", err)
return 3
}
dialerRoot = newDialer
}
}
}
dialerRoot = dialer.NewFilterDialer(filterRoot.Access, dialerRoot) // must follow after resolving in chain
var nameResolver dialer.Resolver = net.DefaultResolver
if len(args.dnsServers) > 0 {
nameResolver, err = resolver.FastFromURLs(args.dnsServers...)
if err != nil {
mainLogger.Critical("Failed to create name resolver: %v", err)
return 3
}
}
nameResolver = resolver.Prefer(nameResolver, args.dnsPreferAddress.Value())
if args.dnsCacheTTL > 0 {
dialerRoot = dialer.NewNameResolveCachingDialer(
dialerRoot,
nameResolver,
args.dnsCacheTTL,
args.dnsCacheNegTTL,
args.dnsCacheTimeout,
)
} else {
dialerRoot = dialer.NewNameResolvingDialer(dialerRoot, nameResolver)
}
// unholy plug
if args.tt {
dialerRoot = dialer.NewTTInterceptor(dialerRoot, ttDemuxLogger)
}
// handler requisites
forwarder := forward.PairConnections
if args.bwLimit.Kind != forward.LimitKindNone {
limitProvider, err := forward.ProviderFromSpec(args.bwLimit, jsLimitLogger)
if err != nil {
mainLogger.Critical("Failed to create BW limit parameters provider: %v", err)
return 3
}
forwarder = forward.NewBWLimit(limitProvider).PairConnections
}
stopContext, _ := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
mainLogger.Info("Starting proxy server...")
listenerFactory := net.Listen
switch {
case args.mode.value == proxyModeStdIO:
listenerFactory = handler.DummyListen
case args.bindReusePort:
if reuseport.Available() {
listenerFactory = reuseport.Listen
} else {
mainLogger.Warning("reuseport was requested but not available!")
}
}
if args.unixSockUnlink {
listenerFactory = func(orig func(string, string) (net.Listener, error)) func(string, string) (net.Listener, error) {
return func(network, address string) (net.Listener, error) {
if (network == "unix" || network == "unixdgram") && len(address) > 0 && address[0] != '@' {
os.Remove(address)
}
return orig(network, address)
}
}(listenerFactory)
}
if args.unixSockMode != 0 {
listenerFactory = func(orig func(string, string) (net.Listener, error)) func(string, string) (net.Listener, error) {
return func(network, address string) (net.Listener, error) {
if (network == "unix" || network == "unixdgram") && len(address) > 0 && address[0] != '@' {
defer os.Chmod(address, args.unixSockMode.Value())
}
return orig(network, address)
}
}(listenerFactory)
}
var listener net.Listener
if args.bind.address == "" {
// socket activation
listeners, err := activation.Listeners()
if err != nil {
mainLogger.Critical("socket activation failed: %v", err)
return 3
}
if len(listeners) != 1 {
mainLogger.Critical("socket activation failed: unexpected number of listeners: %d",
len(listeners))
return 3
}
if listeners[0] == nil {
mainLogger.Critical("socket activation failed: nil listener returned")
return 3
}
listener = listeners[0]
} else {
newListener, err := listenerFactory(args.bind.af, args.bind.address)
if err != nil {
mainLogger.Critical("listen failed: %v", err)
return 3
}
listener = newListener
}
if args.proxyproto {
mainLogger.Info("Listening proxy protocol")
listener = &proxyproto.Listener{Listener: listener}
}
if args.cert != "" {
cfg, err1 := makeServerTLSConfig(args, tlsSessionLogger)
if err1 != nil {
mainLogger.Critical("TLS config construction failed: %v", err1)
return 3
}
listener = tlsutil.NewTaggedConnListener(listener) // attach DTO container
listener = tls.NewListener(listener, cfg)
} else if args.autocert {
// cert caching chain
var certCache autocert.Cache
switch args.autocertCache.kind {
case cacheKindDir:
certCache = autocert.DirCache(args.autocertCache.value)
case cacheKindRedis:
certCache, err = certcache.RedisCacheFromURL(args.autocertCache.value, args.autocertCacheRedisPrefix)
if err != nil {
mainLogger.Critical("redis cache construction failed: %v", err)
return 3
}
case cacheKindRedisCluster:
certCache, err = certcache.RedisClusterCacheFromURL(args.autocertCache.value, args.autocertCacheRedisPrefix)
if err != nil {
mainLogger.Critical("redis cluster cache construction failed: %v", err)
return 3
}
default:
mainLogger.Critical("unknown cert cache type %#v", args.autocertCache.kind)
return 3
}
if len(args.autocertCacheEncKey.Value()) > 0 {
certCache, err = certcache.NewEncryptedCache(args.autocertCacheEncKey.Value(), certCache)
if err != nil {
mainLogger.Critical("unable to construct cache encryption layer: %v", err)
return 3
}
}
if args.autocertLocalCacheTTL > 0 {
lcc := certcache.NewLocalCertCache(
certCache,
args.autocertLocalCacheTTL,
)
certCache = lcc
}
if cacheCloser, ok := certCache.(io.Closer); ok {
defer cacheCloser.Close()
}
m := &autocert.Manager{
Cache: certCache,
Prompt: autocert.AcceptTOS,
Client: &acme.Client{DirectoryURL: args.autocertACME},
Email: args.autocertEmail,
}
if args.autocertWhitelist.values != nil {
m.HostPolicy = autocert.HostWhitelist(args.autocertWhitelist.values...)
}
if args.autocertHTTP != "" {
go func() {
mainLogger.Critical("HTTP-01 ACME challenge server stopped: %v",
http.ListenAndServe(args.autocertHTTP, m.HTTPHandler(nil)))
}()
}
cfg, err := makeServerTLSConfig(args, tlsSessionLogger)
if err != nil {
mainLogger.Critical("TLS config construction failed: %v", err)
return 3
}
cfg.GetCertificate = m.GetCertificate
if len(cfg.NextProtos) > 0 {
cfg.NextProtos = append(cfg.NextProtos, acme.ALPNProto)
}
listener = tlsutil.NewTaggedConnListener(listener) // attach DTO container
listener = tls.NewListener(listener, cfg)
}
defer listener.Close()
// debug endpoints setup
if args.bindPprof.address != "" {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
pprofListener, err := listenerFactory(args.bindPprof.af, args.bindPprof.address)
if err == nil {
go func() { log.Fatal(http.Serve(pprofListener, mux)) }()
}
}
mainLogger.Info("Proxy server started.")
switch args.mode.value {
case proxyModeHTTP:
server := http.Server{
Handler: handler.NewProxyHandler(&handler.Config{
Dialer: dialerRoot,
Auth: authProvider,
Logger: proxyLogger,
UserIPHints: args.userIPHints,
Forward: forwarder,
}),
ErrorLog: log.New(logWriter, "HTTPSRV : ", log.LstdFlags|log.Lshortfile),
ReadTimeout: 0,
ReadHeaderTimeout: args.reqHeaderTimeout,
WriteTimeout: 0,
IdleTimeout: 0,
Protocols: new(http.Protocols),
BaseContext: func(_ net.Listener) context.Context {
return stopContext
},
ConnContext: func(ctx context.Context, conn net.Conn) context.Context {
return tlsutil.TLSSessionIDToContext(ctx, conn)
},
}
if args.disableHTTP2 {
server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
server.Protocols.SetHTTP1(true)
} else {
server.Protocols.SetHTTP1(true)
server.Protocols.SetHTTP2(true)
server.Protocols.SetUnencryptedHTTP2(true)
}
shutdownComplete := make(chan struct{})
go func() {
<-stopContext.Done()
mainLogger.Info("Shutting down...")
shutdownContext, cl := context.WithTimeout(context.Background(), args.shutdownTimeout)
defer cl()
server.Shutdown(shutdownContext)
close(shutdownComplete)
}()
// setup done
if err := server.Serve(listener); err == http.ErrServerClosed {
// need to wait shutdown to exit
<-shutdownComplete
mainLogger.Info("Reached normal server termination.")
} else {
mainLogger.Critical("Server terminated with a reason: %v", err)
}
return 0
case proxyModeSOCKS5:
opts := []socks5.Option{
socks5.WithLogger(socks5.NewLogger(log.New(logWriter, "SOCKSSRV: ", log.LstdFlags|log.Lshortfile))),
socks5.WithRule(
&socks5.PermitCommand{
EnableConnect: true,
},
),
socks5.WithConnectHandle(
handler.SOCKSHandler(
dialerRoot,
proxyLogger,
forwarder,
),
),
socks5.WithResolver(handler.DummySocksResolver{}),
}
switch cs := authProvider.(type) {
case auth.NoAuth:
// pass, authentication is not needed
case socks5.CredentialStore:
opts = append(opts, socks5.WithCredential(cs))
default:
mainLogger.Critical("Chosen authentication method is not supported by this proxy operation mode.")
return 2
}
go func() {
<-stopContext.Done()
mainLogger.Info("Shutting down...")
listener.Close()
}()
server := socks5.NewServer(opts...)
if err := server.Serve(listener); err != nil {
if errors.Is(err, net.ErrClosed) {
mainLogger.Info("Reached normal server termination.")
return 0
} else {
mainLogger.Critical("Server failure: %v", err)
return 1
}
}
mainLogger.Info("Reached normal server termination.")
return 0
case proxyModeStdIO:
handler := handler.StdIOHandler(dialerRoot, proxyLogger, forwarder)
address := net.JoinHostPort(args.positionalArgs[0], args.positionalArgs[1])
if err := handler(stopContext, os.Stdin, os.Stdout, address); err != nil {
mainLogger.Error("Connection interrupted: %v", err)
}
return 0
case proxyModePortForward:
logger := clog.NewCondLogger(log.New(logWriter, "PORT-FWD: ",
log.LstdFlags|log.Lshortfile),
args.verbosity)