[1] | 1 | package main
|
---|
| 2 |
|
---|
| 3 | import (
|
---|
| 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"
|
---|
[4] | 16 | "time"
|
---|
[1] | 17 |
|
---|
| 18 | "github.com/valyala/fasthttp"
|
---|
| 19 | "golang.org/x/net/html"
|
---|
| 20 | "golang.org/x/text/encoding/charmap"
|
---|
| 21 | )
|
---|
| 22 |
|
---|
| 23 | const (
|
---|
| 24 | STATE_DEFAULT int = 0
|
---|
| 25 | STATE_IN_STYLE int = 1
|
---|
| 26 | STATE_IN_NOSCRIPT int = 2
|
---|
| 27 | )
|
---|
| 28 |
|
---|
| 29 | var CLIENT *fasthttp.Client = &fasthttp.Client{
|
---|
| 30 | MaxResponseBodySize: 10 * 1024 * 1024, // 10M
|
---|
| 31 | }
|
---|
| 32 |
|
---|
[27] | 33 | var CSS_URL_REGEXP *regexp.Regexp = regexp.MustCompile("url\\((['\"]?)[ \\t\\f]*([\u0009\u0021\u0023-\u0026\u0028\u002a-\u007E]+)(['\"]?)\\)?")
|
---|
[1] | 34 |
|
---|
| 35 | var UNSAFE_ELEMENTS [][]byte = [][]byte{
|
---|
| 36 | []byte("applet"),
|
---|
| 37 | []byte("canvas"),
|
---|
| 38 | []byte("embed"),
|
---|
| 39 | //[]byte("iframe"),
|
---|
| 40 | []byte("script"),
|
---|
| 41 | }
|
---|
| 42 |
|
---|
| 43 | var SAFE_ATTRIBUTES [][]byte = [][]byte{
|
---|
| 44 | []byte("abbr"),
|
---|
| 45 | []byte("accesskey"),
|
---|
| 46 | []byte("align"),
|
---|
| 47 | []byte("alt"),
|
---|
[13] | 48 | []byte("as"),
|
---|
[1] | 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 |
|
---|
| 79 | var 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 |
|
---|
| 97 | type Proxy struct {
|
---|
[4] | 98 | Key []byte
|
---|
| 99 | RequestTimeout time.Duration
|
---|
[1] | 100 | }
|
---|
| 101 |
|
---|
| 102 | type RequestConfig struct {
|
---|
| 103 | Key []byte
|
---|
[23] | 104 | BaseURL *url.URL
|
---|
[1] | 105 | }
|
---|
| 106 |
|
---|
[2] | 107 | var HTML_FORM_EXTENSION string = `<input type="hidden" name="mortyurl" value="%s" /><input type="hidden" name="mortyhash" value="%s" />`
|
---|
[1] | 108 |
|
---|
| 109 | var HTML_BODY_EXTENSION string = `
|
---|
| 110 | <div id="mortyheader">
|
---|
| 111 | <input type="checkbox" id="mortytoggle" autocomplete="off" />
|
---|
[36] | 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>
|
---|
[1] | 113 | </div>
|
---|
| 114 | <style>
|
---|
[36] | 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; }
|
---|
[5] | 119 | #mortyheader label { text-align: right; cursor: pointer; display: block; color: #444; padding: 0; margin: 0; }
|
---|
[1] | 120 | input[type=checkbox]#mortytoggle { display: none; }
|
---|
| 121 | input[type=checkbox]#mortytoggle:checked ~ div { display: none; }
|
---|
| 122 | </style>
|
---|
| 123 | `
|
---|
| 124 |
|
---|
| 125 | func (p *Proxy) RequestHandler(ctx *fasthttp.RequestCtx) {
|
---|
[10] | 126 |
|
---|
| 127 | if appRequestHandler(ctx) {
|
---|
| 128 | return
|
---|
| 129 | }
|
---|
| 130 |
|
---|
[1] | 131 | requestHash := popRequestParam(ctx, []byte("mortyhash"))
|
---|
| 132 |
|
---|
| 133 | requestURI := popRequestParam(ctx, []byte("mortyurl"))
|
---|
| 134 |
|
---|
| 135 | if requestURI == nil {
|
---|
[35] | 136 | p.serveMainPage(ctx, 200, nil)
|
---|
[1] | 137 | return
|
---|
| 138 | }
|
---|
| 139 |
|
---|
| 140 | if p.Key != nil {
|
---|
| 141 | if !verifyRequestURI(requestURI, requestHash, p.Key) {
|
---|
[35] | 142 | // HTTP status code 403 : Forbidden
|
---|
| 143 | p.serveMainPage(ctx, 403, errors.New(`invalid "mortyhash" parameter`))
|
---|
[1] | 144 | return
|
---|
| 145 | }
|
---|
| 146 | }
|
---|
| 147 |
|
---|
| 148 | parsedURI, err := url.Parse(string(requestURI))
|
---|
| 149 |
|
---|
[18] | 150 | if strings.HasSuffix(parsedURI.Host, ".onion") {
|
---|
[35] | 151 | // HTTP status code 501 : Not Implemented
|
---|
| 152 | p.serveMainPage(ctx, 501, errors.New("Tor urls are not supported yet"))
|
---|
[18] | 153 | return
|
---|
| 154 | }
|
---|
| 155 |
|
---|
[11] | 156 | if err != nil {
|
---|
[35] | 157 | // HTTP status code 500 : Internal Server Error
|
---|
| 158 | p.serveMainPage(ctx, 500, err)
|
---|
[1] | 159 | return
|
---|
| 160 | }
|
---|
| 161 |
|
---|
| 162 | req := fasthttp.AcquireRequest()
|
---|
| 163 | defer fasthttp.ReleaseRequest(req)
|
---|
[12] | 164 | req.SetConnectionClose()
|
---|
[1] | 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 |
|
---|
[11] | 188 | err = CLIENT.DoTimeout(req, resp, p.RequestTimeout)
|
---|
| 189 |
|
---|
| 190 | if err != nil {
|
---|
[35] | 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 | }
|
---|
[1] | 198 | return
|
---|
| 199 | }
|
---|
| 200 |
|
---|
| 201 | if resp.StatusCode() != 200 {
|
---|
| 202 | switch resp.StatusCode() {
|
---|
[7] | 203 | case 301, 302, 303, 307, 308:
|
---|
[1] | 204 | loc := resp.Header.Peek("Location")
|
---|
| 205 | if loc != nil {
|
---|
[23] | 206 | rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
|
---|
| 207 | url, err := rc.ProxifyURI(string(loc))
|
---|
[1] | 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 | }
|
---|
[37] | 216 | error_message := fmt.Sprintf("invalid response: %d", resp.StatusCode())
|
---|
| 217 | p.serveMainPage(ctx, resp.StatusCode(), errors.New(error_message))
|
---|
[1] | 218 | return
|
---|
| 219 | }
|
---|
| 220 |
|
---|
| 221 | contentType := resp.Header.Peek("Content-Type")
|
---|
| 222 |
|
---|
| 223 | if contentType == nil {
|
---|
[35] | 224 | // HTTP status code 503 : Service Unavailable
|
---|
| 225 | p.serveMainPage(ctx, 503, errors.New("invalid content type"))
|
---|
[1] | 226 | return
|
---|
| 227 | }
|
---|
| 228 |
|
---|
[17] | 229 | if bytes.Contains(bytes.ToLower(contentType), []byte("javascript")) {
|
---|
[35] | 230 | // HTTP status code 403 : Forbidden
|
---|
| 231 | p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
|
---|
[17] | 232 | return
|
---|
| 233 | }
|
---|
| 234 |
|
---|
[1] | 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())
|
---|
[11] | 242 | if err != nil {
|
---|
[35] | 243 | // HTTP status code 503 : Service Unavailable
|
---|
| 244 | p.serveMainPage(ctx, 503, err)
|
---|
[1] | 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")):
|
---|
[23] | 255 | sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
|
---|
[1] | 256 | case bytes.Contains(contentType, []byte("html")):
|
---|
[23] | 257 | sanitizeHTML(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
|
---|
[1] | 258 | default:
|
---|
| 259 | ctx.Write(responseBody)
|
---|
| 260 | }
|
---|
| 261 | }
|
---|
| 262 |
|
---|
[10] | 263 | func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
|
---|
[11] | 264 | // serve robots.txt
|
---|
[10] | 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 | }
|
---|
[11] | 270 |
|
---|
[10] | 271 | return false
|
---|
| 272 | }
|
---|
| 273 |
|
---|
[1] | 274 | func 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 |
|
---|
[9] | 289 | func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
|
---|
[1] | 290 | // TODO
|
---|
| 291 |
|
---|
| 292 | urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
|
---|
| 293 |
|
---|
| 294 | if urlSlices == nil {
|
---|
[9] | 295 | out.Write(css)
|
---|
[1] | 296 | return
|
---|
| 297 | }
|
---|
| 298 |
|
---|
| 299 | startIndex := 0
|
---|
| 300 |
|
---|
| 301 | for _, s := range urlSlices {
|
---|
[15] | 302 | urlStart := s[4]
|
---|
| 303 | urlEnd := s[5]
|
---|
[1] | 304 |
|
---|
[23] | 305 | if uri, err := rc.ProxifyURI(string(css[urlStart:urlEnd])); err == nil {
|
---|
[9] | 306 | out.Write(css[startIndex:urlStart])
|
---|
| 307 | out.Write([]byte(uri))
|
---|
[1] | 308 | startIndex = urlEnd
|
---|
| 309 | } else {
|
---|
[36] | 310 | log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
|
---|
[1] | 311 | }
|
---|
| 312 | }
|
---|
| 313 | if startIndex < len(css) {
|
---|
[9] | 314 | out.Write(css[startIndex:len(css)])
|
---|
[1] | 315 | }
|
---|
| 316 | }
|
---|
| 317 |
|
---|
[9] | 318 | func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
|
---|
[1] | 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 | }
|
---|
[38] | 350 | if bytes.Equal(tag, []byte("base")) {
|
---|
| 351 | for {
|
---|
| 352 | attrName, attrValue, moreAttr := decoder.TagAttr()
|
---|
| 353 | if !bytes.Equal(attrName, []byte("href")) {
|
---|
| 354 | continue
|
---|
| 355 | }
|
---|
| 356 | parsedURI, err := url.Parse(string(attrValue))
|
---|
| 357 | if err == nil {
|
---|
| 358 | rc.BaseURL = parsedURI
|
---|
| 359 | }
|
---|
| 360 | if !moreAttr {
|
---|
| 361 | break
|
---|
| 362 | }
|
---|
| 363 | }
|
---|
| 364 | break
|
---|
| 365 | }
|
---|
[1] | 366 | if bytes.Equal(tag, []byte("noscript")) {
|
---|
| 367 | state = STATE_IN_NOSCRIPT
|
---|
| 368 | break
|
---|
| 369 | }
|
---|
| 370 | var attrs [][][]byte
|
---|
| 371 | if hasAttrs {
|
---|
| 372 | for {
|
---|
| 373 | attrName, attrValue, moreAttr := decoder.TagAttr()
|
---|
[21] | 374 | attrs = append(attrs, [][]byte{
|
---|
| 375 | attrName,
|
---|
| 376 | attrValue,
|
---|
| 377 | []byte(html.EscapeString(string(attrValue))),
|
---|
| 378 | })
|
---|
[1] | 379 | if !moreAttr {
|
---|
| 380 | break
|
---|
| 381 | }
|
---|
| 382 | }
|
---|
[13] | 383 | }
|
---|
| 384 | if bytes.Equal(tag, []byte("link")) {
|
---|
| 385 | sanitizeLinkTag(rc, out, attrs)
|
---|
| 386 | break
|
---|
| 387 | }
|
---|
| 388 |
|
---|
| 389 | fmt.Fprintf(out, "<%s", tag)
|
---|
| 390 |
|
---|
| 391 | if hasAttrs {
|
---|
[1] | 392 | if bytes.Equal(tag, []byte("meta")) {
|
---|
[9] | 393 | sanitizeMetaAttrs(rc, out, attrs)
|
---|
[1] | 394 | } else {
|
---|
[9] | 395 | sanitizeAttrs(rc, out, attrs)
|
---|
[1] | 396 | }
|
---|
| 397 | }
|
---|
[13] | 398 |
|
---|
[1] | 399 | if token == html.SelfClosingTagToken {
|
---|
[9] | 400 | fmt.Fprintf(out, " />")
|
---|
[1] | 401 | } else {
|
---|
[9] | 402 | fmt.Fprintf(out, ">")
|
---|
[1] | 403 | if bytes.Equal(tag, []byte("style")) {
|
---|
| 404 | state = STATE_IN_STYLE
|
---|
| 405 | }
|
---|
| 406 | }
|
---|
[13] | 407 |
|
---|
[1] | 408 | if bytes.Equal(tag, []byte("form")) {
|
---|
| 409 | var formURL *url.URL
|
---|
| 410 | for _, attr := range attrs {
|
---|
| 411 | if bytes.Equal(attr[0], []byte("action")) {
|
---|
| 412 | formURL, _ = url.Parse(string(attr[1]))
|
---|
[28] | 413 | formURL = mergeURIs(rc.BaseURL, formURL)
|
---|
[1] | 414 | break
|
---|
| 415 | }
|
---|
| 416 | }
|
---|
| 417 | if formURL == nil {
|
---|
[23] | 418 | formURL = rc.BaseURL
|
---|
[1] | 419 | }
|
---|
[2] | 420 | urlStr := formURL.String()
|
---|
| 421 | var key string
|
---|
| 422 | if rc.Key != nil {
|
---|
| 423 | key = hash(urlStr, rc.Key)
|
---|
| 424 | }
|
---|
[9] | 425 | fmt.Fprintf(out, HTML_FORM_EXTENSION, urlStr, key)
|
---|
[1] | 426 |
|
---|
| 427 | }
|
---|
| 428 |
|
---|
| 429 | case html.EndTagToken:
|
---|
| 430 | tag, _ := decoder.TagName()
|
---|
| 431 | writeEndTag := true
|
---|
| 432 | switch string(tag) {
|
---|
| 433 | case "body":
|
---|
[23] | 434 | fmt.Fprintf(out, HTML_BODY_EXTENSION, rc.BaseURL.String())
|
---|
[1] | 435 | case "style":
|
---|
| 436 | state = STATE_DEFAULT
|
---|
| 437 | case "noscript":
|
---|
| 438 | state = STATE_DEFAULT
|
---|
| 439 | writeEndTag = false
|
---|
| 440 | }
|
---|
| 441 | // skip noscript tags - only the tag, not the content, because javascript is sanitized
|
---|
| 442 | if writeEndTag {
|
---|
[9] | 443 | fmt.Fprintf(out, "</%s>", tag)
|
---|
[1] | 444 | }
|
---|
| 445 |
|
---|
| 446 | case html.TextToken:
|
---|
| 447 | switch state {
|
---|
| 448 | case STATE_DEFAULT:
|
---|
[9] | 449 | fmt.Fprintf(out, "%s", decoder.Raw())
|
---|
[1] | 450 | case STATE_IN_STYLE:
|
---|
[9] | 451 | sanitizeCSS(rc, out, decoder.Raw())
|
---|
[1] | 452 | case STATE_IN_NOSCRIPT:
|
---|
[9] | 453 | sanitizeHTML(rc, out, decoder.Raw())
|
---|
[1] | 454 | }
|
---|
| 455 |
|
---|
| 456 | case html.DoctypeToken, html.CommentToken:
|
---|
[9] | 457 | out.Write(decoder.Raw())
|
---|
[1] | 458 | }
|
---|
| 459 | } else {
|
---|
| 460 | switch token {
|
---|
| 461 | case html.StartTagToken:
|
---|
| 462 | tag, _ := decoder.TagName()
|
---|
| 463 | if inArray(tag, UNSAFE_ELEMENTS) {
|
---|
| 464 | unsafeElements = append(unsafeElements, tag)
|
---|
| 465 | }
|
---|
| 466 |
|
---|
| 467 | case html.EndTagToken:
|
---|
| 468 | tag, _ := decoder.TagName()
|
---|
| 469 | if bytes.Equal(unsafeElements[len(unsafeElements)-1], tag) {
|
---|
| 470 | unsafeElements = unsafeElements[:len(unsafeElements)-1]
|
---|
| 471 | }
|
---|
| 472 | }
|
---|
| 473 | }
|
---|
| 474 | }
|
---|
| 475 | }
|
---|
| 476 |
|
---|
[13] | 477 | func sanitizeLinkTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
| 478 | exclude := false
|
---|
| 479 | for _, attr := range attrs {
|
---|
| 480 | attrName := attr[0]
|
---|
| 481 | attrValue := attr[1]
|
---|
| 482 | if bytes.Equal(attrName, []byte("rel")) {
|
---|
| 483 | if bytes.Equal(attrValue, []byte("dns-prefetch")) {
|
---|
| 484 | exclude = true
|
---|
| 485 | break
|
---|
| 486 | }
|
---|
| 487 | }
|
---|
| 488 | if bytes.Equal(attrName, []byte("as")) {
|
---|
| 489 | if bytes.Equal(attrValue, []byte("script")) {
|
---|
| 490 | exclude = true
|
---|
| 491 | break
|
---|
| 492 | }
|
---|
| 493 | }
|
---|
| 494 | }
|
---|
| 495 |
|
---|
| 496 | if !exclude {
|
---|
| 497 | out.Write([]byte("<link"))
|
---|
| 498 | for _, attr := range attrs {
|
---|
[21] | 499 | sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
|
---|
[13] | 500 | }
|
---|
| 501 | out.Write([]byte(">"))
|
---|
| 502 | }
|
---|
| 503 | }
|
---|
| 504 |
|
---|
[9] | 505 | func sanitizeMetaAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
[1] | 506 | var http_equiv []byte
|
---|
| 507 | var content []byte
|
---|
| 508 |
|
---|
| 509 | for _, attr := range attrs {
|
---|
| 510 | attrName := attr[0]
|
---|
| 511 | attrValue := attr[1]
|
---|
| 512 | if bytes.Equal(attrName, []byte("http-equiv")) {
|
---|
| 513 | http_equiv = bytes.ToLower(attrValue)
|
---|
| 514 | }
|
---|
| 515 | if bytes.Equal(attrName, []byte("content")) {
|
---|
| 516 | content = attrValue
|
---|
| 517 | }
|
---|
| 518 | }
|
---|
| 519 |
|
---|
[14] | 520 | urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
|
---|
| 521 | if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
|
---|
| 522 | contentUrl := content[urlIndex+4:]
|
---|
[36] | 523 | // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
|
---|
[37] | 524 | if len(contentUrl) >= 2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
|
---|
[36] | 525 | if contentUrl[0] == contentUrl[len(contentUrl)-1] {
|
---|
[37] | 526 | contentUrl = contentUrl[1 : len(contentUrl)-1]
|
---|
[36] | 527 | }
|
---|
| 528 | }
|
---|
| 529 | // output proxify result
|
---|
[23] | 530 | if uri, err := rc.ProxifyURI(string(contentUrl)); err == nil {
|
---|
[14] | 531 | fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
|
---|
[1] | 532 | }
|
---|
| 533 | } else {
|
---|
[9] | 534 | sanitizeAttrs(rc, out, attrs)
|
---|
[1] | 535 | }
|
---|
| 536 |
|
---|
| 537 | }
|
---|
| 538 |
|
---|
[9] | 539 | func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
[1] | 540 | for _, attr := range attrs {
|
---|
[21] | 541 | sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
|
---|
[1] | 542 | }
|
---|
| 543 | }
|
---|
| 544 |
|
---|
[21] | 545 | func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
|
---|
[1] | 546 | if inArray(attrName, SAFE_ATTRIBUTES) {
|
---|
[21] | 547 | fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
|
---|
[1] | 548 | return
|
---|
| 549 | }
|
---|
| 550 | switch string(attrName) {
|
---|
| 551 | case "src", "href", "action":
|
---|
[23] | 552 | if uri, err := rc.ProxifyURI(string(attrValue)); err == nil {
|
---|
[9] | 553 | fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
|
---|
[1] | 554 | } else {
|
---|
[36] | 555 | log.Println("cannot proxify uri:", string(attrValue))
|
---|
[1] | 556 | }
|
---|
| 557 | case "style":
|
---|
[21] | 558 | cssAttr := bytes.NewBuffer(nil)
|
---|
| 559 | sanitizeCSS(rc, cssAttr, attrValue)
|
---|
| 560 | fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
|
---|
[1] | 561 | }
|
---|
| 562 | }
|
---|
| 563 |
|
---|
[36] | 564 | func mergeURIs(u1, u2 *url.URL) *url.URL {
|
---|
[28] | 565 | return u1.ResolveReference(u2)
|
---|
[1] | 566 | }
|
---|
| 567 |
|
---|
[23] | 568 | func (rc *RequestConfig) ProxifyURI(uri string) (string, error) {
|
---|
[28] | 569 | // remove javascript protocol
|
---|
| 570 | if strings.HasPrefix(uri, "javascript:") {
|
---|
| 571 | return "", nil
|
---|
| 572 | }
|
---|
[1] | 573 | // TODO check malicious data: - e.g. data:script
|
---|
| 574 | if strings.HasPrefix(uri, "data:") {
|
---|
| 575 | return uri, nil
|
---|
| 576 | }
|
---|
| 577 |
|
---|
| 578 | if len(uri) > 0 && uri[0] == '#' {
|
---|
| 579 | return uri, nil
|
---|
| 580 | }
|
---|
| 581 |
|
---|
| 582 | u, err := url.Parse(uri)
|
---|
| 583 | if err != nil {
|
---|
| 584 | return "", err
|
---|
| 585 | }
|
---|
[28] | 586 | u = mergeURIs(rc.BaseURL, u)
|
---|
[1] | 587 |
|
---|
| 588 | uri = u.String()
|
---|
| 589 |
|
---|
| 590 | if rc.Key == nil {
|
---|
| 591 | return fmt.Sprintf("./?mortyurl=%s", url.QueryEscape(uri)), nil
|
---|
| 592 | }
|
---|
| 593 | return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s", hash(uri, rc.Key), url.QueryEscape(uri)), nil
|
---|
| 594 | }
|
---|
| 595 |
|
---|
| 596 | func inArray(b []byte, a [][]byte) bool {
|
---|
| 597 | for _, b2 := range a {
|
---|
| 598 | if bytes.Equal(b, b2) {
|
---|
| 599 | return true
|
---|
| 600 | }
|
---|
| 601 | }
|
---|
| 602 | return false
|
---|
| 603 | }
|
---|
| 604 |
|
---|
| 605 | func hash(msg string, key []byte) string {
|
---|
| 606 | mac := hmac.New(sha256.New, key)
|
---|
| 607 | mac.Write([]byte(msg))
|
---|
| 608 | return hex.EncodeToString(mac.Sum(nil))
|
---|
| 609 | }
|
---|
| 610 |
|
---|
| 611 | func verifyRequestURI(uri, hashMsg, key []byte) bool {
|
---|
| 612 | h := make([]byte, hex.DecodedLen(len(hashMsg)))
|
---|
| 613 | _, err := hex.Decode(h, hashMsg)
|
---|
| 614 | if err != nil {
|
---|
| 615 | log.Println("hmac error:", err)
|
---|
| 616 | return false
|
---|
| 617 | }
|
---|
| 618 | mac := hmac.New(sha256.New, key)
|
---|
| 619 | mac.Write(uri)
|
---|
| 620 | return hmac.Equal(h, mac.Sum(nil))
|
---|
| 621 | }
|
---|
| 622 |
|
---|
[35] | 623 | func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
|
---|
[1] | 624 | ctx.SetContentType("text/html")
|
---|
[35] | 625 | ctx.SetStatusCode(statusCode)
|
---|
[1] | 626 | ctx.Write([]byte(`<!doctype html>
|
---|
| 627 | <head>
|
---|
[11] | 628 | <title>MortyProxy</title>
|
---|
[36] | 629 | <meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
|
---|
[11] | 630 | <style>
|
---|
[36] | 631 | html { height: 100%; }
|
---|
| 632 | body { 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; }
|
---|
[11] | 633 | input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
|
---|
[36] | 634 | input[placeholder] { width:80%; }
|
---|
[11] | 635 | a { text-decoration: none; #2980b9; }
|
---|
| 636 | h1, h2 { font-weight: 200; margin-bottom: 2rem; }
|
---|
| 637 | h1 { font-size: 3em; }
|
---|
[36] | 638 | .container { flex:1; min-height: 100%; margin-bottom: 1em; }
|
---|
| 639 | .footer { margin: 1em; }
|
---|
[11] | 640 | .footer p { font-size: 0.8em; }
|
---|
| 641 | </style>
|
---|
[1] | 642 | </head>
|
---|
[11] | 643 | <body>
|
---|
[36] | 644 | <div class="container">
|
---|
| 645 | <h1>MortyProxy</h1>
|
---|
| 646 | `))
|
---|
[11] | 647 | if err != nil {
|
---|
| 648 | log.Println("error:", err)
|
---|
| 649 | ctx.Write([]byte("<h2>Error: "))
|
---|
| 650 | ctx.Write([]byte(html.EscapeString(err.Error())))
|
---|
| 651 | ctx.Write([]byte("</h2>"))
|
---|
| 652 | }
|
---|
[1] | 653 | if p.Key == nil {
|
---|
| 654 | ctx.Write([]byte(`
|
---|
[36] | 655 | <form action="post">
|
---|
| 656 | Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
|
---|
| 657 | <input type="submit" value="go" />
|
---|
| 658 | </form>`))
|
---|
[11] | 659 | } else {
|
---|
| 660 | ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
|
---|
[1] | 661 | }
|
---|
| 662 | ctx.Write([]byte(`
|
---|
[36] | 663 | </div>
|
---|
| 664 | <div class="footer">
|
---|
| 665 | <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 />
|
---|
| 666 | <a href="https://github.com/asciimoo/morty">view on github</a>
|
---|
| 667 | </p>
|
---|
| 668 | </div>
|
---|
[1] | 669 | </body>
|
---|
| 670 | </html>`))
|
---|
| 671 | }
|
---|
| 672 |
|
---|
| 673 | func main() {
|
---|
| 674 |
|
---|
[2] | 675 | listen := flag.String("listen", "127.0.0.1:3000", "Listen address")
|
---|
[1] | 676 | key := flag.String("key", "", "HMAC url validation key (hexadecimal encoded) - leave blank to disable")
|
---|
[24] | 677 | ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
|
---|
[4] | 678 | requestTimeout := flag.Uint("timeout", 2, "Request timeout")
|
---|
[1] | 679 | flag.Parse()
|
---|
| 680 |
|
---|
[24] | 681 | if *ipv6 {
|
---|
| 682 | CLIENT.Dial = fasthttp.DialDualStack
|
---|
| 683 | }
|
---|
| 684 |
|
---|
[4] | 685 | p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
|
---|
[1] | 686 |
|
---|
| 687 | if *key != "" {
|
---|
| 688 | p.Key = []byte(*key)
|
---|
| 689 | }
|
---|
| 690 |
|
---|
| 691 | log.Println("listening on", *listen)
|
---|
| 692 |
|
---|
| 693 | if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
|
---|
| 694 | log.Fatal("Error in ListenAndServe:", err)
|
---|
| 695 | }
|
---|
| 696 | }
|
---|