-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathproxy.go
488 lines (428 loc) · 13.2 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
// Copyright (c) 2012-2019 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package camo provides an HTTP proxy server with content type
// restrictions as well as regex host allow list support.
package camo
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/cactus/go-camo/pkg/camo/encoding"
"github.com/cactus/go-camo/pkg/htrie"
"github.com/cactus/mlog"
)
// Config holds configuration data used when creating a Proxy with New.
type Config struct {
// HMACKey is a byte slice to be used as the hmac key
HMACKey []byte
// Server name used in Headers and Via checks
ServerName string
// MaxSize is the maximum valid image size response (in bytes).
MaxSize int64
// MaxRedirects is the maximum number of redirects to follow.
MaxRedirects int
// Request timeout is a timeout for fetching upstream data.
RequestTimeout time.Duration
// Keepalive enable/disable
DisableKeepAlivesFE bool
DisableKeepAlivesBE bool
// x-forwarded-for enable/disable
EnableXFwdFor bool
// additional content types to allow
AllowContentVideo bool
AllowContentAudio bool
// allow URLs to contain user/pass credentials
AllowCredetialURLs bool
// Whether to call/increment metrics
CollectMetrics bool
// no ip filtering (test mode)
noIPFiltering bool
}
// The FilterFunc type is a function that validates a *url.URL
// A true value approves the url. A false value rejects the url.
type FilterFunc func(*url.URL) bool
// A Proxy is a Camo like HTTP proxy, that provides content type
// restrictions as well as regex host allow list support.
type Proxy struct {
client *http.Client
config *Config
acceptTypesFilter *htrie.GlobPathChecker
acceptTypesString string
filters []FilterFunc
filtersLen int
}
// ServerHTTP handles the client request, validates the request is validly
// HMAC signed, filters based on the Allow list, and then proxies
// valid requests to the desired endpoint. Responses are filtered for
// proper image content types.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if p.config.DisableKeepAlivesFE {
w.Header().Set("Connection", "close")
}
if req.Header.Get("Via") == p.config.ServerName {
http.Error(w, "Request loop failure", http.StatusNotFound)
return
}
// split path and get components
components := strings.Split(req.URL.Path, "/")
if len(components) < 3 {
http.Error(w, "Malformed request path", http.StatusNotFound)
return
}
sigHash, encodedURL := components[1], components[2]
if mlog.HasDebug() {
mlog.Debugm("client request", mlog.Map{"req": req})
}
sURL, ok := encoding.DecodeURL(p.config.HMACKey, sigHash, encodedURL)
if !ok {
http.Error(w, "Bad Signature", http.StatusForbidden)
return
}
if mlog.HasDebug() {
mlog.Debugm("signed client url", mlog.Map{"url": sURL})
}
u, err := url.Parse(sURL)
if err != nil {
if mlog.HasDebug() {
mlog.Debugm("url parse error", mlog.Map{"err": err})
}
http.Error(w, "Bad url", http.StatusBadRequest)
return
}
err = p.checkURL(u)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
nreq, err := http.NewRequestWithContext(req.Context(), req.Method, sURL, nil)
if err != nil {
if mlog.HasDebug() {
mlog.Debugm("could not create NewRequest", mlog.Map{"err": err})
}
http.Error(w, "Error Fetching Resource", http.StatusBadGateway)
return
}
// filter headers
p.copyHeaders(&nreq.Header, &req.Header, &ValidReqHeaders)
// x-forwarded-for (if appropriate)
if p.config.EnableXFwdFor {
xfwd4 := req.Header.Get("X-Forwarded-For")
if xfwd4 == "" {
hostIP, _, err := net.SplitHostPort(req.RemoteAddr)
if err == nil {
// add forwarded for header, as long as it isn't a private
// ip address (use isRejectedIP to get private filtering for free)
if ip := net.ParseIP(hostIP); ip != nil {
if !isRejectedIP(ip) {
nreq.Header.Add("X-Forwarded-For", hostIP)
}
}
}
} else {
nreq.Header.Add("X-Forwarded-For", xfwd4)
}
}
// add/squash an accept header if the client didn't send one
nreq.Header.Set("Accept", p.acceptTypesString)
nreq.Header.Add("User-Agent", p.config.ServerName)
nreq.Header.Add("Via", p.config.ServerName)
if mlog.HasDebug() {
mlog.Debugm("built outgoing request", mlog.Map{"req": nreq})
}
resp, err := p.client.Do(nreq)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
// handle client aborting request early in the request lifetime
if errors.Is(err, context.Canceled) {
if mlog.HasDebug() {
mlog.Debugm("client aborted request (early)", mlog.Map{"req": req})
}
return
} else if errors.Is(err, RedirectErr) {
// Got a bad redirect
if mlog.HasDebug() {
mlog.Debugm("bad redirect from server", mlog.Map{"err": err})
}
http.Error(w, "Error Fetching Resource", http.StatusNotFound)
return
}
// handle other errors
if mlog.HasDebug() {
mlog.Debugm("could not connect to endpoint", mlog.Map{"err": err})
}
// this is a bit janky, but some of these errors don't support
// the newer error semantics yet...
switch errString := err.Error(); {
case containsOneOf(errString, "timeout", "Client.Timeout"):
http.Error(w, "Error Fetching Resource", http.StatusGatewayTimeout)
case strings.Contains(errString, "use of closed"):
http.Error(w, "Error Fetching Resource", http.StatusBadGateway)
default:
// some other error. call it a not found (camo compliant)
http.Error(w, "Error Fetching Resource", http.StatusNotFound)
}
return
}
if mlog.HasDebug() {
mlog.Debugm("response from upstream", mlog.Map{"resp": resp})
}
// check for too large a response
if p.config.MaxSize > 0 && resp.ContentLength > p.config.MaxSize {
if p.config.CollectMetrics {
contentLengthExceeded.Inc()
}
if mlog.HasDebug() {
mlog.Debugm("content length exceeded", mlog.Map{"url": sURL})
}
http.Error(w, "Content length exceeded", http.StatusNotFound)
return
}
switch resp.StatusCode {
case 200, 206:
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
if mlog.HasDebug() {
mlog.Debug("Empty content-type returned")
}
http.Error(w, "Empty content-type returned", http.StatusBadRequest)
return
}
if !p.acceptTypesFilter.CheckPath(contentType) {
if mlog.HasDebug() {
mlog.Debugm("Unsupported content-type returned", mlog.Map{"type": u})
}
http.Error(w, "Unsupported content-type returned", http.StatusBadRequest)
return
}
case 300:
http.Error(w, "Multiple choices not supported", http.StatusNotFound)
return
case 301, 302, 303, 307:
// if we get a redirect here, we either disabled following,
// or followed until max depth and still got one (redirect loop)
http.Error(w, "Not Found", http.StatusNotFound)
return
case 304:
h := w.Header()
p.copyHeaders(&h, &resp.Header, &ValidRespHeaders)
w.WriteHeader(304)
return
case 404:
http.Error(w, "Not Found", http.StatusNotFound)
return
case 500, 502, 503, 504:
// upstream errors should probably just 502. client can try later.
http.Error(w, "Error Fetching Resource", http.StatusBadGateway)
return
default:
http.Error(w, "Not Found", http.StatusNotFound)
return
}
h := w.Header()
p.copyHeaders(&h, &resp.Header, &ValidRespHeaders)
w.WriteHeader(resp.StatusCode)
// get a []byte from bufpool, and put it back on defer
buf := *bufPool.Get().(*[]byte)
defer bufPool.Put(&buf)
// wrap body in limit reader, so even while chunk/streaming, we read
// less than desired max size
var bodyRC io.ReadCloser = resp.Body
if p.config.MaxSize > 0 {
bodyRC = NewLimitReadCloser(resp.Body, p.config.MaxSize)
}
// since this uses io.Copy/CopyBuffer from the respBody, it is streaming
// from the request to the response. This means it will nearly
// always end up with a chunked response.
written, err := io.CopyBuffer(w, bodyRC, buf)
if err != nil {
if p.config.CollectMetrics {
responseFailed.Inc()
}
if err == context.Canceled || errors.Is(err, context.Canceled) {
// client aborted/closed request, which is why copy failed to finish
if mlog.HasDebug() {
mlog.Debugm("client aborted request (late)", mlog.Map{"req": req})
}
return
}
// got an early EOF from the server side
if errors.Is(err, io.ErrUnexpectedEOF) {
if mlog.HasDebug() {
mlog.Debugm("server sent unexpected EOF", mlog.Map{"req": req})
}
return
}
// only log broken pipe errors at debug level
if isBrokenPipe(err) {
if mlog.HasDebug() {
mlog.Debugm("error writing response", mlog.Map{"err": err, "req": req})
}
return
}
// unknown error (not: a broken pipe; server early EOF; client close)
mlog.Printm("error writing response", mlog.Map{"err": err, "req": req})
return
}
if p.config.MaxSize > 0 && written >= p.config.MaxSize {
if p.config.CollectMetrics {
responseTruncated.Inc()
}
if mlog.HasDebug() {
mlog.Debugm("response to client truncated: size > MaxSize", mlog.Map{"req": req})
}
return
}
if mlog.HasDebug() {
mlog.Debugm("response to client", mlog.Map{"resp": w})
}
}
func (p *Proxy) checkURL(reqURL *url.URL) error {
// reject localhost urls
// lower case for matching is done by CheckHostname, so no need to
// ToLower here also
uHostname := reqURL.Hostname()
if uHostname == "" || localsFilter.CheckHostname(uHostname) {
return errors.New("Bad url host")
}
// if not allowed, reject credentialed/userinfo urls
if !p.config.AllowCredetialURLs && reqURL.User != nil {
return errors.New("Userinfo URL rejected")
}
// ip/whitelist/blacklist filtering
if !p.config.noIPFiltering {
// filter out rejected networks
if ip := net.ParseIP(uHostname); ip != nil {
if isRejectedIP(ip) {
return errors.New("Denylist host failure")
}
} else {
if ips, err := net.LookupIP(uHostname); err == nil {
for _, ip := range ips {
if isRejectedIP(ip) {
return errors.New("Denylist host failure")
}
}
}
}
}
// evaluate filters. first false value "fails"
for i := 0; i < p.filtersLen; i++ {
if !p.filters[i](reqURL) {
return errors.New("Rejected due to filter-ruleset")
}
}
return nil
}
// copy headers from src into dst
// empty filter map will result in no filtering being done
func (p *Proxy) copyHeaders(dst, src *http.Header, filter *map[string]bool) {
f := *filter
filtering := false
if len(f) > 0 {
filtering = true
}
for k, vv := range *src {
if x, ok := f[k]; filtering && (!ok || !x) {
continue
}
for _, v := range vv {
dst.Add(k, v)
}
}
}
// NewWithFilters returns a new Proxy that utilises the passed in proxy filters.
// filters are evaluated in order, and the first false response from a filter
// function halts further evaluation and fails the request.
func NewWithFilters(pc Config, filters []FilterFunc) (*Proxy, error) {
proxy, err := New(pc)
if err != nil {
return nil, err
}
filterFuncs := make([]FilterFunc, 0)
// check for nil entries, and copy the slice in case the original
// is mutated.
for _, filter := range filters {
if filter != nil {
filterFuncs = append(filterFuncs, filter)
}
}
proxy.filters = filterFuncs
proxy.filtersLen = len(filterFuncs)
return proxy, nil
}
// New returns a new Proxy. Returns an error if Proxy could not be constructed.
func New(pc Config) (*Proxy, error) {
tr := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
// max idle conns. Go DetaultTransport uses 100, which seems like a
// fairly reasonable number. Very busy servers may wish to raise
// or lower this value.
MaxIdleConns: 100,
MaxIdleConnsPerHost: 8,
// more defaults from DefaultTransport, with a few tweaks
IdleConnTimeout: 30 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: pc.DisableKeepAlivesBE,
// no need for compression with images
// some xml/svg can be compressed, but apparently some clients can
// exhibit weird behavior when those are compressed
DisableCompression: true,
}
client := &http.Client{
Transport: tr,
// timeout
Timeout: pc.RequestTimeout,
}
acceptTypes := []string{"image/*"}
// add additional accept types, if appropriate
if pc.AllowContentVideo {
acceptTypes = append(acceptTypes, "video/*")
}
if pc.AllowContentAudio {
acceptTypes = append(acceptTypes, "audio/*")
}
// re-use the htrie glob path checker for accept types validation
acceptTypesFilter := htrie.NewGlobPathChecker()
for _, v := range acceptTypes {
err := acceptTypesFilter.AddRule("|i|" + v)
if err != nil {
return nil, err
}
}
p := &Proxy{
client: client,
config: &pc,
acceptTypesString: strings.Join(acceptTypes, ", "),
acceptTypesFilter: acceptTypesFilter,
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= pc.MaxRedirects {
if mlog.HasDebug() {
mlog.Debug("Got bad redirect: Too many redirects", mlog.Map{"url": req})
}
return fmt.Errorf("Too many redirects: %w", RedirectErr)
}
err := p.checkURL(req.URL)
if err != nil {
if mlog.HasDebug() {
mlog.Debugm("Got bad redirect", mlog.Map{"url": req})
}
return fmt.Errorf("Bad redirect: %w", RedirectErr)
}
return nil
}
return p, nil
}