source: code/trunk/morty.go@ 36

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

Merge pull request #28 from dalf/http_status_code

[mod] returns different HTTP status codes according to the errors

File size: 17.0 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 log.Println("invalid request:", resp.StatusCode())
217 return
218 }
219
220 contentType := resp.Header.Peek("Content-Type")
221
222 if contentType == nil {
223 // HTTP status code 503 : Service Unavailable
224 p.serveMainPage(ctx, 503, errors.New("invalid content type"))
225 return
226 }
227
228 if bytes.Contains(bytes.ToLower(contentType), []byte("javascript")) {
229 // HTTP status code 403 : Forbidden
230 p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
231 return
232 }
233
234 contentInfo := bytes.SplitN(contentType, []byte(";"), 2)
235
236 var responseBody []byte
237
238 if len(contentInfo) == 2 && bytes.Contains(contentInfo[1], []byte("ISO-8859-2")) && bytes.Contains(contentInfo[0], []byte("text")) {
239 var err error
240 responseBody, err = charmap.ISO8859_2.NewDecoder().Bytes(resp.Body())
241 if err != nil {
242 // HTTP status code 503 : Service Unavailable
243 p.serveMainPage(ctx, 503, err)
244 return
245 }
246 } else {
247 responseBody = resp.Body()
248 }
249
250 ctx.SetContentType(fmt.Sprintf("%s; charset=UTF-8", contentInfo[0]))
251
252 switch {
253 case bytes.Contains(contentType, []byte("css")):
254 sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
255 case bytes.Contains(contentType, []byte("html")):
256 sanitizeHTML(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
257 default:
258 ctx.Write(responseBody)
259 }
260}
261
262func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
263 // serve robots.txt
264 if bytes.Equal(ctx.Path(), []byte("/robots.txt")) {
265 ctx.SetContentType("text/plain")
266 ctx.Write([]byte("User-Agent: *\nDisallow: /\n"))
267 return true
268 }
269
270 return false
271}
272
273func popRequestParam(ctx *fasthttp.RequestCtx, paramName []byte) []byte {
274 param := ctx.QueryArgs().PeekBytes(paramName)
275
276 if param == nil {
277 param = ctx.PostArgs().PeekBytes(paramName)
278 if param != nil {
279 ctx.PostArgs().DelBytes(paramName)
280 }
281 } else {
282 ctx.QueryArgs().DelBytes(paramName)
283 }
284
285 return param
286}
287
288func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
289 // TODO
290
291 urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
292
293 if urlSlices == nil {
294 out.Write(css)
295 return
296 }
297
298 startIndex := 0
299
300 for _, s := range urlSlices {
301 urlStart := s[4]
302 urlEnd := s[5]
303
304 if uri, err := rc.ProxifyURI(string(css[urlStart:urlEnd])); err == nil {
305 out.Write(css[startIndex:urlStart])
306 out.Write([]byte(uri))
307 startIndex = urlEnd
308 } else {
309 log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
310 }
311 }
312 if startIndex < len(css) {
313 out.Write(css[startIndex:len(css)])
314 }
315}
316
317func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
318 r := bytes.NewReader(htmlDoc)
319 decoder := html.NewTokenizer(r)
320 decoder.AllowCDATA(true)
321
322 unsafeElements := make([][]byte, 0, 8)
323 state := STATE_DEFAULT
324
325 for {
326 token := decoder.Next()
327 if token == html.ErrorToken {
328 err := decoder.Err()
329 if err != io.EOF {
330 log.Println("failed to parse HTML:")
331 }
332 break
333 }
334
335 if len(unsafeElements) == 0 {
336
337 switch token {
338 case html.StartTagToken, html.SelfClosingTagToken:
339 tag, hasAttrs := decoder.TagName()
340 safe := !inArray(tag, UNSAFE_ELEMENTS)
341 if !safe {
342 if !inArray(tag, SELF_CLOSING_ELEMENTS) {
343 var unsafeTag []byte = make([]byte, len(tag))
344 copy(unsafeTag, tag)
345 unsafeElements = append(unsafeElements, unsafeTag)
346 }
347 break
348 }
349 if bytes.Equal(tag, []byte("noscript")) {
350 state = STATE_IN_NOSCRIPT
351 break
352 }
353 var attrs [][][]byte
354 if hasAttrs {
355 for {
356 attrName, attrValue, moreAttr := decoder.TagAttr()
357 attrs = append(attrs, [][]byte{
358 attrName,
359 attrValue,
360 []byte(html.EscapeString(string(attrValue))),
361 })
362 if !moreAttr {
363 break
364 }
365 }
366 }
367 if bytes.Equal(tag, []byte("link")) {
368 sanitizeLinkTag(rc, out, attrs)
369 break
370 }
371
372 fmt.Fprintf(out, "<%s", tag)
373
374 if hasAttrs {
375 if bytes.Equal(tag, []byte("meta")) {
376 sanitizeMetaAttrs(rc, out, attrs)
377 } else {
378 sanitizeAttrs(rc, out, attrs)
379 }
380 }
381
382 if token == html.SelfClosingTagToken {
383 fmt.Fprintf(out, " />")
384 } else {
385 fmt.Fprintf(out, ">")
386 if bytes.Equal(tag, []byte("style")) {
387 state = STATE_IN_STYLE
388 }
389 }
390
391 if bytes.Equal(tag, []byte("form")) {
392 var formURL *url.URL
393 for _, attr := range attrs {
394 if bytes.Equal(attr[0], []byte("action")) {
395 formURL, _ = url.Parse(string(attr[1]))
396 formURL = mergeURIs(rc.BaseURL, formURL)
397 break
398 }
399 }
400 if formURL == nil {
401 formURL = rc.BaseURL
402 }
403 urlStr := formURL.String()
404 var key string
405 if rc.Key != nil {
406 key = hash(urlStr, rc.Key)
407 }
408 fmt.Fprintf(out, HTML_FORM_EXTENSION, urlStr, key)
409
410 }
411
412 case html.EndTagToken:
413 tag, _ := decoder.TagName()
414 writeEndTag := true
415 switch string(tag) {
416 case "body":
417 fmt.Fprintf(out, HTML_BODY_EXTENSION, rc.BaseURL.String())
418 case "style":
419 state = STATE_DEFAULT
420 case "noscript":
421 state = STATE_DEFAULT
422 writeEndTag = false
423 }
424 // skip noscript tags - only the tag, not the content, because javascript is sanitized
425 if writeEndTag {
426 fmt.Fprintf(out, "</%s>", tag)
427 }
428
429 case html.TextToken:
430 switch state {
431 case STATE_DEFAULT:
432 fmt.Fprintf(out, "%s", decoder.Raw())
433 case STATE_IN_STYLE:
434 sanitizeCSS(rc, out, decoder.Raw())
435 case STATE_IN_NOSCRIPT:
436 sanitizeHTML(rc, out, decoder.Raw())
437 }
438
439 case html.DoctypeToken, html.CommentToken:
440 out.Write(decoder.Raw())
441 }
442 } else {
443 switch token {
444 case html.StartTagToken:
445 tag, _ := decoder.TagName()
446 if inArray(tag, UNSAFE_ELEMENTS) {
447 unsafeElements = append(unsafeElements, tag)
448 }
449
450 case html.EndTagToken:
451 tag, _ := decoder.TagName()
452 if bytes.Equal(unsafeElements[len(unsafeElements)-1], tag) {
453 unsafeElements = unsafeElements[:len(unsafeElements)-1]
454 }
455 }
456 }
457 }
458}
459
460func sanitizeLinkTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
461 exclude := false
462 for _, attr := range attrs {
463 attrName := attr[0]
464 attrValue := attr[1]
465 if bytes.Equal(attrName, []byte("rel")) {
466 if bytes.Equal(attrValue, []byte("dns-prefetch")) {
467 exclude = true
468 break
469 }
470 }
471 if bytes.Equal(attrName, []byte("as")) {
472 if bytes.Equal(attrValue, []byte("script")) {
473 exclude = true
474 break
475 }
476 }
477 }
478
479 if !exclude {
480 out.Write([]byte("<link"))
481 for _, attr := range attrs {
482 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
483 }
484 out.Write([]byte(">"))
485 }
486}
487
488func sanitizeMetaAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
489 var http_equiv []byte
490 var content []byte
491
492 for _, attr := range attrs {
493 attrName := attr[0]
494 attrValue := attr[1]
495 if bytes.Equal(attrName, []byte("http-equiv")) {
496 http_equiv = bytes.ToLower(attrValue)
497 }
498 if bytes.Equal(attrName, []byte("content")) {
499 content = attrValue
500 }
501 }
502
503 urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
504 if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
505 contentUrl := content[urlIndex+4:]
506 // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
507 if len(contentUrl)>=2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
508 if contentUrl[0] == contentUrl[len(contentUrl)-1] {
509 contentUrl=contentUrl[1:len(contentUrl)-1]
510 }
511 }
512 // output proxify result
513 if uri, err := rc.ProxifyURI(string(contentUrl)); err == nil {
514 fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
515 }
516 } else {
517 sanitizeAttrs(rc, out, attrs)
518 }
519
520}
521
522func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
523 for _, attr := range attrs {
524 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
525 }
526}
527
528func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
529 if inArray(attrName, SAFE_ATTRIBUTES) {
530 fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
531 return
532 }
533 switch string(attrName) {
534 case "src", "href", "action":
535 if uri, err := rc.ProxifyURI(string(attrValue)); err == nil {
536 fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
537 } else {
538 log.Println("cannot proxify uri:", string(attrValue))
539 }
540 case "style":
541 cssAttr := bytes.NewBuffer(nil)
542 sanitizeCSS(rc, cssAttr, attrValue)
543 fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
544 }
545}
546
547func mergeURIs(u1, u2 *url.URL) *url.URL {
548 return u1.ResolveReference(u2)
549}
550
551func (rc *RequestConfig) ProxifyURI(uri string) (string, error) {
552 // remove javascript protocol
553 if strings.HasPrefix(uri, "javascript:") {
554 return "", nil
555 }
556 // TODO check malicious data: - e.g. data:script
557 if strings.HasPrefix(uri, "data:") {
558 return uri, nil
559 }
560
561 if len(uri) > 0 && uri[0] == '#' {
562 return uri, nil
563 }
564
565 u, err := url.Parse(uri)
566 if err != nil {
567 return "", err
568 }
569 u = mergeURIs(rc.BaseURL, u)
570
571 uri = u.String()
572
573 if rc.Key == nil {
574 return fmt.Sprintf("./?mortyurl=%s", url.QueryEscape(uri)), nil
575 }
576 return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s", hash(uri, rc.Key), url.QueryEscape(uri)), nil
577}
578
579func inArray(b []byte, a [][]byte) bool {
580 for _, b2 := range a {
581 if bytes.Equal(b, b2) {
582 return true
583 }
584 }
585 return false
586}
587
588func hash(msg string, key []byte) string {
589 mac := hmac.New(sha256.New, key)
590 mac.Write([]byte(msg))
591 return hex.EncodeToString(mac.Sum(nil))
592}
593
594func verifyRequestURI(uri, hashMsg, key []byte) bool {
595 h := make([]byte, hex.DecodedLen(len(hashMsg)))
596 _, err := hex.Decode(h, hashMsg)
597 if err != nil {
598 log.Println("hmac error:", err)
599 return false
600 }
601 mac := hmac.New(sha256.New, key)
602 mac.Write(uri)
603 return hmac.Equal(h, mac.Sum(nil))
604}
605
606func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
607 ctx.SetContentType("text/html")
608 ctx.SetStatusCode(statusCode)
609 ctx.Write([]byte(`<!doctype html>
610<head>
611<title>MortyProxy</title>
612<meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
613<style>
614html { height: 100%; }
615body { 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; }
616input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
617input[placeholder] { width:80%; }
618a { text-decoration: none; #2980b9; }
619h1, h2 { font-weight: 200; margin-bottom: 2rem; }
620h1 { font-size: 3em; }
621.container { flex:1; min-height: 100%; margin-bottom: 1em; }
622.footer { margin: 1em; }
623.footer p { font-size: 0.8em; }
624</style>
625</head>
626<body>
627 <div class="container">
628 <h1>MortyProxy</h1>
629`))
630 if err != nil {
631 log.Println("error:", err)
632 ctx.Write([]byte("<h2>Error: "))
633 ctx.Write([]byte(html.EscapeString(err.Error())))
634 ctx.Write([]byte("</h2>"))
635 }
636 if p.Key == nil {
637 ctx.Write([]byte(`
638 <form action="post">
639 Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
640 <input type="submit" value="go" />
641 </form>`))
642 } else {
643 ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
644 }
645 ctx.Write([]byte(`
646 </div>
647 <div class="footer">
648 <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 />
649 <a href="https://github.com/asciimoo/morty">view on github</a>
650 </p>
651 </div>
652</body>
653</html>`))
654}
655
656func main() {
657
658 listen := flag.String("listen", "127.0.0.1:3000", "Listen address")
659 key := flag.String("key", "", "HMAC url validation key (hexadecimal encoded) - leave blank to disable")
660 ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
661 requestTimeout := flag.Uint("timeout", 2, "Request timeout")
662 flag.Parse()
663
664 if *ipv6 {
665 CLIENT.Dial = fasthttp.DialDualStack
666 }
667
668 p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
669
670 if *key != "" {
671 p.Key = []byte(*key)
672 }
673
674 log.Println("listening on", *listen)
675
676 if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
677 log.Fatal("Error in ListenAndServe:", err)
678 }
679}
Note: See TracBrowser for help on using the repository browser.