-
Notifications
You must be signed in to change notification settings - Fork 4
/
proxy.go
875 lines (798 loc) · 22.5 KB
/
proxy.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
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
// MIT License
//
// Copyright (c) 2023 TTBT Enterprises LLC
// Copyright (c) 2023 Robin Thellend <rthellend@rthellend.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package proxy implements a simple lightweight TLS termination proxy that uses
// Let's Encrypt to provide TLS encryption for any number of TCP servers and
// server names concurrently on the same port.
package proxy
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"github.com/c2FmZQ/storage"
"github.com/c2FmZQ/storage/autocertcache"
"github.com/c2FmZQ/storage/crypto"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/exp/slices"
yaml "gopkg.in/yaml.v3"
"github.com/c2FmZQ/tlsproxy/certmanager"
"github.com/c2FmZQ/tlsproxy/proxy/internal/netw"
)
const (
startTimeKey = "s"
handshakeDoneKey = "h"
dialDoneKey = "d"
serverNameKey = "sn"
modeKey = "m"
protoKey = "p"
subjectKey = "sub"
internalConnKey = "ic"
)
var (
errAccessDenied = errors.New("access denied")
)
// Proxy receives TLS connections and forwards them to the configured
// backends.
type Proxy struct {
certManager interface {
HTTPHandler(fallback http.Handler) http.Handler
TLSConfig() *tls.Config
}
cfg *Config
ctx context.Context
cancel func()
listener net.Listener
mu sync.Mutex
defServerName string
backends map[string]*Backend
connections map[connKey]*netw.Conn
consoleChan chan net.Conn
consoleServer *http.Server
metrics map[string]*backendMetrics
events map[string]int64
}
type connKey struct {
dst net.Addr
src net.Addr
}
type backendMetrics struct {
numConnections int64
numBytesSent int64
numBytesReceived int64
}
// New returns a new initialized Proxy.
func New(cfg *Config, passphrase []byte) (*Proxy, error) {
opts := []crypto.Option{
crypto.WithAlgo(crypto.PickFastest),
crypto.WithLogger(logger{}),
}
mkFile := filepath.Join(cfg.CacheDir, "masterkey")
mk, err := crypto.ReadMasterKey(passphrase, mkFile, opts...)
if errors.Is(err, os.ErrNotExist) {
if mk, err = crypto.CreateMasterKey(opts...); err != nil {
return nil, errors.New("failed to create master key")
}
err = mk.Save(passphrase, mkFile)
}
if err != nil {
return nil, fmt.Errorf("masterkey: %w", err)
}
p := &Proxy{
certManager: &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocertcache.New("autocert", storage.New(cfg.CacheDir, mk)),
Email: cfg.Email,
},
connections: make(map[connKey]*netw.Conn),
}
p.Reconfigure(cfg)
return p, nil
}
// NewTestProxy returns a test Proxy that uses an internal certificate manager
// instead of letsencrypt.
func NewTestProxy(cfg *Config) (*Proxy, error) {
cm, err := certmanager.New("root-ca.example.com", func(fmt string, args ...interface{}) {
log.Printf("DBUG CertManager: "+fmt, args...)
})
if err != nil {
return nil, err
}
p := &Proxy{
certManager: cm,
connections: make(map[connKey]*netw.Conn),
}
p.Reconfigure(cfg)
return p, nil
}
// Reconfigure updates the proxy's configuration. Some parameters cannot be
// changed after Start has been called, e.g. HTTPAddr, TLSAddr, CacheDir.
func (p *Proxy) Reconfigure(cfg *Config) error {
p.mu.Lock()
defer p.mu.Unlock()
a, _ := yaml.Marshal(p.cfg)
b, _ := yaml.Marshal(cfg)
if bytes.Equal(a, b) {
return nil
}
if err := cfg.Check(); err != nil {
return err
}
if p.cfg != nil {
log.Print("INFO Configuration changed")
}
p.defServerName = cfg.DefaultServerName
backends := make(map[string]*Backend, len(cfg.Backends))
for _, be := range cfg.Backends {
for _, sn := range be.ServerNames {
backends[sn] = be
}
tc := p.baseTLSConfig()
if be.ClientAuth {
tc.ClientAuth = tls.RequireAndVerifyClientCert
if be.ClientCAs != "" {
c, err := loadCerts(be.ClientCAs)
if err != nil {
return err
}
tc.ClientCAs = c
}
tc.VerifyConnection = func(cs tls.ConnectionState) error {
be, err := p.backend(cs.ServerName)
if err != nil {
return err
}
if !be.ClientAuth {
return nil
}
if len(cs.PeerCertificates) == 0 {
return errors.New("no certificate")
}
subject := cs.PeerCertificates[0].Subject.String()
if err := be.authorize(subject); err != nil {
p.recordEvent(fmt.Sprintf("deny [%s] to %s", subject, cs.ServerName))
return fmt.Errorf("%w [%s]", err, subject)
}
if subject != "" {
p.recordEvent(fmt.Sprintf("allow [%s] to %s", subject, cs.ServerName))
}
return nil
}
}
if be.ALPNProtos != nil {
tc.NextProtos = *be.ALPNProtos
}
be.tlsConfig = tc
if be.ForwardRootCAs != "" {
c, err := loadCerts(be.ForwardRootCAs)
if err != nil {
return err
}
be.forwardRootCAs = c
}
}
p.backends = backends
p.cfg = cfg
p.startConsoleIfNeeded()
return nil
}
// Start starts a TLS proxy with the given configuration. The proxy runs
// in background until the context is canceled.
func (p *Proxy) Start(ctx context.Context) error {
var httpServer *http.Server
if p.cfg.HTTPAddr != "" {
httpServer = &http.Server{
Handler: p.certManager.HTTPHandler(nil),
}
httpListener, err := net.Listen("tcp", p.cfg.HTTPAddr)
if err != nil {
return err
}
go func() {
httpServer.SetKeepAlivesEnabled(false)
if err := httpServer.Serve(httpListener); err != http.ErrServerClosed {
log.Fatalf("http: %v", err)
}
}()
}
listener, err := netw.Listen("tcp", p.cfg.TLSAddr)
if err != nil {
return err
}
p.listener = listener
p.ctx, p.cancel = context.WithCancel(ctx)
go func() {
<-p.ctx.Done()
p.cancel()
if httpServer != nil {
httpServer.Close()
}
if p.consoleServer != nil {
p.consoleServer.Close()
}
p.listener.Close()
}()
p.startConsoleIfNeeded()
go func() {
log.Printf("INFO Accepting TLS connections on %s", p.listener.Addr())
for {
conn, err := p.listener.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
log.Print("INFO Accept loop terminated")
break
}
log.Printf("ERR Accept: %v", err)
continue
}
go p.handleConnection(conn.(*netw.Conn))
}
}()
return nil
}
// Stop signals the background goroutines to exit.
func (p *Proxy) Stop() {
if p.cancel != nil {
p.cancel()
p.cancel = nil
}
}
func (p *Proxy) startConsoleIfNeeded() {
if p.ctx == nil || p.consoleChan != nil {
return
}
var needed bool
for _, be := range p.backends {
if be.Mode == ModeConsole {
needed = true
break
}
}
if !needed {
return
}
mux := http.NewServeMux()
mux.HandleFunc("/", p.metricsHandler)
addPProfHandlers(mux)
p.consoleChan = make(chan net.Conn)
p.consoleServer = startInternalHTTPServer(p.ctx, mux, p.consoleChan)
}
func (p *Proxy) baseTLSConfig() *tls.Config {
tc := p.certManager.TLSConfig()
getCert := tc.GetCertificate
tc.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if hello.ServerName == "" {
hello.ServerName = p.defaultServerName()
}
return getCert(hello)
}
// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
tc.NextProtos = []string{
"h2", "http/1.1",
}
tc.MinVersion = tls.VersionTLS12
return tc
}
func (p *Proxy) handleConnection(conn *netw.Conn) {
closeConnNeeded := true
defer func() {
if closeConnNeeded {
conn.Close()
}
}()
conn.SetAnnotation(startTimeKey, time.Now())
numOpen := p.addConn(conn)
conn.OnClose(func() {
p.removeConn(conn)
if mode := conn.Annotation(modeKey, "").(string); mode == ModeConsole {
startTime := conn.Annotation(startTimeKey, time.Time{}).(time.Time)
log.Printf("END %s; Total:%s Recv:%d Sent:%d",
formatConnDesc(conn), time.Since(startTime),
conn.BytesReceived(), conn.BytesSent())
}
})
if numOpen >= p.cfg.MaxOpen {
p.recordEvent("too many open connections")
log.Printf("ERR %s: too many open connections: %d >= %d", conn.RemoteAddr(), numOpen, p.cfg.MaxOpen)
sendCloseNotify(conn)
return
}
setKeepAlive(conn)
hello, err := peekClientHello(conn)
if err != nil {
p.recordEvent("invalid ClientHello")
log.Printf("ERR %s ➔ %q: invalid ClientHello: %v", conn.RemoteAddr(), hello.ServerName, err)
return
}
serverName := hello.ServerName
if serverName == "" {
p.recordEvent("no SNI")
serverName = p.defaultServerName()
}
conn.SetAnnotation(serverNameKey, serverName)
be, err := p.backend(serverName)
if err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q: %v", conn.RemoteAddr(), serverName, err)
sendUnrecognizedName(conn)
return
}
conn.SetAnnotation(modeKey, be.Mode)
switch {
case be.Mode == ModeTLSPassthrough:
if err := p.checkIP(be, conn, serverName); err != nil {
return
}
p.handleTLSPassthroughConnection(conn, serverName)
case len(hello.ALPNProtos) == 1 && hello.ALPNProtos[0] == acme.ALPNProto && hello.ServerName != "":
tc := p.baseTLSConfig()
tc.NextProtos = []string{acme.ALPNProto}
p.handleACMEConnection(tls.Server(conn, tc), serverName)
case be.Mode == ModeConsole:
if err := p.checkIP(be, conn, serverName); err != nil {
return
}
p.handleConsoleConnection(tls.Server(conn, be.tlsConfig), serverName)
closeConnNeeded = false
default:
if err := p.checkIP(be, conn, serverName); err != nil {
return
}
p.handleTLSConnection(tls.Server(conn, be.tlsConfig), serverName)
}
}
// checkIP is just a wrapper around be.checkIP. It must be called before the TLS
// handshake completes.
func (p *Proxy) checkIP(be *Backend, conn net.Conn, serverName string) error {
if err := be.checkIP(conn.RemoteAddr()); err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q CheckIP: %v", conn.RemoteAddr(), serverName, err)
sendUnrecognizedName(conn)
return err
}
return nil
}
func (p *Proxy) handleACMEConnection(conn *tls.Conn, serverName string) {
ctx, cancel := context.WithTimeout(p.ctx, 2*time.Minute)
defer cancel()
log.Printf("INFO ACME %s ➔ %s", conn.RemoteAddr(), serverName)
if err := conn.HandshakeContext(ctx); err != nil {
p.recordEvent("tls handshake failed")
log.Printf("ERR %s ➔ %q Handshake: %v", conn.RemoteAddr(), serverName, unwrapErr(err))
}
}
func (p *Proxy) authorizeTLSConnection(conn *tls.Conn, serverName string) bool {
ctx, cancel := context.WithTimeout(p.ctx, 2*time.Minute)
defer cancel()
if err := conn.HandshakeContext(ctx); err != nil {
switch {
case err.Error() == "tls: client didn't provide a certificate":
p.recordEvent(fmt.Sprintf("deny no cert to %s", serverName))
case errors.Is(err, errAccessDenied):
p.recordEvent("access denied")
default:
p.recordEvent("tls handshake failed")
}
log.Printf("ERR %s ➔ %q Handshake: %v", conn.RemoteAddr(), serverName, unwrapErr(err))
return false
}
netwConn := conn.NetConn().(*netw.Conn)
netwConn.SetAnnotation(handshakeDoneKey, time.Now())
cs := conn.ConnectionState()
if (cs.ServerName == "" && serverName != p.defaultServerName()) || (cs.ServerName != "" && cs.ServerName != serverName) {
p.recordEvent("mismatched server name")
log.Printf("ERR %s ➔ %q Mismatched server name", conn.RemoteAddr(), serverName)
return false
}
proto := cs.NegotiatedProtocol
var subject string
if len(cs.PeerCertificates) > 0 {
subject = cs.PeerCertificates[0].Subject.String()
}
netwConn.SetAnnotation(protoKey, proto)
netwConn.SetAnnotation(subjectKey, subject)
// The checks below should already have been done in VerifyConnection.
be, err := p.backend(serverName)
if err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q: %v", conn.RemoteAddr(), serverName, err)
return false
}
if be.ClientACL != nil {
if err := be.authorize(subject); err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q Authorize(%q): %v", conn.RemoteAddr(), serverName, subject, err)
return false
}
}
return true
}
func (p *Proxy) handleConsoleConnection(conn *tls.Conn, serverName string) {
if !p.authorizeTLSConnection(conn, serverName) {
conn.Close()
return
}
be, err := p.backend(serverName)
if err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q: %v", conn.RemoteAddr(), serverName, err)
conn.Close()
return
}
if err := be.limiter.Wait(p.ctx); err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q Wait: %v", conn.RemoteAddr(), serverName, err)
conn.Close()
return
}
if be.Mode != ModeConsole {
p.recordEvent("wrong mode")
log.Printf("ERR %s ➔ %q Mode is not %s", conn.RemoteAddr(), serverName, ModeConsole)
conn.Close()
return
}
log.Printf("BEGIN %s", formatConnDesc(conn.NetConn().(*netw.Conn)))
p.consoleChan <- conn
}
func (p *Proxy) handleTLSConnection(extConn *tls.Conn, serverName string) {
if !p.authorizeTLSConnection(extConn, serverName) {
return
}
be, err := p.backend(serverName)
if err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q: %v", extConn.RemoteAddr(), serverName, err)
return
}
if err := be.limiter.Wait(p.ctx); err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q Wait: %v", extConn.RemoteAddr(), serverName, err)
return
}
extNetwConn := extConn.NetConn().(*netw.Conn)
proto := extNetwConn.Annotation(protoKey, "").(string)
intConn, err := be.dial(proto)
if err != nil {
p.recordEvent("dial error")
log.Printf("ERR %s ➔ %q Dial: %v", extConn.RemoteAddr(), serverName, err)
return
}
defer intConn.Close()
setKeepAlive(intConn)
extNetwConn.SetAnnotation(dialDoneKey, time.Now())
extNetwConn.SetAnnotation(internalConnKey, intConn)
desc := formatConnDesc(extNetwConn)
log.Printf("BEGIN %s", desc)
if err := be.bridgeConns(extConn, intConn); err != nil {
log.Printf("ERR %s %v", desc, err)
}
startTime := extNetwConn.Annotation(startTimeKey, time.Time{}).(time.Time)
hsTime := extNetwConn.Annotation(handshakeDoneKey, time.Time{}).(time.Time)
dialTime := extNetwConn.Annotation(dialDoneKey, time.Time{}).(time.Time)
totalTime := time.Since(startTime)
log.Printf("END %s; HS:%s Dial:%s Total:%s Recv:%d Sent:%d", desc,
hsTime.Sub(startTime), dialTime.Sub(hsTime), totalTime,
extNetwConn.BytesReceived(), extNetwConn.BytesSent())
}
func (p *Proxy) handleTLSPassthroughConnection(extConn net.Conn, serverName string) {
be, err := p.backend(serverName)
if err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q: %v", extConn.RemoteAddr(), serverName, err)
sendUnrecognizedName(extConn)
return
}
if err := be.limiter.Wait(p.ctx); err != nil {
p.recordEvent(err.Error())
log.Printf("ERR %s ➔ %q Wait: %v", extConn.RemoteAddr(), serverName, err)
sendInternalError(extConn)
return
}
extNetwConn := extConn.(*netw.Conn)
intConn, err := be.dial("")
if err != nil {
p.recordEvent("dial error")
log.Printf("ERR %s ➔ %q Dial: %v", extConn.RemoteAddr(), serverName, err)
sendInternalError(extConn)
return
}
defer intConn.Close()
setKeepAlive(intConn)
extNetwConn.SetAnnotation(dialDoneKey, time.Now())
extNetwConn.SetAnnotation(internalConnKey, intConn)
desc := formatConnDesc(extNetwConn)
log.Printf("BEGIN %s", desc)
if err := be.bridgeConns(extConn, intConn); err != nil {
log.Printf("ERR %s %v", desc, err)
}
startTime := extNetwConn.Annotation(startTimeKey, time.Time{}).(time.Time)
dialTime := extNetwConn.Annotation(dialDoneKey, time.Time{}).(time.Time)
totalTime := time.Since(startTime)
log.Printf("END %s; PT Dial:%s Total:%s Recv:%d Sent:%d", desc,
dialTime.Sub(startTime), totalTime, extNetwConn.BytesReceived(), extNetwConn.BytesSent())
}
func (p *Proxy) defaultServerName() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.defServerName
}
func (p *Proxy) backend(serverName string) (*Backend, error) {
p.mu.Lock()
defer p.mu.Unlock()
be, ok := p.backends[serverName]
if !ok {
return nil, errors.New("unexpected SNI")
}
return be, nil
}
func formatConnDesc(c *netw.Conn) string {
serverName := c.Annotation(serverNameKey, "").(string)
mode := c.Annotation(modeKey, "").(string)
proto := c.Annotation(protoKey, "").(string)
subject := c.Annotation(subjectKey, "").(string)
var intConn net.Conn
if ic, ok := c.Annotation(internalConnKey, intConn).(net.Conn); ok {
intConn = ic
}
var buf bytes.Buffer
if subject == "" {
buf.WriteString("[-] ")
} else {
buf.WriteString("[" + subject + "] ")
}
buf.WriteString(c.RemoteAddr().String())
if serverName != "" {
buf.WriteString(" ➔ ")
buf.WriteString(serverName)
buf.WriteString("|" + mode)
if proto != "" {
buf.WriteString("/" + proto)
}
if intConn != nil {
buf.WriteString("|" + intConn.LocalAddr().String())
buf.WriteString(" ➔ ")
buf.WriteString(intConn.RemoteAddr().String())
}
}
return buf.String()
}
func setKeepAlive(conn net.Conn) {
switch c := conn.(type) {
case *tls.Conn:
setKeepAlive(c.NetConn())
case *net.TCPConn:
c.SetKeepAlivePeriod(30 * time.Second)
c.SetKeepAlive(true)
case *netw.Conn:
setKeepAlive(c.Conn)
default:
log.Fatalf("setKeepAlive called with unexpected type: %T", conn)
}
}
func loadCerts(s string) (*x509.CertPool, error) {
var b []byte
if len(s) > 0 && s[0] == '/' {
var err error
if b, err = os.ReadFile(s); err != nil {
return nil, err
}
} else {
b = []byte(s)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(b) {
return nil, errors.New("invalid certs")
}
return pool, nil
}
func (be *Backend) dial(proto string) (net.Conn, error) {
var max int
for {
be.mu.Lock()
sz := len(be.Addresses)
if max == 0 {
max = sz
}
addr := be.Addresses[be.next]
be.next = (be.next + 1) % sz
be.mu.Unlock()
dialer := &net.Dialer{
Timeout: be.ForwardTimeout,
KeepAlive: 30 * time.Second,
}
var c net.Conn
var err error
if be.Mode == ModeTLS {
var protos []string
if proto != "" {
protos = append(protos, proto)
}
tc := &tls.Config{
InsecureSkipVerify: be.InsecureSkipVerify,
ServerName: be.ForwardServerName,
NextProtos: protos,
}
if be.forwardRootCAs != nil {
tc.RootCAs = be.forwardRootCAs
}
c, err = tls.DialWithDialer(dialer, "tcp", addr, tc)
} else {
c, err = dialer.Dial("tcp", addr)
}
if err != nil {
max--
if max > 0 {
log.Printf("ERR dial %q: %v", addr, err)
continue
}
return nil, err
}
return c, nil
}
}
func (be *Backend) authorize(subject string) error {
if be.ClientACL == nil {
return nil
}
if subject == "" || !slices.Contains(*be.ClientACL, subject) {
return errAccessDenied
}
return nil
}
func (be *Backend) checkIP(addr net.Addr) error {
var ip net.IP
switch a := addr.(type) {
case *net.TCPAddr:
ip = a.IP
default:
return fmt.Errorf("can't get IP address from %T", addr)
}
if be.denyIPs != nil {
for _, n := range *be.denyIPs {
if n.Contains(ip) {
return errAccessDenied
}
}
}
if be.allowIPs != nil {
for _, n := range *be.allowIPs {
if n.Contains(ip) {
return nil
}
}
return errAccessDenied
}
return nil
}
func (be *Backend) bridgeConns(client, server net.Conn) error {
serverClose := true
if be.ServerCloseEndsConnection != nil {
serverClose = *be.ServerCloseEndsConnection
}
clientClose := false
if be.ClientCloseEndsConnection != nil {
clientClose = *be.ClientCloseEndsConnection
}
timeout := time.Minute
if be.HalfCloseTimeout != nil {
timeout = *be.HalfCloseTimeout
}
ch := make(chan error)
go func() {
ch <- forward(client, server, serverClose, timeout)
}()
var retErr error
if err := forward(server, client, clientClose, timeout); err != nil && !errors.Is(err, net.ErrClosed) {
retErr = fmt.Errorf("[ext➔ int]: %w", unwrapErr(err))
}
if err := <-ch; err != nil && !errors.Is(err, net.ErrClosed) {
retErr = fmt.Errorf("[int➔ ext]: %w", unwrapErr(err))
}
return retErr
}
func forward(out net.Conn, in net.Conn, closeWhenDone bool, halfClosedTimeout time.Duration) error {
if _, err := io.Copy(out, in); err != nil || closeWhenDone {
out.Close()
in.Close()
return err
}
if err := closeWrite(out); err != nil {
out.Close()
in.Close()
return nil
}
if err := closeRead(in); err != nil {
out.Close()
in.Close()
return nil
}
// At this point, the connection is either half closed, or fully closed.
// If it is half closed, the remote end will get an EOF on the next
// read. It can still send data back in the other direction. There are
// some broken clients or network devices that never close their end of
// the connection. So, we need to set a deadline to avoid keeping
// connections open forever.
out.SetReadDeadline(time.Now().Add(halfClosedTimeout))
return nil
}
func closeWrite(c net.Conn) error {
type closeWriter interface {
CloseWrite() error
}
if cc, ok := c.(closeWriter); ok {
return cc.CloseWrite()
}
if cc, ok := c.(*netw.Conn); ok {
return closeWrite(cc.Conn)
}
return fmt.Errorf("unexpected type: %T", c)
}
func closeRead(c net.Conn) error {
type closeReader interface {
CloseRead() error
}
if cc, ok := c.(closeReader); ok {
return cc.CloseRead()
}
if cc, ok := c.(*netw.Conn); ok {
return closeRead(cc.Conn)
}
return nil
}
func unwrapErr(err error) error {
if e, ok := err.(*net.OpError); ok {
return unwrapErr(e.Err)
}
return err
}
type logger struct{}
func (logger) Debug(args ...any) {}
func (logger) Debugf(f string, args ...any) {}
func (logger) Info(args ...any) {
log.Print(append([]any{"INFO "}, args)...)
}
func (logger) Infof(f string, args ...any) {
log.Printf("INFO "+f, args...)
}
func (logger) Error(args ...any) {
log.Print(append([]any{"ERROR "}, args)...)
}
func (logger) Errorf(f string, args ...any) {
log.Printf("ERROR "+f, args...)
}
func (logger) Fatal(args ...any) {
log.Fatal(append([]any{"FATAL "}, args)...)
}
func (logger) Fatalf(f string, args ...any) {
log.Fatalf("FATAL "+f, args...)
}