[1] | 1 | package main
|
---|
| 2 |
|
---|
| 3 | import (
|
---|
| 4 | "bytes"
|
---|
| 5 | "crypto/hmac"
|
---|
| 6 | "crypto/sha256"
|
---|
[67] | 7 | "encoding/base64"
|
---|
[1] | 8 | "encoding/hex"
|
---|
| 9 | "errors"
|
---|
| 10 | "flag"
|
---|
| 11 | "fmt"
|
---|
[121] | 12 | "html/template"
|
---|
[1] | 13 | "io"
|
---|
| 14 | "log"
|
---|
[68] | 15 | "mime"
|
---|
[1] | 16 | "net/url"
|
---|
[78] | 17 | "os"
|
---|
[68] | 18 | "path/filepath"
|
---|
[1] | 19 | "regexp"
|
---|
| 20 | "strings"
|
---|
[4] | 21 | "time"
|
---|
[60] | 22 | "unicode/utf8"
|
---|
[1] | 23 |
|
---|
| 24 | "github.com/valyala/fasthttp"
|
---|
[109] | 25 | "github.com/valyala/fasthttp/fasthttpproxy"
|
---|
[1] | 26 | "golang.org/x/net/html"
|
---|
[45] | 27 | "golang.org/x/net/html/charset"
|
---|
| 28 | "golang.org/x/text/encoding"
|
---|
[68] | 29 |
|
---|
| 30 | "github.com/asciimoo/morty/contenttype"
|
---|
[1] | 31 | )
|
---|
| 32 |
|
---|
| 33 | const (
|
---|
| 34 | STATE_DEFAULT int = 0
|
---|
| 35 | STATE_IN_STYLE int = 1
|
---|
| 36 | STATE_IN_NOSCRIPT int = 2
|
---|
| 37 | )
|
---|
| 38 |
|
---|
[77] | 39 | const VERSION = "v0.2.0"
|
---|
[74] | 40 |
|
---|
[100] | 41 | var DEBUG = os.Getenv("DEBUG") != "false"
|
---|
[96] | 42 |
|
---|
[1] | 43 | var CLIENT *fasthttp.Client = &fasthttp.Client{
|
---|
| 44 | MaxResponseBodySize: 10 * 1024 * 1024, // 10M
|
---|
[113] | 45 | ReadBufferSize: 16 * 1024, // 16K
|
---|
[1] | 46 | }
|
---|
| 47 |
|
---|
[27] | 48 | var CSS_URL_REGEXP *regexp.Regexp = regexp.MustCompile("url\\((['\"]?)[ \\t\\f]*([\u0009\u0021\u0023-\u0026\u0028\u002a-\u007E]+)(['\"]?)\\)?")
|
---|
[1] | 49 |
|
---|
[68] | 50 | var ALLOWED_CONTENTTYPE_FILTER contenttype.Filter = contenttype.NewFilterOr([]contenttype.Filter{
|
---|
| 51 | // html
|
---|
| 52 | contenttype.NewFilterEquals("text", "html", ""),
|
---|
| 53 | contenttype.NewFilterEquals("application", "xhtml", "xml"),
|
---|
| 54 | // css
|
---|
| 55 | contenttype.NewFilterEquals("text", "css", ""),
|
---|
| 56 | // images
|
---|
| 57 | contenttype.NewFilterEquals("image", "gif", ""),
|
---|
| 58 | contenttype.NewFilterEquals("image", "png", ""),
|
---|
| 59 | contenttype.NewFilterEquals("image", "jpeg", ""),
|
---|
| 60 | contenttype.NewFilterEquals("image", "pjpeg", ""),
|
---|
| 61 | contenttype.NewFilterEquals("image", "webp", ""),
|
---|
| 62 | contenttype.NewFilterEquals("image", "tiff", ""),
|
---|
| 63 | contenttype.NewFilterEquals("image", "vnd.microsoft.icon", ""),
|
---|
| 64 | contenttype.NewFilterEquals("image", "bmp", ""),
|
---|
| 65 | contenttype.NewFilterEquals("image", "x-ms-bmp", ""),
|
---|
[88] | 66 | contenttype.NewFilterEquals("image", "x-icon", ""),
|
---|
[68] | 67 | // fonts
|
---|
| 68 | contenttype.NewFilterEquals("application", "font-otf", ""),
|
---|
| 69 | contenttype.NewFilterEquals("application", "font-ttf", ""),
|
---|
| 70 | contenttype.NewFilterEquals("application", "font-woff", ""),
|
---|
| 71 | contenttype.NewFilterEquals("application", "vnd.ms-fontobject", ""),
|
---|
| 72 | })
|
---|
| 73 |
|
---|
| 74 | var ALLOWED_CONTENTTYPE_ATTACHMENT_FILTER contenttype.Filter = contenttype.NewFilterOr([]contenttype.Filter{
|
---|
| 75 | // texts
|
---|
| 76 | contenttype.NewFilterEquals("text", "csv", ""),
|
---|
[103] | 77 | contenttype.NewFilterEquals("text", "tab-separated-values", ""),
|
---|
[68] | 78 | contenttype.NewFilterEquals("text", "plain", ""),
|
---|
| 79 | // API
|
---|
| 80 | contenttype.NewFilterEquals("application", "json", ""),
|
---|
| 81 | // Documents
|
---|
| 82 | contenttype.NewFilterEquals("application", "x-latex", ""),
|
---|
| 83 | contenttype.NewFilterEquals("application", "pdf", ""),
|
---|
| 84 | contenttype.NewFilterEquals("application", "vnd.oasis.opendocument.text", ""),
|
---|
| 85 | contenttype.NewFilterEquals("application", "vnd.oasis.opendocument.spreadsheet", ""),
|
---|
| 86 | contenttype.NewFilterEquals("application", "vnd.oasis.opendocument.presentation", ""),
|
---|
| 87 | contenttype.NewFilterEquals("application", "vnd.oasis.opendocument.graphics", ""),
|
---|
| 88 | // Compressed archives
|
---|
| 89 | contenttype.NewFilterEquals("application", "zip", ""),
|
---|
| 90 | contenttype.NewFilterEquals("application", "gzip", ""),
|
---|
| 91 | contenttype.NewFilterEquals("application", "x-compressed", ""),
|
---|
| 92 | contenttype.NewFilterEquals("application", "x-gtar", ""),
|
---|
| 93 | contenttype.NewFilterEquals("application", "x-compress", ""),
|
---|
| 94 | // Generic binary
|
---|
| 95 | contenttype.NewFilterEquals("application", "octet-stream", ""),
|
---|
| 96 | })
|
---|
| 97 |
|
---|
| 98 | var ALLOWED_CONTENTTYPE_PARAMETERS map[string]bool = map[string]bool{
|
---|
| 99 | "charset": true,
|
---|
| 100 | }
|
---|
| 101 |
|
---|
[1] | 102 | var UNSAFE_ELEMENTS [][]byte = [][]byte{
|
---|
| 103 | []byte("applet"),
|
---|
| 104 | []byte("canvas"),
|
---|
| 105 | []byte("embed"),
|
---|
| 106 | //[]byte("iframe"),
|
---|
[46] | 107 | []byte("math"),
|
---|
[1] | 108 | []byte("script"),
|
---|
[46] | 109 | []byte("svg"),
|
---|
[1] | 110 | }
|
---|
| 111 |
|
---|
| 112 | var SAFE_ATTRIBUTES [][]byte = [][]byte{
|
---|
| 113 | []byte("abbr"),
|
---|
| 114 | []byte("accesskey"),
|
---|
| 115 | []byte("align"),
|
---|
| 116 | []byte("alt"),
|
---|
[13] | 117 | []byte("as"),
|
---|
[1] | 118 | []byte("autocomplete"),
|
---|
| 119 | []byte("charset"),
|
---|
| 120 | []byte("checked"),
|
---|
| 121 | []byte("class"),
|
---|
| 122 | []byte("content"),
|
---|
| 123 | []byte("contenteditable"),
|
---|
| 124 | []byte("contextmenu"),
|
---|
| 125 | []byte("dir"),
|
---|
| 126 | []byte("for"),
|
---|
| 127 | []byte("height"),
|
---|
| 128 | []byte("hidden"),
|
---|
[46] | 129 | []byte("hreflang"),
|
---|
[1] | 130 | []byte("id"),
|
---|
| 131 | []byte("lang"),
|
---|
| 132 | []byte("media"),
|
---|
| 133 | []byte("method"),
|
---|
| 134 | []byte("name"),
|
---|
| 135 | []byte("nowrap"),
|
---|
| 136 | []byte("placeholder"),
|
---|
| 137 | []byte("property"),
|
---|
| 138 | []byte("rel"),
|
---|
| 139 | []byte("spellcheck"),
|
---|
| 140 | []byte("tabindex"),
|
---|
| 141 | []byte("target"),
|
---|
| 142 | []byte("title"),
|
---|
| 143 | []byte("translate"),
|
---|
| 144 | []byte("type"),
|
---|
| 145 | []byte("value"),
|
---|
| 146 | []byte("width"),
|
---|
| 147 | }
|
---|
| 148 |
|
---|
[46] | 149 | var LINK_REL_SAFE_VALUES [][]byte = [][]byte{
|
---|
| 150 | []byte("alternate"),
|
---|
| 151 | []byte("archives"),
|
---|
| 152 | []byte("author"),
|
---|
| 153 | []byte("copyright"),
|
---|
| 154 | []byte("first"),
|
---|
| 155 | []byte("help"),
|
---|
| 156 | []byte("icon"),
|
---|
| 157 | []byte("index"),
|
---|
| 158 | []byte("last"),
|
---|
| 159 | []byte("license"),
|
---|
| 160 | []byte("manifest"),
|
---|
| 161 | []byte("next"),
|
---|
| 162 | []byte("pingback"),
|
---|
| 163 | []byte("prev"),
|
---|
| 164 | []byte("publisher"),
|
---|
| 165 | []byte("search"),
|
---|
| 166 | []byte("shortcut icon"),
|
---|
| 167 | []byte("stylesheet"),
|
---|
| 168 | []byte("up"),
|
---|
| 169 | }
|
---|
| 170 |
|
---|
| 171 | var LINK_HTTP_EQUIV_SAFE_VALUES [][]byte = [][]byte{
|
---|
| 172 | // X-UA-Compatible will be added automaticaly, so it can be skipped
|
---|
| 173 | []byte("date"),
|
---|
| 174 | []byte("last-modified"),
|
---|
[50] | 175 | []byte("refresh"), // URL rewrite
|
---|
[46] | 176 | // []byte("location"), TODO URL rewrite
|
---|
| 177 | []byte("content-language"),
|
---|
| 178 | }
|
---|
| 179 |
|
---|
[1] | 180 | type Proxy struct {
|
---|
[4] | 181 | Key []byte
|
---|
| 182 | RequestTimeout time.Duration
|
---|
[1] | 183 | }
|
---|
| 184 |
|
---|
| 185 | type RequestConfig struct {
|
---|
[124] | 186 | Key []byte
|
---|
| 187 | BaseURL *url.URL
|
---|
| 188 | BodyInjected bool
|
---|
[1] | 189 | }
|
---|
| 190 |
|
---|
[121] | 191 | type HTMLBodyExtParam struct {
|
---|
| 192 | BaseURL string
|
---|
| 193 | HasMortyKey bool
|
---|
| 194 | }
|
---|
[1] | 195 |
|
---|
[121] | 196 | type HTMLFormExtParam struct {
|
---|
[122] | 197 | BaseURL string
|
---|
| 198 | MortyHash string
|
---|
[121] | 199 | }
|
---|
[1] | 200 |
|
---|
[121] | 201 | var HTML_FORM_EXTENSION *template.Template
|
---|
| 202 | var HTML_BODY_EXTENSION *template.Template
|
---|
[46] | 203 | var HTML_HEAD_CONTENT_TYPE string = `<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
---|
| 204 | <meta http-equiv="X-UA-Compatible" content="IE=edge">
|
---|
[67] | 205 | <meta name="referrer" content="no-referrer">
|
---|
[46] | 206 | `
|
---|
[45] | 207 |
|
---|
[69] | 208 | var MORTY_HTML_PAGE_START string = `<!doctype html>
|
---|
| 209 | <html>
|
---|
| 210 | <head>
|
---|
| 211 | <title>MortyProxy</title>
|
---|
| 212 | <meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
|
---|
| 213 | <style>
|
---|
| 214 | html { height: 100%; }
|
---|
| 215 | 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; }
|
---|
| 216 | input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
|
---|
| 217 | input[placeholder] { width:80%; }
|
---|
| 218 | a { text-decoration: none; #2980b9; }
|
---|
| 219 | h1, h2 { font-weight: 200; margin-bottom: 2rem; }
|
---|
| 220 | h1 { font-size: 3em; }
|
---|
| 221 | .container { flex:1; min-height: 100%; margin-bottom: 1em; }
|
---|
| 222 | .footer { margin: 1em; }
|
---|
| 223 | .footer p { font-size: 0.8em; }
|
---|
| 224 | </style>
|
---|
| 225 | </head>
|
---|
| 226 | <body>
|
---|
| 227 | <div class="container">
|
---|
| 228 | <h1>MortyProxy</h1>
|
---|
| 229 | `
|
---|
| 230 |
|
---|
| 231 | var MORTY_HTML_PAGE_END string = `
|
---|
| 232 | </div>
|
---|
| 233 | <div class="footer">
|
---|
| 234 | <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 />
|
---|
| 235 | <a href="https://github.com/asciimoo/morty">view on github</a>
|
---|
| 236 | </p>
|
---|
| 237 | </div>
|
---|
| 238 | </body>
|
---|
| 239 | </html>`
|
---|
| 240 |
|
---|
[67] | 241 | var FAVICON_BYTES []byte
|
---|
| 242 |
|
---|
| 243 | func init() {
|
---|
| 244 | FaviconBase64 := "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVRIx2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII"
|
---|
| 245 |
|
---|
| 246 | FAVICON_BYTES, _ = base64.StdEncoding.DecodeString(FaviconBase64)
|
---|
[121] | 247 | var err error
|
---|
| 248 | HTML_FORM_EXTENSION, err = template.New("html_form_extension").Parse(
|
---|
[123] | 249 | `<input type="hidden" name="mortyurl" value="{{.BaseURL}}" />{{if .MortyHash}}<input type="hidden" name="mortyhash" value="{{.MortyHash}}" />{{end}}`)
|
---|
[121] | 250 | if err != nil {
|
---|
| 251 | panic(err)
|
---|
| 252 | }
|
---|
| 253 | HTML_BODY_EXTENSION, err = template.New("html_body_extension").Parse(`
|
---|
| 254 | <input type="checkbox" id="mortytoggle" autocomplete="off" />
|
---|
| 255 | <div id="mortyheader">
|
---|
| 256 | <form method="get">
|
---|
| 257 | <label for="mortytoggle">hide</label>
|
---|
| 258 | <span><a href="/">Morty Proxy</a></span>
|
---|
| 259 | <input type="url" value="{{.BaseURL}}" name="mortyurl" {{if .HasMortyKey }}readonly="true"{{end}} />
|
---|
| 260 | This is a <a href="https://github.com/asciimoo/morty">proxified and sanitized</a> view of the page, visit <a href="{{.BaseURL}}" rel="noreferrer">original site</a>.
|
---|
| 261 | </form>
|
---|
| 262 | </div>
|
---|
| 263 | <style>
|
---|
| 264 | body{ position: absolute !important; top: 42px !important; left: 0 !important; right: 0 !important; bottom: 0 !important; }
|
---|
| 265 | #mortyheader { position: fixed; margin: 0; box-sizing: border-box; -webkit-box-sizing: border-box; top: 0; left: 0; right: 0; z-index: 2147483647 !important; font-size: 12px; line-height: normal; border-width: 0px 0px 2px 0; border-style: solid; border-color: #AAAAAA; background: #FFF; padding: 4px; color: #444; height: 42px; }
|
---|
| 266 | #mortyheader p { padding: 0 0 0.7em 0; display: block; }
|
---|
| 267 | #mortyheader a { color: #3498db; font-weight: bold; display: inline; }
|
---|
| 268 | #mortyheader label { text-align: right; cursor: pointer; position: fixed; right: 4px; top: 4px; display: block; color: #444; }
|
---|
| 269 | #mortyheader > form > span { font-size: 24px; font-weight: bold; margin-right: 20px; margin-left: 20px; }
|
---|
| 270 | input[type=checkbox]#mortytoggle { display: none; }
|
---|
| 271 | input[type=checkbox]#mortytoggle:checked ~ div { display: none; visibility: hidden; }
|
---|
| 272 | #mortyheader input[type=url] { width: 50%; padding: 4px; font-size: 16px; }
|
---|
| 273 | </style>
|
---|
| 274 | `)
|
---|
| 275 | if err != nil {
|
---|
| 276 | panic(err)
|
---|
| 277 | }
|
---|
[67] | 278 | }
|
---|
| 279 |
|
---|
[1] | 280 | func (p *Proxy) RequestHandler(ctx *fasthttp.RequestCtx) {
|
---|
[10] | 281 |
|
---|
| 282 | if appRequestHandler(ctx) {
|
---|
| 283 | return
|
---|
| 284 | }
|
---|
| 285 |
|
---|
[1] | 286 | requestHash := popRequestParam(ctx, []byte("mortyhash"))
|
---|
| 287 |
|
---|
| 288 | requestURI := popRequestParam(ctx, []byte("mortyurl"))
|
---|
| 289 |
|
---|
| 290 | if requestURI == nil {
|
---|
[35] | 291 | p.serveMainPage(ctx, 200, nil)
|
---|
[1] | 292 | return
|
---|
| 293 | }
|
---|
| 294 |
|
---|
| 295 | if p.Key != nil {
|
---|
| 296 | if !verifyRequestURI(requestURI, requestHash, p.Key) {
|
---|
[35] | 297 | // HTTP status code 403 : Forbidden
|
---|
| 298 | p.serveMainPage(ctx, 403, errors.New(`invalid "mortyhash" parameter`))
|
---|
[1] | 299 | return
|
---|
| 300 | }
|
---|
| 301 | }
|
---|
| 302 |
|
---|
[118] | 303 | requestURIQuery := ctx.QueryArgs().QueryString()
|
---|
| 304 | if len(requestURIQuery) > 0 {
|
---|
| 305 | requestURI = append(requestURI, '?')
|
---|
| 306 | requestURI = append(requestURI, requestURIQuery...)
|
---|
| 307 | }
|
---|
| 308 |
|
---|
[97] | 309 | parsedURI, err := url.Parse(string(requestURI))
|
---|
[1] | 310 |
|
---|
[11] | 311 | if err != nil {
|
---|
[35] | 312 | // HTTP status code 500 : Internal Server Error
|
---|
| 313 | p.serveMainPage(ctx, 500, err)
|
---|
[1] | 314 | return
|
---|
| 315 | }
|
---|
| 316 |
|
---|
[120] | 317 | if parsedURI.Scheme == "" {
|
---|
| 318 | parsedURI.Scheme = "https"
|
---|
| 319 | requestURI = append([]byte("https://"), requestURI...)
|
---|
| 320 | }
|
---|
| 321 |
|
---|
[69] | 322 | // Serve an intermediate page for protocols other than HTTP(S)
|
---|
| 323 | if (parsedURI.Scheme != "http" && parsedURI.Scheme != "https") || strings.HasSuffix(parsedURI.Host, ".onion") {
|
---|
| 324 | p.serveExitMortyPage(ctx, parsedURI)
|
---|
| 325 | return
|
---|
| 326 | }
|
---|
| 327 |
|
---|
[1] | 328 | req := fasthttp.AcquireRequest()
|
---|
| 329 | defer fasthttp.ReleaseRequest(req)
|
---|
[12] | 330 | req.SetConnectionClose()
|
---|
[1] | 331 |
|
---|
[47] | 332 | requestURIStr := string(requestURI)
|
---|
[1] | 333 |
|
---|
[97] | 334 | if DEBUG {
|
---|
| 335 | log.Println("getting", requestURIStr)
|
---|
| 336 | }
|
---|
[1] | 337 |
|
---|
[47] | 338 | req.SetRequestURI(requestURIStr)
|
---|
[111] | 339 | req.Header.SetUserAgentBytes([]byte("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"))
|
---|
[1] | 340 |
|
---|
| 341 | resp := fasthttp.AcquireResponse()
|
---|
| 342 | defer fasthttp.ReleaseResponse(resp)
|
---|
| 343 |
|
---|
| 344 | req.Header.SetMethodBytes(ctx.Method())
|
---|
| 345 | if ctx.IsPost() || ctx.IsPut() {
|
---|
| 346 | req.SetBody(ctx.PostBody())
|
---|
| 347 | }
|
---|
| 348 |
|
---|
[11] | 349 | err = CLIENT.DoTimeout(req, resp, p.RequestTimeout)
|
---|
| 350 |
|
---|
| 351 | if err != nil {
|
---|
[35] | 352 | if err == fasthttp.ErrTimeout {
|
---|
| 353 | // HTTP status code 504 : Gateway Time-Out
|
---|
| 354 | p.serveMainPage(ctx, 504, err)
|
---|
| 355 | } else {
|
---|
| 356 | // HTTP status code 500 : Internal Server Error
|
---|
| 357 | p.serveMainPage(ctx, 500, err)
|
---|
| 358 | }
|
---|
[1] | 359 | return
|
---|
| 360 | }
|
---|
| 361 |
|
---|
| 362 | if resp.StatusCode() != 200 {
|
---|
| 363 | switch resp.StatusCode() {
|
---|
[7] | 364 | case 301, 302, 303, 307, 308:
|
---|
[1] | 365 | loc := resp.Header.Peek("Location")
|
---|
| 366 | if loc != nil {
|
---|
[97] | 367 | rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
|
---|
| 368 | url, err := rc.ProxifyURI(loc)
|
---|
| 369 | if err == nil {
|
---|
| 370 | ctx.SetStatusCode(resp.StatusCode())
|
---|
| 371 | ctx.Response.Header.Add("Location", url)
|
---|
| 372 | if DEBUG {
|
---|
| 373 | log.Println("redirect to", string(loc))
|
---|
[96] | 374 | }
|
---|
[1] | 375 | return
|
---|
| 376 | }
|
---|
| 377 | }
|
---|
| 378 | }
|
---|
[47] | 379 | error_message := fmt.Sprintf("invalid response: %d (%s)", resp.StatusCode(), requestURIStr)
|
---|
[37] | 380 | p.serveMainPage(ctx, resp.StatusCode(), errors.New(error_message))
|
---|
[1] | 381 | return
|
---|
| 382 | }
|
---|
| 383 |
|
---|
[68] | 384 | contentTypeBytes := resp.Header.Peek("Content-Type")
|
---|
[1] | 385 |
|
---|
[68] | 386 | if contentTypeBytes == nil {
|
---|
[35] | 387 | // HTTP status code 503 : Service Unavailable
|
---|
| 388 | p.serveMainPage(ctx, 503, errors.New("invalid content type"))
|
---|
[1] | 389 | return
|
---|
| 390 | }
|
---|
| 391 |
|
---|
[68] | 392 | contentTypeString := string(contentTypeBytes)
|
---|
| 393 |
|
---|
| 394 | // decode Content-Type header
|
---|
| 395 | contentType, error := contenttype.ParseContentType(contentTypeString)
|
---|
| 396 | if error != nil {
|
---|
| 397 | // HTTP status code 503 : Service Unavailable
|
---|
| 398 | p.serveMainPage(ctx, 503, errors.New("invalid content type"))
|
---|
[63] | 399 | return
|
---|
| 400 | }
|
---|
| 401 |
|
---|
[68] | 402 | // content-disposition
|
---|
| 403 | contentDispositionBytes := ctx.Request.Header.Peek("Content-Disposition")
|
---|
[64] | 404 |
|
---|
[68] | 405 | // check content type
|
---|
| 406 | if !ALLOWED_CONTENTTYPE_FILTER(contentType) {
|
---|
| 407 | // it is not a usual content type
|
---|
| 408 | if ALLOWED_CONTENTTYPE_ATTACHMENT_FILTER(contentType) {
|
---|
| 409 | // force attachment for allowed content type
|
---|
| 410 | contentDispositionBytes = contentDispositionForceAttachment(contentDispositionBytes, parsedURI)
|
---|
| 411 | } else {
|
---|
| 412 | // deny access to forbidden content type
|
---|
| 413 | // HTTP status code 403 : Forbidden
|
---|
| 414 | p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
|
---|
| 415 | return
|
---|
| 416 | }
|
---|
| 417 | }
|
---|
| 418 |
|
---|
| 419 | // HACK : replace */xhtml by text/html
|
---|
| 420 | if contentType.SubType == "xhtml" {
|
---|
| 421 | contentType.TopLevelType = "text"
|
---|
| 422 | contentType.SubType = "html"
|
---|
| 423 | contentType.Suffix = ""
|
---|
| 424 | }
|
---|
| 425 |
|
---|
| 426 | // conversion to UTF-8
|
---|
[1] | 427 | var responseBody []byte
|
---|
| 428 |
|
---|
[68] | 429 | if contentType.TopLevelType == "text" {
|
---|
| 430 | e, ename, _ := charset.DetermineEncoding(resp.Body(), contentTypeString)
|
---|
[45] | 431 | if (e != encoding.Nop) && (!strings.EqualFold("utf-8", ename)) {
|
---|
| 432 | responseBody, err = e.NewDecoder().Bytes(resp.Body())
|
---|
| 433 | if err != nil {
|
---|
| 434 | // HTTP status code 503 : Service Unavailable
|
---|
| 435 | p.serveMainPage(ctx, 503, err)
|
---|
| 436 | return
|
---|
| 437 | }
|
---|
| 438 | } else {
|
---|
| 439 | responseBody = resp.Body()
|
---|
[1] | 440 | }
|
---|
[68] | 441 | // update the charset or specify it
|
---|
| 442 | contentType.Parameters["charset"] = "UTF-8"
|
---|
[1] | 443 | } else {
|
---|
| 444 | responseBody = resp.Body()
|
---|
| 445 | }
|
---|
| 446 |
|
---|
[68] | 447 | //
|
---|
| 448 | contentType.FilterParameters(ALLOWED_CONTENTTYPE_PARAMETERS)
|
---|
[1] | 449 |
|
---|
[68] | 450 | // set the content type
|
---|
| 451 | ctx.SetContentType(contentType.String())
|
---|
| 452 |
|
---|
| 453 | // output according to MIME type
|
---|
[1] | 454 | switch {
|
---|
[68] | 455 | case contentType.SubType == "css" && contentType.Suffix == "":
|
---|
[23] | 456 | sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
|
---|
[68] | 457 | case contentType.SubType == "html" && contentType.Suffix == "":
|
---|
[124] | 458 | rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
|
---|
| 459 | sanitizeHTML(rc, ctx, responseBody)
|
---|
| 460 | if !rc.BodyInjected {
|
---|
| 461 | p := HTMLBodyExtParam{rc.BaseURL.String(), false}
|
---|
| 462 | if len(rc.Key) > 0 {
|
---|
| 463 | p.HasMortyKey = true
|
---|
| 464 | }
|
---|
| 465 | err := HTML_BODY_EXTENSION.Execute(ctx, p)
|
---|
| 466 | if err != nil {
|
---|
| 467 | if DEBUG {
|
---|
| 468 | fmt.Println("failed to inject body extension", err)
|
---|
| 469 | }
|
---|
| 470 | }
|
---|
| 471 | }
|
---|
[1] | 472 | default:
|
---|
[68] | 473 | if contentDispositionBytes != nil {
|
---|
| 474 | ctx.Response.Header.AddBytesV("Content-Disposition", contentDispositionBytes)
|
---|
[39] | 475 | }
|
---|
[1] | 476 | ctx.Write(responseBody)
|
---|
| 477 | }
|
---|
| 478 | }
|
---|
| 479 |
|
---|
[68] | 480 | // force content-disposition to attachment
|
---|
| 481 | func contentDispositionForceAttachment(contentDispositionBytes []byte, url *url.URL) []byte {
|
---|
| 482 | var contentDispositionParams map[string]string
|
---|
| 483 |
|
---|
| 484 | if contentDispositionBytes != nil {
|
---|
| 485 | var err error
|
---|
| 486 | _, contentDispositionParams, err = mime.ParseMediaType(string(contentDispositionBytes))
|
---|
| 487 | if err != nil {
|
---|
| 488 | contentDispositionParams = make(map[string]string)
|
---|
| 489 | }
|
---|
| 490 | } else {
|
---|
| 491 | contentDispositionParams = make(map[string]string)
|
---|
| 492 | }
|
---|
| 493 |
|
---|
| 494 | _, fileNameDefined := contentDispositionParams["filename"]
|
---|
| 495 | if !fileNameDefined {
|
---|
| 496 | // TODO : sanitize filename
|
---|
| 497 | contentDispositionParams["fileName"] = filepath.Base(url.Path)
|
---|
| 498 | }
|
---|
| 499 |
|
---|
| 500 | return []byte(mime.FormatMediaType("attachment", contentDispositionParams))
|
---|
| 501 | }
|
---|
| 502 |
|
---|
[10] | 503 | func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
|
---|
[11] | 504 | // serve robots.txt
|
---|
[10] | 505 | if bytes.Equal(ctx.Path(), []byte("/robots.txt")) {
|
---|
| 506 | ctx.SetContentType("text/plain")
|
---|
| 507 | ctx.Write([]byte("User-Agent: *\nDisallow: /\n"))
|
---|
| 508 | return true
|
---|
| 509 | }
|
---|
[11] | 510 |
|
---|
[67] | 511 | // server favicon.ico
|
---|
| 512 | if bytes.Equal(ctx.Path(), []byte("/favicon.ico")) {
|
---|
| 513 | ctx.SetContentType("image/png")
|
---|
| 514 | ctx.Write(FAVICON_BYTES)
|
---|
| 515 | return true
|
---|
| 516 | }
|
---|
| 517 |
|
---|
[10] | 518 | return false
|
---|
| 519 | }
|
---|
| 520 |
|
---|
[1] | 521 | func popRequestParam(ctx *fasthttp.RequestCtx, paramName []byte) []byte {
|
---|
| 522 | param := ctx.QueryArgs().PeekBytes(paramName)
|
---|
| 523 |
|
---|
| 524 | if param == nil {
|
---|
| 525 | param = ctx.PostArgs().PeekBytes(paramName)
|
---|
[121] | 526 | ctx.PostArgs().DelBytes(paramName)
|
---|
[1] | 527 | }
|
---|
[121] | 528 | ctx.QueryArgs().DelBytes(paramName)
|
---|
[1] | 529 |
|
---|
| 530 | return param
|
---|
| 531 | }
|
---|
| 532 |
|
---|
[9] | 533 | func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
|
---|
[1] | 534 | // TODO
|
---|
| 535 |
|
---|
| 536 | urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
|
---|
| 537 |
|
---|
| 538 | if urlSlices == nil {
|
---|
[9] | 539 | out.Write(css)
|
---|
[1] | 540 | return
|
---|
| 541 | }
|
---|
| 542 |
|
---|
| 543 | startIndex := 0
|
---|
| 544 |
|
---|
| 545 | for _, s := range urlSlices {
|
---|
[15] | 546 | urlStart := s[4]
|
---|
| 547 | urlEnd := s[5]
|
---|
[1] | 548 |
|
---|
[60] | 549 | if uri, err := rc.ProxifyURI(css[urlStart:urlEnd]); err == nil {
|
---|
[9] | 550 | out.Write(css[startIndex:urlStart])
|
---|
| 551 | out.Write([]byte(uri))
|
---|
[1] | 552 | startIndex = urlEnd
|
---|
[97] | 553 | } else if DEBUG {
|
---|
[36] | 554 | log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
|
---|
[1] | 555 | }
|
---|
| 556 | }
|
---|
| 557 | if startIndex < len(css) {
|
---|
[9] | 558 | out.Write(css[startIndex:len(css)])
|
---|
[1] | 559 | }
|
---|
| 560 | }
|
---|
| 561 |
|
---|
[9] | 562 | func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
|
---|
[1] | 563 | r := bytes.NewReader(htmlDoc)
|
---|
| 564 | decoder := html.NewTokenizer(r)
|
---|
| 565 | decoder.AllowCDATA(true)
|
---|
| 566 |
|
---|
| 567 | unsafeElements := make([][]byte, 0, 8)
|
---|
| 568 | state := STATE_DEFAULT
|
---|
| 569 | for {
|
---|
| 570 | token := decoder.Next()
|
---|
| 571 | if token == html.ErrorToken {
|
---|
| 572 | err := decoder.Err()
|
---|
| 573 | if err != io.EOF {
|
---|
[97] | 574 | log.Println("failed to parse HTML")
|
---|
[1] | 575 | }
|
---|
| 576 | break
|
---|
| 577 | }
|
---|
| 578 |
|
---|
| 579 | if len(unsafeElements) == 0 {
|
---|
| 580 |
|
---|
| 581 | switch token {
|
---|
| 582 | case html.StartTagToken, html.SelfClosingTagToken:
|
---|
| 583 | tag, hasAttrs := decoder.TagName()
|
---|
| 584 | safe := !inArray(tag, UNSAFE_ELEMENTS)
|
---|
| 585 | if !safe {
|
---|
[116] | 586 | if token != html.SelfClosingTagToken {
|
---|
[1] | 587 | var unsafeTag []byte = make([]byte, len(tag))
|
---|
| 588 | copy(unsafeTag, tag)
|
---|
| 589 | unsafeElements = append(unsafeElements, unsafeTag)
|
---|
| 590 | }
|
---|
| 591 | break
|
---|
| 592 | }
|
---|
[38] | 593 | if bytes.Equal(tag, []byte("base")) {
|
---|
| 594 | for {
|
---|
| 595 | attrName, attrValue, moreAttr := decoder.TagAttr()
|
---|
[45] | 596 | if bytes.Equal(attrName, []byte("href")) {
|
---|
| 597 | parsedURI, err := url.Parse(string(attrValue))
|
---|
| 598 | if err == nil {
|
---|
| 599 | rc.BaseURL = parsedURI
|
---|
| 600 | }
|
---|
[38] | 601 | }
|
---|
| 602 | if !moreAttr {
|
---|
| 603 | break
|
---|
| 604 | }
|
---|
| 605 | }
|
---|
| 606 | break
|
---|
| 607 | }
|
---|
[1] | 608 | if bytes.Equal(tag, []byte("noscript")) {
|
---|
| 609 | state = STATE_IN_NOSCRIPT
|
---|
| 610 | break
|
---|
| 611 | }
|
---|
| 612 | var attrs [][][]byte
|
---|
| 613 | if hasAttrs {
|
---|
| 614 | for {
|
---|
| 615 | attrName, attrValue, moreAttr := decoder.TagAttr()
|
---|
[21] | 616 | attrs = append(attrs, [][]byte{
|
---|
| 617 | attrName,
|
---|
| 618 | attrValue,
|
---|
| 619 | []byte(html.EscapeString(string(attrValue))),
|
---|
| 620 | })
|
---|
[1] | 621 | if !moreAttr {
|
---|
| 622 | break
|
---|
| 623 | }
|
---|
| 624 | }
|
---|
[13] | 625 | }
|
---|
| 626 | if bytes.Equal(tag, []byte("link")) {
|
---|
| 627 | sanitizeLinkTag(rc, out, attrs)
|
---|
| 628 | break
|
---|
| 629 | }
|
---|
| 630 |
|
---|
[45] | 631 | if bytes.Equal(tag, []byte("meta")) {
|
---|
| 632 | sanitizeMetaTag(rc, out, attrs)
|
---|
| 633 | break
|
---|
| 634 | }
|
---|
| 635 |
|
---|
[13] | 636 | fmt.Fprintf(out, "<%s", tag)
|
---|
| 637 |
|
---|
| 638 | if hasAttrs {
|
---|
[45] | 639 | sanitizeAttrs(rc, out, attrs)
|
---|
[1] | 640 | }
|
---|
[13] | 641 |
|
---|
[1] | 642 | if token == html.SelfClosingTagToken {
|
---|
[9] | 643 | fmt.Fprintf(out, " />")
|
---|
[1] | 644 | } else {
|
---|
[9] | 645 | fmt.Fprintf(out, ">")
|
---|
[1] | 646 | if bytes.Equal(tag, []byte("style")) {
|
---|
| 647 | state = STATE_IN_STYLE
|
---|
| 648 | }
|
---|
| 649 | }
|
---|
[13] | 650 |
|
---|
[45] | 651 | if bytes.Equal(tag, []byte("head")) {
|
---|
[46] | 652 | fmt.Fprintf(out, HTML_HEAD_CONTENT_TYPE)
|
---|
[45] | 653 | }
|
---|
| 654 |
|
---|
[1] | 655 | if bytes.Equal(tag, []byte("form")) {
|
---|
| 656 | var formURL *url.URL
|
---|
| 657 | for _, attr := range attrs {
|
---|
| 658 | if bytes.Equal(attr[0], []byte("action")) {
|
---|
| 659 | formURL, _ = url.Parse(string(attr[1]))
|
---|
[28] | 660 | formURL = mergeURIs(rc.BaseURL, formURL)
|
---|
[1] | 661 | break
|
---|
| 662 | }
|
---|
| 663 | }
|
---|
| 664 | if formURL == nil {
|
---|
[23] | 665 | formURL = rc.BaseURL
|
---|
[1] | 666 | }
|
---|
[2] | 667 | urlStr := formURL.String()
|
---|
| 668 | var key string
|
---|
| 669 | if rc.Key != nil {
|
---|
| 670 | key = hash(urlStr, rc.Key)
|
---|
| 671 | }
|
---|
[121] | 672 | err := HTML_FORM_EXTENSION.Execute(out, HTMLFormExtParam{urlStr, key})
|
---|
| 673 | if err != nil {
|
---|
| 674 | if DEBUG {
|
---|
| 675 | fmt.Println("failed to inject body extension", err)
|
---|
| 676 | }
|
---|
| 677 | }
|
---|
[1] | 678 | }
|
---|
| 679 |
|
---|
| 680 | case html.EndTagToken:
|
---|
| 681 | tag, _ := decoder.TagName()
|
---|
| 682 | writeEndTag := true
|
---|
| 683 | switch string(tag) {
|
---|
| 684 | case "body":
|
---|
[121] | 685 | p := HTMLBodyExtParam{rc.BaseURL.String(), false}
|
---|
| 686 | if len(rc.Key) > 0 {
|
---|
| 687 | p.HasMortyKey = true
|
---|
| 688 | }
|
---|
| 689 | err := HTML_BODY_EXTENSION.Execute(out, p)
|
---|
| 690 | if err != nil {
|
---|
| 691 | if DEBUG {
|
---|
| 692 | fmt.Println("failed to inject body extension", err)
|
---|
| 693 | }
|
---|
| 694 | }
|
---|
[124] | 695 | rc.BodyInjected = true
|
---|
[1] | 696 | case "style":
|
---|
| 697 | state = STATE_DEFAULT
|
---|
| 698 | case "noscript":
|
---|
| 699 | state = STATE_DEFAULT
|
---|
| 700 | writeEndTag = false
|
---|
| 701 | }
|
---|
| 702 | // skip noscript tags - only the tag, not the content, because javascript is sanitized
|
---|
| 703 | if writeEndTag {
|
---|
[9] | 704 | fmt.Fprintf(out, "</%s>", tag)
|
---|
[1] | 705 | }
|
---|
| 706 |
|
---|
| 707 | case html.TextToken:
|
---|
| 708 | switch state {
|
---|
| 709 | case STATE_DEFAULT:
|
---|
[9] | 710 | fmt.Fprintf(out, "%s", decoder.Raw())
|
---|
[1] | 711 | case STATE_IN_STYLE:
|
---|
[9] | 712 | sanitizeCSS(rc, out, decoder.Raw())
|
---|
[1] | 713 | case STATE_IN_NOSCRIPT:
|
---|
[9] | 714 | sanitizeHTML(rc, out, decoder.Raw())
|
---|
[1] | 715 | }
|
---|
| 716 |
|
---|
[62] | 717 | case html.CommentToken:
|
---|
| 718 | // ignore comment. TODO : parse IE conditional comment
|
---|
| 719 |
|
---|
| 720 | case html.DoctypeToken:
|
---|
[9] | 721 | out.Write(decoder.Raw())
|
---|
[1] | 722 | }
|
---|
| 723 | } else {
|
---|
| 724 | switch token {
|
---|
[116] | 725 | case html.StartTagToken, html.SelfClosingTagToken:
|
---|
[1] | 726 | tag, _ := decoder.TagName()
|
---|
| 727 | if inArray(tag, UNSAFE_ELEMENTS) {
|
---|
| 728 | unsafeElements = append(unsafeElements, tag)
|
---|
| 729 | }
|
---|
| 730 |
|
---|
| 731 | case html.EndTagToken:
|
---|
| 732 | tag, _ := decoder.TagName()
|
---|
| 733 | if bytes.Equal(unsafeElements[len(unsafeElements)-1], tag) {
|
---|
| 734 | unsafeElements = unsafeElements[:len(unsafeElements)-1]
|
---|
| 735 | }
|
---|
| 736 | }
|
---|
| 737 | }
|
---|
| 738 | }
|
---|
| 739 | }
|
---|
| 740 |
|
---|
[13] | 741 | func sanitizeLinkTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
| 742 | exclude := false
|
---|
| 743 | for _, attr := range attrs {
|
---|
| 744 | attrName := attr[0]
|
---|
| 745 | attrValue := attr[1]
|
---|
| 746 | if bytes.Equal(attrName, []byte("rel")) {
|
---|
[46] | 747 | if !inArray(attrValue, LINK_REL_SAFE_VALUES) {
|
---|
[13] | 748 | exclude = true
|
---|
| 749 | break
|
---|
| 750 | }
|
---|
| 751 | }
|
---|
| 752 | if bytes.Equal(attrName, []byte("as")) {
|
---|
| 753 | if bytes.Equal(attrValue, []byte("script")) {
|
---|
| 754 | exclude = true
|
---|
| 755 | break
|
---|
| 756 | }
|
---|
| 757 | }
|
---|
| 758 | }
|
---|
| 759 |
|
---|
| 760 | if !exclude {
|
---|
| 761 | out.Write([]byte("<link"))
|
---|
| 762 | for _, attr := range attrs {
|
---|
[21] | 763 | sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
|
---|
[13] | 764 | }
|
---|
| 765 | out.Write([]byte(">"))
|
---|
| 766 | }
|
---|
| 767 | }
|
---|
| 768 |
|
---|
[45] | 769 | func sanitizeMetaTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
[1] | 770 | var http_equiv []byte
|
---|
| 771 | var content []byte
|
---|
| 772 |
|
---|
| 773 | for _, attr := range attrs {
|
---|
| 774 | attrName := attr[0]
|
---|
| 775 | attrValue := attr[1]
|
---|
| 776 | if bytes.Equal(attrName, []byte("http-equiv")) {
|
---|
| 777 | http_equiv = bytes.ToLower(attrValue)
|
---|
[46] | 778 | // exclude some <meta http-equiv="..." ..>
|
---|
| 779 | if !inArray(http_equiv, LINK_HTTP_EQUIV_SAFE_VALUES) {
|
---|
| 780 | return
|
---|
| 781 | }
|
---|
[1] | 782 | }
|
---|
| 783 | if bytes.Equal(attrName, []byte("content")) {
|
---|
| 784 | content = attrValue
|
---|
| 785 | }
|
---|
[45] | 786 | if bytes.Equal(attrName, []byte("charset")) {
|
---|
| 787 | // exclude <meta charset="...">
|
---|
| 788 | return
|
---|
| 789 | }
|
---|
[1] | 790 | }
|
---|
| 791 |
|
---|
[45] | 792 | out.Write([]byte("<meta"))
|
---|
[14] | 793 | urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
|
---|
| 794 | if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
|
---|
| 795 | contentUrl := content[urlIndex+4:]
|
---|
[36] | 796 | // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
|
---|
[37] | 797 | if len(contentUrl) >= 2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
|
---|
[36] | 798 | if contentUrl[0] == contentUrl[len(contentUrl)-1] {
|
---|
[37] | 799 | contentUrl = contentUrl[1 : len(contentUrl)-1]
|
---|
[36] | 800 | }
|
---|
| 801 | }
|
---|
| 802 | // output proxify result
|
---|
[60] | 803 | if uri, err := rc.ProxifyURI(contentUrl); err == nil {
|
---|
[14] | 804 | fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
|
---|
[1] | 805 | }
|
---|
| 806 | } else {
|
---|
[46] | 807 | if len(http_equiv) > 0 {
|
---|
| 808 | fmt.Fprintf(out, ` http-equiv="%s"`, http_equiv)
|
---|
| 809 | }
|
---|
[9] | 810 | sanitizeAttrs(rc, out, attrs)
|
---|
[1] | 811 | }
|
---|
[45] | 812 | out.Write([]byte(">"))
|
---|
[1] | 813 | }
|
---|
| 814 |
|
---|
[9] | 815 | func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
|
---|
[1] | 816 | for _, attr := range attrs {
|
---|
[21] | 817 | sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
|
---|
[1] | 818 | }
|
---|
| 819 | }
|
---|
| 820 |
|
---|
[21] | 821 | func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
|
---|
[1] | 822 | if inArray(attrName, SAFE_ATTRIBUTES) {
|
---|
[21] | 823 | fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
|
---|
[1] | 824 | return
|
---|
| 825 | }
|
---|
| 826 | switch string(attrName) {
|
---|
| 827 | case "src", "href", "action":
|
---|
[60] | 828 | if uri, err := rc.ProxifyURI(attrValue); err == nil {
|
---|
[9] | 829 | fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
|
---|
[97] | 830 | } else if DEBUG {
|
---|
[36] | 831 | log.Println("cannot proxify uri:", string(attrValue))
|
---|
[1] | 832 | }
|
---|
| 833 | case "style":
|
---|
[21] | 834 | cssAttr := bytes.NewBuffer(nil)
|
---|
| 835 | sanitizeCSS(rc, cssAttr, attrValue)
|
---|
| 836 | fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
|
---|
[1] | 837 | }
|
---|
| 838 | }
|
---|
| 839 |
|
---|
[36] | 840 | func mergeURIs(u1, u2 *url.URL) *url.URL {
|
---|
[71] | 841 | if u2 == nil {
|
---|
| 842 | return u1
|
---|
| 843 | }
|
---|
[28] | 844 | return u1.ResolveReference(u2)
|
---|
[1] | 845 | }
|
---|
| 846 |
|
---|
[60] | 847 | // Sanitized URI : removes all runes bellow 32 (included) as the begining and end of URI, and lower case the scheme.
|
---|
| 848 | // avoid memory allocation (except for the scheme)
|
---|
| 849 | func sanitizeURI(uri []byte) ([]byte, string) {
|
---|
| 850 | first_rune_index := 0
|
---|
| 851 | first_rune_seen := false
|
---|
| 852 | scheme_last_index := -1
|
---|
| 853 | buffer := bytes.NewBuffer(make([]byte, 0, 10))
|
---|
| 854 |
|
---|
| 855 | // remove trailing space and special characters
|
---|
| 856 | uri = bytes.TrimRight(uri, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20")
|
---|
| 857 |
|
---|
| 858 | // loop over byte by byte
|
---|
| 859 | for i, c := range uri {
|
---|
| 860 | // ignore special characters and space (c <= 32)
|
---|
| 861 | if c > 32 {
|
---|
| 862 | // append to the lower case of the rune to buffer
|
---|
| 863 | if c < utf8.RuneSelf && 'A' <= c && c <= 'Z' {
|
---|
| 864 | c = c + 'a' - 'A'
|
---|
| 865 | }
|
---|
| 866 |
|
---|
| 867 | buffer.WriteByte(c)
|
---|
| 868 |
|
---|
| 869 | // update the first rune index that is not a special rune
|
---|
| 870 | if !first_rune_seen {
|
---|
| 871 | first_rune_index = i
|
---|
| 872 | first_rune_seen = true
|
---|
| 873 | }
|
---|
| 874 |
|
---|
| 875 | if c == ':' {
|
---|
| 876 | // colon rune found, we have found the scheme
|
---|
| 877 | scheme_last_index = i
|
---|
| 878 | break
|
---|
| 879 | } else if c == '/' || c == '?' || c == '\\' || c == '#' {
|
---|
| 880 | // special case : most probably a relative URI
|
---|
| 881 | break
|
---|
| 882 | }
|
---|
| 883 | }
|
---|
| 884 | }
|
---|
| 885 |
|
---|
| 886 | if scheme_last_index != -1 {
|
---|
| 887 | // scheme found
|
---|
| 888 | // copy the "lower case without special runes scheme" before the ":" rune
|
---|
| 889 | scheme_start_index := scheme_last_index - buffer.Len() + 1
|
---|
| 890 | copy(uri[scheme_start_index:], buffer.Bytes())
|
---|
| 891 | // and return the result
|
---|
| 892 | return uri[scheme_start_index:], buffer.String()
|
---|
| 893 | } else {
|
---|
| 894 | // scheme NOT found
|
---|
| 895 | return uri[first_rune_index:], ""
|
---|
| 896 | }
|
---|
| 897 | }
|
---|
| 898 |
|
---|
| 899 | func (rc *RequestConfig) ProxifyURI(uri []byte) (string, error) {
|
---|
| 900 | // sanitize URI
|
---|
| 901 | uri, scheme := sanitizeURI(uri)
|
---|
| 902 |
|
---|
[28] | 903 | // remove javascript protocol
|
---|
[60] | 904 | if scheme == "javascript:" {
|
---|
[28] | 905 | return "", nil
|
---|
| 906 | }
|
---|
[57] | 907 |
|
---|
[1] | 908 | // TODO check malicious data: - e.g. data:script
|
---|
[60] | 909 | if scheme == "data:" {
|
---|
[61] | 910 | if bytes.HasPrefix(uri, []byte("data:image/png")) ||
|
---|
| 911 | bytes.HasPrefix(uri, []byte("data:image/jpeg")) ||
|
---|
| 912 | bytes.HasPrefix(uri, []byte("data:image/pjpeg")) ||
|
---|
| 913 | bytes.HasPrefix(uri, []byte("data:image/gif")) ||
|
---|
| 914 | bytes.HasPrefix(uri, []byte("data:image/webp")) {
|
---|
| 915 | // should be safe
|
---|
| 916 | return string(uri), nil
|
---|
| 917 | } else {
|
---|
| 918 | // unsafe data
|
---|
| 919 | return "", nil
|
---|
| 920 | }
|
---|
[1] | 921 | }
|
---|
| 922 |
|
---|
[57] | 923 | // parse the uri
|
---|
[60] | 924 | u, err := url.Parse(string(uri))
|
---|
[1] | 925 | if err != nil {
|
---|
| 926 | return "", err
|
---|
| 927 | }
|
---|
[57] | 928 |
|
---|
| 929 | // get the fragment (with the prefix "#")
|
---|
| 930 | fragment := ""
|
---|
| 931 | if len(u.Fragment) > 0 {
|
---|
| 932 | fragment = "#" + u.Fragment
|
---|
| 933 | }
|
---|
| 934 |
|
---|
| 935 | // reset the fragment: it is not included in the mortyurl
|
---|
| 936 | u.Fragment = ""
|
---|
| 937 |
|
---|
| 938 | // merge the URI with the document URI
|
---|
[28] | 939 | u = mergeURIs(rc.BaseURL, u)
|
---|
[1] | 940 |
|
---|
[57] | 941 | // simple internal link ?
|
---|
| 942 | // some web pages describe the whole link https://same:auth@same.host/same.path?same.query#new.fragment
|
---|
| 943 | if u.Scheme == rc.BaseURL.Scheme &&
|
---|
| 944 | (rc.BaseURL.User == nil || (u.User != nil && u.User.String() == rc.BaseURL.User.String())) &&
|
---|
| 945 | u.Host == rc.BaseURL.Host &&
|
---|
| 946 | u.Path == rc.BaseURL.Path &&
|
---|
| 947 | u.RawQuery == rc.BaseURL.RawQuery {
|
---|
| 948 | // the fragment is the only difference between the document URI and the uri parameter
|
---|
| 949 | return fragment, nil
|
---|
| 950 | }
|
---|
| 951 |
|
---|
| 952 | // return full URI and fragment (if not empty)
|
---|
[60] | 953 | morty_uri := u.String()
|
---|
[1] | 954 |
|
---|
| 955 | if rc.Key == nil {
|
---|
[60] | 956 | return fmt.Sprintf("./?mortyurl=%s%s", url.QueryEscape(morty_uri), fragment), nil
|
---|
[1] | 957 | }
|
---|
[60] | 958 | return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s%s", hash(morty_uri, rc.Key), url.QueryEscape(morty_uri), fragment), nil
|
---|
[1] | 959 | }
|
---|
| 960 |
|
---|
| 961 | func inArray(b []byte, a [][]byte) bool {
|
---|
| 962 | for _, b2 := range a {
|
---|
| 963 | if bytes.Equal(b, b2) {
|
---|
| 964 | return true
|
---|
| 965 | }
|
---|
| 966 | }
|
---|
| 967 | return false
|
---|
| 968 | }
|
---|
| 969 |
|
---|
| 970 | func hash(msg string, key []byte) string {
|
---|
| 971 | mac := hmac.New(sha256.New, key)
|
---|
| 972 | mac.Write([]byte(msg))
|
---|
| 973 | return hex.EncodeToString(mac.Sum(nil))
|
---|
| 974 | }
|
---|
| 975 |
|
---|
| 976 | func verifyRequestURI(uri, hashMsg, key []byte) bool {
|
---|
| 977 | h := make([]byte, hex.DecodedLen(len(hashMsg)))
|
---|
| 978 | _, err := hex.Decode(h, hashMsg)
|
---|
| 979 | if err != nil {
|
---|
[97] | 980 | if DEBUG {
|
---|
| 981 | log.Println("hmac error:", err)
|
---|
| 982 | }
|
---|
[1] | 983 | return false
|
---|
| 984 | }
|
---|
| 985 | mac := hmac.New(sha256.New, key)
|
---|
| 986 | mac.Write(uri)
|
---|
| 987 | return hmac.Equal(h, mac.Sum(nil))
|
---|
| 988 | }
|
---|
| 989 |
|
---|
[69] | 990 | func (p *Proxy) serveExitMortyPage(ctx *fasthttp.RequestCtx, uri *url.URL) {
|
---|
| 991 | ctx.SetContentType("text/html")
|
---|
| 992 | ctx.SetStatusCode(403)
|
---|
| 993 | ctx.Write([]byte(MORTY_HTML_PAGE_START))
|
---|
| 994 | ctx.Write([]byte("<h2>You are about to exit MortyProxy</h2>"))
|
---|
| 995 | ctx.Write([]byte("<p>Following</p><p><a href=\""))
|
---|
| 996 | ctx.Write([]byte(html.EscapeString(uri.String())))
|
---|
| 997 | ctx.Write([]byte("\" rel=\"noreferrer\">"))
|
---|
| 998 | ctx.Write([]byte(html.EscapeString(uri.String())))
|
---|
| 999 | ctx.Write([]byte("</a></p><p>the content of this URL will be <b>NOT</b> sanitized.</p>"))
|
---|
| 1000 | ctx.Write([]byte(MORTY_HTML_PAGE_END))
|
---|
| 1001 | }
|
---|
| 1002 |
|
---|
[35] | 1003 | func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
|
---|
[67] | 1004 | ctx.SetContentType("text/html; charset=UTF-8")
|
---|
[35] | 1005 | ctx.SetStatusCode(statusCode)
|
---|
[69] | 1006 | ctx.Write([]byte(MORTY_HTML_PAGE_START))
|
---|
[11] | 1007 | if err != nil {
|
---|
[97] | 1008 | if DEBUG {
|
---|
| 1009 | log.Println("error:", err)
|
---|
| 1010 | }
|
---|
[11] | 1011 | ctx.Write([]byte("<h2>Error: "))
|
---|
| 1012 | ctx.Write([]byte(html.EscapeString(err.Error())))
|
---|
| 1013 | ctx.Write([]byte("</h2>"))
|
---|
| 1014 | }
|
---|
[1] | 1015 | if p.Key == nil {
|
---|
| 1016 | ctx.Write([]byte(`
|
---|
[36] | 1017 | <form action="post">
|
---|
| 1018 | Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
|
---|
| 1019 | <input type="submit" value="go" />
|
---|
| 1020 | </form>`))
|
---|
[11] | 1021 | } else {
|
---|
| 1022 | ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
|
---|
[1] | 1023 | }
|
---|
[69] | 1024 | ctx.Write([]byte(MORTY_HTML_PAGE_END))
|
---|
[1] | 1025 | }
|
---|
| 1026 |
|
---|
| 1027 | func main() {
|
---|
[78] | 1028 | default_listen_addr := os.Getenv("MORTY_ADDRESS")
|
---|
| 1029 | if default_listen_addr == "" {
|
---|
| 1030 | default_listen_addr = "127.0.0.1:3000"
|
---|
| 1031 | }
|
---|
| 1032 | default_key := os.Getenv("MORTY_KEY")
|
---|
| 1033 | listen := flag.String("listen", default_listen_addr, "Listen address")
|
---|
[92] | 1034 | key := flag.String("key", default_key, "HMAC url validation key (base64 encoded) - leave blank to disable validation")
|
---|
[24] | 1035 | ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
|
---|
[74] | 1036 | version := flag.Bool("version", false, "Show version")
|
---|
[4] | 1037 | requestTimeout := flag.Uint("timeout", 2, "Request timeout")
|
---|
[109] | 1038 | socks5 := flag.String("socks5", "", "SOCKS5 proxy")
|
---|
[1] | 1039 | flag.Parse()
|
---|
| 1040 |
|
---|
[74] | 1041 | if *version {
|
---|
| 1042 | fmt.Println(VERSION)
|
---|
| 1043 | return
|
---|
| 1044 | }
|
---|
| 1045 |
|
---|
[24] | 1046 | if *ipv6 {
|
---|
[109] | 1047 | CLIENT.DialDualStack = true
|
---|
[24] | 1048 | }
|
---|
| 1049 |
|
---|
[109] | 1050 | if *socks5 != "" {
|
---|
| 1051 | // this disables CLIENT.DialDualStack
|
---|
| 1052 | CLIENT.Dial = fasthttpproxy.FasthttpSocksDialer(*socks5)
|
---|
| 1053 | }
|
---|
| 1054 |
|
---|
[4] | 1055 | p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
|
---|
[1] | 1056 |
|
---|
| 1057 | if *key != "" {
|
---|
[92] | 1058 | var err error
|
---|
| 1059 | p.Key, err = base64.StdEncoding.DecodeString(*key)
|
---|
[94] | 1060 | if err != nil {
|
---|
| 1061 | log.Fatal("Error parsing -key", err.Error())
|
---|
| 1062 | os.Exit(1)
|
---|
[92] | 1063 | }
|
---|
[1] | 1064 | }
|
---|
| 1065 |
|
---|
| 1066 | log.Println("listening on", *listen)
|
---|
| 1067 |
|
---|
| 1068 | if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
|
---|
| 1069 | log.Fatal("Error in ListenAndServe:", err)
|
---|
| 1070 | }
|
---|
| 1071 | }
|
---|