Skip to content

Instantly share code, notes, and snippets.

@kitlith
Last active April 17, 2017 03:09
Show Gist options
  • Save kitlith/82eaa0721921f151b8bed3a3233c6f5e to your computer and use it in GitHub Desktop.
Save kitlith/82eaa0721921f151b8bed3a3233c6f5e to your computer and use it in GitHub Desktop.
WIP Mitmproxy script(s) that implement request/response rewriting for unencrypted connections.
from rewrite import form_rewrite
rewrite_table = {
"http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi": {
"Comments": "placeholder"
}
}
def request(flow): # An example for using the form rewriter.
form_rewrite(flow, rewrite_table)
from mitmproxy import flowfilter
from mitmproxy.addons import stickycookie
sc = stickycookie.StickyCookie()
def start():
# This is a hack, but it works. Means I don't have to duplicate the entire sticky cookie implementation
sc.flt = flowfilter.parse("html-kit.com")
def response(flow):
sc.response(flow)
# Now that we're done saving the cookies, strip them.
for name, (value, attrs) in flow.response.cookies.items(multi=True): # taken from
# FIXME: We now know that Cookie.py screws up some cookies with
# valid RFC 822/1123 datetime specifications for expiry. Sigh.
dom_port_path = stickycookie.ckey(attrs, flow)
if stickycookie.domain_match(flow.request.host, dom_port_path[0]):
flow.response.cookies.pop(name) # TODO: Is there a better way to do this?
def request(flow):
sc.request(flow)
# Using http://www.html-kit.com/tools/cookietester/ as a test for cookie stripping.
import json
from collections.abc import Mapping
def _rewrite(obj, rewrite):
for name in rewrite:
if isinstance(rewrite[name], Mapping) and name in obj:
_rewrite(obj[name], rewrite[name])
continue
obj[name] = rewrite[name]
return obj
def form_rewrite(flow, rewrite):
if flow.request.urlencoded_form:
if flow.request.pretty_url not in rewrite:
return
flow.request.urlencoded_form = _rewrite(flow.request.urlencoded_form, rewrite[flow.request.pretty_url])
# Using https://www.cs.tut.fi/~jkorpela/forms/testing.html as a test for form rewriting.
def json_rewrite(content, rewrite):
try:
obj = json.loads(content)
obj = _rewrite(obj, rewrite)
content = json.dumps(obj)
except ValueError:
return # If it's not json, do nothing.
from rewrite import form_rewrite
import cookies
def start():
cookies.start()
def request(flow):
cookies.request(flow)
val = "" # Another example for using the form rewriter.
if "Comments" in flow.request.urlencoded_form:
val = flow.request.urlencoded_form["Comments"]
rewrite_table = {
"https://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi": {
"Comments": "This is a very insightful comment that replaced the following: {}"
.format(val)
}
}
form_rewrite(flow, rewrite_table)
def response(flow):
cookies.response(flow)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment