-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.go
480 lines (436 loc) · 12.9 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
package main
import (
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/coreos/go-systemd/v22/activation"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/ssh/terminal"
"github.com/SenseUnit/dumbproxy/auth"
"github.com/SenseUnit/dumbproxy/dialer"
"github.com/SenseUnit/dumbproxy/handler"
clog "github.com/SenseUnit/dumbproxy/log"
)
var (
home, _ = os.UserHomeDir()
version = "undefined"
)
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 []string
func (a *CSVArg) Set(s string) error {
*a = strings.Split(s, ",")
return nil
}
func (a *CSVArg) String() string {
if a == nil {
return "<nil>"
}
if *a == nil {
return "<empty>"
}
return strings.Join(*a, ",")
}
type TLSVersionArg uint16
func (a *TLSVersionArg) Set(s string) error {
var ver uint16
switch strings.ToUpper(s) {
case "TLS10":
ver = tls.VersionTLS10
case "TLS11":
ver = tls.VersionTLS11
case "TLS12":
ver = tls.VersionTLS12
case "TLS13":
ver = tls.VersionTLS13
case "TLS1.0":
ver = tls.VersionTLS10
case "TLS1.1":
ver = tls.VersionTLS11
case "TLS1.2":
ver = tls.VersionTLS12
case "TLS1.3":
ver = tls.VersionTLS13
case "10":
ver = tls.VersionTLS10
case "11":
ver = tls.VersionTLS11
case "12":
ver = tls.VersionTLS12
case "13":
ver = tls.VersionTLS13
case "1.0":
ver = tls.VersionTLS10
case "1.1":
ver = tls.VersionTLS11
case "1.2":
ver = tls.VersionTLS12
case "1.3":
ver = tls.VersionTLS13
case "":
default:
return fmt.Errorf("unknown TLS version %q", s)
}
*a = TLSVersionArg(ver)
return nil
}
func (a *TLSVersionArg) String() string {
switch *a {
case tls.VersionTLS10:
return "TLS10"
case tls.VersionTLS11:
return "TLS11"
case tls.VersionTLS12:
return "TLS12"
case tls.VersionTLS13:
return "TLS13"
default:
return fmt.Sprintf("%#04x", *a)
}
}
type CLIArgs struct {
bind_address string
auth string
verbosity int
timeout time.Duration
cert, key, cafile string
list_ciphers bool
ciphers string
disableHTTP2 bool
showVersion bool
autocert bool
autocertWhitelist CSVArg
autocertDir string
autocertACME string
autocertEmail string
autocertHTTP string
passwd string
passwdCost int
positionalArgs []string
proxy []string
sourceIPHints string
userIPHints bool
minTLSVersion TLSVersionArg
maxTLSVersion TLSVersionArg
}
func parse_args() CLIArgs {
args := CLIArgs{
minTLSVersion: TLSVersionArg(tls.VersionTLS12),
maxTLSVersion: TLSVersionArg(tls.VersionTLS13),
}
flag.StringVar(&args.bind_address, "bind-address", ":8080", "HTTP proxy listen address. Set empty value to use systemd socket activation.")
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.DurationVar(&args.timeout, "timeout", 10*time.Second, "timeout for network operations")
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.StringVar(&args.ciphers, "ciphers", "", "colon-separated list of enabled ciphers")
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.StringVar(&args.autocertDir, "autocert-dir", filepath.Join(home, ".dumbproxy", "autocert"), "path to autocert cache")
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.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.Func("proxy", "upstream proxy URL. Can be repeated multiple times to chain proxies. Examples: socks5h://127.0.0.1:9050; https://user:[email protected]:443", func(p string) error {
args.proxy = append(args.proxy, 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", "minimal TLS version accepted by server")
flag.Var(&args.maxTLSVersion, "max-tls-version", "maximum TLS version accepted by server")
flag.Parse()
args.positionalArgs = flag.Args()
return args
}
func run() int {
args := parse_args()
if args.showVersion {
fmt.Println(version)
return 0
}
if args.list_ciphers {
list_ciphers()
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
}
logWriter := clog.NewLogWriter(os.Stderr)
defer logWriter.Close()
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)
auth, err := auth.NewAuth(args.auth, authLogger)
if err != nil {
mainLogger.Critical("Failed to instantiate auth provider: %v", err)
return 3
}
defer auth.Stop()
var d dialer.Dialer = dialer.NewBoundDialer(new(net.Dialer), args.sourceIPHints)
for _, proxyURL := range args.proxy {
newDialer, err := dialer.ProxyDialerFromURL(proxyURL, d)
if err != nil {
mainLogger.Critical("Failed to create dialer for proxy %q: %v", proxyURL, err)
return 3
}
d = newDialer
}
server := http.Server{
Addr: args.bind_address,
Handler: handler.NewProxyHandler(
args.timeout,
auth,
dialer.MaybeWrapWithContextDialer(d),
args.userIPHints,
proxyLogger),
ErrorLog: log.New(logWriter, "HTTPSRV : ", log.LstdFlags|log.Lshortfile),
ReadTimeout: 0,
ReadHeaderTimeout: 0,
WriteTimeout: 0,
IdleTimeout: 0,
}
if args.disableHTTP2 {
server.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
}
mainLogger.Info("Starting proxy server...")
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 := net.Listen("tcp", args.bind_address)
if err != nil {
mainLogger.Critical("listen failed: %v", err)
return 3
}
listener = newListener
}
if args.cert != "" {
cfg, err1 := makeServerTLSConfig(args.cert, args.key, args.cafile,
args.ciphers, uint16(args.minTLSVersion), uint16(args.maxTLSVersion), !args.disableHTTP2)
if err1 != nil {
mainLogger.Critical("TLS config construction failed: %v", err1)
return 3
}
listener = tls.NewListener(listener, cfg)
} else if args.autocert {
m := &autocert.Manager{
Cache: autocert.DirCache(args.autocertDir),
Prompt: autocert.AcceptTOS,
Client: &acme.Client{DirectoryURL: args.autocertACME},
Email: args.autocertEmail,
}
if args.autocertWhitelist != nil {
m.HostPolicy = autocert.HostWhitelist([]string(args.autocertWhitelist)...)
}
if args.autocertHTTP != "" {
go func() {
log.Fatalf("HTTP-01 ACME challenge server stopped: %v",
http.ListenAndServe(args.autocertHTTP, m.HTTPHandler(nil)))
}()
}
cfg := m.TLSConfig()
cfg, err = updateServerTLSConfig(cfg, args.cafile, args.ciphers,
uint16(args.minTLSVersion), uint16(args.maxTLSVersion), !args.disableHTTP2)
if err != nil {
mainLogger.Critical("TLS config construction failed: %v", err)
return 3
}
listener = tls.NewListener(listener, cfg)
}
mainLogger.Info("Proxy server started.")
err = server.Serve(listener)
mainLogger.Critical("Server terminated with a reason: %v", err)
mainLogger.Info("Shutting down...")
return 0
}
func makeServerTLSConfig(certfile, keyfile, cafile, ciphers string, minVer, maxVer uint16, h2 bool) (*tls.Config, error) {
cfg := tls.Config{
MinVersion: minVer,
MaxVersion: maxVer,
}
cert, err := tls.LoadX509KeyPair(certfile, keyfile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{cert}
if cafile != "" {
roots := x509.NewCertPool()
certs, err := ioutil.ReadFile(cafile)
if err != nil {
return nil, err
}
if ok := roots.AppendCertsFromPEM(certs); !ok {
return nil, errors.New("Failed to load CA certificates")
}
cfg.ClientCAs = roots
cfg.ClientAuth = tls.VerifyClientCertIfGiven
}
cfg.CipherSuites = makeCipherList(ciphers)
if h2 {
cfg.NextProtos = []string{"h2", "http/1.1"}
} else {
cfg.NextProtos = []string{"http/1.1"}
}
return &cfg, nil
}
func updateServerTLSConfig(cfg *tls.Config, cafile, ciphers string, minVer, maxVer uint16, h2 bool) (*tls.Config, error) {
if cafile != "" {
roots := x509.NewCertPool()
certs, err := ioutil.ReadFile(cafile)
if err != nil {
return nil, err
}
if ok := roots.AppendCertsFromPEM(certs); !ok {
return nil, errors.New("Failed to load CA certificates")
}
cfg.ClientCAs = roots
cfg.ClientAuth = tls.VerifyClientCertIfGiven
}
cfg.CipherSuites = makeCipherList(ciphers)
if h2 {
cfg.NextProtos = []string{"h2", "http/1.1", "acme-tls/1"}
} else {
cfg.NextProtos = []string{"http/1.1", "acme-tls/1"}
}
cfg.MinVersion = minVer
cfg.MaxVersion = maxVer
return cfg, nil
}
func makeCipherList(ciphers string) []uint16 {
if ciphers == "" {
return nil
}
cipherIDs := make(map[string]uint16)
for _, cipher := range tls.CipherSuites() {
cipherIDs[cipher.Name] = cipher.ID
}
cipherNameList := strings.Split(ciphers, ":")
cipherIDList := make([]uint16, 0, len(cipherNameList))
for _, name := range cipherNameList {
id, ok := cipherIDs[name]
if !ok {
log.Printf("WARNING: Unknown cipher \"%s\"", name)
}
cipherIDList = append(cipherIDList, id)
}
return cipherIDList
}
func list_ciphers() {
for _, cipher := range tls.CipherSuites() {
fmt.Println(cipher.Name)
}
}
func passwd(filename string, cost int, args ...string) error {
var (
username, password, password2 string
err error
)
if len(args) > 0 {
username = args[0]
} else {
username, err = prompt("Enter username: ", false)
if err != nil {
return fmt.Errorf("can't get username: %w", err)
}
}
if len(args) > 1 {
password = args[1]
} else {
password, err = prompt("Enter password: ", true)
if err != nil {
return fmt.Errorf("can't get password: %w", err)
}
password2, err = prompt("Repeat password: ", true)
if err != nil {
return fmt.Errorf("can't get password (repeat): %w", err)
}
if password != password2 {
return fmt.Errorf("passwords do not match")
}
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return fmt.Errorf("can't generate password hash: %w", err)
}
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("can't open file: %w", err)
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("%s:%s\n", username, hash))
if err != nil {
return fmt.Errorf("can't write to file: %w", err)
}
return nil
}
func prompt(prompt string, secure bool) (string, error) {
var input string
fmt.Print(prompt)
if secure {
b, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
input = string(b)
fmt.Println()
} else {
fmt.Scanln(&input)
}
return input, nil
}
func main() {
os.Exit(run())
}