-
Notifications
You must be signed in to change notification settings - Fork 1
/
forwarder.go
427 lines (378 loc) · 10.4 KB
/
forwarder.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
package backend
import (
"bytes"
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"strings"
"time"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
"github.com/anxiousmodernman/co-chair/proto/server"
"github.com/asdine/storm"
"github.com/asdine/storm/q"
"github.com/sirupsen/logrus"
"github.com/vulcand/oxy/trace"
)
// NewTCPForwarder constructs a TCPForwarder from a variable list of options.
// Passing a database (either by pass or by reference) is required or the
// TCPForwarder will fail at runtime.
func NewTCPForwarder(opts ...Opt) (*TCPForwarder, error) {
var fwdr TCPForwarder
for _, opt := range opts {
opt(&fwdr)
}
return &fwdr, nil
}
// An Opt lets us set values on a TCPForwarder.
type Opt func(*TCPForwarder)
// WithDBPath opens a DB at path and sets it on our TCPForwarder.
func WithDBPath(path string) Opt {
return func(fwdr *TCPForwarder) {
db, err := storm.Open(path)
if err != nil {
panic(err)
}
fwdr.DB = db
}
}
// WithDB sets a *storm.DB directly on our TCPForwarder.
func WithDB(db *storm.DB) Opt {
return func(fwdr *TCPForwarder) {
fwdr.DB = db
}
}
// WithAddr sets the ip:port our TCPForwarder will listen on. Has
// no effect if used in conjunction with WithListener.
func WithAddr(addr string) Opt {
return func(fwdr *TCPForwarder) {
fwdr.Addr = addr
}
}
// WithLogger sets our logger.
func WithLogger(logger *logrus.Logger) Opt {
return func(fwdr *TCPForwarder) {
fwdr.logger = logger
}
}
// WithProxyClient sets our grpc server.ProxyClient.
func WithProxyClient(pc server.ProxyClient) Opt {
return func(fwdr *TCPForwarder) {
fwdr.C = pc
}
}
// WithListener sets our TCPForwarder's net.Listener.
func WithListener(l net.Listener) Opt {
return func(fwdr *TCPForwarder) {
fwdr.L = l
}
}
// TCPForwarder is our actual listener type that clients will connect to. This
// implementation then inspects the requests that come in on connections, and
// selects an appropriate backend by talking gRPC to a Proxy instance via C, its
// embedded server.ProxyClient.
type TCPForwarder struct {
C server.ProxyClient
L net.Listener
logger *logrus.Logger
DB *storm.DB
Addr string
}
// GetCertificate fetches tls.Certificate from the database for
// each connection. This lets us dynamically fetch certs.
func (f *TCPForwarder) GetCertificate(hi *tls.ClientHelloInfo) (*tls.Certificate, error) {
host := hi.ServerName
fmt.Println("SERVER Name", hi.ServerName)
var bd BackendData
err := f.DB.One("Domain", host, &bd)
if err != nil {
if err == storm.ErrNotFound {
return nil, fmt.Errorf("%s no found", host)
}
f.logger.Error(err)
return nil, err
}
cert, err := tls.X509KeyPair(bd.BackendCert, bd.BackendKey)
return &cert, err
}
// Start accepts TCP connections.
func (f *TCPForwarder) Start() error {
if f.DB == nil {
return errors.New("database is nil")
}
// If we did not have a listener set directly, spin one up.
// This is the normal path, because we do not set a listener
// in main.go, currently.
if f.L == nil {
var tlsConf tls.Config
tlsConf.GetCertificate = f.GetCertificate
tlsConf.NextProtos = []string{"h2"}
lis, err := tls.Listen("tcp", f.Addr, &tlsConf)
if err != nil {
return err
}
f.L = lis
}
go func() {
for {
conn, err := f.L.Accept()
if err != nil {
if err, ok := err.(net.Error); ok && err.Temporary() {
f.logger.Errorf("accept err (temporary): %v", err)
continue
}
f.logger.Errorf("accept err: %v", err)
return
}
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
go f.handleConn(ctx, conn)
}
}()
return nil
}
// Where all the fun happens!
func (f *TCPForwarder) handleConn(ctx context.Context, conn net.Conn) {
_, done := context.WithCancel(ctx)
defer done()
defer conn.Close()
conn.SetDeadline(time.Now().Add(3 * time.Second))
// bufForBackend collects all the connection's reads until we select a backend,
// then we write all of bufForBackend's contents to the backend conn before
// tunneling the rest of the bytes through.
bufForBackend := bytes.NewBuffer([]byte(""))
// tee is how we copy/collect our initial reads of conn into bufForBackend
tee := io.TeeReader(conn, bufForBackend)
prefaceBytes := make([]byte, len([]byte(http2.ClientPreface)))
_, err := tee.Read(prefaceBytes)
if err != nil {
// Treat EOF like an error here
f.logger.Errorf("first read: %v", err)
return
}
var matched BackendData
var found []BackendData
if hasHTTP2Preface(prefaceBytes) {
headers := gatherHTTP2Headers(tee)
query := f.DB.Select(
q.In("Protocol", []server.Backend_Protocol{
server.Backend_GRPC,
server.Backend_HTTP2,
}),
q.Eq("Domain", HostWithoutPort(headers[":authority"])),
)
err := query.Find(&found)
if err != nil {
f.logger.Error(err)
return
}
matched = found[0]
} else {
partial := make([]byte, 4096)
n, err := tee.Read(partial)
if err != nil && err != io.EOF {
f.logger.Errorf("http1 error: %v", err)
return
}
joined := bytes.Join([][]byte{bufForBackend.Bytes(), partial[:n]}, []byte(""))
var host string
lines := strings.Split(string(joined), "\r\n")
for _, line := range lines {
if strings.HasPrefix(line, "Host:") {
host = strings.TrimSpace(strings.Split(line, ":")[1])
}
}
query := f.DB.Select(q.Eq("Domain", HostWithoutPort(host)))
err = query.Find(&found)
if err != nil {
f.logger.Errorf("http1 query error: %v", err)
return
}
matched = found[0]
}
if err := f.DialAndTunnel(&matched, bufForBackend, conn); err != nil {
f.logger.Errorf("could not proxy: %v", err)
}
}
// DialAndTunnel connects to the passed in backend, and tunnels traffic
// to it and from it.
func (f *TCPForwarder) DialAndTunnel(bd *BackendData, buffered *bytes.Buffer, conn net.Conn) error {
if len(bd.IPs) < 1 {
return fmt.Errorf("backend %s has no configured IPs", bd.Domain)
}
f.logger.Debugf("dialing backend: %v", bd.IPs[0])
bTLSConfig := &tls.Config{InsecureSkipVerify: true}
if bd.Protocol == server.Backend_GRPC || bd.Protocol == server.Backend_HTTP2 {
bTLSConfig.NextProtos = []string{"h2"}
}
bConn, err := tls.Dial("tcp", bd.IPs[0], bTLSConfig)
if err != nil {
return fmt.Errorf("dial backend: %v", err)
}
defer bConn.Close()
bConn.SetDeadline(time.Now().Add(3 * time.Second))
// our first backend write is the little buffer we read
// from the incoming conn, by writing here we
// pass it upstream after we've inspected it.
_, err = bConn.Write(buffered.Bytes())
if err != nil {
return fmt.Errorf("first write to backend: %v", err)
}
t := Tunnel{ErrorState: nil, ErrorSig: make(chan error)}
f.logger.Debug("proxying")
go t.pipe(conn, bConn, "conn->bConn")
go t.pipe(bConn, conn, "bConn->conn")
return <-t.ErrorSig
}
// Stop ...
func (f *TCPForwarder) Stop() error {
return f.L.Close()
}
func (t *Tunnel) pipe(src, dst net.Conn, dir string) {
buff := make([]byte, 0xffff)
for {
if t.ErrorState != nil {
return
}
n, err := src.Read(buff)
if err != nil {
t.err(fmt.Errorf("%s read: %v", dir, err))
return
}
b := buff[:n]
n, err = dst.Write(b)
if err != nil {
t.err(fmt.Errorf("%s write: %v", dir, err))
return
}
}
}
// A Tunnel streams data between two conns.
type Tunnel struct {
ErrorState error
ErrorSig chan error
}
func (t *Tunnel) err(err error) {
t.ErrorState = err
t.ErrorSig <- err
}
// NewTCPForwarderFromGRPCClient ...
func NewTCPForwarderFromGRPCClient(l net.Listener, pc server.ProxyClient, db *storm.DB, logger *logrus.Logger) *TCPForwarder {
return &TCPForwarder{
C: pc,
L: l,
logger: logger,
DB: db,
}
}
func certFromFile(path string) ([][]byte, *x509.Certificate, error) {
data, err := ioutil.ReadFile(path)
block, _ := pem.Decode(data)
if block == nil || block.Type != "PUBLIC KEY" {
return nil, nil, errors.New("invalid public key")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, err
}
ret := make([][]byte, 1)
ret = append(ret, cert.Raw)
return ret, cert, nil
}
func privateKeyFromFile(path string) (*rsa.PrivateKey, error) {
privateKey, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
priv, _ := pem.Decode(privateKey)
return x509.ParsePKCS1PrivateKey(priv.Bytes)
}
type TimedRecord struct {
TS []byte
Data trace.Record
}
func debugRequest(req *http.Request) {
data, _ := httputil.DumpRequest(req, false)
fmt.Printf("%s\n\n", string(data))
}
// adapted from cmux
func gatherHTTP2Headers(r io.Reader) map[string]string {
headers := make(map[string]string)
done := false
// w, r
framer := http2.NewFramer(ioutil.Discard, r)
hdec := hpack.NewDecoder(uint32(4<<16), func(hf hpack.HeaderField) {
headers[hf.Name] = hf.Value
})
for {
f, err := framer.ReadFrame()
if err != nil {
return nil
}
switch f := f.(type) {
case *http2.SettingsFrame:
// Sender acknoweldged the SETTINGS frame. No need to write
// SETTINGS again.
if f.IsAck() {
break
}
if err := framer.WriteSettings(); err != nil {
return nil
}
case *http2.ContinuationFrame:
if _, err := hdec.Write(f.HeaderBlockFragment()); err != nil {
return nil
}
done = done || f.FrameHeader.Flags&http2.FlagHeadersEndHeaders != 0
case *http2.HeadersFrame:
if _, err := hdec.Write(f.HeaderBlockFragment()); err != nil {
return nil
}
done = done || f.FrameHeader.Flags&http2.FlagHeadersEndHeaders != 0
case *http2.WindowUpdateFrame:
// TODO do we need to write this?
//err = framer.WriteWindowUpdate(f.StreamID, f.Increment)
//if err != nil {
// fmt.Println("window update err", err)
//}
}
if done {
return headers
}
}
}
func hasHTTP2Preface(b []byte) bool {
return bytes.Equal(b, []byte(http2.ClientPreface))
}
// HostWithoutPort extracts a hostname from an request, omitting
// any ":PORT" portion, if present. This is the value from the "Host:" header
// in HTTP1, or the ":authority" header in HTTP2.
func HostWithoutPort(s string) string {
if strings.Contains(s, ":") {
return strings.Split(s, ":")[0]
}
return s
}
// MatchHeaders compares headers from an HTTP2 request to values in our database.
func MatchHeaders(fromReq, fromDB map[string]string) bool {
var matched = false
for k, dbVal := range fromDB {
if headerVal, ok := fromReq[k]; ok && headerVal == dbVal {
matched = true
} else {
// return early if we get a different value
return false
}
}
return matched
}