source: code/trunk/morty.go@ 37

Last change on this file since 37 was 37, checked in by asciimoo, 9 years ago

[enh] display response errors to users ++ code formatting

File size: 17.1 KB
Line 
1package main
2
3import (
4 "bytes"
5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "flag"
10 "fmt"
11 "io"
12 "log"
13 "net/url"
14 "regexp"
15 "strings"
16 "time"
17
18 "github.com/valyala/fasthttp"
19 "golang.org/x/net/html"
20 "golang.org/x/text/encoding/charmap"
21)
22
23const (
24 STATE_DEFAULT int = 0
25 STATE_IN_STYLE int = 1
26 STATE_IN_NOSCRIPT int = 2
27)
28
29var CLIENT *fasthttp.Client = &fasthttp.Client{
30 MaxResponseBodySize: 10 * 1024 * 1024, // 10M
31}
32
33var CSS_URL_REGEXP *regexp.Regexp = regexp.MustCompile("url\\((['\"]?)[ \\t\\f]*([\u0009\u0021\u0023-\u0026\u0028\u002a-\u007E]+)(['\"]?)\\)?")
34
35var UNSAFE_ELEMENTS [][]byte = [][]byte{
36 []byte("applet"),
37 []byte("canvas"),
38 []byte("embed"),
39 //[]byte("iframe"),
40 []byte("script"),
41}
42
43var SAFE_ATTRIBUTES [][]byte = [][]byte{
44 []byte("abbr"),
45 []byte("accesskey"),
46 []byte("align"),
47 []byte("alt"),
48 []byte("as"),
49 []byte("autocomplete"),
50 []byte("charset"),
51 []byte("checked"),
52 []byte("class"),
53 []byte("content"),
54 []byte("contenteditable"),
55 []byte("contextmenu"),
56 []byte("dir"),
57 []byte("for"),
58 []byte("height"),
59 []byte("hidden"),
60 []byte("id"),
61 []byte("lang"),
62 []byte("media"),
63 []byte("method"),
64 []byte("name"),
65 []byte("nowrap"),
66 []byte("placeholder"),
67 []byte("property"),
68 []byte("rel"),
69 []byte("spellcheck"),
70 []byte("tabindex"),
71 []byte("target"),
72 []byte("title"),
73 []byte("translate"),
74 []byte("type"),
75 []byte("value"),
76 []byte("width"),
77}
78
79var SELF_CLOSING_ELEMENTS [][]byte = [][]byte{
80 []byte("area"),
81 []byte("base"),
82 []byte("br"),
83 []byte("col"),
84 []byte("embed"),
85 []byte("hr"),
86 []byte("img"),
87 []byte("input"),
88 []byte("keygen"),
89 []byte("link"),
90 []byte("meta"),
91 []byte("param"),
92 []byte("source"),
93 []byte("track"),
94 []byte("wbr"),
95}
96
97type Proxy struct {
98 Key []byte
99 RequestTimeout time.Duration
100}
101
102type RequestConfig struct {
103 Key []byte
104 BaseURL *url.URL
105}
106
107var HTML_FORM_EXTENSION string = `<input type="hidden" name="mortyurl" value="%s" /><input type="hidden" name="mortyhash" value="%s" />`
108
109var HTML_BODY_EXTENSION string = `
110<div id="mortyheader">
111 <input type="checkbox" id="mortytoggle" autocomplete="off" />
112 <div><p>This is a proxified and sanitized view of the page,<br />visit <a href="%s" rel="noreferrer">original site</a>.</p><p><label for="mortytoggle">hide</label></p></div>
113</div>
114<style>
115#mortyheader { position: fixed; padding: 12px 12px 12px 0; margin: 0; box-sizing: content-box; top: 15%%; left: 0; max-width: 140px; color: #444; overflow: hidden; z-index: 110000; font-size: 12px; line-height: normal; }
116#mortyheader a { color: #3498db; font-weight: bold; }
117#mortyheader p { padding: 0 0 0.7em 0; margin: 0; }
118#mortyheader > div { padding: 8px; font-size: 12px !important; font-family: sans !important; border-width: 4px 4px 4px 0; border-style: solid; border-color: #1abc9c; background: #FFF; line-height: 1em; }
119#mortyheader label { text-align: right; cursor: pointer; display: block; color: #444; padding: 0; margin: 0; }
120input[type=checkbox]#mortytoggle { display: none; }
121input[type=checkbox]#mortytoggle:checked ~ div { display: none; }
122</style>
123`
124
125func (p *Proxy) RequestHandler(ctx *fasthttp.RequestCtx) {
126
127 if appRequestHandler(ctx) {
128 return
129 }
130
131 requestHash := popRequestParam(ctx, []byte("mortyhash"))
132
133 requestURI := popRequestParam(ctx, []byte("mortyurl"))
134
135 if requestURI == nil {
136 p.serveMainPage(ctx, 200, nil)
137 return
138 }
139
140 if p.Key != nil {
141 if !verifyRequestURI(requestURI, requestHash, p.Key) {
142 // HTTP status code 403 : Forbidden
143 p.serveMainPage(ctx, 403, errors.New(`invalid "mortyhash" parameter`))
144 return
145 }
146 }
147
148 parsedURI, err := url.Parse(string(requestURI))
149
150 if strings.HasSuffix(parsedURI.Host, ".onion") {
151 // HTTP status code 501 : Not Implemented
152 p.serveMainPage(ctx, 501, errors.New("Tor urls are not supported yet"))
153 return
154 }
155
156 if err != nil {
157 // HTTP status code 500 : Internal Server Error
158 p.serveMainPage(ctx, 500, err)
159 return
160 }
161
162 req := fasthttp.AcquireRequest()
163 defer fasthttp.ReleaseRequest(req)
164 req.SetConnectionClose()
165
166 reqQuery := parsedURI.Query()
167 ctx.QueryArgs().VisitAll(func(key, value []byte) {
168 reqQuery.Add(string(key), string(value))
169 })
170
171 parsedURI.RawQuery = reqQuery.Encode()
172
173 uriStr := parsedURI.String()
174
175 log.Println("getting", uriStr)
176
177 req.SetRequestURI(uriStr)
178 req.Header.SetUserAgentBytes([]byte("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"))
179
180 resp := fasthttp.AcquireResponse()
181 defer fasthttp.ReleaseResponse(resp)
182
183 req.Header.SetMethodBytes(ctx.Method())
184 if ctx.IsPost() || ctx.IsPut() {
185 req.SetBody(ctx.PostBody())
186 }
187
188 err = CLIENT.DoTimeout(req, resp, p.RequestTimeout)
189
190 if err != nil {
191 if err == fasthttp.ErrTimeout {
192 // HTTP status code 504 : Gateway Time-Out
193 p.serveMainPage(ctx, 504, err)
194 } else {
195 // HTTP status code 500 : Internal Server Error
196 p.serveMainPage(ctx, 500, err)
197 }
198 return
199 }
200
201 if resp.StatusCode() != 200 {
202 switch resp.StatusCode() {
203 case 301, 302, 303, 307, 308:
204 loc := resp.Header.Peek("Location")
205 if loc != nil {
206 rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
207 url, err := rc.ProxifyURI(string(loc))
208 if err == nil {
209 ctx.SetStatusCode(resp.StatusCode())
210 ctx.Response.Header.Add("Location", url)
211 log.Println("redirect to", string(loc))
212 return
213 }
214 }
215 }
216 error_message := fmt.Sprintf("invalid response: %d", resp.StatusCode())
217 p.serveMainPage(ctx, resp.StatusCode(), errors.New(error_message))
218 return
219 }
220
221 contentType := resp.Header.Peek("Content-Type")
222
223 if contentType == nil {
224 // HTTP status code 503 : Service Unavailable
225 p.serveMainPage(ctx, 503, errors.New("invalid content type"))
226 return
227 }
228
229 if bytes.Contains(bytes.ToLower(contentType), []byte("javascript")) {
230 // HTTP status code 403 : Forbidden
231 p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
232 return
233 }
234
235 contentInfo := bytes.SplitN(contentType, []byte(";"), 2)
236
237 var responseBody []byte
238
239 if len(contentInfo) == 2 && bytes.Contains(contentInfo[1], []byte("ISO-8859-2")) && bytes.Contains(contentInfo[0], []byte("text")) {
240 var err error
241 responseBody, err = charmap.ISO8859_2.NewDecoder().Bytes(resp.Body())
242 if err != nil {
243 // HTTP status code 503 : Service Unavailable
244 p.serveMainPage(ctx, 503, err)
245 return
246 }
247 } else {
248 responseBody = resp.Body()
249 }
250
251 ctx.SetContentType(fmt.Sprintf("%s; charset=UTF-8", contentInfo[0]))
252
253 switch {
254 case bytes.Contains(contentType, []byte("css")):
255 sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
256 case bytes.Contains(contentType, []byte("html")):
257 sanitizeHTML(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
258 default:
259 ctx.Write(responseBody)
260 }
261}
262
263func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
264 // serve robots.txt
265 if bytes.Equal(ctx.Path(), []byte("/robots.txt")) {
266 ctx.SetContentType("text/plain")
267 ctx.Write([]byte("User-Agent: *\nDisallow: /\n"))
268 return true
269 }
270
271 return false
272}
273
274func popRequestParam(ctx *fasthttp.RequestCtx, paramName []byte) []byte {
275 param := ctx.QueryArgs().PeekBytes(paramName)
276
277 if param == nil {
278 param = ctx.PostArgs().PeekBytes(paramName)
279 if param != nil {
280 ctx.PostArgs().DelBytes(paramName)
281 }
282 } else {
283 ctx.QueryArgs().DelBytes(paramName)
284 }
285
286 return param
287}
288
289func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
290 // TODO
291
292 urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
293
294 if urlSlices == nil {
295 out.Write(css)
296 return
297 }
298
299 startIndex := 0
300
301 for _, s := range urlSlices {
302 urlStart := s[4]
303 urlEnd := s[5]
304
305 if uri, err := rc.ProxifyURI(string(css[urlStart:urlEnd])); err == nil {
306 out.Write(css[startIndex:urlStart])
307 out.Write([]byte(uri))
308 startIndex = urlEnd
309 } else {
310 log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
311 }
312 }
313 if startIndex < len(css) {
314 out.Write(css[startIndex:len(css)])
315 }
316}
317
318func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
319 r := bytes.NewReader(htmlDoc)
320 decoder := html.NewTokenizer(r)
321 decoder.AllowCDATA(true)
322
323 unsafeElements := make([][]byte, 0, 8)
324 state := STATE_DEFAULT
325
326 for {
327 token := decoder.Next()
328 if token == html.ErrorToken {
329 err := decoder.Err()
330 if err != io.EOF {
331 log.Println("failed to parse HTML:")
332 }
333 break
334 }
335
336 if len(unsafeElements) == 0 {
337
338 switch token {
339 case html.StartTagToken, html.SelfClosingTagToken:
340 tag, hasAttrs := decoder.TagName()
341 safe := !inArray(tag, UNSAFE_ELEMENTS)
342 if !safe {
343 if !inArray(tag, SELF_CLOSING_ELEMENTS) {
344 var unsafeTag []byte = make([]byte, len(tag))
345 copy(unsafeTag, tag)
346 unsafeElements = append(unsafeElements, unsafeTag)
347 }
348 break
349 }
350 if bytes.Equal(tag, []byte("noscript")) {
351 state = STATE_IN_NOSCRIPT
352 break
353 }
354 var attrs [][][]byte
355 if hasAttrs {
356 for {
357 attrName, attrValue, moreAttr := decoder.TagAttr()
358 attrs = append(attrs, [][]byte{
359 attrName,
360 attrValue,
361 []byte(html.EscapeString(string(attrValue))),
362 })
363 if !moreAttr {
364 break
365 }
366 }
367 }
368 if bytes.Equal(tag, []byte("link")) {
369 sanitizeLinkTag(rc, out, attrs)
370 break
371 }
372
373 fmt.Fprintf(out, "<%s", tag)
374
375 if hasAttrs {
376 if bytes.Equal(tag, []byte("meta")) {
377 sanitizeMetaAttrs(rc, out, attrs)
378 } else {
379 sanitizeAttrs(rc, out, attrs)
380 }
381 }
382
383 if token == html.SelfClosingTagToken {
384 fmt.Fprintf(out, " />")
385 } else {
386 fmt.Fprintf(out, ">")
387 if bytes.Equal(tag, []byte("style")) {
388 state = STATE_IN_STYLE
389 }
390 }
391
392 if bytes.Equal(tag, []byte("form")) {
393 var formURL *url.URL
394 for _, attr := range attrs {
395 if bytes.Equal(attr[0], []byte("action")) {
396 formURL, _ = url.Parse(string(attr[1]))
397 formURL = mergeURIs(rc.BaseURL, formURL)
398 break
399 }
400 }
401 if formURL == nil {
402 formURL = rc.BaseURL
403 }
404 urlStr := formURL.String()
405 var key string
406 if rc.Key != nil {
407 key = hash(urlStr, rc.Key)
408 }
409 fmt.Fprintf(out, HTML_FORM_EXTENSION, urlStr, key)
410
411 }
412
413 case html.EndTagToken:
414 tag, _ := decoder.TagName()
415 writeEndTag := true
416 switch string(tag) {
417 case "body":
418 fmt.Fprintf(out, HTML_BODY_EXTENSION, rc.BaseURL.String())
419 case "style":
420 state = STATE_DEFAULT
421 case "noscript":
422 state = STATE_DEFAULT
423 writeEndTag = false
424 }
425 // skip noscript tags - only the tag, not the content, because javascript is sanitized
426 if writeEndTag {
427 fmt.Fprintf(out, "</%s>", tag)
428 }
429
430 case html.TextToken:
431 switch state {
432 case STATE_DEFAULT:
433 fmt.Fprintf(out, "%s", decoder.Raw())
434 case STATE_IN_STYLE:
435 sanitizeCSS(rc, out, decoder.Raw())
436 case STATE_IN_NOSCRIPT:
437 sanitizeHTML(rc, out, decoder.Raw())
438 }
439
440 case html.DoctypeToken, html.CommentToken:
441 out.Write(decoder.Raw())
442 }
443 } else {
444 switch token {
445 case html.StartTagToken:
446 tag, _ := decoder.TagName()
447 if inArray(tag, UNSAFE_ELEMENTS) {
448 unsafeElements = append(unsafeElements, tag)
449 }
450
451 case html.EndTagToken:
452 tag, _ := decoder.TagName()
453 if bytes.Equal(unsafeElements[len(unsafeElements)-1], tag) {
454 unsafeElements = unsafeElements[:len(unsafeElements)-1]
455 }
456 }
457 }
458 }
459}
460
461func sanitizeLinkTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
462 exclude := false
463 for _, attr := range attrs {
464 attrName := attr[0]
465 attrValue := attr[1]
466 if bytes.Equal(attrName, []byte("rel")) {
467 if bytes.Equal(attrValue, []byte("dns-prefetch")) {
468 exclude = true
469 break
470 }
471 }
472 if bytes.Equal(attrName, []byte("as")) {
473 if bytes.Equal(attrValue, []byte("script")) {
474 exclude = true
475 break
476 }
477 }
478 }
479
480 if !exclude {
481 out.Write([]byte("<link"))
482 for _, attr := range attrs {
483 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
484 }
485 out.Write([]byte(">"))
486 }
487}
488
489func sanitizeMetaAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
490 var http_equiv []byte
491 var content []byte
492
493 for _, attr := range attrs {
494 attrName := attr[0]
495 attrValue := attr[1]
496 if bytes.Equal(attrName, []byte("http-equiv")) {
497 http_equiv = bytes.ToLower(attrValue)
498 }
499 if bytes.Equal(attrName, []byte("content")) {
500 content = attrValue
501 }
502 }
503
504 urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
505 if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
506 contentUrl := content[urlIndex+4:]
507 // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
508 if len(contentUrl) >= 2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
509 if contentUrl[0] == contentUrl[len(contentUrl)-1] {
510 contentUrl = contentUrl[1 : len(contentUrl)-1]
511 }
512 }
513 // output proxify result
514 if uri, err := rc.ProxifyURI(string(contentUrl)); err == nil {
515 fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
516 }
517 } else {
518 sanitizeAttrs(rc, out, attrs)
519 }
520
521}
522
523func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
524 for _, attr := range attrs {
525 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
526 }
527}
528
529func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
530 if inArray(attrName, SAFE_ATTRIBUTES) {
531 fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
532 return
533 }
534 switch string(attrName) {
535 case "src", "href", "action":
536 if uri, err := rc.ProxifyURI(string(attrValue)); err == nil {
537 fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
538 } else {
539 log.Println("cannot proxify uri:", string(attrValue))
540 }
541 case "style":
542 cssAttr := bytes.NewBuffer(nil)
543 sanitizeCSS(rc, cssAttr, attrValue)
544 fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
545 }
546}
547
548func mergeURIs(u1, u2 *url.URL) *url.URL {
549 return u1.ResolveReference(u2)
550}
551
552func (rc *RequestConfig) ProxifyURI(uri string) (string, error) {
553 // remove javascript protocol
554 if strings.HasPrefix(uri, "javascript:") {
555 return "", nil
556 }
557 // TODO check malicious data: - e.g. data:script
558 if strings.HasPrefix(uri, "data:") {
559 return uri, nil
560 }
561
562 if len(uri) > 0 && uri[0] == '#' {
563 return uri, nil
564 }
565
566 u, err := url.Parse(uri)
567 if err != nil {
568 return "", err
569 }
570 u = mergeURIs(rc.BaseURL, u)
571
572 uri = u.String()
573
574 if rc.Key == nil {
575 return fmt.Sprintf("./?mortyurl=%s", url.QueryEscape(uri)), nil
576 }
577 return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s", hash(uri, rc.Key), url.QueryEscape(uri)), nil
578}
579
580func inArray(b []byte, a [][]byte) bool {
581 for _, b2 := range a {
582 if bytes.Equal(b, b2) {
583 return true
584 }
585 }
586 return false
587}
588
589func hash(msg string, key []byte) string {
590 mac := hmac.New(sha256.New, key)
591 mac.Write([]byte(msg))
592 return hex.EncodeToString(mac.Sum(nil))
593}
594
595func verifyRequestURI(uri, hashMsg, key []byte) bool {
596 h := make([]byte, hex.DecodedLen(len(hashMsg)))
597 _, err := hex.Decode(h, hashMsg)
598 if err != nil {
599 log.Println("hmac error:", err)
600 return false
601 }
602 mac := hmac.New(sha256.New, key)
603 mac.Write(uri)
604 return hmac.Equal(h, mac.Sum(nil))
605}
606
607func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
608 ctx.SetContentType("text/html")
609 ctx.SetStatusCode(statusCode)
610 ctx.Write([]byte(`<!doctype html>
611<head>
612<title>MortyProxy</title>
613<meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
614<style>
615html { height: 100%; }
616body { min-height : 100%; display: flex; flex-direction:column; font-family: 'Garamond', 'Georgia', serif; text-align: center; color: #444; background: #FAFAFA; margin: 0; padding: 0; font-size: 1.1em; }
617input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
618input[placeholder] { width:80%; }
619a { text-decoration: none; #2980b9; }
620h1, h2 { font-weight: 200; margin-bottom: 2rem; }
621h1 { font-size: 3em; }
622.container { flex:1; min-height: 100%; margin-bottom: 1em; }
623.footer { margin: 1em; }
624.footer p { font-size: 0.8em; }
625</style>
626</head>
627<body>
628 <div class="container">
629 <h1>MortyProxy</h1>
630`))
631 if err != nil {
632 log.Println("error:", err)
633 ctx.Write([]byte("<h2>Error: "))
634 ctx.Write([]byte(html.EscapeString(err.Error())))
635 ctx.Write([]byte("</h2>"))
636 }
637 if p.Key == nil {
638 ctx.Write([]byte(`
639 <form action="post">
640 Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
641 <input type="submit" value="go" />
642 </form>`))
643 } else {
644 ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
645 }
646 ctx.Write([]byte(`
647 </div>
648 <div class="footer">
649 <p>Morty rewrites web pages to exclude malicious HTML tags and CSS/HTML attributes. It also replaces external resource references to prevent third-party information leaks.<br />
650 <a href="https://github.com/asciimoo/morty">view on github</a>
651 </p>
652 </div>
653</body>
654</html>`))
655}
656
657func main() {
658
659 listen := flag.String("listen", "127.0.0.1:3000", "Listen address")
660 key := flag.String("key", "", "HMAC url validation key (hexadecimal encoded) - leave blank to disable")
661 ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
662 requestTimeout := flag.Uint("timeout", 2, "Request timeout")
663 flag.Parse()
664
665 if *ipv6 {
666 CLIENT.Dial = fasthttp.DialDualStack
667 }
668
669 p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
670
671 if *key != "" {
672 p.Key = []byte(*key)
673 }
674
675 log.Println("listening on", *listen)
676
677 if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
678 log.Fatal("Error in ListenAndServe:", err)
679 }
680}
Note: See TracBrowser for help on using the repository browser.