Skip to content

Instantly share code, notes, and snippets.

@yorkxin
Last active August 21, 2019 17:40
Show Gist options
  • Save yorkxin/236b6adcb3e543959a85 to your computer and use it in GitHub Desktop.
Save yorkxin/236b6adcb3e543959a85 to your computer and use it in GitHub Desktop.
Proxy to remote server with CORS support

cors.py for mitmproxy

Hacking CORS restriction to enable in-browser XHR to any server.

Usage

Say you are running an web app at localhost, and you want to send XHR to http://remote-server:80, but the CORS restriction forbids access because you are sending requests from an origin that remote-server:80 does not allow.

Run:

mitmproxy -s cors.py -R http://remote-server:80 -b localhost -p 8080

Now localhost:8080 is tunnelled to remote-server:80.

And you can XHR to proxied server from localhost:

fetch("http://localhost:8080/api.json")
  .then(function(response) {
    // enjoy the response
  });

Bonus: You can inspect HTTP requests in mitmproxy.

from libmproxy.protocol.http import HTTPResponse
from netlib.odict import ODictCaseless
def response(context, flow):
flow.response.headers["Access-Control-Allow-Origin"] = ["*"]
# Use this if the application sends auth info via header
flow.response.headers["Access-Control-Expose-Headers"] = ["X-Application-Session-Id"]
def request(context, flow):
# Hijack CORS OPTIONS request
if flow.request.method == "OPTIONS":
headers = ODictCaseless([
["Access-Control-Allow-Origin", "*"],
["Access-Control-Allow-Methods", "POST"],
["Access-Control-Allow-Headers", "X-Application-Session-Id"],
["Access-Control-Max-Age", 1728000]
])
resp = HTTPResponse([1, 1], 200, "OK", headers, "")
flow.reply(resp)
@wereHamster
Copy link

See https://gist.github.com/wereHamster/414aad4a41fca394a450 for changes needed to make the script compatible with mitmproxy 0.14 (I have not tested it yet with 0.15).

@jhass
Copy link

jhass commented Feb 13, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment