-
Notifications
You must be signed in to change notification settings - Fork 4
/
backend.go
349 lines (332 loc) · 9.04 KB
/
backend.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
// 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
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"slices"
"strings"
"time"
"github.com/pires/go-proxyproto"
"github.com/c2FmZQ/tlsproxy/proxy/internal/netw"
)
func (be *Backend) incInFlight(delta int) int {
be.mu.Lock()
defer be.mu.Unlock()
be.inFlight += delta
if be.inFlight == 0 && be.shutdown && be.httpServer != nil {
close(be.httpConnChan)
be.httpServer = nil
}
return be.inFlight
}
func (be *Backend) close(ctx context.Context) {
be.mu.Lock()
defer be.mu.Unlock()
if be.httpServer == nil {
return
}
if ctx == nil {
be.httpServer.Close()
close(be.httpConnChan)
be.httpServer = nil
if h3 := be.http3Server; h3 != nil {
be.http3Server = nil
h3.Close()
}
return
}
go be.httpServer.Shutdown(ctx)
be.shutdown = true
if be.inFlight == 0 {
close(be.httpConnChan)
be.httpServer = nil
if h3 := be.http3Server; h3 != nil {
be.http3Server = nil
h3.Close()
}
}
}
func (be *Backend) dial(ctx context.Context, protos ...string) (net.Conn, error) {
var (
addresses = be.Addresses
mode = be.Mode
timeout = be.ForwardTimeout
insecureSkipVerify = be.InsecureSkipVerify
serverName = be.ForwardServerName
rootCAs = be.forwardRootCAs
proxyProtoVersion = be.proxyProtocolVersion
next = &be.next
)
if id, ok := ctx.Value(ctxOverrideIDKey).(int); ok && id >= 0 && id < len(be.PathOverrides) {
po := be.PathOverrides[id]
addresses = po.Addresses
mode = po.Mode
timeout = po.ForwardTimeout
insecureSkipVerify = po.InsecureSkipVerify
serverName = po.ForwardServerName
rootCAs = po.forwardRootCAs
proxyProtoVersion = po.proxyProtocolVersion
next = &po.next
}
if len(addresses) == 0 {
return nil, errors.New("no backend addresses")
}
tc := &tls.Config{
InsecureSkipVerify: insecureSkipVerify,
ServerName: serverName,
NextProtos: protos,
RootCAs: rootCAs,
GetClientCertificate: be.getClientCert(ctx),
VerifyConnection: func(cs tls.ConnectionState) error {
if len(cs.PeerCertificates) == 0 {
return tlsCertificateRequired
}
cert := cs.PeerCertificates[0]
if m, ok := be.pkiMap[hex.EncodeToString(cert.AuthorityKeyId)]; ok {
if m.IsRevoked(cert.SerialNumber) {
return tlsCertificateRevoked
}
} else if len(cert.OCSPServer) > 0 {
if err := be.ocspCache.VerifyChains(cs.VerifiedChains, cs.OCSPResponse); err != nil {
be.recordEvent(fmt.Sprintf("backend X509 %s [%s] (OCSP:%v)", idnaToUnicode(cs.ServerName), cert.Subject, err))
return tlsCertificateRevoked
}
}
return nil
},
}
var max int
for {
be.mu.Lock()
sz := len(addresses)
if max == 0 {
max = sz
}
addr := addresses[*next]
*next = (*next + 1) % sz
be.mu.Unlock()
var c net.Conn
var err error
if mode == ModeQUIC {
ctx, cancel := context.WithTimeout(ctx, timeout)
c, err = be.dialQUICStream(ctx, addr, tc)
cancel()
} else {
dialer := &net.Dialer{
Timeout: timeout,
KeepAlive: 30 * time.Second,
}
c, err = dialer.DialContext(ctx, "tcp", addr)
if err == nil && proxyProtoVersion > 0 {
if err = writeProxyHeader(proxyProtoVersion, c, ctx.Value(connCtxKey).(anyConn)); err != nil {
c.Close()
}
}
}
if err != nil {
max--
if max > 0 {
log.Printf("ERR dial %q: %v", addr, err)
continue
}
return nil, err
}
if mode == ModeTLS || mode == ModeHTTPS {
c = tls.Client(c, tc)
}
wc := netw.NewConn(c)
wc.OnClose(func() {
be.outConns.remove(wc)
})
be.outConns.add(wc)
wc.SetAnnotation(startTimeKey, time.Now())
wc.SetAnnotation(modeKey, mode)
wc.SetAnnotation(protoKey, strings.Join(protos, ","))
if cc, ok := ctx.Value(connCtxKey).(anyConn); ok {
wc.SetAnnotation(serverNameKey, connServerName(cc))
annotatedConn(cc).SetAnnotation(internalConnKey, wc)
if proxyProtoVersion > 0 {
wc.SetAnnotation(proxyProtoKey, cc.RemoteAddr().Network()+":"+cc.RemoteAddr().String())
}
}
return wc, nil
}
}
func writeProxyHeader(v byte, out io.Writer, in anyConn) error {
header := proxyproto.HeaderProxyFromAddrs(v, in.RemoteAddr(), in.LocalAddr())
header.Command = proxyproto.PROXY
var tlvs []proxyproto.TLV
if sn := connServerName(in); sn != "" {
tlvs = append(tlvs, proxyproto.TLV{
Type: proxyproto.PP2_TYPE_AUTHORITY,
Value: []byte(sn),
})
}
if proto := connProto(in); proto != "" {
tlvs = append(tlvs, proxyproto.TLV{
Type: proxyproto.PP2_TYPE_ALPN,
Value: []byte(proto),
})
}
if err := header.SetTLVs(tlvs); err != nil {
return err
}
if _, err := header.WriteTo(out); err != nil {
return err
}
return nil
}
func (be *Backend) authorize(cert *x509.Certificate) error {
if be.ClientAuth == nil || be.ClientAuth.ACL == nil {
return nil
}
if subject := cert.Subject.String(); subject != "" && (slices.Contains(*be.ClientAuth.ACL, subject) || slices.Contains(*be.ClientAuth.ACL, "SUBJECT:"+subject)) {
return nil
}
for _, v := range cert.DNSNames {
if slices.Contains(*be.ClientAuth.ACL, "DNS:"+v) {
return nil
}
}
for _, v := range cert.EmailAddresses {
if slices.Contains(*be.ClientAuth.ACL, "EMAIL:"+v) {
return nil
}
}
for _, v := range cert.URIs {
if slices.Contains(*be.ClientAuth.ACL, "URI:"+v.String()) {
return nil
}
}
return tlsAccessDenied
}
func (be *Backend) checkIP(addr net.Addr) error {
var ip net.IP
switch a := addr.(type) {
case *net.TCPAddr:
ip = a.IP
case *net.UDPAddr:
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
}