forked from andybalholm/redwood
/
proxy.go
543 lines (479 loc) · 13.4 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
package redwood
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"time"
"github.com/andybalholm/cascadia"
"github.com/andybalholm/dhash"
"github.com/klauspost/compress/gzip"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
)
type ProxyHandler struct {
// TLS is whether this is an HTTPS connection.
TLS bool
// connectPort is the server port that was specified in a CONNECT request.
connectPort string
// user is a user that has already been authenticated.
user string
// rt is the RoundTripper that will be used to fulfill the requests.
// If it is nil, a default Transport will be used.
rt http.RoundTripper
}
// lanAddress returns whether addr is in one of the LAN address ranges.
func lanAddress(addr string) bool {
ip := net.ParseIP(addr)
if ip4 := ip.To4(); ip4 != nil {
switch ip4[0] {
case 10, 127:
return true
case 172:
return ip4[1]&0xf0 == 16
case 192:
return ip4[1] == 168
}
return false
}
if ip[0]&0xfe == 0xfc {
return true
}
if ip[0] == 0xfe && (ip[1]&0xfc) == 0x80 {
return true
}
return false
}
var titleSelector = cascadia.MustCompile("title")
func (h ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
activeConnections.Add(1)
defer activeConnections.Done()
conf := GetConfig()
if !conf.ACLsLoaded {
http.Error(w, "Redwood proxy configuration needs to be updated for this version of Redwood.\n(Use ACLs)", 500)
return
}
if len(r.URL.String()) > 10000 {
http.Error(w, "URL too long", http.StatusRequestURITooLong)
return
}
client := r.RemoteAddr
host, _, err := net.SplitHostPort(client)
if err == nil {
client = host
}
if conf.AuthCacheTime > 0 {
auth := r.Header.Get("Proxy-Authorization")
if auth == "" {
authCacheLock.RLock()
ar, ok := authCache[client]
authCacheLock.RUnlock()
if ok && time.Now().Sub(ar.Time) < time.Duration(conf.AuthCacheTime)*time.Second {
r.Header.Set("Proxy-Authorization", ar.ProxyAuthorization)
}
} else {
authCacheLock.Lock()
authCache[client] = authRecord{
ProxyAuthorization: auth,
Time: time.Now(),
}
authCacheLock.Unlock()
}
}
if r.Header.Get("Proxy-Authorization") != "" {
user, pass := ProxyCredentials(r)
if !conf.ValidCredentials(user, pass) {
log.Printf("Incorrect username or password from %v: %q:%q", r.RemoteAddr, user, pass)
r.Header.Del("Proxy-Authorization")
}
}
// Reconstruct the URL if it is incomplete (i.e. on a transparent proxy).
if r.URL.Host == "" {
r.URL.Host = r.Host
}
if r.URL.Scheme == "" {
if h.TLS {
r.URL.Scheme = "https"
} else {
r.URL.Scheme = "http"
}
}
var userAgent string
if conf.LogUserAgent {
userAgent = r.Header.Get("User-Agent")
}
if realHost, ok := conf.VirtualHosts[r.Host]; ok {
r.Host = realHost
r.URL.Host = realHost
}
user := client
var authUser string
if h.user != "" {
authUser = h.user
} else if u, _ := ProxyCredentials(r); u != "" {
authUser = u
}
if authUser != "" {
user = authUser
}
tally := conf.URLRules.MatchingRules(r.URL)
scores := conf.categoryScores(tally)
categories := conf.significantCategories(scores)
reqACLs := conf.ACLs.requestACLs(r, authUser)
possibleActions := []string{
"allow",
"block",
"block-invisible",
}
if r.Header.Get("Proxy-Authorization") == "" && !h.TLS {
possibleActions = append(possibleActions, "require-auth")
}
if r.Method == "CONNECT" && conf.TLSReady {
possibleActions = append(possibleActions, "ssl-bump")
}
thisRule, ignored := conf.ChooseACLCategoryAction(reqACLs, categories, possibleActions...)
if r.Method == "CONNECT" && conf.TLSReady && thisRule.Action == "" {
// If the result is unclear, go ahead and start to bump the connection.
// The ACLs will be checked one more time anyway.
thisRule.Action = "ssl-bump"
}
switch thisRule.Action {
case "require-auth":
conf.send407(w)
log.Printf("Missing required proxy authentication from %v to %v", r.RemoteAddr, r.URL)
return
case "block":
conf.showBlockPage(w, r, user, tally, scores, thisRule)
logAccess(r, nil, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
return
case "block-invisible":
showInvisibleBlock(w)
logAccess(r, nil, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
return
case "ssl-bump":
conn, err := newHijackedConn(w)
if err != nil {
fmt.Fprintln(conn, "HTTP/1.1 500 Internal Server Error")
fmt.Fprintln(conn)
fmt.Fprintln(conn, err)
conn.Close()
return
}
fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n")
SSLBump(conn, r.URL.Host, user, authUser)
return
}
if r.Host == localServer {
conf.ServeMux.ServeHTTP(w, r)
return
}
if r.Method == "CONNECT" {
conn, err := newHijackedConn(w)
if err != nil {
fmt.Fprintln(conn, "HTTP/1.1 500 Internal Server Error")
fmt.Fprintln(conn)
fmt.Fprintln(conn, err)
conn.Close()
return
}
fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n")
logAccess(r, nil, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
connectDirect(conn, r.URL.Host, nil)
return
}
if r.Header.Get("Upgrade") == "websocket" {
h.makeWebsocketConnection(w, r)
return
}
r.Header.Add("Via", r.Proto+" Redwood")
r.Header.Add("X-Forwarded-For", client)
gzipOK := !conf.DisableGZIP && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && !lanAddress(client)
r.Header.Del("Accept-Encoding")
urlChanged := conf.changeQuery(r.URL)
if !urlChanged {
// Rebuild the URL in a way that will preserve which characters are escaped
// and which aren't, for compatibility with broken servers.
rawURL := r.RequestURI
if strings.HasPrefix(rawURL, r.URL.Scheme) {
rawURL = rawURL[len(r.URL.Scheme):]
rawURL = strings.TrimPrefix(rawURL, "://")
slash := strings.Index(rawURL, "/")
if slash == -1 {
rawURL = "/"
} else {
rawURL = rawURL[slash:]
}
}
q := strings.Index(rawURL, "?")
if q != -1 {
rawURL = rawURL[:q]
}
if strings.HasPrefix(rawURL, "//") {
// The path should start with a single slash not two.
rawURL = rawURL[1:]
}
r.URL.Opaque = rawURL
}
proxied := false
var rt http.RoundTripper
if h.rt == nil {
if r.URL.Opaque != "" && transport.Proxy != nil {
if p, _ := transport.Proxy(r); p != nil {
// If the request is going through a proxy, the host needs to be
// included in the opaque element.
r.URL.Opaque = "//" + r.URL.Host + r.URL.Opaque
proxied = true
}
}
rt = &transport
} else {
rt = h.rt
}
if !proxied {
r.Header.Del("Proxy-Authorization")
}
resp, err := rt.RoundTrip(r)
r.URL.Opaque = ""
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
log.Printf("error fetching %s: %s", r.URL, err)
logAccess(r, nil, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
return
}
defer resp.Body.Close()
// Prevent switching to QUIC.
resp.Header.Del("Alternate-Protocol")
originalContentType := resp.Header.Get("Content-Type")
fixContentType(resp)
respACLs := conf.ACLs.responseACLs(resp)
acls := unionACLSets(reqACLs, respACLs)
thisRule, ignored = conf.ChooseACLCategoryAction(acls, categories, "allow", "block", "block-invisible", "hash-image", "phrase-scan")
if thisRule.Action == "" {
thisRule.Action = "allow"
}
switch thisRule.Action {
case "allow":
resp.Header.Set("Content-Type", originalContentType)
copyResponseHeader(w, resp)
n, err := io.Copy(w, resp.Body)
if err != nil {
log.Printf("error while copying response (URL: %s): %s", r.URL, err)
}
logAccess(r, resp, int(n), false, user, tally, scores, thisRule, "", ignored, userAgent)
return
case "block":
conf.showBlockPage(w, r, user, tally, scores, thisRule)
logAccess(r, resp, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
return
case "block-invisible":
showInvisibleBlock(w)
logAccess(r, resp, 0, false, user, tally, scores, thisRule, "", ignored, userAgent)
return
}
lr := &io.LimitedReader{
R: resp.Body,
N: 1e6,
}
content, err := ioutil.ReadAll(lr)
if err != nil {
log.Printf("error while reading response body (URL: %s): %s", r.URL, err)
}
if lr.N == 0 {
log.Println("response body too long to filter:", r.URL)
resp.Header.Set("Content-Type", originalContentType)
var dest io.Writer = w
if gzipOK {
resp.Header.Set("Content-Encoding", "gzip")
resp.Header.Del("Content-Length")
gzw := gzip.NewWriter(w)
defer gzw.Close()
dest = gzw
}
copyResponseHeader(w, resp)
dest.Write(content)
n, err := io.Copy(dest, resp.Body)
if err != nil {
log.Printf("error while copying response (URL: %s): %s", r.URL, err)
}
logAccess(r, resp, int(n)+len(content), false, user, tally, scores, ACLActionRule{Action: "allow", Needed: []string{"too-long-to-filter"}}, "", ignored, userAgent)
return
}
modified := false
pageTitle := ""
switch thisRule.Action {
case "phrase-scan":
contentType := resp.Header.Get("Content-Type")
_, cs, _ := charset.DetermineEncoding(content, contentType)
if strings.Contains(contentType, "html") {
var doc *html.Node
if conf.LogTitle {
doc, err = parseHTML(content, cs)
if err != nil {
log.Printf("Error parsing HTML from %s: %s", r.URL, err)
} else {
t := titleSelector.MatchFirst(doc)
if t != nil {
if titleText := t.FirstChild; titleText != nil && titleText.Type == html.TextNode {
pageTitle = titleText.Data
}
}
}
}
modified = conf.pruneContent(r.URL, &content, cs, acls, doc)
if modified {
resp.Header.Set("Content-Type", "text/html; charset=utf-8")
cs = "utf-8"
resp.Header.Del("Content-Length")
}
}
conf.scanContent(content, contentType, cs, tally)
case "hash-image":
img, _, err := image.Decode(bytes.NewReader(content))
if err != nil {
log.Printf("Error decoding image from %v: %v", r.URL, err)
break
}
hash := dhash.New(img)
for _, h := range conf.ImageHashes {
if dhash.Distance(hash, h) <= conf.DhashThreshold {
tally[rule{imageHash, h.String()}]++
}
}
}
scores = conf.categoryScores(tally)
categories = conf.significantCategories(scores)
thisRule, ignored = conf.ChooseACLCategoryAction(acls, categories, "allow", "block", "block-invisible")
if thisRule.Action == "" {
thisRule.Action = "allow"
}
switch thisRule.Action {
case "block":
conf.showBlockPage(w, r, user, tally, scores, thisRule)
logAccess(r, resp, len(content), modified, user, tally, scores, thisRule, pageTitle, ignored, userAgent)
return
case "block-invisible":
showInvisibleBlock(w)
logAccess(r, resp, len(content), modified, user, tally, scores, thisRule, pageTitle, ignored, userAgent)
return
}
if !modified {
resp.Header.Set("Content-Type", originalContentType)
}
if gzipOK && len(content) > 1000 {
resp.Header.Set("Content-Encoding", "gzip")
resp.Header.Del("Content-Length")
copyResponseHeader(w, resp)
gzw := gzip.NewWriter(w)
gzw.Write(content)
gzw.Close()
} else {
copyResponseHeader(w, resp)
w.Write(content)
}
logAccess(r, resp, len(content), modified, user, tally, scores, thisRule, pageTitle, ignored, userAgent)
}
// copyResponseHeader writes resp's header and status code to w.
func copyResponseHeader(w http.ResponseWriter, resp *http.Response) {
newHeader := w.Header()
for key, values := range resp.Header {
for _, v := range values {
newHeader.Add(key, v)
}
}
w.WriteHeader(resp.StatusCode)
}
// A hijackedConn is a connection that has been hijacked (to fulfill a CONNECT
// request).
type hijackedConn struct {
net.Conn
io.Reader
}
func (hc *hijackedConn) Read(b []byte) (int, error) {
return hc.Reader.Read(b)
}
func newHijackedConn(w http.ResponseWriter) (*hijackedConn, error) {
hj, ok := w.(http.Hijacker)
if !ok {
return nil, errors.New("connection doesn't support hijacking")
}
conn, bufrw, err := hj.Hijack()
if err != nil {
return nil, err
}
err = bufrw.Flush()
if err != nil {
return nil, err
}
return &hijackedConn{
Conn: conn,
Reader: bufrw.Reader,
}, nil
}
var transport = http.Transport{
TLSClientConfig: unverifiedClientConfig,
Proxy: http.ProxyFromEnvironment,
}
// This is to deal with the problem of stale keepalive connections, which cause
// transport.RoundTrip to return io.EOF.
func init() {
go func() {
for _ = range time.Tick(10 * time.Second) {
transport.CloseIdleConnections()
}
}()
transport.RegisterProtocol("ftp", FTPTransport{})
}
func (h ProxyHandler) makeWebsocketConnection(w http.ResponseWriter, r *http.Request) {
addr := r.Host
if _, _, err := net.SplitHostPort(addr); err != nil {
// There is no port specified; we need to add it.
port := h.connectPort
if port == "" {
port = "80"
}
addr = net.JoinHostPort(addr, port)
}
var err error
var serverConn net.Conn
if h.TLS {
serverConn, err = tls.Dial("tcp", addr, unverifiedClientConfig)
} else {
serverConn, err = net.Dial("tcp", addr)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = r.Write(serverConn)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Couldn't create a websocket connection", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go func() {
io.Copy(conn, serverConn)
conn.Close()
}()
io.Copy(serverConn, bufrw)
serverConn.Close()
return
}