-
Notifications
You must be signed in to change notification settings - Fork 37
/
proxy.go
1644 lines (1451 loc) · 42.3 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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"compress/flate"
"context"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/gif"
"image/jpeg"
_ "image/jpeg"
_ "image/png"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/andybalholm/brotli"
"github.com/andybalholm/cascadia"
"github.com/andybalholm/dhash"
"github.com/baruwa-enterprise/clamd"
"github.com/dustmop/soup"
"github.com/golang/gddo/httputil"
"github.com/golang/gddo/httputil/header"
"github.com/klauspost/compress/gzip"
"github.com/qri-io/starlib/bsoup"
"go.starlark.net/starlark"
"golang.org/x/image/draw"
_ "golang.org/x/image/webp"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
)
type proxyHandler struct {
// TLS is whether this is an HTTPS connection.
TLS bool
// tlsFingerprint is the JA3 TLS fingerprint of the client (if available).
tlsFingerprint string
// 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
// localPort is the TCP port that this proxyHandler is receiving requests on.
localPort int
// 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
// session is the TLSSession object, if this is an SSLBumped connection,
// or nil otherwise.
session *TLSSession
}
var titleSelector = cascadia.MustCompile("title")
func (h proxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
activeConnections.Add(1)
defer activeConnections.Done()
// If a request is directed to Redwood, rather than proxied or intercepted,
// it should be handled as an API request.
if !h.TLS && r.URL.Host == "" && strings.Contains(r.Host, ":") {
handleAPI(w, r)
return
}
client := r.RemoteAddr
host, _, err := net.SplitHostPort(client)
if err == nil {
client = host
}
// Don't look for authentication if the session is already authenticated,
// or if it's already SSLBumped.
if h.user != "" || h.TLS {
h.ServeHTTPAuthenticated(w, r, client, h.user)
return
}
ui := &UserInfo{
Request: r,
}
ui.Authenticate(nil)
h.ServeHTTPAuthenticated(w, r, ui.ClientIP, ui.AuthenticatedUser)
}
// ServeHTTPAuthenticated performs the part of serving a proxy request that
// happens after the user is authenticated. (If no user successfully authenticated,
// authUser may be empty.)
func (h proxyHandler) ServeHTTPAuthenticated(w http.ResponseWriter, r *http.Request, client, authUser string) {
user := client
if authUser != "" {
user = authUser
}
if len(r.URL.String()) > 10000 {
http.Error(w, "URL too long", http.StatusRequestURITooLong)
return
}
// Reconstruct the URL if it is incomplete (i.e. on a transparent proxy).
if r.URL.Scheme == "" {
if h.TLS {
r.URL.Scheme = "https"
} else {
r.URL.Scheme = "http"
}
}
if r.URL.Host == "" {
if r.Host != "" {
r.URL.Host = r.Host
} else {
log.Printf("Request from %s has no host in URL: %v", client, r.URL)
// Delay a while since some programs really hammer us with this kind of request.
time.Sleep(time.Second)
http.Error(w, "No host in request URL, and no Host header.", http.StatusBadRequest)
return
}
}
if realHost, ok := getConfig().VirtualHosts[r.Host]; ok {
r.Host = realHost
r.URL.Host = realHost
}
// Handle IPv6 hostname without brackets in CONNECT request.
if r.Method == "CONNECT" {
hostport := r.URL.Host
host, port, err := net.SplitHostPort(hostport)
if err, ok := err.(*net.AddrError); ok && err.Err == "too many colons in address" {
colon := strings.LastIndex(hostport, ":")
host, port = hostport[:colon], hostport[colon+1:]
if ip := net.ParseIP(host); ip != nil {
r.URL.Host = net.JoinHostPort(host, port)
}
}
}
// Some proxy interception programs send HTTP traffic as CONNECT requests
// for port 80.
if _, port, err := net.SplitHostPort(r.URL.Host); err == nil && port == "80" && r.Method == "CONNECT" {
conn, err := newHijackedConn(w)
if err != nil {
log.Printf("Error hijacking connection for CONNECT request to %s: %v", r.URL.Host, err)
panic(http.ErrAbortHandler)
}
fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n")
server := &http.Server{
Handler: proxyHandler{
TLS: false,
connectPort: port,
user: authUser,
rt: h.rt,
},
IdleTimeout: getConfig().CloseIdleConnections,
}
server.Serve(&singleListener{conn: conn})
return
}
if h.tlsFingerprint != "" {
r = r.WithContext(context.WithValue(r.Context(), tlsFingerprintKey{}, h.tlsFingerprint))
}
request := &Request{
Request: r,
User: authUser,
LocalPort: h.localPort,
ExpectedUser: getConfig().UserForPort[h.localPort],
ClientIP: client,
Session: h.session,
}
filterRequest(request, !h.TLS)
if request.Action.Action == "require-auth" {
send407(w)
logAuthEvent("proxy-auth-header", "missing", r.RemoteAddr, h.localPort, "", "", "", "", r, "Missing required proxy authentication")
return
}
if r.Method == "CONNECT" && getConfig().TLSReady {
// SSLBump takes priority overy any action besides require-auth, because showing a block page
// doesn't work till after the connection is bumped.
conn, err := newHijackedConn(w)
if err != nil {
log.Printf("Error hijacking connection for CONNECT request to %s: %v", r.URL.Host, err)
panic(http.ErrAbortHandler)
}
fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n")
SSLBump(conn, r.URL.Host, user, authUser, r)
return
}
switch request.Action.Action {
case "block":
showBlockPage(w, r, nil, user, request.Tally, request.Scores.data, request.Action, request.LogData)
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
return
case "block-invisible":
showInvisibleBlock(w)
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
return
}
if r.Host == localServer {
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
getConfig().ServeMux.ServeHTTP(w, r)
return
}
if r.Method == "CONNECT" {
// …and not TLSReady
conn, err := newHijackedConn(w)
if err != nil {
log.Printf("Error hijacking connection for CONNECT request to %s: %v", r.URL.Host, err)
panic(http.ErrAbortHandler)
}
fmt.Fprint(conn, "HTTP/1.1 200 Connection Established\r\n\r\n")
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
connectDirect(conn, r.URL.Host, nil, dialer)
return
}
if r.Header.Get("Upgrade") == "websocket" {
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
h.makeWebsocketConnection(w, r)
return
}
if len(r.Header["X-Forwarded-For"]) >= 10 {
w.Header().Set("Connection", "close")
http.Error(w, "Proxy forwarding loop", http.StatusBadRequest)
log.Printf("Proxy forwarding loop from %s to %v", r.Header.Get("X-Forwarded-For"), r.URL)
return
}
{
conf := getConfig()
headerRule, _ := conf.ChooseACLCategoryAction(request.ACLs.data, request.Scores.data, conf.Threshold, "disable-proxy-headers")
if headerRule.Action != "disable-proxy-headers" {
viaHosts := r.Header["Via"]
viaHosts = append(viaHosts, strings.TrimPrefix(r.Proto, "HTTP/")+" Redwood")
r.Header.Set("Via", strings.Join(viaHosts, ", "))
r.Header.Add("X-Forwarded-For", client)
}
}
// Limit Accept-Encoding header to encodings we can handle.
acceptEncoding := header.ParseAccept(r.Header, "Accept-Encoding")
filteredEncodings := make([]header.AcceptSpec, 0, len(acceptEncoding))
for _, a := range acceptEncoding {
switch a.Value {
case "br", "gzip", "deflate":
filteredEncodings = append(filteredEncodings, a)
}
}
switch {
case len(filteredEncodings) == 0:
r.Header.Del("Accept-Encoding")
case len(filteredEncodings) != len(acceptEncoding):
specs := make([]string, len(filteredEncodings))
for i, a := range filteredEncodings {
if a.Q == 1 {
specs[i] = a.Value
} else {
specs[i] = fmt.Sprintf("%s;q=%f", a.Value, a.Q)
}
}
r.Header.Set("Accept-Encoding", strings.Join(specs, ", "))
}
getConfig().changeQuery(r.URL)
var rt http.RoundTripper
switch {
case r.URL.Scheme == "ftp":
rt = FTPTransport{}
case request.hostChanged:
rt = transportWithExtraRootCerts
case h.rt != nil:
rt = h.rt
default:
rt = transportWithExtraRootCerts
}
// Some HTTP/2 servers don't like having a body on a GET request, even if
// it is empty.
if r.ContentLength == 0 {
r.Body.Close()
r.Body = nil
}
removeHopByHopHeaders(r.Header)
resp, err := rt.RoundTrip(r)
if err == context.Canceled {
return
}
if err != nil {
showErrorPage(w, r, err)
log.Printf("error fetching %s: %s", r.URL, err)
logAccess(r, nil, 0, false, user, request.Tally, request.Scores.data, request.Action, "", request.Ignored, nil, request.LogData)
return
}
defer resp.Body.Close()
// Prevent switching to QUIC.
resp.Header.Del("Alternate-Protocol")
resp.Header.Del("Alt-Svc")
removeHopByHopHeaders(resp.Header)
// This was a workaround for https://github.com/golang/go/issues/31753,
// which has been fixed. But it's also needed to protect our own content sniffing in acl.go.
if resp.Header.Get("Content-Type") == "" && resp.Header.Get("Content-Encoding") == "gzip" && r.Method != "HEAD" {
gzr, err := gzip.NewReader(resp.Body)
if err != nil {
log.Printf("Error creating gzip reader for %v: %v", r.URL, err)
} else {
resp.Body = gzr
resp.Header.Del("Content-Encoding")
}
}
response := &Response{
Request: request,
Response: resp,
LogData: request.LogData,
}
response.Scores = request.Scores
response.Tally = make(map[rule]int)
for k, v := range request.Tally {
response.Tally[k] = v
}
var scanAction ACLActionRule
{
conf := getConfig()
respACLs := conf.ACLs.responseACLs(resp)
response.ACLs.data = unionACLSets(request.ACLs.data, respACLs)
headerRule, _ := conf.ChooseACLCategoryAction(response.ACLs.data, response.Scores.data, conf.Threshold, "disable-proxy-headers")
if headerRule.Action != "disable-proxy-headers" {
viaHosts := resp.Header["Via"]
viaHosts = append(viaHosts, strings.TrimPrefix(resp.Proto, "HTTP/")+" Redwood")
resp.Header.Set("Via", strings.Join(viaHosts, ", "))
}
var possibleActions []string
if r.Method != "HEAD" {
possibleActions = append(possibleActions, "hash-image", "phrase-scan")
if conf.ClamAV != nil {
possibleActions = append(possibleActions, "virus-scan")
}
}
scanAction, _ = conf.ChooseACLCategoryAction(response.ACLs.data, response.Scores.data, conf.Threshold, possibleActions...)
}
switch scanAction.Action {
case "phrase-scan":
if err := doPhraseScan(response); err != nil {
showErrorPage(w, r, err)
return
}
case "hash-image":
if err := doImageHash(response); err != nil {
showErrorPage(w, r, err)
return
}
case "virus-scan":
if err := doVirusScan(response); err != nil {
showErrorPage(w, r, err)
return
}
if response.Action.Action == "block" {
showBlockPage(w, r, resp, user, response.Tally, response.Scores.data, response.Action, response.LogData)
logAccess(r, resp, response.Response.ContentLength, false, user, response.Tally, response.Scores.data, response.Action, "", nil, response.ClamdResponses(), response.LogData)
return
}
}
response.Scores.data = getConfig().categoryScores(response.Tally)
contentRule, _ := getConfig().ChooseACLCategoryAction(response.ACLs.data, response.Scores.data, 1, "log-content")
if contentRule.Action == "log-content" {
content, _ := response.Content(math.MaxInt)
if content != nil {
logContent(r.URL, content, response.Scores.data)
}
}
response.PossibleActions = []string{"allow", "block", "block-invisible"}
callStarlarkFunctions("filter_response", response)
response.chooseAction()
switch response.Action.Action {
case "block":
showBlockPage(w, r, resp, user, response.Tally, response.Scores.data, response.Action, response.LogData)
logAccess(r, resp, 0, response.Modified, user, response.Tally, response.Scores.data, response.Action, response.PageTitle, response.Ignored, response.ClamdResponses(), response.LogData)
return
case "block-invisible":
showInvisibleBlock(w)
logAccess(r, resp, 0, response.Modified, user, response.Tally, response.Scores.data, response.Action, response.PageTitle, response.Ignored, response.ClamdResponses(), response.LogData)
return
}
if response.Response.ContentLength > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(response.Response.ContentLength, 10))
}
copyResponseHeader(w, resp)
n, err := io.Copy(w, response.Response.Body)
if err != nil {
if err != context.Canceled {
log.Printf("error while copying response (URL: %s): %s", r.URL, err)
}
if ct, ok := rt.(*connTransport); ok {
ct.Conn.Close()
}
}
logAccess(r, resp, n, response.Modified, user, response.Tally, response.Scores.data, response.Action, response.PageTitle, response.Ignored, response.ClamdResponses(), response.LogData)
}
func filterRequest(req *Request, checkAuth bool) {
r := req.Request
req.Tally = getConfig().URLRules.MatchingRules(r.URL)
req.Scores.data = getConfig().categoryScores(req.Tally)
for _, classifier := range getConfig().ExternalClassifiers {
v := make(url.Values)
v.Set("url", r.URL.String())
v.Set("method", r.Method)
cr, err := clientWithExtraRootCerts.PostForm(classifier, v)
if err != nil {
log.Printf("Error checking external-classifier (%s): %v", classifier, err)
continue
}
if cr.StatusCode != 200 {
log.Printf("Bad HTTP status checking external-classifier (%s): %s", classifier, cr.Status)
continue
}
jd := json.NewDecoder(cr.Body)
externalScores := make(map[string]int)
err = jd.Decode(&externalScores)
cr.Body.Close()
if err != nil {
log.Printf("Error decoding response from external-classifier (%s): %v", classifier, err)
continue
}
if req.Scores.data == nil {
req.Scores.data = make(map[string]int)
}
for k, v := range externalScores {
req.Scores.data[k] += v
}
}
req.ACLs.data = getConfig().ACLs.requestACLs(r, req.User)
req.PossibleActions = []string{
"allow",
"block",
"block-invisible",
}
if req.User == "" && checkAuth {
req.PossibleActions = append(req.PossibleActions, "require-auth")
}
callStarlarkFunctions("filter_request", req)
req.chooseAction()
}
func doPhraseScan(response *Response) error {
content, err := response.Content(getConfig().MaxContentScanSize)
if err != nil {
return err
}
if content != nil {
conf := getConfig()
contentType := response.Response.Header.Get("Content-Type")
_, cs, _ := charset.DetermineEncoding(content, contentType)
modified := false
if strings.Contains(contentType, "html") {
if conf.LogTitle {
response.ParsedHTML, err = parseHTML(content, cs)
if err != nil {
log.Printf("Error parsing HTML from %s: %s", response.Request.Request.URL, err)
} else {
t := titleSelector.MatchFirst(response.ParsedHTML)
if t != nil {
if titleText := t.FirstChild; titleText != nil && titleText.Type == html.TextNode {
response.PageTitle = strings.Replace(strings.TrimSpace(titleText.Data), "\n", " ", -1)
}
}
}
}
modified = conf.pruneContent(response.Request.Request.URL, &content, cs, &response.ParsedHTML)
if modified {
cs = "utf-8"
}
}
conf.scanContent(content, contentType, cs, response.Tally)
if strings.Contains(contentType, "html") {
aclsWithCategories := copyACLSet(response.ACLs.data)
for name, score := range response.Scores.data {
if category, ok := conf.Categories[name]; ok && category.action == ACL && score > 0 {
aclsWithCategories[name] = true
}
}
modifiedAfterScan := conf.doFilteredPruning(response.Request.Request.URL, content, cs, aclsWithCategories, &response.ParsedHTML)
censorRule, _ := conf.ChooseACLCategoryAction(response.ACLs.data, response.Scores.data, conf.Threshold, "censor-words")
if censorRule.Action == "censor-words" {
if response.ParsedHTML == nil {
response.ParsedHTML, _ = parseHTML(content, cs)
}
if censorHTML(response.ParsedHTML, conf.CensoredWords) {
modifiedAfterScan = true
}
}
if modifiedAfterScan {
b := new(bytes.Buffer)
if err := html.Render(b, response.ParsedHTML); err != nil {
log.Printf("Error rendering modified content from %s: %v", response.Request.Request.URL, err)
} else {
content = b.Bytes()
modified = true
}
}
if modified {
response.SetContent(content, "text/html; charset=utf-8")
}
}
}
return nil
}
func doImageHash(response *Response) error {
content, err := response.Content(getConfig().MaxContentScanSize)
if err != nil {
return err
}
if content != nil {
conf := getConfig()
response.image, _, err = image.Decode(bytes.NewReader(content))
if err != nil {
log.Printf("Error decoding image from %v: %v", response.Request.Request.URL, err)
return nil
}
hash := dhash.New(response.image)
for _, h := range conf.ImageHashes {
distance := dhash.Distance(hash, h.Hash)
if distance <= h.Threshold || h.Threshold == -1 && distance <= conf.DhashThreshold {
response.Tally[simpleRule{imageHash, h.String()}]++
}
}
}
return nil
}
// Thumbnail returns a JPEG thumbnail of the image in the response body.
// It will be no more than maxSize pixels in width or height.
// If the response body isn't a supported image type, or if it is
// longer than MaxContentScanSize, Thumbnail returns nil.
func (resp *Response) Thumbnail(maxSize int) []byte {
if resp.image == nil {
content, err := resp.Content(getConfig().MaxContentScanSize)
if err != nil {
log.Printf("Error downloading image from %v to make thumbnail: %v", resp.Request.Request.URL, err)
}
if content == nil {
return nil
}
resp.image, _, err = image.Decode(bytes.NewReader(content))
if err != nil {
log.Printf("Error decoding image from %v: %v", resp.Request.Request.URL, err)
return nil
}
}
img := resp.image
sb := img.Bounds()
size := sb.Dx()
if dy := sb.Dy(); dy > size {
size = dy
}
if size > maxSize {
ratio := float64(maxSize) / float64(size)
dst := image.NewRGBA(image.Rect(0, 0, int(ratio*float64(sb.Dx())), int(ratio*float64(sb.Dy()))))
draw.BiLinear.Scale(dst, dst.Bounds(), img, sb, draw.Over, nil)
img = dst
}
b := new(bytes.Buffer)
err := jpeg.Encode(b, img, &jpeg.Options{Quality: 80})
if err != nil {
return nil
}
return b.Bytes()
}
func doVirusScan(response *Response) error {
content, err := response.Content(getConfig().MaxContentScanSize)
if err != nil {
return err
}
clam := getConfig().ClamAV
if content != nil {
response.clamResponses, err = clam.ScanReader(response.Request.Request.Context(), bytes.NewReader(content))
if err != nil {
log.Printf("Error doing virus scan on %v: %v", response.Request.Request.URL, err)
}
for _, res := range response.clamResponses {
if res.Status == "FOUND" {
log.Printf("Detected virus in %v: %s", response.Request.Request.URL, res.Signature)
response.Action = ACLActionRule{
Action: "block",
Needed: []string{"virus", res.Signature},
}
}
}
} else {
// Although the response is too long for synchronous virus scanning, scan it anyway,
// so that we can log the result.
// Make the channel buffered, so that sending won't block.
response.clamChan = make(chan []*clamd.Response, 1)
pr, pw := io.Pipe()
tr := io.TeeReader(response.Response.Body, pw)
response.Response.Body = pr
go func() {
cr, _ := clam.ScanReader(response.Request.Request.Context(), tr)
io.Copy(ioutil.Discard, tr)
pw.Close()
response.clamChan <- cr
}()
}
return nil
}
// 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 {
if key == "Content-Length" {
continue
}
for _, v := range values {
newHeader.Add(key, v)
}
}
if resp.Close {
newHeader.Add("Connection", "close")
}
statusCode := resp.StatusCode
if statusCode < 100 || statusCode >= 600 {
statusCode = http.StatusBadGateway
}
w.WriteHeader(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 {
conn.Close()
return nil, err
}
return &hijackedConn{
Conn: conn,
Reader: bufrw.Reader,
}, nil
}
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 = nil
var serverConn net.Conn
if ct, ok := h.rt.(*connTransport); ok {
serverConn = ct.Conn
} else if h.TLS {
serverConn, err = dialWithExtraRootCerts("tcp", addr)
} else {
serverConn, err = net.Dial("tcp", addr)
}
if err != nil {
log.Printf("Error making websocket connection to %s: %v", addr, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Some servers are very particular about the
// capitalization of the special WebSocket headers.
for k, v := range r.Header {
if strings.HasPrefix(k, "Sec-Websocket-") {
newKey := "Sec-WebSocket-" + strings.TrimPrefix(k, "Sec-Websocket-")
delete(r.Header, k)
r.Header[newKey] = v
}
}
err = r.Write(serverConn)
if err != nil {
log.Printf("Error sending websocket request to %s: %v", addr, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
hj, ok := w.(http.Hijacker)
if !ok {
log.Printf("Couldn't hijack client connection for websocket to %s", addr)
http.Error(w, "Couldn't create a websocket connection", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
log.Printf("Error hijacking client connection for websocket to %s: %v", addr, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
go func() {
io.Copy(conn, serverConn)
conn.Close()
}()
io.Copy(serverConn, bufrw)
serverConn.Close()
return
}
var hopByHop = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Proxy-Connection",
"TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
}
// removeHopByHopHeaders removes header fields listed in
// http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3.1
func removeHopByHopHeaders(h http.Header) {
toRemove := hopByHop
if c := h.Get("Connection"); c != "" {
for _, key := range strings.Split(c, ",") {
toRemove = append(toRemove, strings.TrimSpace(key))
}
}
for _, key := range toRemove {
h.Del(key)
}
}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away. (Copied from net/http package)
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
// A swallowErrorsWriter wraps an io.Writer so that writes always "succeed".
type swallowErrorsWriter struct {
w io.Writer
err error
}
func (s *swallowErrorsWriter) Write(p []byte) (n int, err error) {
if s.err == nil {
n, err = s.w.Write(p)
if err != nil {
s.err = err
}
}
return len(p), nil
}
// A Request is the parameter for the Starlark filter_request function.
type Request struct {
Request *http.Request
User string
ExpectedUser string
ClientIP string
LocalPort int
Session *TLSSession
// LogData is extra data to be included in log lines.
LogData starlark.Value
scoresAndACLs
frozen bool
misc starlark.Dict
hostChanged bool
}
func (r *Request) String() string {
return fmt.Sprintf("Request(%q)", r.Request.URL.String())
}
func (r *Request) Type() string {
return "Request"
}
func (r *Request) Freeze() {
if !r.frozen {
r.frozen = true
r.ACLs.Freeze()
r.Scores.Freeze()
r.misc.Freeze()
if r.LogData != nil {
r.LogData.Freeze()
}
}
}
func (r *Request) Truth() starlark.Bool {
return starlark.True
}
func (r *Request) Hash() (uint32, error) {
return 0, errors.New("unhashable type: Request")
}
var requestAttrNames = []string{"url", "method", "host", "path", "user", "expected_user", "local_port", "query", "header", "client_ip", "acls", "scores", "action", "possible_actions", "session", "misc", "log_data", "authenticated_clients"}
func (r *Request) AttrNames() []string {
return requestAttrNames
}
func (r *Request) Attr(name string) (starlark.Value, error) {
switch name {
case "url":
return starlark.String(r.Request.URL.String()), nil
case "method":
return starlark.String(r.Request.Method), nil
case "host":
return starlark.String(r.Request.Host), nil
case "path":
return starlark.String(r.Request.URL.Path), nil
case "user":
return starlark.String(r.User), nil
case "expected_user":
return starlark.String(r.ExpectedUser), nil
case "client_ip":
return starlark.String(r.ClientIP), nil
case "local_port":
return starlark.MakeInt(r.LocalPort), nil
case "acls":
return &r.ACLs, nil
case "scores":
return &r.Scores, nil
case "action":
ar, _ := r.currentAction()
return starlark.String(ar.Action), nil
case "possible_actions":
return stringTuple(r.PossibleActions), nil
case "header":
return &HeaderDict{data: r.Request.Header}, nil
case "query":
return &QueryDict{
data: r.Request.URL.Query(),
rawQuery: &r.Request.URL.RawQuery,
}, nil
case "session":
if r.Session == nil {
return starlark.None, nil
}
return r.Session, nil
case "misc":
return &r.misc, nil
case "log_data":
if r.LogData == nil {
return starlark.None, nil
}
return r.LogData, nil
case "authenticated_clients":
var clients starlark.Tuple
authCacheLock.RLock()
defer authCacheLock.RUnlock()
for ip, user := range authCache[r.LocalPort] {
if user == r.ExpectedUser {
clients = append(clients, starlark.String(ip))
}
}
return clients, nil
case "body":
content, err := io.ReadAll(r.Request.Body)
if err != nil {
return starlark.None, err
}
r.Request.Body = io.NopCloser(bytes.NewReader(content))
return starlark.String(content), nil
default:
return nil, nil
}
}
func (r *Request) SetField(name string, val starlark.Value) error {
if r.frozen {
return errors.New("can't set a field of a frozen object")
}
switch name {
case "url":
var u string
if err := assignStarlarkString(&u, val); err != nil {
return err
}
parsed, err := url.Parse(u)
if err != nil {
return err
}
if parsed.Host != r.Request.URL.Host {
r.Request.Host = parsed.Host
r.hostChanged = true
}
r.Request.URL = parsed
return nil
case "path":
return assignStarlarkString(&r.Request.URL.Path, val)
case "action":
var newAction string
if err := assignStarlarkString(&newAction, val); err != nil {
return err
}
return r.setAction(newAction)
case "log_data":
r.LogData = val
return nil
case "body":