Repository navigation
Expand file tree
/
Copy pathtokenizer.go
More file actions
582 lines (491 loc) · 16.6 KB
/
Copy pathtokenizer.go
File metadata and controls
582 lines (491 loc) · 16.6 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
package tokenizer
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"syscall"
"time"
"unicode"
"github.com/elazarl/goproxy"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/nacl/box"
"golang.org/x/exp/maps"
"github.com/superfly/flysrc-go"
)
var FilteredHeaders = []string{headerProxyAuthorization, headerProxyTokenizer}
// UpstreamTrust is the trusted certificate pool to use for upstream requests.
var UpstreamTrust *x509.CertPool
func init() {
var err error
UpstreamTrust, err = x509.SystemCertPool()
if err != nil {
panic(err)
}
}
const headerProxyTokenizer = "Proxy-Tokenizer"
type tokenizer struct {
*goproxy.ProxyHttpServer
// OpenProxy dictates whether requests without any sealed secrets are allowed.
OpenProxy bool
// RequireFlySrc will reject requests without a fly-src when set.
RequireFlySrc bool
// allowPrivateUpstreams disables the denial of private, loopback,
// unspecified, link-local, and fdaa::/8 upstream addresses. Only for tests.
allowPrivateUpstreams bool
// tokenizerHostnames is a list of hostnames where tokenizer can be reached.
// If provided, this allows tokenizer to transparently proxy requests (ie.
// accept normal HTTP requests with arbitrary hostnames) while blocking
// circular requests back to itself. Any DNS names for tokenizer as well as
// static IP addresses should be included.
tokenizerHostnames []string
priv *[32]byte
pub *[32]byte
flysrcParser *flysrc.Parser
}
func (t *tokenizer) GetFlysrcParser() *flysrc.Parser {
return t.flysrcParser
}
type Option func(*tokenizer)
// OpenProxy specifies that requests without any sealed secrets are allowed.
func OpenProxy() Option {
return func(t *tokenizer) {
t.OpenProxy = true
}
}
// AllowPrivateUpstreams permits dialing private, loopback, unspecified,
// link-local, and fdaa::/8 upstream addresses. Only for tests that run their
// upstream on loopback.
func AllowPrivateUpstreams() Option {
return func(t *tokenizer) {
t.allowPrivateUpstreams = true
}
}
// RequireFlySrc specifies that requests without a fly-src will be rejected.
func RequireFlySrc() Option {
return func(t *tokenizer) {
t.RequireFlySrc = true
}
}
// WithFlysrcParser specifies a preconfigured flysrc parser to use instead of the
// default flysrc parser.
func WithFlysrcParser(parser *flysrc.Parser) Option {
return func(t *tokenizer) {
t.flysrcParser = parser
}
}
// TokenizerHostnames is a list of hostnames where tokenizer can be reached. If
// provided, this allows tokenizer to transparently proxy requests (ie. accept
// normal HTTP requests with arbitrary hostnames) while blocking circular
// requests back to itself. Any DNS names for tokenizer as well as static IP
// addresses should be included.
func TokenizerHostnames(hostnames ...string) Option {
return func(t *tokenizer) {
t.tokenizerHostnames = hostnames
}
}
func ParseOpenKey(openKey string) (*[32]byte, *[32]byte, error) {
privBytes, err := hex.DecodeString(openKey)
if err != nil {
return nil, nil, fmt.Errorf("bad private key")
}
if len(privBytes) != 32 {
return nil, nil, fmt.Errorf("bad private key size: %d", len(privBytes))
}
priv := (*[32]byte)(privBytes)
pub := new([32]byte)
curve25519.ScalarBaseMult(pub, priv)
return priv, pub, nil
}
func NewTokenizer(openKey string, opts ...Option) *tokenizer {
priv, pub, err := ParseOpenKey(openKey)
if err != nil {
logrus.WithError(err).Panic(err.Error())
}
proxy := goproxy.NewProxyHttpServer()
tkz := &tokenizer{ProxyHttpServer: proxy, priv: priv, pub: pub, flysrcParser: nil}
for _, opt := range opts {
opt(tkz)
}
if tkz.RequireFlySrc && tkz.flysrcParser == nil {
logrus.Panic("FlySrc is required but no flysrc Parser is specified")
}
hostnameMap := map[string]bool{}
for _, hostname := range tkz.tokenizerHostnames {
hostnameMap[hostname] = true
}
// fly-proxy rewrites incoming requests to not include the full URI so we
// have to look at the host header.
proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case len(hostnameMap) == 0:
logrus.WithFields(reqLogFields(r)).Warn("I'm not that kind of server")
http.Error(w, "I'm not that kind of server", 400)
return
case r.Host == "":
logrus.WithFields(reqLogFields(r)).Warn("must specify host")
http.Error(w, "must specify host", 400)
return
}
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
if strings.Contains(err.Error(), "missing port in address") {
host = r.Host
} else {
logrus.WithFields(reqLogFields(r)).Warn("bad host")
http.Error(w, "bad host", 400)
return
}
}
if hostnameMap[host] {
logrus.WithFields(reqLogFields(r)).Warn("circular request")
http.Error(w, "circular request", 400)
return
}
r.URL.Scheme = "http"
r.URL.Host = r.Host
tkz.ServeHTTP(w, r)
})
proxy.Tr = &http.Transport{
Dial: dialFunc(tkz.tokenizerHostnames, tkz.allowPrivateUpstreams),
// probably not necessary, but I don't want to worry about desync/smuggling
DisableKeepAlives: true,
}
proxy.ConnectDial = nil
proxy.ConnectDialWithReq = nil
proxy.OnRequest().HandleConnectFunc(tkz.HandleConnect)
proxy.OnRequest().DoFunc(tkz.HandleRequest)
proxy.OnResponse().DoFunc(tkz.HandleResponse)
return tkz
}
func (t *tokenizer) SealKey() string {
return hex.EncodeToString(t.pub[:])
}
// data that we can pass around between callbacks
type proxyUserData struct {
// responseProcessors are invoked in HandleResponse to transform the
// upstream response before returning it to the caller. Currently only
// JWTProcessorConfig uses this to seal the access token.
responseProcessors []func(*http.Response) error
// start time of the current request.
requestStart time.Time
reqLog logrus.FieldLogger
}
// HandleConnect implements goproxy.FuncHttpsHandler. CONNECT is refused:
// request validators check the Host header, but a tunneled request is
// delivered to whatever the CONNECT line named, so honoring CONNECT would let
// a client use a host-scoped secret against a different host.
func (t *tokenizer) HandleConnect(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
logrus.WithField("connect_host", host).WithFields(reqLogFields(ctx.Req)).Warn("CONNECT not supported")
ctx.Resp = errorResponse(ErrBadRequest)
return goproxy.RejectConnect, ""
}
func getSource(req *http.Request) string {
var forwards []string
if forwardedFor := req.Header.Get("X-Forwarded-For"); forwardedFor != "" {
forwards = strings.Split(forwardedFor, ", ")
}
srcs := append(forwards, req.RemoteAddr)
return strings.Join(srcs, ", ")
}
func reqLogFields(req *http.Request) logrus.Fields {
return logrus.Fields{
"source": getSource(req),
"method": req.Method,
"host": req.Host,
"path": req.URL.Path,
"queryKeys": strings.Join(maps.Keys(req.URL.Query()), ", "),
}
}
// HandleRequest implements goproxy.FuncReqHandler
func (t *tokenizer) HandleRequest(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
if ctx.UserData == nil {
ctx.UserData = &proxyUserData{}
}
pud, ok := ctx.UserData.(*proxyUserData)
if !ok || !pud.requestStart.IsZero() || pud.reqLog != nil {
logrus.Warn("bad proxyUserData")
return nil, errorResponse(ErrInternal)
}
pud.requestStart = time.Now()
pud.reqLog = logrus.WithFields(reqLogFields(ctx.Req))
if t.flysrcParser != nil {
src, err := t.flysrcParser.FromRequest(req)
if err != nil {
if t.RequireFlySrc {
pud.reqLog.Warn(err.Error())
return nil, errorResponse(ErrBadRequest)
}
} else {
pud.reqLog = pud.reqLog.WithFields(logrus.Fields{
"flysrc-org": src.Org,
"flysrc-app": src.App,
"flysrc-instance": src.Instance,
"flysrc-timestamp": src.Timestamp,
})
}
}
var processors []RequestProcessor
reqResult, err := t.processorsFromRequest(req)
if len(reqResult.safeSecrets) > 0 {
pud.reqLog = pud.reqLog.WithField("secrets", reqResult.safeSecrets)
}
if err != nil {
pud.reqLog.WithError(err).Warn("find processor")
return req, errorResponse(err)
} else {
processors = append(processors, reqResult.request...)
pud.responseProcessors = append(pud.responseProcessors, reqResult.response...)
}
if len(processors) == 0 && !t.OpenProxy {
pud.reqLog.Warn("no processors")
return nil, errorResponse(ErrBadRequest)
}
pud.reqLog = pud.reqLog.WithField("processors", len(processors))
for _, processor := range processors {
if err := processor(req); err != nil {
pud.reqLog.WithError(err).Warn("run processor")
return nil, errorResponse(ErrBadRequest)
}
}
for _, h := range FilteredHeaders {
req.Header.Del(h)
}
return req, nil
}
// HandleResponse implements goproxy.FuncRespHandler
func (t *tokenizer) HandleResponse(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
// This callback is hit twice if there was an error in the downstream
// request. The first time a nil request is given and the second time we're
// given whatever we returned the first time. Skip logging on the second
// call. This should continue to work okay if
// https://github.com/elazarl/goproxy/pull/512 is ever merged.
if ctx.Error != nil && resp != nil {
return resp
}
pud, ok := ctx.UserData.(*proxyUserData)
if !ok || pud.requestStart.IsZero() || pud.reqLog == nil {
logrus.Warn("missing proxyUserData")
return errorResponse(ErrInternal)
}
log := pud.reqLog.WithField("durMS", int64(time.Since(pud.requestStart)/time.Millisecond))
if resp != nil {
log = log.WithField("status", resp.StatusCode)
resp.Header.Set("Connection", "close")
// Run response processors (e.g. JWT token sealing)
for _, rp := range pud.responseProcessors {
if err := rp(resp); err != nil {
log.WithError(err).Warn("run response processor")
return errorResponse(err)
}
}
}
// reset pud
pud.requestStart = time.Time{}
pud.reqLog = nil
pud.responseProcessors = nil
if ctx.Error != nil {
log.WithError(ctx.Error).Warn()
return errorResponse(ctx.Error)
}
log.Info()
return resp
}
// loggerSecret holds one secret and params from the Proxy-Tokenizer header for logging.
// The secrets are sanitized of their hazmat.
type loggerSecret struct {
Secret string `json:"secret"`
Params string `json:"params"`
}
type processorsResult struct {
request []RequestProcessor
response []func(*http.Response) error
safeSecrets []loggerSecret
}
// OpenSealed decodes and unseals a sealed token and returns its raw (unparsed) contents.
func (t *tokenizer) OpenSealed(b64Secret string) ([]byte, error) {
ctSecret, err := base64.StdEncoding.DecodeString(strings.TrimSpace(b64Secret))
if err != nil {
return nil, fmt.Errorf("bad Proxy-Tokenizer encoding: %w", err)
}
jsonSecret, ok := box.OpenAnonymous(nil, ctSecret, t.pub, t.priv)
if !ok {
return nil, errors.New("failed Proxy-Tokenizer decryption")
}
return jsonSecret, nil
}
func (t *tokenizer) processorsFromRequest(req *http.Request) (*processorsResult, error) {
hdrs := req.Header[headerProxyTokenizer]
result := &processorsResult{
request: make([]RequestProcessor, 0, len(hdrs)),
}
for _, hdr := range hdrs {
b64Secret, params, err := parseHeaderProxyTokenizer(hdr)
if err != nil {
return result, err
}
jsonSecret, err := t.OpenSealed(b64Secret)
if err != nil {
return result, err
}
secret := new(Secret)
if err = json.Unmarshal(jsonSecret, secret); err != nil {
return result, fmt.Errorf("bad secret json: %w", err)
}
// capture secret and params for logger
safeSecret := secret.StripHazmatString()
pstr, _ := json.Marshal(params)
result.safeSecrets = append(result.safeSecrets, loggerSecret{safeSecret, string(pstr)})
if err = secret.AuthRequest(t, req); err != nil {
return result, fmt.Errorf("unauthorized to use secret: %w", err)
}
for _, v := range secret.RequestValidators {
if err := v.Validate(req); err != nil {
return result, fmt.Errorf("request validator failed: %w", err)
}
}
sealCtx := &SealingContext{
AuthConfig: secret.AuthConfig,
RequestValidators: secret.RequestValidators,
SealKey: t.pub,
}
processor, err := secret.Processor(params, sealCtx)
if err != nil {
return result, err
}
result.request = append(result.request, processor)
// Check if the processor also handles responses
if rpc, ok := secret.ProcessorConfig.(ResponseProcessorConfig); ok {
respProc, err := rpc.ResponseProcessor(params, sealCtx)
if err != nil {
return result, err
}
if respProc != nil {
result.response = append(result.response, respProc)
}
}
}
return result, nil
}
func parseHeaderProxyTokenizer(hdr string) (string, map[string]string, error) {
b64Secret, paramJSON, _ := strings.Cut(hdr, ";")
b64Secret = strings.TrimFunc(b64Secret, unicode.IsSpace)
paramJSON = strings.TrimFunc(paramJSON, unicode.IsSpace)
if b64Secret == "" {
return "", nil, fmt.Errorf("%w: bad tokenizer header", ErrBadRequest)
}
processorParams := make(map[string]string)
if paramJSON != "" {
if err := json.Unmarshal([]byte(paramJSON), &processorParams); err != nil {
return "", nil, fmt.Errorf("%w: %w", ErrBadRequest, err)
}
}
return b64Secret, processorParams, nil
}
func formatHeaderProxyTokenizer(b64Secret string, processorParams map[string]string) string {
hdr := b64Secret
if len(processorParams) > 0 {
paramJSON, _ := json.Marshal(processorParams)
hdr = fmt.Sprintf("%s; %s", hdr, paramJSON)
}
return hdr
}
func errorResponse(err error) *http.Response {
status := http.StatusBadGateway
switch {
case errors.Is(err, ErrNotAuthorized):
status = http.StatusProxyAuthRequired
case errors.Is(err, ErrBadRequest):
status = http.StatusBadRequest
case errors.Is(err, ErrInternal):
status = http.StatusBadGateway
}
return &http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: status,
Body: io.NopCloser(bytes.NewReader([]byte(err.Error()))),
Header: make(http.Header),
}
}
// dialFunc returns a function for dialing network addresses. Ours does a few
// special things.
// - It denies connections to private, loopback, unspecified, link-local, and
// fdaa::/8 addresses unless allowPrivate is set.
// - It denies connections to the given set of IP addresses. This is to prevent
// circular requests back to tokenizer. Invalid IPs are ignored.
// - It rejects requests for TLS upstreams. We need to see/modify requests, so
// our proxy can't do passthrough TLS.
// - It forces the upstream connection to be TLS. We want the actual upstream
// connection to be over TLS because security.
func dialFunc(badAddrs []string, allowPrivate bool) func(string, string) (net.Conn, error) {
_, fdaaNet, err := net.ParseCIDR("fdaa::/8")
if err != nil {
panic(err)
}
netDialer := net.Dialer{}
baMap := map[string]bool{}
for _, ba := range badAddrs {
if ip := net.ParseIP(ba); ip != nil {
baMap[ip.String()] = true
}
}
netDialer.ControlContext = func(ctx context.Context, network, address string, c syscall.RawConn) error {
h, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
switch ip := net.ParseIP(h); {
case ip == nil:
return fmt.Errorf("bad ip: %s", address)
case baMap[ip.String()]:
return fmt.Errorf("%w: dialing address %s denied", ErrBadRequest, address)
case allowPrivate:
return nil
case ip.IsPrivate():
return fmt.Errorf("%w: dialing private address %s denied", ErrBadRequest, address)
case ip.IsLoopback():
return fmt.Errorf("%w: dialing loopback address %s denied", ErrBadRequest, address)
case ip.IsUnspecified():
return fmt.Errorf("%w: dialing unspecified address %s denied", ErrBadRequest, address)
case ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(), ip.IsInterfaceLocalMulticast():
return fmt.Errorf("%w: dialing link-local address %s denied", ErrBadRequest, address)
case fdaaNet.Contains(ip):
return fmt.Errorf("%w: dialing fdaa::/8 address %s denied", ErrBadRequest, address)
default:
return nil
}
}
return func(network, addr string) (net.Conn, error) {
switch network {
case "tcp", "tcp4", "tcp6":
default:
return nil, fmt.Errorf("%w: dialing network %s not supported", ErrBadRequest, network)
}
hostname, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrBadRequest, err)
}
if hostname == "" || port == "" {
return nil, fmt.Errorf("%w: attempt to dial without host or port: %q", ErrBadRequest, addr)
}
switch port {
case "443":
return nil, fmt.Errorf("%w: proxied request must be HTTP", ErrBadRequest)
case "80":
port = "443"
}
addr = net.JoinHostPort(hostname, port)
return tls.DialWithDialer(&netDialer, network, addr, &tls.Config{RootCAs: UpstreamTrust})
}
}