-
Notifications
You must be signed in to change notification settings - Fork 37
/
blockpage.go
276 lines (241 loc) · 7.29 KB
/
blockpage.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"strconv"
"strings"
"go.starlark.net/starlark"
)
// Functions for displaying block pages.
// transparent1x1 is a single-pixel transparent GIF file.
const transparent1x1 = "GIF89a\x10\x00\x10\x00\x80\xff\x00\xc0\xc0\xc0\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x02\x0e\x84\x8f\xa9\xcb\xed\x0f\xa3\x9c\xb4\u068b\xb3>\x05\x00;"
func (c *config) loadBlockPage(path string) error {
if strings.HasPrefix(path, "http") {
c.BlockTemplate = nil
c.BlockpageURL = path
return nil
}
bt := template.New("blockpage")
content, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("error loading block page template: %v", err)
}
_, err = bt.Parse(string(content))
if err != nil {
return fmt.Errorf("error parsing block page template: %v", err)
}
c.BlockTemplate = bt
c.BlockpageURL = ""
return nil
}
type blockData struct {
URL string
Categories string
Conditions string
User string
Tally string
Scores string
RuleDescription string
Referer string
Request *http.Request
Response *http.Response
}
func (c *config) aclDescription(name string) string {
cat, ok := c.Categories[name]
if ok {
return cat.description
}
d, ok := c.ACLs.Descriptions[name]
if ok {
return d
}
return name
}
// Convert rule conditions into category descriptions as much as possible.
func (c *config) aclDescriptions(rule ACLActionRule) []string {
var categories []string
for _, acl := range rule.Needed {
categories = append(categories, c.aclDescription(acl))
}
for _, acl := range rule.Disallowed {
categories = append(categories, "not "+c.aclDescription(acl))
}
return categories
}
// showBlockPage shows a block page for a page that was blocked by an ACL.
func showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule, extraData any) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("X-Redwood-Block-Page", "403 Access Denied")
c := getConfig()
switch {
case c.BlockTemplate != nil:
data := blockData{
URL: r.URL.String(),
Conditions: rule.Conditions(),
User: user,
Tally: listTally(stringTally(tally)),
Scores: listTally(scores),
Categories: strings.Join(c.aclDescriptions(rule), ", "),
RuleDescription: rule.Description,
Referer: r.Referer(),
Request: r,
Response: resp,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
err := c.BlockTemplate.Execute(w, data)
if err != nil {
log.Println("Error filling in block page template:", err)
}
case c.BlockpageURL != "":
clientIP := r.RemoteAddr
if host, _, err := net.SplitHostPort(clientIP); err == nil {
clientIP = host
}
if e, ok := extraData.(starlark.Value); ok {
j, err := starlark.Call(&starlark.Thread{Name: "json.encode"}, starlarkJSONEncode, starlark.Tuple{e}, nil)
if err == nil {
if j, ok := j.(starlark.String); ok {
extraData = json.RawMessage(j)
}
}
}
d := map[string]interface{}{
"url": r.URL.String(),
"rule": rule,
"user": user,
"tally": stringTally(tally),
"scores": scores,
"categories": c.aclDescriptions(rule),
"method": r.Method,
"client-ip": clientIP,
"referer": r.Referer(),
"request-header": r.Header,
"log-data": extraData,
}
if resp != nil {
d["response-header"] = resp.Header
}
data, err := json.Marshal(d)
if err != nil {
log.Println("Error generating JSON info for block page:", err)
http.Error(w, "", http.StatusForbidden)
return
}
blockReq, err := http.NewRequestWithContext(r.Context(), "POST", c.BlockpageURL, bytes.NewReader(data))
if err != nil {
log.Printf("Error fetching blockpage from %s: %v", c.BlockpageURL, err)
http.Error(w, "", http.StatusForbidden)
return
}
blockReq.Header.Set("Content-Type", "application/json")
blockResp, err := transportWithExtraRootCerts.RoundTrip(blockReq)
if err != nil {
log.Printf("Error fetching blockpage from %s: %v", c.BlockpageURL, err)
http.Error(w, "", http.StatusForbidden)
return
}
defer blockResp.Body.Close()
removeHopByHopHeaders(blockResp.Header)
if blockResp.ContentLength > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(blockResp.ContentLength, 10))
}
if blockResp.StatusCode == http.StatusOK {
blockResp.StatusCode = http.StatusForbidden
}
copyResponseHeader(w, blockResp)
_, err = io.Copy(w, blockResp.Body)
if err != nil {
panic(http.ErrAbortHandler)
}
default:
http.Error(w, "", http.StatusForbidden)
return
}
}
// showInvisibleBlock blocks the request with an invisible image.
func showInvisibleBlock(w http.ResponseWriter) {
w.Header().Set("Content-Type", "image/gif")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, transparent1x1)
}
func (c *config) loadErrorPage(path string) error {
if strings.HasPrefix(path, "http") {
c.ErrorTemplate = nil
c.ErrorURL = path
return nil
}
bt := template.New("errorpage")
content, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("error loading error page template: %v", err)
}
_, err = bt.Parse(string(content))
if err != nil {
return fmt.Errorf("error parsing error page template: %v", err)
}
c.ErrorTemplate = bt
c.ErrorURL = ""
return nil
}
// showErrorPage shows an error page for a request that failed (as we were
// fetching it from the origin server).
func showErrorPage(w http.ResponseWriter, r *http.Request, pageError error) {
w.Header().Set("Access-Control-Allow-Origin", "*")
c := getConfig()
d := map[string]interface{}{
"url": r.URL.String(),
"error": pageError.Error(),
}
var dnsError *net.DNSError
if errors.As(pageError, &dnsError) {
d["dns error"] = dnsError
}
w.Header().Set("Connection", "close")
switch {
case c.ErrorTemplate != nil:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadGateway)
err := c.ErrorTemplate.Execute(w, d)
if err != nil {
log.Println("Error filling in error page template:", err)
panic(http.ErrAbortHandler)
}
case c.ErrorURL != "":
data, err := json.Marshal(d)
if err != nil {
log.Println("Error generating JSON info for error page:", err)
http.Error(w, pageError.Error(), http.StatusBadGateway)
return
}
errorResp, err := clientWithExtraRootCerts.Post(c.ErrorURL, "application/json", bytes.NewReader(data))
if err != nil {
log.Printf("Error fetching error page from %s: %v", c.ErrorURL, err)
http.Error(w, pageError.Error(), http.StatusBadGateway)
return
}
defer errorResp.Body.Close()
removeHopByHopHeaders(errorResp.Header)
if errorResp.ContentLength > 0 {
w.Header().Set("Content-Length", strconv.FormatInt(errorResp.ContentLength, 10))
}
errorResp.StatusCode = http.StatusBadGateway
copyResponseHeader(w, errorResp)
_, err = io.Copy(w, errorResp.Body)
if err != nil {
panic(http.ErrAbortHandler)
}
default:
http.Error(w, pageError.Error(), http.StatusBadGateway)
return
}
}