repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
mitmproxy/mitmproxy
1,565
mitmproxy__mitmproxy-1565
[ "1549" ]
1e5a5b03f8d56df62a04a368bd5eb2d59cb7582a
diff --git a/mitmproxy/exceptions.py b/mitmproxy/exceptions.py --- a/mitmproxy/exceptions.py +++ b/mitmproxy/exceptions.py @@ -27,6 +27,10 @@ class Kill(ProxyException): class ProtocolException(ProxyException): + """ + ProtocolExceptions are caused by invalid user input, unavailable network resources, + or other events that are outside of our influence. + """ pass diff --git a/mitmproxy/protocol/http.py b/mitmproxy/protocol/http.py --- a/mitmproxy/protocol/http.py +++ b/mitmproxy/protocol/http.py @@ -153,12 +153,13 @@ def __call__(self): # We optimistically guess there might be an HTTP client on the # other end self.send_error_response(400, repr(e)) - self.log( - "request", - "warn", - "HTTP protocol error in client request: %s" % e + six.reraise( + exceptions.ProtocolException, + exceptions.ProtocolException( + "HTTP protocol error in client request: {}".format(e) + ), + sys.exc_info()[2] ) - return self.log("request", "debug", [repr(request)]) diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py --- a/mitmproxy/proxy/server.py +++ b/mitmproxy/proxy/server.py @@ -132,7 +132,7 @@ def handle(self): self.log(str(e), "warn") self.log("Invalid certificate, closing connection. Pass --insecure to disable validation.", "warn") else: - self.log(repr(e), "warn") + self.log(str(e), "warn") self.log(traceback.format_exc(), "debug") # If an error propagates to the topmost level,
mitmdump error logging is broken. ##### Steps to reproduce the problem: 1. `mitmdump` 2. `curl -x localhost:8080 example!!.com` ##### What is the expected behavior? Proper console output ##### What went wrong? ``` λ mitmdump 127.0.0.1:56178: clientconnect 127.0.0.1:56178: request -> H -> T -> T -> P -> -> p -> r -> o -> t -> o -> c -> o -> l -> -> e -> r -> r -> o -> r -> -> i -> n -> -> c -> l -> i -> e -> n -> t -> -> r -> e -> q -> u -> e -> s -> t -> : -> -> B -> a -> d -> -> H -> T -> T -> P -> -> r -> e -> q -> u -> e -> s -> t -> -> l -> i -> n -> e -> : -> -> b -> ' -> G -> E -> T -> -> H -> T -> T -> P -> : -> / -> / -> e -> x -> a -> m -> p -> l -> e -> ! -> ! -> . -> c -> o -> m -> / -> -> H -> T -> T -> P -> / -> 1 -> . -> 1 -> ' 127.0.0.1:56178: clientdisconnect ``` --- Mitmproxy Version: master Operating System: Win10 x64
2016-09-22T03:59:53
mitmproxy/mitmproxy
1,567
mitmproxy__mitmproxy-1567
[ "1467" ]
f59ae4a57f65fa76812c3a29965df8a4b35448e9
diff --git a/mitmproxy/builtins/script.py b/mitmproxy/builtins/script.py --- a/mitmproxy/builtins/script.py +++ b/mitmproxy/builtins/script.py @@ -53,6 +53,33 @@ def parse_command(command): return args[0], args[1:] +def cut_traceback(tb, func_name): + """ + Cut off a traceback at the function with the given name. + The func_name's frame is excluded. + + Args: + tb: traceback object, as returned by sys.exc_info()[2] + func_name: function name + + Returns: + Reduced traceback. + """ + tb_orig = tb + + for _, _, fname, _ in traceback.extract_tb(tb): + tb = tb.tb_next + if fname == func_name: + break + + if tb is None: + # We could not find the method, take the full stack trace. + # This may happen on some Python interpreters/flavors (e.g. PyInstaller). + return tb_orig + else: + return tb + + @contextlib.contextmanager def scriptenv(path, args): oldargs = sys.argv @@ -63,11 +90,7 @@ def scriptenv(path, args): yield except Exception: etype, value, tb = sys.exc_info() - scriptdir = os.path.dirname(os.path.abspath(path)) - for i, s in enumerate(reversed(traceback.extract_tb(tb))): - tb = tb.tb_next - if not os.path.abspath(s[0]).startswith(scriptdir): - break + tb = cut_traceback(tb, "scriptenv").tb_next ctx.log.error( "Script error: %s" % "".join( traceback.format_exception(etype, value, tb)
diff --git a/test/mitmproxy/builtins/test_script.py b/test/mitmproxy/builtins/test_script.py --- a/test/mitmproxy/builtins/test_script.py +++ b/test/mitmproxy/builtins/test_script.py @@ -1,10 +1,12 @@ -import time +import traceback -from mitmproxy.builtins import script +import sys +import time from mitmproxy import exceptions +from mitmproxy import options +from mitmproxy.builtins import script from mitmproxy.flow import master from mitmproxy.flow import state -from mitmproxy import options from .. import tutils, mastertest @@ -104,6 +106,10 @@ def test_exception(self): f = tutils.tflow(resp=True) m.request(f) assert m.event_log[0][0] == "error" + assert len(m.event_log[0][1].splitlines()) == 6 + assert 'addonscripts/error.py", line 7, in request' in m.event_log[0][1] + assert 'addonscripts/error.py", line 3, in mkerr' in m.event_log[0][1] + assert m.event_log[0][1].endswith("ValueError: Error!\n") def test_duplicate_flow(self): s = state.State() @@ -136,6 +142,24 @@ def test_addon(self): ] +class TestCutTraceback: + def raise_(self, i): + if i > 0: + self.raise_(i - 1) + raise RuntimeError() + + def test_simple(self): + try: + self.raise_(4) + except RuntimeError: + tb = sys.exc_info()[2] + tb_cut = script.cut_traceback(tb, "test_simple") + assert len(traceback.extract_tb(tb_cut)) == 5 + + tb_cut2 = script.cut_traceback(tb, "nonexistent") + assert len(traceback.extract_tb(tb_cut2)) == len(traceback.extract_tb(tb)) + + class TestScriptLoader(mastertest.MasterTest): def test_run_once(self): s = state.State()
No stacktrace for errors in done() hook. ##### Steps to reproduce the problem: 1. Create inline script which raises in `done()` 2. `mitmdump -s script.py -n -r foo` ##### What is the expected behavior? Should print error message. ##### What went wrong? Only displays "mitmdump: errors occurred during run" --- Mitmproxy Version: master Operating System: Win10 x64
2016-09-22T08:13:28
mitmproxy/mitmproxy
1,578
mitmproxy__mitmproxy-1578
[ "1221", "1221" ]
eeec17902fdcd7de766dc79ed6a2e3a73ad4ce3d
diff --git a/pathod/pathoc.py b/pathod/pathoc.py --- a/pathod/pathoc.py +++ b/pathod/pathoc.py @@ -478,21 +478,31 @@ def request(self, r): def main(args): # pragma: no cover - memo = set([]) - trycount = 0 + memo = set() p = None + + if args.repeat == 1: + requests = args.requests + else: + # If we are replaying more than once, we must convert the request generators to lists + # or they will be exhausted after the first run. + # This is bad for the edge-case where get:/:x10000000 (see 0da3e51) is combined with -n 2, + # but does not matter otherwise. + requests = [list(x) for x in args.requests] + try: - cnt = 0 + requests_done = 0 while True: - if cnt == args.repeat and args.repeat != 0: + if requests_done == args.repeat: break - if args.wait and cnt != 0: + if args.wait and requests_done > 0: time.sleep(args.wait) - cnt += 1 - playlist = itertools.chain(*args.requests) + requests_done += 1 if args.random: - playlist = random.choice(args.requests) + playlist = random.choice(requests) + else: + playlist = itertools.chain.from_iterable(requests) p = Pathoc( (args.host, args.port), ssl=args.ssl, diff --git a/pathod/pathoc_cmdline.py b/pathod/pathoc_cmdline.py --- a/pathod/pathoc_cmdline.py +++ b/pathod/pathoc_cmdline.py @@ -50,7 +50,7 @@ def args_pathoc(argv, stdout=sys.stdout, stderr=sys.stderr): ) parser.add_argument( "-n", dest='repeat', default=1, type=int, metavar="N", - help='Repeat N times. If 0 repeat for ever.' + help='Repeat N times. Pass -1 to repeat infinitely.' ) parser.add_argument( "-w", dest='wait', default=0, type=float, metavar="N",
pathoc -n seems broken ##### Steps to reproduce the problem: > pathoc -n 2 google.com get:/ > 07-06-16 12:22:24: >> 'GET':/ > << 302 Found: 261 bytes ##### What is the expected behavior? Two requests printed. ##### What went wrong? Only one request is printed. --- Mitmproxy Version: -master Operating System: osx <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) --> pathoc -n seems broken ##### Steps to reproduce the problem: > pathoc -n 2 google.com get:/ > 07-06-16 12:22:24: >> 'GET':/ > << 302 Found: 261 bytes ##### What is the expected behavior? Two requests printed. ##### What went wrong? Only one request is printed. --- Mitmproxy Version: -master Operating System: osx <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
This is caused by [this line](https://github.com/mitmproxy/mitmproxy/blob/20bcfbb5d03fd463449412dc3a626b2958a862ca/pathod/pathoc.py#L493), where 0da3e51e1c08eed2c8054d4a71bc591268b19af1 made `args.requests[0]` a generator that is exhausted after the first pass. While looking into this, I realized that `pathoc get:/:x10` is similar to `pathoc -n 10 get:/`, with the major difference being that the former does everything on the same connection. We probably want to document that somehow. This is caused by [this line](https://github.com/mitmproxy/mitmproxy/blob/20bcfbb5d03fd463449412dc3a626b2958a862ca/pathod/pathoc.py#L493), where 0da3e51e1c08eed2c8054d4a71bc591268b19af1 made `args.requests[0]` a generator that is exhausted after the first pass. While looking into this, I realized that `pathoc get:/:x10` is similar to `pathoc -n 10 get:/`, with the major difference being that the former does everything on the same connection. We probably want to document that somehow.
2016-09-25T04:31:04
mitmproxy/mitmproxy
1,610
mitmproxy__mitmproxy-1610
[ "1605", "1605" ]
61a1b96ca4bfa63ddbef65913ccd50b4327f90a6
diff --git a/mitmproxy/console/master.py b/mitmproxy/console/master.py --- a/mitmproxy/console/master.py +++ b/mitmproxy/console/master.py @@ -685,24 +685,18 @@ def clear_events(self): # Handlers @controller.handler def error(self, f): - f = flow.FlowMaster.error(self, f) - if f: - self.process_flow(f) - return f + super(ConsoleMaster, self).error(f) + self.process_flow(f) @controller.handler def request(self, f): - f = flow.FlowMaster.request(self, f) - if f: - self.process_flow(f) - return f + super(ConsoleMaster, self).request(f) + self.process_flow(f) @controller.handler def response(self, f): - f = flow.FlowMaster.response(self, f) - if f: - self.process_flow(f) - return f + super(ConsoleMaster, self).response(f) + self.process_flow(f) @controller.handler def tcp_message(self, f):
diff --git a/test/mitmproxy/console/test_master.py b/test/mitmproxy/console/test_master.py --- a/test/mitmproxy/console/test_master.py +++ b/test/mitmproxy/console/test_master.py @@ -122,3 +122,16 @@ def test_basic(self): for i in (1, 2, 3): self.dummy_cycle(m, 1, b"") assert len(m.state.flows) == i + + def test_intercept(self): + """regression test for https://github.com/mitmproxy/mitmproxy/issues/1605""" + m = self.mkmaster(intercept="~b bar") + f = tutils.tflow(req=netlib.tutils.treq(content=b"foo")) + m.request(f) + assert not m.state.flows[0].intercepted + f = tutils.tflow(req=netlib.tutils.treq(content=b"bar")) + m.request(f) + assert m.state.flows[1].intercepted + f = tutils.tflow(resp=netlib.tutils.tresp(content=b"bar")) + m.request(f) + assert m.state.flows[2].intercepted
Interception does not work ##### Steps to reproduce the problem: 1. `mitmproxy -i '.*'` 2. `curl -x localhost:8080 example.com` ##### What is the expected behavior? Request should be intercepted ##### What went wrong? Request is not intercepted. ##### Any other comments? What have you tried so far? https://discourse.mitmproxy.org/t/is-intercept-working-in-the-head-of-master/186 --- Mitmproxy Version: master Operating System: Win10 x64 <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) --> Interception does not work ##### Steps to reproduce the problem: 1. `mitmproxy -i '.*'` 2. `curl -x localhost:8080 example.com` ##### What is the expected behavior? Request should be intercepted ##### What went wrong? Request is not intercepted. ##### Any other comments? What have you tried so far? https://discourse.mitmproxy.org/t/is-intercept-working-in-the-head-of-master/186 --- Mitmproxy Version: master Operating System: Win10 x64 <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
I am facing the same issue, some of the requests from my device are not being intercepted by mitm ( or maybe it's intercepting it but not being displayed I am facing the same issue, some of the requests from my device are not being intercepted by mitm ( or maybe it's intercepting it but not being displayed
2016-10-14T03:32:22
mitmproxy/mitmproxy
1,655
mitmproxy__mitmproxy-1655
[ "1650" ]
37a05e27526d22a23f7579dd1dbb0a04ea4eedcc
diff --git a/examples/har_dump.py b/examples/har_dump.py --- a/examples/har_dump.py +++ b/examples/har_dump.py @@ -3,7 +3,6 @@ """ -import pprint import json import sys import base64 @@ -128,19 +127,22 @@ def response(flow): "timings": timings, } - # Store binay data as base64 + # Store binary data as base64 if strutils.is_mostly_bin(flow.response.content): - b64 = base64.b64encode(flow.response.content) - entry["response"]["content"]["text"] = b64.decode('ascii') + entry["response"]["content"]["text"] = base64.b64encode(flow.response.content).decode() entry["response"]["content"]["encoding"] = "base64" else: - entry["response"]["content"]["text"] = flow.response.text + entry["response"]["content"]["text"] = flow.response.get_text(strict=False) if flow.request.method in ["POST", "PUT", "PATCH"]: + params = [ + {"name": a.decode("utf8", "surrogateescape"), "value": b.decode("utf8", "surrogateescape")} + for a, b in flow.request.urlencoded_form.items(multi=True) + ] entry["request"]["postData"] = { "mimeType": flow.request.headers.get("Content-Type", "").split(";")[0], - "text": flow.request.content, - "params": name_value(flow.request.urlencoded_form) + "text": flow.request.get_text(strict=False), + "params": params } if flow.server_conn: @@ -155,16 +157,17 @@ def done(): """ dump_file = sys.argv[1] + json_dump = json.dumps(HAR, indent=2) # type: str + if dump_file == '-': - mitmproxy.ctx.log(pprint.pformat(HAR)) + mitmproxy.ctx.log(json_dump) else: - json_dump = json.dumps(HAR, indent=2) - + raw = json_dump.encode() # type: bytes if dump_file.endswith('.zhar'): - json_dump = zlib.compress(json_dump, 9) + raw = zlib.compress(raw, 9) - with open(dump_file, "w") as f: - f.write(json_dump) + with open(dump_file, "wb") as f: + f.write(raw) mitmproxy.ctx.log("HAR dump finished (wrote %s bytes to file)" % len(json_dump)) diff --git a/pathod/language/generators.py b/pathod/language/generators.py --- a/pathod/language/generators.py +++ b/pathod/language/generators.py @@ -14,7 +14,7 @@ punctuation=string.punctuation.encode(), whitespace=string.whitespace.encode(), ascii=string.printable.encode(), - bytes=bytes(bytearray(range(256))) + bytes=bytes(range(256)) )
diff --git a/test/mitmproxy/test_examples.py b/test/mitmproxy/test_examples.py --- a/test/mitmproxy/test_examples.py +++ b/test/mitmproxy/test_examples.py @@ -160,3 +160,24 @@ def test_format_cookies(self): f = format_cookies([("n", "v", CA([("expires", "Mon, 24-Aug-2037 00:00:00 GMT")]))])[0] assert f['expires'] + + def test_binary(self): + + f = self.flow() + f.request.method = "POST" + f.request.headers["content-type"] = "application/x-www-form-urlencoded" + f.request.content = b"foo=bar&baz=s%c3%bc%c3%9f" + f.response.headers["random-junk"] = bytes(range(256)) + f.response.content = bytes(range(256)) + + with tutils.tmpdir() as tdir: + path = os.path.join(tdir, "somefile") + + m, sc = tscript("har_dump.py", shlex.quote(path)) + m.addons.invoke(m, "response", f) + m.addons.remove(sc) + + with open(path, "r") as inp: + har = json.load(inp) + + assert len(har["log"]["entries"]) == 1 diff --git a/test/mitmproxy/test_flow.py b/test/mitmproxy/test_flow.py --- a/test/mitmproxy/test_flow.py +++ b/test/mitmproxy/test_flow.py @@ -346,7 +346,7 @@ def test_roundtrip(self): sio = io.BytesIO() f = tutils.tflow() f.marked = True - f.request.content = bytes(bytearray(range(256))) + f.request.content = bytes(range(256)) w = mitmproxy.io.FlowWriter(sio) w.add(f) diff --git a/test/mitmproxy/test_utils_strutils.py b/test/mitmproxy/test_utils_strutils.py --- a/test/mitmproxy/test_utils_strutils.py +++ b/test/mitmproxy/test_utils_strutils.py @@ -3,7 +3,7 @@ def test_always_bytes(): - assert strutils.always_bytes(bytes(bytearray(range(256)))) == bytes(bytearray(range(256))) + assert strutils.always_bytes(bytes(range(256))) == bytes(range(256)) assert strutils.always_bytes("foo") == b"foo" with tutils.raises(ValueError): strutils.always_bytes(u"\u2605", "ascii")
Handle `bytes` in request parameters When POST data is encoded as UTF8, `har_dump.py` would bail with ``` TypeError: b'xxxxx' is not JSON serializable ``` (please excuse my poor python, feel free to reject and solve in some other canonical way)
2016-10-23T01:34:20
mitmproxy/mitmproxy
1,656
mitmproxy__mitmproxy-1656
[ "1573" ]
ea2d6474bf1e9c4c1fd2e4a6ac33e0785fc751de
diff --git a/mitmproxy/export.py b/mitmproxy/export.py --- a/mitmproxy/export.py +++ b/mitmproxy/export.py @@ -1,9 +1,11 @@ +import io import json +import pprint import re import textwrap -import urllib +from typing import Any -import mitmproxy.net.http +from mitmproxy import http def _native(s): @@ -12,14 +14,14 @@ def _native(s): return s -def dictstr(items, indent): +def dictstr(items, indent: str) -> str: lines = [] for k, v in items: lines.append(indent + "%s: %s,\n" % (repr(_native(k)), repr(_native(v)))) return "{\n%s}\n" % "".join(lines) -def curl_command(flow): +def curl_command(flow: http.HTTPFlow) -> str: data = "curl " request = flow.request.copy() @@ -31,8 +33,7 @@ def curl_command(flow): if request.method != "GET": data += "-X %s " % request.method - full_url = request.scheme + "://" + request.host + request.path - data += "'%s'" % full_url + data += "'%s'" % request.url if request.content: data += " --data-binary '%s'" % _native(request.content) @@ -40,64 +41,54 @@ def curl_command(flow): return data -def python_code(flow): - code = textwrap.dedent(""" - import requests - - url = '{url}' - {headers}{params}{data} - response = requests.request( - method='{method}', - url=url,{args} - ) +def python_arg(arg: str, val: Any) -> str: + if not val: + return "" + if arg: + arg += "=" + arg_str = "{}{},\n".format( + arg, + pprint.pformat(val, 79 - len(arg)) + ) + return textwrap.indent(arg_str, " " * 4) - print(response.text) - """).strip() - components = [urllib.parse.quote(c, safe="") for c in flow.request.path_components] - url = flow.request.scheme + "://" + flow.request.host + "/" + "/".join(components) +def python_code(flow: http.HTTPFlow): + code = io.StringIO() - args = "" - headers = "" - if flow.request.headers: - headers += "\nheaders = %s\n" % dictstr(flow.request.headers.fields, " ") - args += "\n headers=headers," + def writearg(arg, val): + code.write(python_arg(arg, val)) - params = "" - if flow.request.query: - params = "\nparams = %s\n" % dictstr(flow.request.query.collect(), " ") - args += "\n params=params," + code.write("import requests\n") + code.write("\n") + if flow.request.method.lower() in ("get", "post", "put", "head", "delete", "patch"): + code.write("response = requests.{}(\n".format(flow.request.method.lower())) + else: + code.write("response = requests.request(\n") + writearg("", flow.request.method) + url_without_query = flow.request.url.split("?", 1)[0] + writearg("", url_without_query) - data = "" - if flow.request.body: - json_obj = is_json(flow.request.headers, flow.request.content) - if json_obj: - data = "\njson = %s\n" % dictstr(sorted(json_obj.items()), " ") - args += "\n json=json," - else: - data = "\ndata = '''%s'''\n" % _native(flow.request.content) - args += "\n data=data," + writearg("params", list(flow.request.query.fields)) - code = code.format( - url=url, - headers=headers, - params=params, - data=data, - method=flow.request.method, - args=args, - ) - return code + headers = flow.request.headers.copy() + # requests adds those by default. + for x in ("host", "content-length"): + headers.pop(x, None) + writearg("headers", dict(headers)) + try: + if "json" not in flow.request.headers.get("content-type", ""): + raise ValueError() + writearg("json", json.loads(flow.request.text)) + except ValueError: + writearg("data", flow.request.content) + code.seek(code.tell() - 2) # remove last comma + code.write("\n)\n") + code.write("\n") + code.write("print(response.text)") -def is_json(headers: mitmproxy.net.http.Headers, content: bytes) -> bool: - if headers: - ct = mitmproxy.net.http.parse_content_type(headers.get("content-type", "")) - if ct and "%s/%s" % (ct[0], ct[1]) == "application/json": - try: - return json.loads(content.decode("utf8", "surrogateescape")) - except ValueError: - return False - return False + return code.getvalue() def locust_code(flow): @@ -111,7 +102,7 @@ def on_start(self): @task() def {name}(self): - url = '{url}' + url = self.locust.host + '{path}' {headers}{params}{data} self.response = self.client.request( method='{method}', @@ -127,13 +118,12 @@ class WebsiteUser(HttpLocust): max_wait = 3000 """).strip() - components = [urllib.parse.quote(c, safe="") for c in flow.request.path_components] - name = re.sub('\W|^(?=\d)', '_', "_".join(components)) - if name == "" or name is None: + name = re.sub('\W|^(?=\d)', '_', flow.request.path.strip("/").split("?", 1)[0]) + if not name: new_name = "_".join([str(flow.request.host), str(flow.request.timestamp_start)]) name = re.sub('\W|^(?=\d)', '_', new_name) - url = flow.request.scheme + "://" + flow.request.host + "/" + "/".join(components) + path_without_query = flow.request.path.split("?")[0] args = "" headers = "" @@ -148,7 +138,11 @@ class WebsiteUser(HttpLocust): params = "" if flow.request.query: - lines = [" %s: %s,\n" % (repr(k), repr(v)) for k, v in flow.request.query.collect()] + lines = [ + " %s: %s,\n" % (repr(k), repr(v)) + for k, v in + flow.request.query.collect() + ] params = "\n params = {\n%s }\n" % "".join(lines) args += "\n params=params," @@ -159,7 +153,7 @@ class WebsiteUser(HttpLocust): code = code.format( name=name, - url=url, + path=path_without_query, headers=headers, params=params, data=data, @@ -167,12 +161,6 @@ class WebsiteUser(HttpLocust): args=args, ) - host = flow.request.scheme + "://" + flow.request.host - code = code.replace(host, "' + self.locust.host + '") - code = code.replace(urllib.parse.quote_plus(host), "' + quote_plus(self.locust.host) + '") - code = code.replace(urllib.parse.quote(host), "' + quote(self.locust.host) + '") - code = code.replace("'' + ", "") - return code diff --git a/mitmproxy/http.py b/mitmproxy/http.py --- a/mitmproxy/http.py +++ b/mitmproxy/http.py @@ -1,9 +1,11 @@ import cgi from mitmproxy import flow + from mitmproxy.net import http from mitmproxy import version from mitmproxy.net import tcp +from mitmproxy import connections # noqa class HTTPRequest(http.Request): @@ -155,22 +157,22 @@ class HTTPFlow(flow.Flow): def __init__(self, client_conn, server_conn, live=None): super().__init__("http", client_conn, server_conn, live) - self.request = None + self.request = None # type: HTTPRequest """ :py:class:`HTTPRequest` object """ - self.response = None + self.response = None # type: HTTPResponse """ :py:class:`HTTPResponse` object """ - self.error = None + self.error = None # type: flow.Error """ :py:class:`Error` object Note that it's possible for a Flow to have both a response and an error object. This might happen, for instance, when a response was received from the server, but there was an error sending it back to the client. """ - self.server_conn = server_conn + self.server_conn = server_conn # type: connections.ServerConnection """ :py:class:`ServerConnection` object """ - self.client_conn = client_conn + self.client_conn = client_conn # type: connections.ClientConnection """:py:class:`ClientConnection` object """ - self.intercepted = False + self.intercepted = False # type: bool """ Is this flow currently being intercepted? """ _stateobject_attributes = flow.Flow._stateobject_attributes.copy()
diff --git a/test/mitmproxy/data/test_flow_export/python_get.py b/test/mitmproxy/data/test_flow_export/python_get.py --- a/test/mitmproxy/data/test_flow_export/python_get.py +++ b/test/mitmproxy/data/test_flow_export/python_get.py @@ -1,22 +1,9 @@ import requests -url = 'http://address/path' - -headers = { - 'header': 'qvalue', - 'content-length': '7', -} - -params = { - 'a': ['foo', 'bar'], - 'b': 'baz', -} - -response = requests.request( - method='GET', - url=url, - headers=headers, - params=params, +response = requests.get( + 'http://address:22/path', + params=[('a', 'foo'), ('a', 'bar'), ('b', 'baz')], + headers={'header': 'qvalue'} ) -print(response.text) +print(response.text) \ No newline at end of file diff --git a/test/mitmproxy/data/test_flow_export/python_patch.py b/test/mitmproxy/data/test_flow_export/python_patch.py --- a/test/mitmproxy/data/test_flow_export/python_patch.py +++ b/test/mitmproxy/data/test_flow_export/python_patch.py @@ -1,24 +1,10 @@ import requests -url = 'http://address/path' - -headers = { - 'header': 'qvalue', - 'content-length': '7', -} - -params = { - 'query': 'param', -} - -data = '''content''' - -response = requests.request( - method='PATCH', - url=url, - headers=headers, - params=params, - data=data, +response = requests.patch( + 'http://address:22/path', + params=[('query', 'param')], + headers={'header': 'qvalue'}, + data=b'content' ) -print(response.text) +print(response.text) \ No newline at end of file diff --git a/test/mitmproxy/data/test_flow_export/python_post.py b/test/mitmproxy/data/test_flow_export/python_post.py --- a/test/mitmproxy/data/test_flow_export/python_post.py +++ b/test/mitmproxy/data/test_flow_export/python_post.py @@ -1,13 +1,8 @@ import requests -url = 'http://address/path' - -data = '''content''' - -response = requests.request( - method='POST', - url=url, - data=data, +response = requests.post( + 'http://address:22/path', + data=b'content' ) print(response.text) diff --git a/test/mitmproxy/data/test_flow_export/python_post_json.py b/test/mitmproxy/data/test_flow_export/python_post_json.py --- a/test/mitmproxy/data/test_flow_export/python_post_json.py +++ b/test/mitmproxy/data/test_flow_export/python_post_json.py @@ -1,23 +1,9 @@ import requests -url = 'http://address/path' - -headers = { - 'content-type': 'application/json', -} - - -json = { - 'email': '[email protected]', - 'name': 'example', -} - - -response = requests.request( - method='POST', - url=url, - headers=headers, - json=json, +response = requests.post( + 'http://address:22/path', + headers={'content-type': 'application/json'}, + json={'email': '[email protected]', 'name': 'example'} ) -print(response.text) +print(response.text) \ No newline at end of file diff --git a/test/mitmproxy/test_flow_export.py b/test/mitmproxy/test_flow_export.py --- a/test/mitmproxy/test_flow_export.py +++ b/test/mitmproxy/test_flow_export.py @@ -34,17 +34,17 @@ def req_patch(): class TestExportCurlCommand: def test_get(self): flow = tutils.tflow(req=req_get()) - result = """curl -H 'header:qvalue' -H 'content-length:7' 'http://address/path?a=foo&a=bar&b=baz'""" + result = """curl -H 'header:qvalue' -H 'content-length:7' 'http://address:22/path?a=foo&a=bar&b=baz'""" assert export.curl_command(flow) == result def test_post(self): flow = tutils.tflow(req=req_post()) - result = """curl -X POST 'http://address/path' --data-binary 'content'""" + result = """curl -X POST 'http://address:22/path' --data-binary 'content'""" assert export.curl_command(flow) == result def test_patch(self): flow = tutils.tflow(req=req_patch()) - result = """curl -H 'header:qvalue' -H 'content-length:7' -X PATCH 'http://address/path?query=param' --data-binary 'content'""" + result = """curl -H 'header:qvalue' -H 'content-length:7' -X PATCH 'http://address:22/path?query=param' --data-binary 'content'""" assert export.curl_command(flow) == result @@ -100,25 +100,6 @@ def test_patch(self): python_equals("data/test_flow_export/locust_task_patch.py", export.locust_task(flow)) -class TestIsJson: - def test_empty(self): - assert export.is_json(None, None) is False - - def test_json_type(self): - headers = Headers(content_type="application/json") - assert export.is_json(headers, b"foobar") is False - - def test_valid(self): - headers = Headers(content_type="application/foobar") - j = export.is_json(headers, b'{"name": "example", "email": "[email protected]"}') - assert j is False - - def test_valid2(self): - headers = Headers(content_type="application/json") - j = export.is_json(headers, b'{"name": "example", "email": "[email protected]"}') - assert isinstance(j, dict) - - class TestURL: def test_url(self): flow = tutils.tflow()
Include port number when exporting
2016-10-23T03:34:08
mitmproxy/mitmproxy
1,664
mitmproxy__mitmproxy-1664
[ "1639" ]
ef4e9b2b855337b61a18ecdfbeaad3bb6a011af4
diff --git a/mitmproxy/connections.py b/mitmproxy/connections.py --- a/mitmproxy/connections.py +++ b/mitmproxy/connections.py @@ -20,6 +20,7 @@ class ClientConnection(tcp.BaseHandler, stateobject.StateObject): timestamp_start: Connection start timestamp timestamp_ssl_setup: TLS established timestamp timestamp_end: Connection end timestamp + sni: Server Name Indication sent by client during the TLS handshake """ def __init__(self, client_connection, address, server): @@ -40,6 +41,7 @@ def __init__(self, client_connection, address, server): self.timestamp_end = None self.timestamp_ssl_setup = None self.protocol = None + self.sni = None def __bool__(self): return bool(self.connection) and not self.finished @@ -61,6 +63,7 @@ def tls_established(self): timestamp_start=float, timestamp_ssl_setup=float, timestamp_end=float, + sni=str, ) def copy(self): @@ -86,12 +89,14 @@ def make_dummy(cls, address): ssl_established=False, timestamp_start=None, timestamp_end=None, - timestamp_ssl_setup=None + timestamp_ssl_setup=None, + sni=None )) def convert_to_ssl(self, *args, **kwargs): super().convert_to_ssl(*args, **kwargs) self.timestamp_ssl_setup = time.time() + self.sni = self.connection.get_servername() def finish(self): super().finish() diff --git a/mitmproxy/io_compat.py b/mitmproxy/io_compat.py --- a/mitmproxy/io_compat.py +++ b/mitmproxy/io_compat.py @@ -66,6 +66,7 @@ def convert_017_018(data): def convert_018_019(data): data["version"] = (0, 19) + data["client_conn"]["sni"] = None return data diff --git a/mitmproxy/tools/console/flowdetailview.py b/mitmproxy/tools/console/flowdetailview.py --- a/mitmproxy/tools/console/flowdetailview.py +++ b/mitmproxy/tools/console/flowdetailview.py @@ -82,6 +82,8 @@ def flowdetails(state, flow): parts = [ ["Address", repr(cc.address)], ] + if cc.sni: + parts.append(["Server Name Indication", cc.sni]) text.extend( common.format_keyvals(parts, key="key", val="text", indent=4)
diff --git a/test/mitmproxy/tutils.py b/test/mitmproxy/tutils.py --- a/test/mitmproxy/tutils.py +++ b/test/mitmproxy/tutils.py @@ -132,6 +132,7 @@ def tclient_conn(): timestamp_start=1, timestamp_ssl_setup=2, timestamp_end=3, + sni="address", )) c.reply = controller.DummyReply() return c
Display Server Name Indication in the UI ##### Steps to reproduce the problem: 1. `mitmproxy` 2. `curl -x localhost:8080 https://example.com/` 3. View Details Tab ##### What is the expected behavior? The Server Name Indication sent by the client should be displayed in the UI. ##### What went wrong? The SNI is not displayed in the "Client Connection" section. ##### Any other comments? What have you tried so far? The first step here is to make a `.sni` attribute in ClientConnection which also gets serialized. I'm happy to help if anyone wants to pick this issue up! :smiley: --- Mitmproxy Version: master Operating System: Win10 x64 <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
refs #582
2016-10-25T02:07:35
mitmproxy/mitmproxy
1,670
mitmproxy__mitmproxy-1670
[ "582" ]
145c2892f720300020fdeec8a257c3247c8dff5b
diff --git a/mitmproxy/connections.py b/mitmproxy/connections.py --- a/mitmproxy/connections.py +++ b/mitmproxy/connections.py @@ -21,6 +21,8 @@ class ClientConnection(tcp.BaseHandler, stateobject.StateObject): timestamp_ssl_setup: TLS established timestamp timestamp_end: Connection end timestamp sni: Server Name Indication sent by client during the TLS handshake + cipher_name: The current used cipher + tls_version: TLS version """ def __init__(self, client_connection, address, server): @@ -42,6 +44,8 @@ def __init__(self, client_connection, address, server): self.timestamp_ssl_setup = None self.protocol = None self.sni = None + self.cipher_name = None + self.tls_version = None def __bool__(self): return bool(self.connection) and not self.finished @@ -64,6 +68,8 @@ def tls_established(self): timestamp_ssl_setup=float, timestamp_end=float, sni=str, + cipher_name=str, + tls_version=str, ) def copy(self): @@ -90,13 +96,17 @@ def make_dummy(cls, address): timestamp_start=None, timestamp_end=None, timestamp_ssl_setup=None, - sni=None + sni=None, + cipher_name=None, + tls_version=None, )) def convert_to_ssl(self, *args, **kwargs): super().convert_to_ssl(*args, **kwargs) self.timestamp_ssl_setup = time.time() self.sni = self.connection.get_servername() + self.cipher_name = self.connection.get_cipher_name() + self.tls_version = self.connection.get_protocol_version_name() def finish(self): super().finish() diff --git a/mitmproxy/io_compat.py b/mitmproxy/io_compat.py --- a/mitmproxy/io_compat.py +++ b/mitmproxy/io_compat.py @@ -67,6 +67,8 @@ def convert_017_018(data): def convert_018_019(data): data["version"] = (0, 19) data["client_conn"]["sni"] = None + data["client_conn"]["cipher_name"] = None + data["client_conn"]["tls_version"] = None return data diff --git a/mitmproxy/tools/console/flowdetailview.py b/mitmproxy/tools/console/flowdetailview.py --- a/mitmproxy/tools/console/flowdetailview.py +++ b/mitmproxy/tools/console/flowdetailview.py @@ -82,8 +82,12 @@ def flowdetails(state, flow): parts = [ ["Address", repr(cc.address)], ] + if cc.tls_version: + parts.append(["TLS Version", cc.tls_version]) if cc.sni: parts.append(["Server Name Indication", cc.sni]) + if cc.cipher_name: + parts.append(["Cipher Name", cc.cipher_name]) text.extend( common.format_keyvals(parts, key="key", val="text", indent=4)
diff --git a/test/mitmproxy/tutils.py b/test/mitmproxy/tutils.py --- a/test/mitmproxy/tutils.py +++ b/test/mitmproxy/tutils.py @@ -133,6 +133,8 @@ def tclient_conn(): timestamp_ssl_setup=2, timestamp_end=3, sni="address", + cipher_name="cipher", + tls_version="TLSv1.2", )) c.reply = controller.DummyReply() return c
View used SSL/TLS Version and Cipher Suite Hey, is it possible to view the Cipher Suite used to encrypt the traffic? I think this could be interesting while testing some application without the need to set specific ciphers. E.g. this information could be saved as an attribute in the HTTPMessage class. Moreover this could be helpful to check if the something was really encrypted, e.g. by setting the attribute to None (or is this information already provided by the scheme attribute?).
> (or is this information already provided by the scheme attribute?) yes. We also have the flow detail view (`X` in 0.11.3, more prominently on the current github master) to view the certificate. Displaying the current cipher suite is useful, but we should keep in mind that the cipher suite may change at any point in time of the TLS connection, which makes displaying/storing it not entirely trivial. It would be nice to have a first PR that just displays the cipher suite that is currently in use. From #1589: It would also be very useful to display the TLS version that has been used for the server and client connections. If anyone picks this up, let me know and I'm happy to help!
2016-10-26T03:37:23
mitmproxy/mitmproxy
1,673
mitmproxy__mitmproxy-1673
[ "1620" ]
a0ad0b06a00a017c6277e8183d955ad2d46a5ce5
diff --git a/mitmproxy/flow.py b/mitmproxy/flow.py --- a/mitmproxy/flow.py +++ b/mitmproxy/flow.py @@ -2,6 +2,7 @@ import copy import uuid +from mitmproxy import controller # noqa from mitmproxy import stateobject from mitmproxy import connections from mitmproxy import version @@ -80,7 +81,7 @@ def __init__( self.error = None # type: Optional[Error] self.intercepted = False # type: bool self._backup = None # type: Optional[Flow] - self.reply = None + self.reply = None # type: Optional[controller.Reply] self.marked = False # type: bool _stateobject_attributes = dict( diff --git a/mitmproxy/tools/console/master.py b/mitmproxy/tools/console/master.py --- a/mitmproxy/tools/console/master.py +++ b/mitmproxy/tools/console/master.py @@ -659,11 +659,10 @@ def refresh_focus(self): ) def process_flow(self, f): - should_intercept = any( - [ - self.state.intercept and flowfilter.match(self.state.intercept, f) and not f.request.is_replay, - f.intercepted, - ] + should_intercept = ( + self.state.intercept and flowfilter.match(self.state.intercept, f) + and not f.request.is_replay + and f.reply.state == "handled" ) if should_intercept: f.intercept(self) diff --git a/mitmproxy/tools/web/master.py b/mitmproxy/tools/web/master.py --- a/mitmproxy/tools/web/master.py +++ b/mitmproxy/tools/web/master.py @@ -9,6 +9,7 @@ from mitmproxy import addons from mitmproxy import controller from mitmproxy import exceptions +from mitmproxy import flowfilter from mitmproxy.addons import state from mitmproxy import options from mitmproxy import master @@ -179,8 +180,12 @@ def run(self): # pragma: no cover self.shutdown() def _process_flow(self, f): - if self.state.intercept and self.state.intercept( - f) and not f.request.is_replay: + should_intercept = ( + self.state.intercept and flowfilter.match(self.state.intercept, f) + and not f.request.is_replay + and f.reply.state == "handled" + ) + if should_intercept: f.intercept(self) return f
StackTrace printed if you quit mitmproxy and any flow is in intercept mode ##### Steps to reproduce the problem: 1. Launch mitmproxy 2. intercept any request 3. quit mitmproxy while the request still intercept ##### What is the expected behavior? Did not expect the stacktrace ... earlier it used to be no such error ##### What went wrong? ``` Traceback (most recent call last): File "/Users/manish/Work/mitmproxy/venv/bin/mitmproxy", line 11, in <module> load_entry_point('mitmproxy', 'console_scripts', 'mitmproxy')() File "/Users/manish/Work/mitmproxy/mitmproxy/main.py", line 80, in mitmproxy m.run() File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 495, in run self.shutdown() File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 647, in shutdown self.state.killall(self) File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 269, in killall self.flows.kill_all(master) File "/Users/manish/Work/mitmproxy/mitmproxy/flow/state.py", line 182, in kill_all f.kill(master) File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 176, in kill master.error(self) File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 238, in wrapper ret = f(master, message) File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 692, in error self.process_flow(f) File "/Users/manish/Work/mitmproxy/mitmproxy/console/master.py", line 681, in process_flow f.intercept(self) File "/Users/manish/Work/mitmproxy/mitmproxy/models/flow.py", line 186, in intercept self.reply.take() File "/Users/manish/Work/mitmproxy/mitmproxy/controller.py", line 314, in take raise exceptions.ControlException("Reply is {}, but expected it to be handled.".format(self.state)) mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be handled. ``` ##### Any other comments? What have you tried so far? This may result in problems in saving flows to file? if any request is in intercept mode it might cause abort at that point .. only flows till that point gets saved.. i think, also, har dump may get problem due to this.. --- Mitmproxy Version: head, master Operating System: mac <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks for the great bug report!
2016-10-26T04:57:12
mitmproxy/mitmproxy
1,681
mitmproxy__mitmproxy-1681
[ "1676", "1676" ]
f26a37556064e191e6356f2a9b5dd634cc436b87
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -102,7 +102,7 @@ def dummy_cert(privkey, cacert, commonname, sans): cert.gmtime_adj_notBefore(-3600 * 48) cert.gmtime_adj_notAfter(DEFAULT_EXP) cert.set_issuer(cacert.get_subject()) - if commonname is not None: + if commonname is not None and len(commonname) < 64: cert.get_subject().CN = commonname cert.set_serial_number(int(time.time() * 10000)) if ss:
OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_mbstring_ncopy', 'string too long')] ##### Steps to reproduce the problem: 1. ??? 2. ``` [1026/094737:ERROR:ssl_client_socket_openssl.cc(1149)] handshake failed; returned -1, SSL error code 1, net_error -100 Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\proxy\server.py", line 115, in handle root_layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\modes\http_proxy.py", line 9, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 379, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http1.py", line 72, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 173, in __call__ self.handle_regular_mode_connect(request) File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 270, in handle_regular_mode_connect layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 374, in __call__ self._establish_tls_with_client() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 463, in _establish_tls_with_client cert, key, chain_file = self._find_cert() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 580, in _find_cert return self.config.certstore.get_cert(host, list(sans)) File "c:\users\user\git\mitmproxy\mitmproxy\certs.py", line 349, in get_cert sans), File "c:\users\user\git\mitmproxy\mitmproxy\certs.py", line 106, in dummy_cert cert.get_subject().CN = commonname File "c:\users\user\git\mitmproxy\venv\lib\site-packages\OpenSSL\crypto.py", line 532, in __setattr__ _raise_current_error() File "c:\users\user\git\mitmproxy\venv\lib\site-packages\OpenSSL\_util.py", line 48, in exception_from_error_queue raise exception_type(errors) OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_mbstring_ncopy', 'string too long')] mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` ##### Any other comments? What have you tried so far? ## ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Windows-10-10.0.14393-SP0 SSL version: OpenSSL 1.0.2j 26 Sep 2016 Windows version: 10 10.0.14393 SP0 Multiprocessor Free OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_mbstring_ncopy', 'string too long')] ##### Steps to reproduce the problem: 1. ??? 2. ``` [1026/094737:ERROR:ssl_client_socket_openssl.cc(1149)] handshake failed; returned -1, SSL error code 1, net_error -100 Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\proxy\server.py", line 115, in handle root_layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\modes\http_proxy.py", line 9, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 379, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http1.py", line 72, in __call__ layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 173, in __call__ self.handle_regular_mode_connect(request) File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 270, in handle_regular_mode_connect layer() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 374, in __call__ self._establish_tls_with_client() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 463, in _establish_tls_with_client cert, key, chain_file = self._find_cert() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 580, in _find_cert return self.config.certstore.get_cert(host, list(sans)) File "c:\users\user\git\mitmproxy\mitmproxy\certs.py", line 349, in get_cert sans), File "c:\users\user\git\mitmproxy\mitmproxy\certs.py", line 106, in dummy_cert cert.get_subject().CN = commonname File "c:\users\user\git\mitmproxy\venv\lib\site-packages\OpenSSL\crypto.py", line 532, in __setattr__ _raise_current_error() File "c:\users\user\git\mitmproxy\venv\lib\site-packages\OpenSSL\_util.py", line 48, in exception_from_error_queue raise exception_type(errors) OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_mbstring_ncopy', 'string too long')] mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` ##### Any other comments? What have you tried so far? ## ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Windows-10-10.0.14393-SP0 SSL version: OpenSSL 1.0.2j 26 Sep 2016 Windows version: 10 10.0.14393 SP0 Multiprocessor Free
2016-10-27T20:12:14
mitmproxy/mitmproxy
1,684
mitmproxy__mitmproxy-1684
[ "1675", "1675" ]
2a901b90c5d97d63b24ba4e56e3decac27b1e1c3
diff --git a/mitmproxy/connections.py b/mitmproxy/connections.py --- a/mitmproxy/connections.py +++ b/mitmproxy/connections.py @@ -104,7 +104,11 @@ def make_dummy(cls, address): def convert_to_ssl(self, *args, **kwargs): super().convert_to_ssl(*args, **kwargs) self.timestamp_ssl_setup = time.time() - self.sni = self.connection.get_servername() + sni = self.connection.get_servername() + if sni: + self.sni = sni.decode("idna") + else: + self.sni = None self.cipher_name = self.connection.get_cipher_name() self.tls_version = self.connection.get_protocol_version_name()
SNI in ClientConnection that caused json.dumps broken The problem seems occurred after #1664 . It seems that the Connection.get_servername() from OpenSSL return bytes. And that cause json dumps failed. I would like pick up this problem, and help display sni and cipher (from #582). Is that just used `str(self.connection.get_servername())` to cast it into str is OK? ##### Steps to reproduce the problem: 1. mitmweb with latest master version 2. curl -x https://example.com 3. mitmweb display error stacktrace ``` Traceback (most recent call last): File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/tornado/ioloop.py", line 1041, in _run return self.callback() File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 172, in <lambda> tornado.ioloop.PeriodicCallback(lambda: self.tick(timeout=0), 5).start() File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/master.py", line 105, in tick handle_func(obj) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/controller.py", line 70, in wrapper master.addons(f.__name__, message) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 90, in __call__ self.invoke(i, name, *args, **kwargs) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 85, in invoke func(*args, **kwargs) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 285, in request self.add_flow(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 205, in add_flow self.flows._add(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 112, in _add view._add(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 33, in _add data=app.convert_flow_to_json_dict(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/app.py", line 174, in broadcast message = json.dumps(kwargs, ensure_ascii=False) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: b'example.com' is not JSON serializable ``` SNI in ClientConnection that caused json.dumps broken The problem seems occurred after #1664 . It seems that the Connection.get_servername() from OpenSSL return bytes. And that cause json dumps failed. I would like pick up this problem, and help display sni and cipher (from #582). Is that just used `str(self.connection.get_servername())` to cast it into str is OK? ##### Steps to reproduce the problem: 1. mitmweb with latest master version 2. curl -x https://example.com 3. mitmweb display error stacktrace ``` Traceback (most recent call last): File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/tornado/ioloop.py", line 1041, in _run return self.callback() File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 172, in <lambda> tornado.ioloop.PeriodicCallback(lambda: self.tick(timeout=0), 5).start() File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/master.py", line 105, in tick handle_func(obj) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/controller.py", line 70, in wrapper master.addons(f.__name__, message) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 90, in __call__ self.invoke(i, name, *args, **kwargs) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addonmanager.py", line 85, in invoke func(*args, **kwargs) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 285, in request self.add_flow(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 205, in add_flow self.flows._add(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/addons/state.py", line 112, in _add view._add(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/master.py", line 33, in _add data=app.convert_flow_to_json_dict(f) File "/Users/han-pc/.pyenv/versions/3.5.2/envs/mitm/lib/python3.5/site-packages/mitmproxy/tools/web/app.py", line 174, in broadcast message = json.dumps(kwargs, ensure_ascii=False) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/Users/han-pc/.pyenv/versions/3.5.2/lib/python3.5/json/encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: b'example.com' is not JSON serializable ```
If the `get_servername` is expected to be a domain name, I think using ``` self.connection.get_servername().decode('idna') ``` should resolve this issue. Hi guys - thanks for catching that! What @mike820324 said - IDNA encoding should be the right way! :smiley: If the `get_servername` is expected to be a domain name, I think using ``` self.connection.get_servername().decode('idna') ``` should resolve this issue. Hi guys - thanks for catching that! What @mike820324 said - IDNA encoding should be the right way! :smiley:
2016-10-27T22:52:39
mitmproxy/mitmproxy
1,711
mitmproxy__mitmproxy-1711
[ "1541" ]
d51b8933b2191261c0aee3879e3bf776140c0522
diff --git a/pathod/language/writer.py b/pathod/language/writer.py --- a/pathod/language/writer.py +++ b/pathod/language/writer.py @@ -57,7 +57,9 @@ def write_values(fp, vals, actions, sofar=0, blocksize=BLOCKSIZE): while actions: a = actions.pop() if a[1] == "pause": - time.sleep(a[2]) + time.sleep( + FOREVER if a[2] == "f" else a[2] + ) elif a[1] == "disconnect": return True elif a[1] == "inject":
pathoc does not accept `:pa,f` to pause forever at end of message ##### Steps to reproduce the problem: `pathoc www.example.com 'get:/:pa,f'` ##### What is the expected behavior? Send request, but pause forever after sending. ##### What went wrong? I get a stack trace with "a float is required". ``` $ pathoc www.example.com 'get:/:pa,f' 08-09-16 16:59:41: >> 'GET':/:pa,f Traceback (most recent call last): File "/usr/local/bin/pathoc", line 11, in <module> sys.exit(go_pathoc()) File "/usr/local/lib/python2.7/dist-packages/pathod/pathoc_cmdline.py", line 226, in go_pathoc pathoc.main(args) File "/usr/local/lib/python2.7/dist-packages/pathod/pathoc.py", line 522, in main ret = p.request(spec) File "/usr/local/lib/python2.7/dist-packages/pathod/pathoc.py", line 452, in request return self.http(r) File "/usr/local/lib/python2.7/dist-packages/pathod/pathoc.py", line 432, in http return resp File "/usr/local/lib/python2.7/dist-packages/pathod/pathoc.py", line 411, in http req = language.serve(r, self.wfile, self.settings) File "/usr/local/lib/python2.7/dist-packages/pathod/language/__init__.py", line 105, in serve disconnect = writer.write_values(fp, vals, actions[:]) File "/usr/local/lib/python2.7/dist-packages/pathod/language/writer.py", line 61, in write_values time.sleep(a[2]) TypeError: a float is required ``` ##### Any other comments? What have you tried so far? All other combinations of pause flags work as expected: ``` $ pathoc www.example.com 'get:/:p2,5' 08-09-16 17:05:07: >> 'GET':/:p2,5 << 200 OK: 1270 bytes $ pathoc www.example.com 'get:/:pr,5' 08-09-16 17:05:21: >> 'GET':/:pr,5 << 200 OK: 1270 bytes $ pathoc www.example.com 'get:/:pa,5' 08-09-16 17:05:41: >> 'GET':/:pa,5 << 200 OK: 1270 bytes $ pathoc www.example.com 'get:/:p2,f' ^C08-09-16 17:04:46: >> 'GET':/:p2,f $ pathoc www.example.com 'get:/:pr,f' ^C08-09-16 17:04:55: >> 'GET':/:pr,f ``` --- pathoc version: 0.17 Operating System: Debian Linux 8.5 "Jessie" x64
2016-11-03T21:14:57
mitmproxy/mitmproxy
1,735
mitmproxy__mitmproxy-1735
[ "1718" ]
9838cfb9d0b66f9e420c3aa3a7c66793bf6ba051
diff --git a/mitmproxy/cmdline.py b/mitmproxy/cmdline.py --- a/mitmproxy/cmdline.py +++ b/mitmproxy/cmdline.py @@ -208,6 +208,11 @@ def get_common_options(args): if args.quiet: args.verbose = 0 + if args.addr in ("localhost", "127.0.0.1", "::1"): + upstream_bind_address = "" + else: + upstream_bind_address = args.addr + return dict( app=args.app, app_host=args.app_host, @@ -251,6 +256,7 @@ def get_common_options(args): ignore_hosts = args.ignore_hosts, listen_host = args.addr, listen_port = args.port, + upstream_bind_address = upstream_bind_address, mode = mode, no_upstream_cert = args.no_upstream_cert, spoof_source_address = args.spoof_source_address, diff --git a/mitmproxy/options.py b/mitmproxy/options.py --- a/mitmproxy/options.py +++ b/mitmproxy/options.py @@ -67,6 +67,7 @@ def __init__( ignore_hosts = (), # type: Sequence[str] listen_host = "", # type: str listen_port = LISTEN_PORT, # type: int + upstream_bind_address = "", # type: str mode = "regular", # type: str no_upstream_cert = False, # type: bool rawtcp = False, # type: bool @@ -127,6 +128,7 @@ def __init__( self.ignore_hosts = ignore_hosts self.listen_host = listen_host self.listen_port = listen_port + self.upstream_bind_address = upstream_bind_address self.mode = mode self.no_upstream_cert = no_upstream_cert self.rawtcp = rawtcp diff --git a/mitmproxy/protocol/base.py b/mitmproxy/protocol/base.py --- a/mitmproxy/protocol/base.py +++ b/mitmproxy/protocol/base.py @@ -121,7 +121,7 @@ def __init__(self, server_address=None): server_address, (self.ctx.client_conn.address.host, 0), True) else: self.server_conn = models.ServerConnection( - server_address, (self.config.options.listen_host, 0)) + server_address, (self.config.options.upstream_bind_address, 0)) self.__check_self_connect()
mitmdump doesn't seem to work when bound to localhost ##### Steps to reproduce the problem: ``` $ mitmdump -b 127.0.0.1 -R https://example.com -p 1234 -s "script.py arg" Proxy server listening at http://127.0.0.1:1234 127.0.0.1:49415: clientconnect 127.0.0.1:49415: GET https://example.com/page << Server connection to example.com:443 failed: Error connecting to "example.com": [Errno 49] Can't assign requested address ``` ##### Any other comments? What have you tried so far? Works when bind argument isn't specified. Doesn't work on Windows either. ##### System information Mitmproxy version: 0.18.2 Python version: 2.7.11 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.11.6 ('', '', '') x86_64
2016-11-12T06:29:48
mitmproxy/mitmproxy
1,738
mitmproxy__mitmproxy-1738
[ "1737" ]
afa124a9f65364031080b81b04400be4bd05e418
diff --git a/mitmproxy/proxy/protocol/tls.py b/mitmproxy/proxy/protocol/tls.py --- a/mitmproxy/proxy/protocol/tls.py +++ b/mitmproxy/proxy/protocol/tls.py @@ -432,7 +432,6 @@ def alpn_for_client_connection(self): def __alpn_select_callback(self, conn_, options): # This gets triggered if we haven't established an upstream connection yet. default_alpn = b'http/1.1' - # alpn_preference = b'h2' if self.alpn_for_client_connection in options: choice = bytes(self.alpn_for_client_connection) @@ -504,6 +503,17 @@ def _establish_tls_with_server(self): if alpn and b"h2" in alpn and not self.config.options.http2: alpn.remove(b"h2") + if self.client_conn.ssl_established: + # If the client has already negotiated an ALP, then force the + # server to use the same. This can only happen if the host gets + # changed after the initial connection was established. E.g.: + # * the client offers http/1.1 and h2, + # * the initial host is only capable of http/1.1, + # * then the first server connection negotiates http/1.1, + # * but after the server_conn change, the new host offers h2 + # * which results in garbage because the layers don' match. + alpn = [self.client_conn.connection.get_alpn_proto_negotiated()] + ciphers_server = self.config.options.ciphers_server if not ciphers_server and self._client_tls: ciphers_server = []
Crash when connecting to HTTP/1.1 server via mitmdump and changing host to a server that supports h2 ##### Steps to reproduce the problem: 1. Run mitmdump with a simple inline script that changes the host to one capable of h2. 2. Open https://holmusk.com (any website that only supports http1.1) via Chrome connected to proxy server 3. Observe mitmdump stdout for error like below - ![observed error](https://cloud.githubusercontent.com/assets/2168895/20243145/69b1f368-a942-11e6-8de8-d5f339b31d20.png) ##### Any other comments? What have you tried so far? 1) Here is the script I am using to change the host - ![sample-script](https://cloud.githubusercontent.com/assets/2168895/20243130/cf5e276e-a941-11e6-8c4d-a358536d3606.png) 2) Changing host to a server that supports HTTP1.1 only helps to bypass the issue. So does passing in the disable http2 flag when starting mitmdump. Also force setting scheme and port to http and 80 helps to mask the issue (since h2 works on https only). 3) I have already created an AWS CloudFront distribution that is capable of h2. `flow.request.host = 'dvmu1lzlfqifb.cloudfront.net'`. Please pass in the original website hostname as a request header `flow.request.headers['Dex-Client-Domain'] = 'https://holmusk.com/'` if you want to use my distribution. ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Linux-4.4.0-45-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial
2016-11-13T11:15:23
mitmproxy/mitmproxy
1,765
mitmproxy__mitmproxy-1765
[ "1759" ]
79c753d8f8ea934c0e3d7973ba520c6e3d903d9f
diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -268,6 +268,11 @@ def _process_flow(self, f): self.log("request", "debug", [repr(request)]) + # set first line format to relative in regular mode, + # see https://github.com/mitmproxy/mitmproxy/issues/1759 + if self.mode is HTTPMode.regular and request.first_line_format == "absolute": + request.first_line_format = "relative" + # update host header in reverse proxy mode if self.config.options.mode == "reverse": f.request.headers["Host"] = self.config.upstream_server.address.host diff --git a/pathod/pathod.py b/pathod/pathod.py --- a/pathod/pathod.py +++ b/pathod/pathod.py @@ -144,6 +144,7 @@ def handle_http_request(self, logger): path = req.path http_version = req.http_version headers = req.headers + first_line_format = req.first_line_format clientcert = None if self.clientcert: @@ -167,6 +168,7 @@ def handle_http_request(self, logger): sni=self.sni, remote_address=self.address(), clientcert=clientcert, + first_line_format=first_line_format ), cipher=None, )
diff --git a/test/mitmproxy/test_server.py b/test/mitmproxy/test_server.py --- a/test/mitmproxy/test_server.py +++ b/test/mitmproxy/test_server.py @@ -282,6 +282,21 @@ def test_stream_modify(self): assert d.content == b"bar" self.master.addons.remove(s) + def test_first_line_rewrite(self): + """ + If mitmproxy is a regular HTTP proxy, it must rewrite an absolute-form request like + GET http://example.com/foo HTTP/1.0 + to + GET /foo HTTP/1.0 + when sending the request upstream. While any server should technically accept + the absolute form, this is not the case in practice. + """ + req = "get:'%s/p/200'" % self.server.urlbase + p = self.pathoc() + with p.connect(): + assert p.request(req).status_code == 200 + assert self.server.last_log()["request"]["first_line_format"] == "relative" + class TestHTTPAuth(tservers.HTTPProxyTest): def test_auth(self):
Smoke Tests weebly.com `curl -L -k -s -A 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0' --proxy http://localhost:8080 http://weebly.com/ -v` gives: ``` 127.0.0.1:60757: clientconnect 127.0.0.1:60757: GET http://weebly.com/ << 301 Moved Permanently 230b 127.0.0.1:60757: GET http://www.weebly.com/ << 302 Found 0b 127.0.0.1:60757: GET http://www.weebly.com/dehttp://www.weebly.com:80/ << 301 Moved Permanently 661b ``` after which the client connection just hangs. This seems to be related to first-line format being absolute. Same for bbc.co.uk ------------ addthis.com `curl -L -k -s -A 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0' --proxy http://localhost:8080 http://addthis.com/ -v` gives: ``` 127.0.0.1:61559: clientconnect 127.0.0.1:61559: GET http://addthis.com/ << 400 Bad Request 0b 127.0.0.1:61559: clientdisconnect ``` ``` > GET http://addthis.com/ HTTP/1.1 > Host: addthis.com > User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0 > Accept: */* > Proxy-Connection: Keep-Alive > < HTTP/1.1 400 Bad Request < Date: Fri, 18 Nov 2016 18:09:02 GMT < Transfer-Encoding: chunked < Connection: keep-alive < Server: cloudflare-nginx < CF-RAY: 303d5f05901763df-FRA < ``` same for soundcloud.com and www.huffingtonpost.com ref #1754
2016-11-20T14:42:55
mitmproxy/mitmproxy
1,767
mitmproxy__mitmproxy-1767
[ "1101" ]
f74e561524d04c93cd7953f34e78ebe67eaa58a8
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -70,6 +70,15 @@ "TLSv1_2": (SSL.TLSv1_2_METHOD, SSL_BASIC_OPTIONS), } +ssl_method_names = { + SSL.SSLv2_METHOD: "SSLv2", + SSL.SSLv3_METHOD: "SSLv3", + SSL.SSLv23_METHOD: "SSLv23", + SSL.TLSv1_METHOD: "TLSv1", + SSL.TLSv1_1_METHOD: "TLSv1.1", + SSL.TLSv1_2_METHOD: "TLSv1.2", +} + class SSLKeyLogger: @@ -510,7 +519,17 @@ def _create_ssl_context(self, :param cipher_list: A textual OpenSSL cipher list, see https://www.openssl.org/docs/apps/ciphers.html :rtype : SSL.Context """ - context = SSL.Context(method) + try: + context = SSL.Context(method) + except ValueError as e: + method_name = ssl_method_names.get(method, "unknown") + raise exceptions.TlsException( + "SSL method \"%s\" is most likely not supported " + "or disabled (for security reasons) in your libssl. " + "Please refer to https://github.com/mitmproxy/mitmproxy/issues/1101 " + "for more details." % method_name + ) + # Options (NO_SSLv2/3) if options is not None: context.set_options(options)
diff --git a/test/mitmproxy/net/test_tcp.py b/test/mitmproxy/net/test_tcp.py --- a/test/mitmproxy/net/test_tcp.py +++ b/test/mitmproxy/net/test_tcp.py @@ -800,3 +800,18 @@ def test_create_logfun(self): tcp.SSLKeyLogger.create_logfun("test"), tcp.SSLKeyLogger) assert not tcp.SSLKeyLogger.create_logfun(False) + + +class TestSSLInvalidMethod(tservers.ServerTestBase): + handler = EchoHandler + ssl = True + + def test_invalid_ssl_method_should_fail(self): + fake_ssl_method = 100500 + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + tutils.raises( + exceptions.TlsException, + c.convert_to_ssl, + method=fake_ssl_method + )
clarify error message on SSLv3 failure openssl SSLv3 support has been disabled on ubuntu 16.04 ([debian/patches/no-sslv3.patch](https://launchpad.net/ubuntu/+source/openssl/1.0.2g-1ubuntu1)),<br />and probably debian unstable + other distros. `mitmproxy --ssl-version-server SSLv3 -R https://google.fr:443` results in the following failure : ``` Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/libmproxy/proxy/server.py", line 120, in handle root_layer() File "/usr/lib/python2.7/dist-packages/libmproxy/proxy/modes/reverse_proxy.py", line 14, in __call__ layer() File "/usr/lib/python2.7/dist-packages/libmproxy/protocol/tls.py", line 267, in __call__ self._establish_tls_with_client_and_server() File "/usr/lib/python2.7/dist-packages/libmproxy/protocol/tls.py", line 392, in _establish_tls_with_client_and_server six.reraise(*sys.exc_info()) File "/usr/lib/python2.7/dist-packages/libmproxy/protocol/tls.py", line 386, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "/usr/lib/python2.7/dist-packages/libmproxy/protocol/tls.py", line 458, in _establish_tls_with_server alpn_protos=alpn, File "/usr/lib/python2.7/dist-packages/libmproxy/models/connections.py", line 183, in establish_ssl self.convert_to_ssl(cert=clientcert, sni=sni, **kwargs) File "/usr/lib/python2.7/dist-packages/netlib/tcp.py", line 605, in convert_to_ssl **sslctx_kwargs File "/usr/lib/python2.7/dist-packages/netlib/tcp.py", line 580, in create_ssl_context **sslctx_kwargs) File "/usr/lib/python2.7/dist-packages/netlib/tcp.py", line 488, in _create_ssl_context context = SSL.Context(method) File "/usr/local/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 478, in __init__ _raise_current_error() File "/usr/local/lib/python2.7/dist-packages/OpenSSL/_util.py", line 48, in exception_from_error_queue raise exception_type(errors) Error: [('SSL routines', 'SSL_CTX_new', 'null ssl method passed')] mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` It would be great to have a message such as "your libssl does not support SSLv3 (it was removed for security reasons)" For those servers wo only support SSLv3 (hello [PDUs](https://en.wikipedia.org/wiki/Power_distribution_unit)), you can use TEMPORARILY a recompiled libssl with SSLv3 enabled : ``` cd $(mktemp -d) sudo apt-get build-dep openssl apt-get source openssl dpkg-source -x openssl*.dsc cd openssl* patch -R -p1 < ./debian/patches/no-sslv3.patch dpkg-buildpackage -rfakeroot -b sudo chown root:root libssl.so.1.0.0 sudo chmod u=rw,go=r libssl.so.1.0.0 sudo cp libssl.so.1.0.0 /lib/x86_64-linux-gnu/libssl.so.1.0.0 ``` (obviously you can keep your recomplied libssl.so.1.0.0 somewhere) After use, restore the distro and SECURE libssl, launching : `sudo apt-get install --reinstall libssl1.0.0` Mitmproxy Version: any Operating System: ubuntu 16.04
Thanks for the report! :smiley: This issue should be easy to fix, so I'll leave it open if anyone wants to give it a shot. It should be enough to catch the exception and return a `netlib.exceptions.TlsException` with a descriptive error message linking to this issue instead.
2016-11-20T17:45:29
mitmproxy/mitmproxy
1,769
mitmproxy__mitmproxy-1769
[ "1749" ]
ebff5f2466ab630f3642283c63823b2596f0b86c
diff --git a/mitmproxy/platform/windows.py b/mitmproxy/platform/windows.py --- a/mitmproxy/platform/windows.py +++ b/mitmproxy/platform/windows.py @@ -8,8 +8,8 @@ import time import configargparse -from pydivert import enum -from pydivert import windivert +import pydivert +import pydivert.consts import pickle import socketserver @@ -149,7 +149,7 @@ class TransparentProxy: Limitations: - No IPv6 support. (Pull Requests welcome) - - TCP ports do not get re-used simulateously on the client, i.e. the proxy will fail if application X + - TCP ports do not get re-used simultaneously on the client, i.e. the proxy will fail if application X connects to example.com and example.org from 192.168.0.42:4242 simultaneously. This could be mitigated by introducing unique "meta-addresses" which mitmproxy sees, but this would remove the correct client info from mitmproxy. @@ -197,13 +197,10 @@ def __init__(self, self.api_thread = threading.Thread(target=self.api.serve_forever) self.api_thread.daemon = True - self.driver = windivert.WinDivert() - self.driver.register() - self.request_filter = custom_filter or " or ".join( ("tcp.DstPort == %d" % p) for p in redirect_ports) - self.request_forward_handle = None + self.request_forward_handle = None # type: pydivert.WinDivert self.request_forward_thread = threading.Thread( target=self.request_forward) self.request_forward_thread.daemon = True @@ -212,18 +209,18 @@ def __init__(self, self.trusted_pids = set() self.tcptable2 = MIB_TCPTABLE2(0) self.tcptable2_size = ctypes.wintypes.DWORD(0) - self.request_local_handle = None + self.request_local_handle = None # type: pydivert.WinDivert self.request_local_thread = threading.Thread(target=self.request_local) self.request_local_thread.daemon = True # The proxy server responds to the client. To the client, # this response should look like it has been sent by the real target self.response_filter = "outbound and tcp.SrcPort == %d" % proxy_port - self.response_handle = None + self.response_handle = None # type: pydivert.WinDivert self.response_thread = threading.Thread(target=self.response) self.response_thread.daemon = True - self.icmp_handle = None + self.icmp_handle = None # type: pydivert.WinDivert @classmethod def setup(cls): @@ -241,25 +238,33 @@ def start(self): # Block all ICMP requests (which are sent on Windows by default). # In layman's terms: If we don't do this, our proxy machine tells the client that it can directly connect to the # real gateway if they are on the same network. - self.icmp_handle = self.driver.open_handle( + self.icmp_handle = pydivert.WinDivert( filter="icmp", - layer=enum.Layer.NETWORK, - flags=enum.Flag.DROP) + layer=pydivert.Layer.NETWORK, + flags=pydivert.Flag.DROP + ) + self.icmp_handle.open() - self.response_handle = self.driver.open_handle( + self.response_handle = pydivert.WinDivert( filter=self.response_filter, - layer=enum.Layer.NETWORK) + layer=pydivert.Layer.NETWORK + ) + self.response_handle.open() self.response_thread.start() if self.mode == "forward" or self.mode == "both": - self.request_forward_handle = self.driver.open_handle( + self.request_forward_handle = pydivert.WinDivert( filter=self.request_filter, - layer=enum.Layer.NETWORK_FORWARD) + layer=pydivert.Layer.NETWORK_FORWARD + ) + self.request_forward_handle.open() self.request_forward_thread.start() if self.mode == "local" or self.mode == "both": - self.request_local_handle = self.driver.open_handle( + self.request_local_handle = pydivert.WinDivert( filter=self.request_filter, - layer=enum.Layer.NETWORK) + layer=pydivert.Layer.NETWORK + ) + self.request_local_handle.open() self.request_local_thread.start() def shutdown(self): @@ -272,17 +277,16 @@ def shutdown(self): self.icmp_handle.close() self.api.shutdown() - def recv(self, handle): + def recv(self, handle: pydivert.WinDivert) -> pydivert.Packet: """ Convenience function that receives a packet from the passed handler and handles error codes. If the process has been shut down, (None, None) is returned. """ try: - raw_packet, metadata = handle.recv() - return self.driver.parse_packet(raw_packet), metadata + return handle.recv() except WindowsError as e: if e.winerror == 995: - return None, None + return None else: raise @@ -306,7 +310,7 @@ def fetch_pids(self): def request_local(self): while True: - packet, metadata = self.recv(self.request_local_handle) + packet = self.recv(self.request_local_handle) if not packet: return @@ -321,49 +325,47 @@ def request_local(self): pid = self.addr_pid_map.get(client, None) if pid not in self.trusted_pids: - self._request(packet, metadata) + self._request(packet) else: - self.request_local_handle.send((packet.raw, metadata)) + self.request_local_handle.send(packet, recalculate_checksum=False) def request_forward(self): """ Redirect packages to the proxy """ while True: - packet, metadata = self.recv(self.request_forward_handle) + packet = self.recv(self.request_forward_handle) if not packet: return - self._request(packet, metadata) + self._request(packet) - def _request(self, packet, metadata): + def _request(self, packet: pydivert.Packet): # print(" * Redirect client -> server to proxy") # print("%s:%s -> %s:%s" % (packet.src_addr, packet.src_port, packet.dst_addr, packet.dst_port)) client = (packet.src_addr, packet.src_port) server = (packet.dst_addr, packet.dst_port) if client in self.client_server_map: - # Force re-add to mark as "newest" entry in the dict. - del self.client_server_map[client] - while len(self.client_server_map) > self.connection_cache_size: - self.client_server_map.popitem(False) - - self.client_server_map[client] = server + self.client_server_map.move_to_end(client) + else: + while len(self.client_server_map) > self.connection_cache_size: + self.client_server_map.popitem(False) + self.client_server_map[client] = server packet.dst_addr, packet.dst_port = self.proxy_addr, self.proxy_port - metadata.direction = enum.Direction.INBOUND + packet.direction = pydivert.consts.Direction.INBOUND - packet = self.driver.update_packet_checksums(packet) # Use any handle thats on the NETWORK layer - request_local may be # unavailable. - self.response_handle.send((packet.raw, metadata)) + self.response_handle.send(packet) def response(self): """ Spoof source address of packets send from the proxy to the client """ while True: - packet, metadata = self.recv(self.response_handle) + packet = self.recv(self.response_handle) if not packet: return @@ -373,11 +375,11 @@ def response(self): server = self.client_server_map.get(client, None) if server: packet.src_addr, packet.src_port = server + packet.recalculate_checksums() else: print("Warning: Previously unseen connection from proxy to %s:%s." % client) - packet = self.driver.update_packet_checksums(packet) - self.response_handle.send((packet.raw, metadata)) + self.response_handle.send(packet, recalculate_checksum=False) if __name__ == "__main__": diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -87,7 +87,7 @@ ], extras_require={ ':sys_platform == "win32"': [ - "pydivert>=0.0.7, <2.0", + "pydivert>=2.0.3, <2.1", ], ':sys_platform != "win32"': [ ],
Update PyDivert Long story short, we should upgrade to PyDivert 2.x! :smiley:
2016-11-21T13:15:28
mitmproxy/mitmproxy
1,794
mitmproxy__mitmproxy-1794
[ "1783", "1783" ]
e64d2ce829a7d2019d6f9c085fb99aa199782014
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -551,7 +551,14 @@ def verify_cert(conn, x509, errno, err_depth, is_cert_verified): context.set_verify(verify_options, verify_cert) if ca_path is None and ca_pemfile is None: ca_pemfile = certifi.where() - context.load_verify_locations(ca_pemfile, ca_path) + try: + context.load_verify_locations(ca_pemfile, ca_path) + except SSL.Error: + raise exceptions.TlsException( + "Cannot load trusted certificates ({}, {}).".format( + ca_pemfile, ca_path + ) + ) # Workaround for # https://github.com/pyca/pyopenssl/issues/190
diff --git a/test/mitmproxy/net/test_tcp.py b/test/mitmproxy/net/test_tcp.py --- a/test/mitmproxy/net/test_tcp.py +++ b/test/mitmproxy/net/test_tcp.py @@ -199,6 +199,18 @@ def test_failure(self): tutils.raises(exceptions.TlsException, c.convert_to_ssl, sni="foo.com") +class TestInvalidTrustFile(tservers.ServerTestBase): + def test_invalid_trust_file_should_fail(self): + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + with tutils.raises(exceptions.TlsException): + c.convert_to_ssl( + sni="example.mitmproxy.org", + verify_options=SSL.VERIFY_PEER, + ca_pemfile=tutils.test_data.path("mitmproxy/net/data/verificationcerts/generate.py") + ) + + class TestSSLUpstreamCertVerificationWBadServerCert(tservers.ServerTestBase): handler = EchoHandler
Empty `--upstream-trusted-ca` file crashes mitmproxy. ##### Steps to reproduce the problem: 1. `touch foo` 2. `mitmdump --upstream-trusted-ca foo` 3. `curl -x localhost:8080 https://example.com/` ``` 127.0.0.1:61162: clientconnect 127.0.0.1:61162: Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/server.py", line 115, in handle root_layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/modes/http_proxy.py", line 9, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 379, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 177, in __call__ if not self._process_flow(flow): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 246, in _process_flow return self.handle_regular_connect(f) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 204, in handle_regular_connect layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 372, in __call__ self._establish_tls_with_client_and_server() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 448, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 534, in _establish_tls_with_server alpn_protos=alpn, File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/connections.py", line 229, in establish_ssl self.convert_to_ssl(cert=clientcert, sni=sni, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 688, in convert_to_ssl **sslctx_kwargs File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 662, in create_ssl_context **sslctx_kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 554, in _create_ssl_context context.load_verify_locations(ca_pemfile, ca_path) File "/usr/local/lib/python3.5/dist-packages/OpenSSL/SSL.py", line 525, in load_verify_locations _raise_current_error() File "/usr/local/lib/python3.5/dist-packages/OpenSSL/_util.py", line 48, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [] ``` ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty Empty `--upstream-trusted-ca` file crashes mitmproxy. ##### Steps to reproduce the problem: 1. `touch foo` 2. `mitmdump --upstream-trusted-ca foo` 3. `curl -x localhost:8080 https://example.com/` ``` 127.0.0.1:61162: clientconnect 127.0.0.1:61162: Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/server.py", line 115, in handle root_layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/modes/http_proxy.py", line 9, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 379, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 177, in __call__ if not self._process_flow(flow): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 246, in _process_flow return self.handle_regular_connect(f) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/http.py", line 204, in handle_regular_connect layer() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 372, in __call__ self._establish_tls_with_client_and_server() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 448, in _establish_tls_with_client_and_server self._establish_tls_with_server() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 534, in _establish_tls_with_server alpn_protos=alpn, File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/connections.py", line 229, in establish_ssl self.convert_to_ssl(cert=clientcert, sni=sni, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 688, in convert_to_ssl **sslctx_kwargs File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 662, in create_ssl_context **sslctx_kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/net/tcp.py", line 554, in _create_ssl_context context.load_verify_locations(ca_pemfile, ca_path) File "/usr/local/lib/python3.5/dist-packages/OpenSSL/SSL.py", line 525, in load_verify_locations _raise_current_error() File "/usr/local/lib/python3.5/dist-packages/OpenSSL/_util.py", line 48, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [] ``` ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty
2016-11-28T01:37:51
mitmproxy/mitmproxy
1,801
mitmproxy__mitmproxy-1801
[ "1799" ]
741c2b7b66cbfb60cdf466063cdba3972b2ce2ee
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -30,10 +30,7 @@ socket_fileobject = socket.SocketIO EINTR = 4 -if os.environ.get("NO_ALPN"): - HAS_ALPN = False -else: - HAS_ALPN = SSL._lib.Cryptography_HAS_ALPN +HAS_ALPN = SSL._lib.Cryptography_HAS_ALPN # To enable all SSL methods use: SSLv23 # then add options to disable certain methods
diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,14 @@ +import pytest +import OpenSSL +import mitmproxy.net.tcp + + +requires_alpn = pytest.mark.skipif( + not mitmproxy.net.tcp.HAS_ALPN, + reason='requires OpenSSL with ALPN support') + + [email protected]() +def disable_alpn(monkeypatch): + monkeypatch.setattr(mitmproxy.net.tcp, 'HAS_ALPN', False) + monkeypatch.setattr(OpenSSL.SSL._lib, 'Cryptography_HAS_ALPN', False) diff --git a/test/mitmproxy/net/test_tcp.py b/test/mitmproxy/net/test_tcp.py --- a/test/mitmproxy/net/test_tcp.py +++ b/test/mitmproxy/net/test_tcp.py @@ -6,7 +6,7 @@ import os import threading import mock - +import pytest from OpenSSL import SSL from mitmproxy import certs @@ -15,6 +15,7 @@ from mitmproxy import exceptions from . import tservers +from ...conftest import requires_alpn class EchoHandler(tcp.BaseHandler): @@ -526,40 +527,47 @@ def test_timeout(self): tutils.raises(exceptions.TcpTimeout, c.rfile.read, 10) +class TestCryptographyALPN: + + def test_has_alpn(self): + if 'OPENSSL_ALPN' in os.environ: + assert tcp.HAS_ALPN + assert SSL._lib.Cryptography_HAS_ALPN + elif 'OPENSSL_OLD' in os.environ: + assert not tcp.HAS_ALPN + assert not SSL._lib.Cryptography_HAS_ALPN + + class TestALPNClient(tservers.ServerTestBase): handler = ALPNHandler ssl = dict( alpn_select=b"bar" ) - if tcp.HAS_ALPN: - def test_alpn(self): - c = tcp.TCPClient(("127.0.0.1", self.port)) - with c.connect(): - c.convert_to_ssl(alpn_protos=[b"foo", b"bar", b"fasel"]) - assert c.get_alpn_proto_negotiated() == b"bar" - assert c.rfile.readline().strip() == b"bar" - - def test_no_alpn(self): - c = tcp.TCPClient(("127.0.0.1", self.port)) - with c.connect(): - c.convert_to_ssl() - assert c.get_alpn_proto_negotiated() == b"" - assert c.rfile.readline().strip() == b"NONE" + @requires_alpn + @pytest.mark.parametrize('has_alpn,alpn_protos, expected_negotiated, expected_response', [ + (True, [b"foo", b"bar", b"fasel"], b'bar', b'bar'), + (True, [], b'', b'NONE'), + (True, None, b'', b'NONE'), + (False, [b"foo", b"bar", b"fasel"], b'', b'NONE'), + (False, [], b'', b'NONE'), + (False, None, b'', b'NONE'), + ]) + def test_alpn(self, monkeypatch, has_alpn, alpn_protos, expected_negotiated, expected_response): + monkeypatch.setattr(tcp, 'HAS_ALPN', has_alpn) + monkeypatch.setattr(SSL._lib, 'Cryptography_HAS_ALPN', has_alpn) - else: - def test_none_alpn(self): - c = tcp.TCPClient(("127.0.0.1", self.port)) - with c.connect(): - c.convert_to_ssl(alpn_protos=[b"foo", b"bar", b"fasel"]) - assert c.get_alpn_proto_negotiated() == b"" - assert c.rfile.readline() == b"NONE" + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + c.convert_to_ssl(alpn_protos=alpn_protos) + assert c.get_alpn_proto_negotiated() == expected_negotiated + assert c.rfile.readline().strip() == expected_response class TestNoSSLNoALPNClient(tservers.ServerTestBase): handler = ALPNHandler - def test_no_ssl_no_alpn(self): + def test_no_ssl_no_alpn(self, disable_alpn): c = tcp.TCPClient(("127.0.0.1", self.port)) with c.connect(): assert c.get_alpn_proto_negotiated() == b"" diff --git a/test/mitmproxy/protocol/test_http2.py b/test/mitmproxy/protocol/test_http2.py --- a/test/mitmproxy/protocol/test_http2.py +++ b/test/mitmproxy/protocol/test_http2.py @@ -1,7 +1,6 @@ # coding=utf-8 -import pytest import os import tempfile import traceback @@ -17,6 +16,7 @@ from mitmproxy.net.http import http1, http2 from .. import tservers +from ...conftest import requires_alpn import logging logging.getLogger("hyper.packages.hpack.hpack").setLevel(logging.WARNING) @@ -27,11 +27,6 @@ logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING) -requires_alpn = pytest.mark.skipif( - not mitmproxy.net.tcp.HAS_ALPN, - reason='requires OpenSSL with ALPN support') - - # inspect the log: # for msg in self.proxy.tmaster.tlog: # print(msg) diff --git a/test/mitmproxy/test_dump.py b/test/mitmproxy/test_dump.py --- a/test/mitmproxy/test_dump.py +++ b/test/mitmproxy/test_dump.py @@ -51,14 +51,14 @@ def test_error(self): assert "error" in o.tfile.getvalue() def test_replay(self): - o = dump.Options(server_replay=["nonexistent"], replay_kill_extra=True) + o = dump.Options(http2=False, server_replay=["nonexistent"], replay_kill_extra=True) tutils.raises(exceptions.OptionsError, dump.DumpMaster, o, proxy.DummyServer()) with tutils.tmpdir() as t: p = os.path.join(t, "rep") self.flowfile(p) - o = dump.Options(server_replay=[p], replay_kill_extra=True) + o = dump.Options(http2=False, server_replay=[p], replay_kill_extra=True) o.verbosity = 0 o.flow_detail = 0 m = dump.DumpMaster(o, proxy.DummyServer()) @@ -66,13 +66,13 @@ def test_replay(self): self.cycle(m, b"content") self.cycle(m, b"content") - o = dump.Options(server_replay=[p], replay_kill_extra=False) + o = dump.Options(http2=False, server_replay=[p], replay_kill_extra=False) o.verbosity = 0 o.flow_detail = 0 m = dump.DumpMaster(o, proxy.DummyServer()) self.cycle(m, b"nonexistent") - o = dump.Options(client_replay=[p], replay_kill_extra=False) + o = dump.Options(http2=False, client_replay=[p], replay_kill_extra=False) o.verbosity = 0 o.flow_detail = 0 m = dump.DumpMaster(o, proxy.DummyServer()) diff --git a/test/pathod/test_pathoc.py b/test/pathod/test_pathoc.py --- a/test/pathod/test_pathoc.py +++ b/test/pathod/test_pathoc.py @@ -1,8 +1,8 @@ import io from mock import Mock +import pytest from mitmproxy.net import http -from mitmproxy.net import tcp from mitmproxy.net.http import http1 from mitmproxy import exceptions @@ -11,6 +11,7 @@ from mitmproxy.test import tutils from . import tservers +from ..conftest import requires_alpn def test_response(): @@ -211,45 +212,57 @@ class TestDaemonHTTP2(PathocTestDaemon): ssl = True explain = False - if tcp.HAS_ALPN: - - def test_http2(self): - c = pathoc.Pathoc( - ("127.0.0.1", self.d.port), - fp=None, - ssl=True, - use_http2=True, - ) - assert isinstance(c.protocol, HTTP2StateProtocol) - - c = pathoc.Pathoc( - ("127.0.0.1", self.d.port), - ) - assert c.protocol == http1 - - def test_http2_alpn(self): - c = pathoc.Pathoc( - ("127.0.0.1", self.d.port), - fp=None, - ssl=True, - use_http2=True, - http2_skip_connection_preface=True, - ) - - tmp_convert_to_ssl = c.convert_to_ssl - c.convert_to_ssl = Mock() - c.convert_to_ssl.side_effect = tmp_convert_to_ssl - with c.connect(): - _, kwargs = c.convert_to_ssl.call_args - assert set(kwargs['alpn_protos']) == set([b'http/1.1', b'h2']) - - def test_request(self): - c = pathoc.Pathoc( - ("127.0.0.1", self.d.port), - fp=None, - ssl=True, - use_http2=True, - ) + @requires_alpn + def test_http2(self): + c = pathoc.Pathoc( + ("127.0.0.1", self.d.port), + fp=None, + ssl=True, + use_http2=True, + ) + assert isinstance(c.protocol, HTTP2StateProtocol) + + c = pathoc.Pathoc( + ("127.0.0.1", self.d.port), + ) + assert c.protocol == http1 + + @requires_alpn + def test_http2_alpn(self): + c = pathoc.Pathoc( + ("127.0.0.1", self.d.port), + fp=None, + ssl=True, + use_http2=True, + http2_skip_connection_preface=True, + ) + + tmp_convert_to_ssl = c.convert_to_ssl + c.convert_to_ssl = Mock() + c.convert_to_ssl.side_effect = tmp_convert_to_ssl + with c.connect(): + _, kwargs = c.convert_to_ssl.call_args + assert set(kwargs['alpn_protos']) == set([b'http/1.1', b'h2']) + + @requires_alpn + def test_request(self): + c = pathoc.Pathoc( + ("127.0.0.1", self.d.port), + fp=None, + ssl=True, + use_http2=True, + ) + with c.connect(): + resp = c.request("get:/p/200") + assert resp.status_code == 200 + + def test_failing_request(self, disable_alpn): + c = pathoc.Pathoc( + ("127.0.0.1", self.d.port), + fp=None, + ssl=True, + use_http2=True, + ) + with pytest.raises(NotImplementedError): with c.connect(): - resp = c.request("get:/p/200") - assert resp.status_code == 200 + c.request("get:/p/200") diff --git a/test/pathod/test_pathod.py b/test/pathod/test_pathod.py --- a/test/pathod/test_pathod.py +++ b/test/pathod/test_pathod.py @@ -1,11 +1,14 @@ import io +import pytest + from pathod import pathod from mitmproxy.net import tcp from mitmproxy import exceptions from mitmproxy.test import tutils from . import tservers +from ..conftest import requires_alpn class TestPathod: @@ -257,8 +260,11 @@ class TestHTTP2(tservers.DaemonTests): ssl = True nohang = True - if tcp.HAS_ALPN: + @requires_alpn + def test_http2(self): + r, _ = self.pathoc(["GET:/"], ssl=True, use_http2=True) + assert r[0].status_code == 800 - def test_http2(self): + def test_no_http2(self, disable_alpn): + with pytest.raises(NotImplementedError): r, _ = self.pathoc(["GET:/"], ssl=True, use_http2=True) - assert r[0].status_code == 800 diff --git a/test/pathod/test_protocols_http2.py b/test/pathod/test_protocols_http2.py --- a/test/pathod/test_protocols_http2.py +++ b/test/pathod/test_protocols_http2.py @@ -11,6 +11,8 @@ from pathod.protocols.http2 import HTTP2StateProtocol, TCPHandler +from ..conftest import requires_alpn + class TestTCPHandlerWrapper: def test_wrapped(self): @@ -66,37 +68,35 @@ def test_perform_connection_preface_server(self, mock_client_method, mock_server assert mock_server_method.called +@requires_alpn class TestCheckALPNMatch(net_tservers.ServerTestBase): handler = EchoHandler ssl = dict( alpn_select=b'h2', ) - if tcp.HAS_ALPN: - - def test_check_alpn(self): - c = tcp.TCPClient(("127.0.0.1", self.port)) - with c.connect(): - c.convert_to_ssl(alpn_protos=[b'h2']) - protocol = HTTP2StateProtocol(c) - assert protocol.check_alpn() + def test_check_alpn(self): + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + c.convert_to_ssl(alpn_protos=[b'h2']) + protocol = HTTP2StateProtocol(c) + assert protocol.check_alpn() +@requires_alpn class TestCheckALPNMismatch(net_tservers.ServerTestBase): handler = EchoHandler ssl = dict( alpn_select=None, ) - if tcp.HAS_ALPN: - - def test_check_alpn(self): - c = tcp.TCPClient(("127.0.0.1", self.port)) - with c.connect(): - c.convert_to_ssl(alpn_protos=[b'h2']) - protocol = HTTP2StateProtocol(c) - with raises(NotImplementedError): - protocol.check_alpn() + def test_check_alpn(self): + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + c.convert_to_ssl(alpn_protos=[b'h2']) + protocol = HTTP2StateProtocol(c) + with raises(NotImplementedError): + protocol.check_alpn() class TestPerformServerConnectionPreface(net_tservers.ServerTestBase):
Make Travis Great Again (Master Edition) Working on improving the speed and accuracy of Travis's testing.
I actually expected the NO_ALPN test to fail; oh well, next up is trying to get that test to run without updated openssl, which likely will fail a lot more easily. Aborted OS X build because it's going to be a very long time before it gets run, due to a large backlog of OS X jobs. I broke the build and it still passed... Once the OS X build finishes (probably tomorrow), I think this'll no longer be a WIP. I removed 3.5 minutes from OS X build times, just based on time spent dealing with Homebrew This is now ready for merge.
2016-12-01T09:36:53
mitmproxy/mitmproxy
1,813
mitmproxy__mitmproxy-1813
[ "1812" ]
9697f5f656210d6d26f1f8c0ebccdcd0fba1c1db
diff --git a/release/rtool.py b/release/rtool.py --- a/release/rtool.py +++ b/release/rtool.py @@ -196,7 +196,7 @@ def make_bdist(): executable += ".exe" # Remove _main suffix from mitmproxy executable - if executable.startswith("mitmproxy_main"): + if "_main" in executable: shutil.move( executable, executable.replace("_main", "")
PyInstaller: OSX builds have mitmproxy_main executable, not mitmproxy ##### Steps to reproduce the problem: 1. Download snapshot from https://snapshots.mitmproxy.org/v0.19/
2016-12-04T17:42:21
mitmproxy/mitmproxy
1,817
mitmproxy__mitmproxy-1817
[ "1816" ]
e44493bda58d38b6349f84cc62795a47819d9a68
diff --git a/mitmproxy/contrib/tls/__init__.py b/mitmproxy/contrib/tls/__init__.py deleted file mode 100644 --- a/mitmproxy/contrib/tls/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# This file is dual licensed under the terms of the Apache License, Version -# 2.0, and the BSD License. See the LICENSE file in the root of this repository -# for complete details. - diff --git a/mitmproxy/contrib/tls/_constructs.py b/mitmproxy/contrib/tls_parser.py similarity index 94% rename from mitmproxy/contrib/tls/_constructs.py rename to mitmproxy/contrib/tls_parser.py --- a/mitmproxy/contrib/tls/_constructs.py +++ b/mitmproxy/contrib/tls_parser.py @@ -1,3 +1,6 @@ +# This file originally comes from https://github.com/pyca/tls/blob/master/tls/_constructs.py. +# Modified by the mitmproxy team. + # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. @@ -113,9 +116,11 @@ ) ) -extensions = "extensions" / Struct( - Int16ub, - "extensions" / GreedyRange(Extension) +extensions = "extensions" / Optional( + Struct( + Int16ub, + "extensions" / GreedyRange(Extension) + ) ) ClientHello = "ClientHello" / Struct( diff --git a/mitmproxy/proxy/protocol/tls.py b/mitmproxy/proxy/protocol/tls.py --- a/mitmproxy/proxy/protocol/tls.py +++ b/mitmproxy/proxy/protocol/tls.py @@ -4,7 +4,7 @@ import construct from mitmproxy import exceptions -from mitmproxy.contrib.tls import _constructs +from mitmproxy.contrib import tls_parser from mitmproxy.proxy.protocol import base from mitmproxy.net import check @@ -248,7 +248,7 @@ def get_client_hello(client_conn): class TlsClientHello: def __init__(self, raw_client_hello): - self._client_hello = _constructs.ClientHello.parse(raw_client_hello) + self._client_hello = tls_parser.ClientHello.parse(raw_client_hello) def raw(self): return self._client_hello @@ -259,21 +259,25 @@ def cipher_suites(self): @property def sni(self): - for extension in self._client_hello.extensions.extensions: - is_valid_sni_extension = ( - extension.type == 0x00 and - len(extension.server_names) == 1 and - extension.server_names[0].name_type == 0 and - check.is_valid_host(extension.server_names[0].host_name) - ) - if is_valid_sni_extension: - return extension.server_names[0].host_name.decode("idna") + if self._client_hello.extensions: + for extension in self._client_hello.extensions.extensions: + is_valid_sni_extension = ( + extension.type == 0x00 and + len(extension.server_names) == 1 and + extension.server_names[0].name_type == 0 and + check.is_valid_host(extension.server_names[0].host_name) + ) + if is_valid_sni_extension: + return extension.server_names[0].host_name.decode("idna") + return None @property def alpn_protocols(self): - for extension in self._client_hello.extensions.extensions: - if extension.type == 0x10: - return list(extension.alpn_protocols) + if self._client_hello.extensions: + for extension in self._client_hello.extensions.extensions: + if extension.type == 0x10: + return list(extension.alpn_protocols) + return [] @classmethod def from_client_conn(cls, client_conn):
diff --git a/test/mitmproxy/contrib/test_tls_parser.py b/test/mitmproxy/contrib/test_tls_parser.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/contrib/test_tls_parser.py @@ -0,0 +1,38 @@ +from mitmproxy.contrib import tls_parser + + +def test_parse_chrome(): + """ + Test if we properly parse a ClientHello sent by Chrome 54. + """ + data = bytes.fromhex( + "03033b70638d2523e1cba15f8364868295305e9c52aceabda4b5147210abc783e6e1000022c02bc02fc02cc030" + "cca9cca8cc14cc13c009c013c00ac014009c009d002f0035000a0100006cff0100010000000010000e00000b65" + "78616d706c652e636f6d0017000000230000000d00120010060106030501050304010403020102030005000501" + "00000000001200000010000e000c02683208687474702f312e3175500000000b00020100000a00080006001d00" + "170018" + ) + c = tls_parser.ClientHello.parse(data) + assert c.version.major == 3 + assert c.version.minor == 3 + + alpn = [a for a in c.extensions.extensions if a.type == 16] + assert len(alpn) == 1 + assert alpn[0].alpn_protocols == [b"h2", b"http/1.1"] + + sni = [a for a in c.extensions.extensions if a.type == 0] + assert len(sni) == 1 + assert sni[0].server_names[0].name_type == 0 + assert sni[0].server_names[0].host_name == b"example.com" + + +def test_parse_no_extensions(): + data = bytes.fromhex( + "03015658a756ab2c2bff55f636814deac086b7ca56b65058c7893ffc6074f5245f70205658a75475103a152637" + "78e1bb6d22e8bbd5b6b0a3a59760ad354e91ba20d353001a0035002f000a000500040009000300060008006000" + "61006200640100" + ) + c = tls_parser.ClientHello.parse(data) + assert c.version.major == 3 + assert c.version.minor == 1 + assert c.extensions is None diff --git a/test/mitmproxy/protocol/test_tls.py b/test/mitmproxy/protocol/test_tls.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/protocol/test_tls.py @@ -0,0 +1,26 @@ +from mitmproxy.proxy.protocol.tls import TlsClientHello + + +class TestClientHello: + + def test_no_extensions(self): + data = bytes.fromhex( + "03015658a756ab2c2bff55f636814deac086b7ca56b65058c7893ffc6074f5245f70205658a75475103a152637" + "78e1bb6d22e8bbd5b6b0a3a59760ad354e91ba20d353001a0035002f000a000500040009000300060008006000" + "61006200640100" + ) + c = TlsClientHello(data) + assert c.sni is None + assert c.alpn_protocols == [] + + def test_extensions(self): + data = bytes.fromhex( + "03033b70638d2523e1cba15f8364868295305e9c52aceabda4b5147210abc783e6e1000022c02bc02fc02cc030" + "cca9cca8cc14cc13c009c013c00ac014009c009d002f0035000a0100006cff0100010000000010000e00000b65" + "78616d706c652e636f6d0017000000230000000d00120010060106030501050304010403020102030005000501" + "00000000001200000010000e000c02683208687474702f312e3175500000000b00020100000a00080006001d00" + "170018" + ) + c = TlsClientHello(data) + assert c.sni == 'example.com' + assert c.alpn_protocols == [b'h2', b'http/1.1']
Error parsing TLSv1.2 ClientHello with no extensions ``` ⇩ [0/0] [showhost] ?:help [*:8001] Traceback (most recent call last): File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 460, in _parse ⇩ [0/0] [showhost] ?:help [*:8001] Error: 192.168.2.28:54194: Traceback (most recent call last): File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 460, in _parse return packer.unpack(self.fmtstr, _read_stream(stream, self.sizeof()))[0] File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 73, in _read_stream raise FieldError("could not read enough bytes, expected %d, found %d" % (length, len(data))) construct.core.FieldError: could not read enough bytes, expected 2, found 0 Traceback (most recent call last): During handling of the above exception, another exception occurred: return self.subcon._parse(stream, context, path) Traceback (most recent call last): File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 2696, in _parse return self.subcon._parse(stream, context, path) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 859, in _parse subobj = sc._parse(stream, context, path) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 462, in _parse raise FieldError("packer %r error during parsing" % self.fmtstr) construct.core.FieldError: packer '>H' error during parsing Traceback (most recent call last): During handling of the above exception, another exception occurred: return cls(raw_client_hello) Traceback (most recent call last): File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 293, in from_client_conn return cls(raw_client_hello) File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 251, in __init__ self._client_hello = _constructs.ClientHello.parse(raw_client_hello) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 175, in parse return self.parse_stream(BytesIO(data), context, **kw) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 186, in parse_stream return self._parse(stream, context, "parsing") File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 2696, in _parse return self.subcon._parse(stream, context, path) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 859, in _parse subobj = sc._parse(stream, context, path) File "/Users/yifanlu/Downloads/mitmproxy/venv3.5/lib/python3.5/site-packages/construct/core.py", line 2700, in _parse raise e.__class__("%s\n %s" % (e, path)) construct.core.FieldError: packer '>H' error during parsing parsing -> ClientHello -> extensions Traceback (most recent call last): During handling of the above exception, another exception occurred: root_layer() Traceback (most recent call last): File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/server.py", line 119, in handle root_layer() File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/modes/transparent_proxy.py", line 19, in __call__ layer() File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 338, in __call__ self._client_hello = TlsClientHello.from_client_conn(self.client_conn) File "/Users/yifanlu/Downloads/mitmproxy/mitmproxy/proxy/protocol/tls.py", line 297, in from_client_conn (repr(e), raw_client_hello.encode("hex")) AttributeError: 'bytes' object has no attribute 'encode' ``` Here is my ClientHello packet ``` Secure Sockets Layer SSL Record Layer: Handshake Protocol: Client Hello Content Type: Handshake (22) Version: TLS 1.1 (0x0302) Length: 55 Handshake Protocol: Client Hello Handshake Type: Client Hello (1) Length: 51 Version: TLS 1.1 (0x0302) Random GMT Unix Time: Dec 4, 2016 22:44:19.000000000 PST Random Bytes: 17991bbc1b718f75650857ad440fa366eae285337fa07c76... Session ID Length: 0 Cipher Suites Length: 12 Cipher Suites (6 suites) Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) Cipher Suite: TLS_RSA_WITH_3DES_EDE_CBC_SHA (0x000a) Cipher Suite: TLS_RSA_WITH_RC4_128_SHA (0x0005) Cipher Suite: TLS_RSA_WITH_RC4_128_MD5 (0x0004) Cipher Suite: TLS_EMPTY_RENEGOTIATION_INFO_SCSV (0x00ff) Compression Methods Length: 1 Compression Methods (1 method) Compression Method: null (0) 0000 16 03 02 00 37 01 00 00 33 03 02 58 45 0c c3 17 ....7...3..XE... 0010 99 1b bc 1b 71 8f 75 65 08 57 ad 44 0f a3 66 ea ....q.ue.W.D..f. 0020 e2 85 33 7f a0 7c 76 ce b5 79 99 00 00 0c 00 35 ..3..|v..y.....5 0030 00 2f 00 0a 00 05 00 04 00 ff 01 00 ./.......... ``` Seems like in `_constructs.py`, `ClientHello` and `ServerHello` assumes the existence of extensions whereas the RFC allows for no extensions ``` struct { ProtocolVersion client_version; Random random; SessionID session_id; CipherSuite cipher_suites<2..2^16-2>; CompressionMethod compression_methods<1..2^8-1>; select (extensions_present) { case false: struct {}; case true: Extension extensions<0..2^16-1>; }; } ClientHello; ```
2016-12-05T09:11:54
mitmproxy/mitmproxy
1,822
mitmproxy__mitmproxy-1822
[ "1780" ]
0a68613c8cb4ea96e291b35061c378fbf3ed1f18
diff --git a/mitmproxy/tools/console/master.py b/mitmproxy/tools/console/master.py --- a/mitmproxy/tools/console/master.py +++ b/mitmproxy/tools/console/master.py @@ -38,6 +38,11 @@ EVENTLOG_SIZE = 500 +class Logger: + def log(self, evt): + signals.add_log(evt.msg, evt.level) + + class ConsoleMaster(master.Master): palette = [] @@ -58,6 +63,7 @@ def __init__(self, options, server): signals.replace_view_state.connect(self.sig_replace_view_state) signals.push_view_state.connect(self.sig_push_view_state) signals.sig_add_log.connect(self.sig_add_log) + self.addons.add(Logger()) self.addons.add(*addons.default_addons()) self.addons.add(intercept.Intercept(), self.view) @@ -447,7 +453,3 @@ def tcp_message(self, f): direction=direction, ), "info") signals.add_log(strutils.bytes_to_escaped_str(message.content), "debug") - - @controller.handler - def log(self, evt): - signals.add_log(evt.msg, evt.level)
Inline script errors not thrown in eventlog ##### Steps to reproduce the problem: 1. edit any inline script and add an error (example sslstrip-test.py attached with function nothing()) [sslstrip-test.txt](https://github.com/mitmproxy/mitmproxy/files/608581/sslstrip-test.txt) 2. mitmproxy --script sslstrip-test.py --eventlog 3. nothing in eventlog (see screenshot) ![mitmproxy-error-not-shown](https://cloud.githubusercontent.com/assets/19553457/20568123/ab76f120-b19b-11e6-836b-dd3800a8c6d4.png) ##### Any other comments? What have you tried so far? Remember that it was working with v0.17.1, Maximilian said it was fixed from v0.18 to v0.18.2, so am i missing something here (a debug mode?)? Mitmproxy is still working, ignoring the script. Thanks a lot, ##### System information Mitmproxy version: 0.19 Python version: 3.5.2+ Platform: Linux-4.8.0-kali1-amd64-x86_64-with-Kali-kali-rolling-kali-rolling SSL version: OpenSSL 1.0.2j 26 Sep 2016 Linux distro: Kali kali-rolling kali-rolling <!-- Cut and paste the output of "mitmdump --sysinfo". If you're using an older version if mitmproxy, please specify the version and OS. -->
2016-12-07T21:49:17
mitmproxy/mitmproxy
1,827
mitmproxy__mitmproxy-1827
[ "1803", "1803" ]
6792cc1de90b02b89da9ae80704ea237c5486e66
diff --git a/mitmproxy/tools/console/master.py b/mitmproxy/tools/console/master.py --- a/mitmproxy/tools/console/master.py +++ b/mitmproxy/tools/console/master.py @@ -49,6 +49,7 @@ class ConsoleMaster(master.Master): def __init__(self, options, server): super().__init__(options, server) self.view = view.View() # type: view.View + self.view.sig_view_update.connect(signals.flow_change.send) self.stream_path = None # This line is just for type hinting self.options = self.options # type: Options
FlowView is not updating ##### Steps to reproduce the problem: 1. Open Flow Reponse View 2. Replay Flow (`r`) ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Windows-10-10.0.14393-SP0 SSL version: OpenSSL 1.0.2h 3 May 2016 Windows version: 10 10.0.14393 SP0 Multiprocessor Free FlowView is not updating ##### Steps to reproduce the problem: 1. Open Flow Reponse View 2. Replay Flow (`r`) ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Windows-10-10.0.14393-SP0 SSL version: OpenSSL 1.0.2h 3 May 2016 Windows version: 10 10.0.14393 SP0 Multiprocessor Free
2016-12-09T16:18:52
mitmproxy/mitmproxy
1,837
mitmproxy__mitmproxy-1837
[ "1809", "1809" ]
b62b92eabe9d6ab1c3ecea87a18740eef730f157
diff --git a/mitmproxy/__init__.py b/mitmproxy/__init__.py --- a/mitmproxy/__init__.py +++ b/mitmproxy/__init__.py @@ -0,0 +1,3 @@ +# https://github.com/mitmproxy/mitmproxy/issues/1809 +# import script here so that pyinstaller registers it. +from . import script # noqa diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,8 +1,8 @@ -from setuptools import setup, find_packages -from codecs import open import os +import runpy +from codecs import open -from mitmproxy import version +from setuptools import setup, find_packages # Based on https://github.com/pypa/sampleproject/blob/master/setup.py # and https://python-packaging-user-guide.readthedocs.org/ @@ -12,9 +12,11 @@ with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() +VERSION = runpy.run_path(os.path.join(here, "mitmproxy", "version.py"))["VERSION"] + setup( name="mitmproxy", - version=version.VERSION, + version=VERSION, description="An interactive, SSL-capable, man-in-the-middle HTTP proxy for penetration testers and software developers.", long_description=long_description, url="http://mitmproxy.org",
mitmdump throw ImportError: No module named 'mitmproxy.script' ##### Steps to reproduce the problem: 1. Download mitmproxy binary from https://github.com/mitmproxy/mitmproxy/releases/download/v0.18.2/mitmproxy-0.18.2-linux.tar.gz 2. Extract and then run : ~$ ./mitmdump -T --host -s inline_script.py 3. mitmdump throw exception: ``` Script error: Traceback (most recent call last): File "/home/john/inline_script.py", line 1, in <module> from mitmproxy.script import concurrent ImportError: No module named 'mitmproxy.script' ``` ##### inline_scripy.py content: ``` from mitmproxy.script import concurrent @concurrent def request(context, flow): print("Request") ``` ##### Any other comments? What have you tried so far? I tried to install mitmproxy from pip. And rerun with inline_script.py: ~$ mitmdump -T -s inline_script.py It runs normally. ##### System information ./mitmdump --sysinfo Mitmproxy version: 0.18.2 Python version: 3.5.2 Platform: Linux-3.13.0-85-generic-x86_64-with-debian-jessie-sid SSL version: OpenSSL 1.0.2j 26 Sep 2016 Linux distro: debian jessie/sid mitmdump throw ImportError: No module named 'mitmproxy.script' ##### Steps to reproduce the problem: 1. Download mitmproxy binary from https://github.com/mitmproxy/mitmproxy/releases/download/v0.18.2/mitmproxy-0.18.2-linux.tar.gz 2. Extract and then run : ~$ ./mitmdump -T --host -s inline_script.py 3. mitmdump throw exception: ``` Script error: Traceback (most recent call last): File "/home/john/inline_script.py", line 1, in <module> from mitmproxy.script import concurrent ImportError: No module named 'mitmproxy.script' ``` ##### inline_scripy.py content: ``` from mitmproxy.script import concurrent @concurrent def request(context, flow): print("Request") ``` ##### Any other comments? What have you tried so far? I tried to install mitmproxy from pip. And rerun with inline_script.py: ~$ mitmdump -T -s inline_script.py It runs normally. ##### System information ./mitmdump --sysinfo Mitmproxy version: 0.18.2 Python version: 3.5.2 Platform: Linux-3.13.0-85-generic-x86_64-with-debian-jessie-sid SSL version: OpenSSL 1.0.2j 26 Sep 2016 Linux distro: debian jessie/sid
This is a bug in the release builds. Nothing uses mitmproxy.script.concurrent within mitmproxy itself, so PyInstaller doesn't include it in the packaged application. If you don't need functioning HTTP/2 (I see you're on Ubuntu 14.04, whose provided openssl is too old to have ALPN, and thus you can't use HTTP/2), you can install mitmproxy via pip for functioning concurrency. We can fix this by either adding `from . import script` to `mitmproxy/__init__.py` or by declaring it as a hiddenimport in pyinstaller. Exposing something useful in `__init__.py` might be useful anyway... @mitmproxy/devs, any preferences? :+1: to `from . import script` in `__init__.py` This is a bug in the release builds. Nothing uses mitmproxy.script.concurrent within mitmproxy itself, so PyInstaller doesn't include it in the packaged application. If you don't need functioning HTTP/2 (I see you're on Ubuntu 14.04, whose provided openssl is too old to have ALPN, and thus you can't use HTTP/2), you can install mitmproxy via pip for functioning concurrency. We can fix this by either adding `from . import script` to `mitmproxy/__init__.py` or by declaring it as a hiddenimport in pyinstaller. Exposing something useful in `__init__.py` might be useful anyway... @mitmproxy/devs, any preferences? :+1: to `from . import script` in `__init__.py`
2016-12-10T20:37:08
mitmproxy/mitmproxy
1,839
mitmproxy__mitmproxy-1839
[ "1830" ]
402332708724797713630af7f41cc2cabd79898e
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -145,9 +145,9 @@ def store_count(self): def inbounds(self, index: int) -> bool: """ - Is this index >= 0 and < len(self) + Is this 0 <= index < len(self) """ - return index >= 0 and index < len(self) + return 0 <= index < len(self) def _rev(self, idx: int) -> int: """ @@ -359,7 +359,7 @@ def index(self) -> typing.Optional[int]: return self.view.index(self.flow) @index.setter - def index(self, idx) -> typing.Optional[int]: + def index(self, idx): if idx < 0 or idx > len(self.view) - 1: raise ValueError("Index out of view bounds") self.flow = self.view[idx] diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -355,9 +355,11 @@ def keypress(self, size, key): elif key == "e": self.master.toggle_eventlog() elif key == "g": - self.master.view.focus.index = 0 + if len(self.master.view): + self.master.view.focus.index = 0 elif key == "G": - self.master.view.focus.index = len(self.master.view) - 1 + if len(self.master.view): + self.master.view.focus.index = len(self.master.view) - 1 elif key == "f": signals.status_prompt.send( prompt = "Filter View",
Pressing g/G crashes mitmproxy when flow list is empty ##### Steps to reproduce the problem: 1. `mitmproxy` 2. `g` or `G` ``` Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 290, in run self.loop.run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/local/lib/python3.5/dist-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/local/lib/python3.5/dist-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/usr/local/lib/python3.5/dist-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowlist.py", line 360, in keypress self.master.view.focus.index = len(self.master.view) - 1 File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 364, in index raise ValueError("Index out of view bounds") ValueError: Index out of view bounds ```
2016-12-11T12:11:22
mitmproxy/mitmproxy
1,840
mitmproxy__mitmproxy-1840
[ "1829" ]
402332708724797713630af7f41cc2cabd79898e
diff --git a/mitmproxy/tools/console/flowview.py b/mitmproxy/tools/console/flowview.py --- a/mitmproxy/tools/console/flowview.py +++ b/mitmproxy/tools/console/flowview.py @@ -1,23 +1,23 @@ import math import os import sys +from functools import lru_cache +from typing import Optional, Union # noqa import urwid -from mitmproxy import exceptions -from typing import Optional, Union # noqa from mitmproxy import contentviews +from mitmproxy import exceptions +from mitmproxy import export from mitmproxy import http +from mitmproxy.net.http import Headers +from mitmproxy.net.http import status_codes from mitmproxy.tools.console import common from mitmproxy.tools.console import flowdetailview from mitmproxy.tools.console import grideditor from mitmproxy.tools.console import searchable from mitmproxy.tools.console import signals from mitmproxy.tools.console import tabs -from mitmproxy import export -from mitmproxy.net.http import Headers -from mitmproxy.net.http import status_codes -from functools import lru_cache class SearchError(Exception): @@ -483,9 +483,12 @@ def view_prev_flow(self, flow): return self._view_nextprev_flow(self.view.index(flow) - 1, flow) def change_this_display_mode(self, t): - name = contentviews.get_by_shortcut(t).name - self.view.settings[self.flow][(self.tab_offset, "prettyview")] = name - signals.flow_change.send(self, flow = self.flow) + view = contentviews.get_by_shortcut(t) + if view: + self.view.settings[self.flow][(self.tab_offset, "prettyview")] = view.name + else: + self.view.settings[self.flow][(self.tab_offset, "prettyview")] = None + signals.flow_change.send(self, flow=self.flow) def keypress(self, size, key): conn = None # type: Optional[Union[http.HTTPRequest, http.HTTPResponse]]
Console: Clearing content view crashes mitmproxy ##### Steps to reproduce the problem: 1. `mitmproxy` 2. `n g enter r enter tab m C` ``` Traceback (most recent call last): File "/media/sf_git/mitmproxy/mitmproxy/tools/console/master.py", line 290, in run self.loop.run() File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/user/venv/lib64/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/user/venv/lib64/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/user/venv/lib64/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/media/sf_git/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/home/user/venv/lib64/python3.5/site-packages/urwid/container.py", line 1116, in keypress return self.footer.keypress((maxcol,),key) File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 132, in keypress return self.master.ab.keypress(*args, **kwargs) File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 85, in keypress self.prompt_execute(k) File "/media/sf_git/mitmproxy/mitmproxy/tools/console/statusbar.py", line 110, in prompt_execute msg = p(txt, *args) File "/media/sf_git/mitmproxy/mitmproxy/tools/console/flowview.py", line 486, in change_this_display_mode name = contentviews.get_by_shortcut(t).name AttributeError: 'NoneType' object has no attribute 'name' ``` ##### Any other comments? What have you tried so far? `change_this_display_mode` has not logic to handle this case. ##### System information Mitmproxy version: 0.19 Python version: 3.5.1 Platform: Linux-4.8.12-1-default-x86_64-with-glibc2.3.4 SSL version: OpenSSL 1.0.2j-fips 26 Sep 2016
2016-12-11T12:22:46
mitmproxy/mitmproxy
1,860
mitmproxy__mitmproxy-1860
[ "1843" ]
6b5673e84911f3e2b1599c22c9b4f482a55b9ef1
diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -182,6 +182,17 @@ def handle_regular_connect(self, f): try: self.set_server((f.request.host, f.request.port)) + + if f.response: + resp = f.response + else: + resp = http.make_connect_response(f.request.data.http_version) + + self.send_response(resp) + + if is_ok(resp.status_code): + layer = self.ctx.next_layer(self) + layer() except ( exceptions.ProtocolException, exceptions.NetlibException ) as e: @@ -192,17 +203,6 @@ def handle_regular_connect(self, f): self.channel.ask("error", f) return False - if f.response: - resp = f.response - else: - resp = http.make_connect_response(f.request.data.http_version) - - self.send_response(resp) - - if is_ok(resp.status_code): - layer = self.ctx.next_layer(self) - layer() - return False def handle_upstream_connect(self, f):
Crash while running smoke tests ``` Traceback (most recent call last): File "...mitmproxy/mitmproxy/net/tcp.py", line 211, in read data = self.o.read(rlen) File "...mitmproxy/venv3.5/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1304, in recv self._raise_ssl_error(self._ssl, result) File "...mitmproxy/venv3.5/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1166, in _raise_ssl_error raise SysCallError(errno, errorcode.get(errno)) OpenSSL.SSL.SysCallError: (54, 'ECONNRESET') During handling of the above exception, another exception occurred: [59/220] Traceback (most recent call last): File "...mitmproxy/mitmproxy/proxy/server.py", line 119, in handle root_layer() File "...mitmproxy/mitmproxy/proxy/modes/http_proxy.py", line 9, in __call__ layer() File "...mitmproxy/mitmproxy/proxy/protocol/tls.py", line 383, in __call__ layer() File "...mitmproxy/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "...mitmproxy/mitmproxy/proxy/protocol/http.py", line 177, in __call__ if not self._process_flow(flow): File "...mitmproxy/mitmproxy/proxy/protocol/http.py", line 246, in _process_flow return self.handle_regular_connect(f) File "...mitmproxy/mitmproxy/proxy/protocol/http.py", line 204, in handle_regular_connect layer() File "...mitmproxy/mitmproxy/proxy/protocol/tls.py", line 383, in __call__ layer() File "...mitmproxy/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "...mitmproxy/mitmproxy/proxy/protocol/http.py", line 177, in __call__ if not self._process_flow(flow): File "...mitmproxy/mitmproxy/proxy/protocol/http.py", line 228, in _process_flow request = self.read_request_headers(f) File "...mitmproxy/mitmproxy/proxy/protocol/http1.py", line 14, in read_request_headers http1.read_request_head(self.client_conn.rfile) File "...mitmproxy/mitmproxy/net/http/http1/read.py", line 52, in read_request_head form, method, scheme, host, port, path, http_version = _read_request_line(rfile) File "...mitmproxy/mitmproxy/net/http/http1/read.py", line 240, in _read_request_line line = _get_first_line(rfile) File "...mitmproxy/mitmproxy/net/http/http1/read.py", line 227, in _get_first_line line = rfile.readline() File "...mitmproxy/mitmproxy/net/tcp.py", line 251, in readline ch = self.read(1) File "...mitmproxy/mitmproxy/net/tcp.py", line 233, in read raise exceptions.TlsException(str(e)) mitmproxy.exceptions.TlsException: (54, 'ECONNRESET') mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` ##### System information Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Darwin-16.1.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.1 ('', '', '') x86_64
2016-12-15T21:58:14
mitmproxy/mitmproxy
1,861
mitmproxy__mitmproxy-1861
[ "1782" ]
6b5673e84911f3e2b1599c22c9b4f482a55b9ef1
diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -178,8 +178,6 @@ def keypress(self, xxx_todo_changeme, key): elif key == "m": self.flow.marked = not self.flow.marked signals.flowlist_change.send(self) - elif key == "M": - self.master.view.toggle_marked() elif key == "r": try: self.master.replay_request(self.flow) @@ -375,6 +373,8 @@ def keypress(self, size, key): prompt = "Load flows", callback = self.master.load_flows_callback ) + elif key == "M": + self.master.view.toggle_marked() elif key == "n": signals.status_prompt_onekey.send( prompt = "Method", diff --git a/mitmproxy/tools/console/statusbar.py b/mitmproxy/tools/console/statusbar.py --- a/mitmproxy/tools/console/statusbar.py +++ b/mitmproxy/tools/console/statusbar.py @@ -263,8 +263,12 @@ def redraw(self): else: arrow = common.SYMBOL_DOWN + marked = "" + if self.master.view.show_marked: + marked = "M" + t = [ - ('heading', ("%s [%s/%s]" % (arrow, offset, fc)).ljust(11)), + ('heading', ("%s %s [%s/%s]" % (arrow, marked, offset, fc)).ljust(11)), ] if self.master.server.bound:
diff --git a/test/mitmproxy/addons/test_view.py b/test/mitmproxy/addons/test_view.py --- a/test/mitmproxy/addons/test_view.py +++ b/test/mitmproxy/addons/test_view.py @@ -123,6 +123,11 @@ def test_filter(): v.set_filter(None) assert len(v) == 4 + v.toggle_marked() + assert len(v) == 0 + v.toggle_marked() + assert len(v) == 4 + v[1].marked = True v.toggle_marked() assert len(v) == 1
marked less than one item ,mitmproxy will broken ##### Steps to reproduce the problem: 1. click `m` toggle flow mark 2. click `M` toggle marked flow view 3. only **1 item** had mark,then click `m` to cancel mark. 4. click `M` return back..mitmproxy will broken. in other words,when marked ** less than one item ** mitmproxy will broken ##### System information ``` Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/master.py", line 482, in run self.loop.run() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/window.py", line 86, in keypress k = super(self.__class__, self).keypress(size, k) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/flowlist.py", line 385, in keypress return urwid.ListBox.keypress(self, size, key) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/urwid/listbox.py", line 987, in keypress key = focus_widget.keypress((maxcol,),key) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/flowlist.py", line 179, in keypress self.state.disable_marked_filter() File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/master.py", line 183, in disable_marked_filter self.set_focus_flow(nearest_marked) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/console/master.py", line 107, in set_focus_flow self.set_focus(self.view.index(f)) File "/usr/local/Cellar/mitmproxy/0.18.2_1/libexec/lib/python2.7/site-packages/mitmproxy/flow/state.py", line 36, in index return self._list.index(f) ValueError: None is not in list mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ```
Thanks for the report! The good news is that this is fixed on master (at least I can't reproduce it, and the instructions are clear), the bad news is see two other bugs: 1. It is not indicated that we enter the marked flow view. 2. Entering the marked flow view without any flows being marked causes the list to go empty. Pressing `M` again does not show the flows again.
2016-12-15T22:59:22
mitmproxy/mitmproxy
1,864
mitmproxy__mitmproxy-1864
[ "1572" ]
c4929bbc190a52e4ac0f38492e085338b3e5827d
diff --git a/mitmproxy/events.py b/mitmproxy/events.py --- a/mitmproxy/events.py +++ b/mitmproxy/events.py @@ -21,9 +21,6 @@ "responseheaders", "error", - "intercept", - "resume", - "websocket_handshake", "websocket_start", "websocket_message",
Missing documentation about unit testing inline scripts At the company I work on we are developing some inline scripts to use internally. We are struggling to create test for our scripts because the only code we found to test scripts are the ones at [/mitmproxy/mitmproxy/blob/v0.17/test/mitmproxy/test_examples.py](/mitmproxy/mitmproxy/blob/v0.17/test/mitmproxy/test_examples.py). The examples are quite good but real documentation is missing for the ones who wants to unit test. Is there another place where I can find better (maybe more advanced) test examples ?
This is a really good question, thanks for raising it! :smiley: With mitmproxy 0.18 we are introducing some significant improvements to our internal architecture, in particular many feature are now implemented as addons to mitmproxy's core (see https://github.com/mitmproxy/mitmproxy/tree/master/mitmproxy/builtins). Fundamentally, addons are not much different from inline scripts¹ and you can actually have your inline script's `start()` method just return an Addon instance (see e.g. the [filt.py](https://github.com/mitmproxy/mitmproxy/blob/master/examples/filt.py) example). Long story short: 1. We'll have our 0.18 release pretty soon. If you are developing some larger inline scripts (i.e. large enough to require testing), I would recommend working with that right away and use the return-addon-from-start approach discussed above. 2. If you do that, you now have all your functionality in a regular Python class and you can import your inline script as a normal Python module. You can have dummy requests and responses from `netlib.tutils`. If you need dummy flows, we're happy to accept a PR that moves `test/mitmproxy/tutils.py` into the mitmproxy package itself. There are a couple of changes to the scripting API in 0.18 we're excited about. We'd like to make sure that we cover all major use cases elegantly, so getting early feedback for this would be wonderful. There's no updated documentation yet (#1445), but all examples have been updated to the new syntax - it's mostly just about removing unecessary arguments from the hooks. ¹) An addon is a class that basically just defines a couple of functions which are equivalent to the inline script hooks. _Just a context for the original question_: At the company I work on, we are searching for ways to implement a reverse proxy for one of our APIs and since the main programming language over here is python we searched for some projects that could help us with that. A coworker of mine stumbled across this project which we found promissing so we are trying to write scripts based on mitmproxy and test them to see if they will work for us. Anyway, this addons approach seems good but I will need more time to fully understand the codebase and then write good tests. This is when a documentation helps a lot. Thanks for the contact @mhils and congratulations for the project ! I've spent some time today working on the testing situation for addons. We now expose a testing truss for addons from the mitmproxy library: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/test/taddons.py You can see this in action here: https://github.com/mitmproxy/mitmproxy/blob/master/test/mitmproxy/addons/test_intercept.py We'll let this mature a bit, wash it across our own test suite, and then document it for the next release. Comments, suggestions and improvements appreciated!
2016-12-16T21:04:32
mitmproxy/mitmproxy
1,873
mitmproxy__mitmproxy-1873
[ "1867" ]
d4298cd74728982388cb8d93f93b0e463dc67b91
diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -1,6 +1,5 @@ import h2.exceptions import time -import traceback import enum from mitmproxy import connections # noqa @@ -431,7 +430,7 @@ def send_error_response(self, code, message, headers=None) -> None: response = http.make_error_response(code, message, headers) self.send_response(response) except (exceptions.NetlibException, h2.exceptions.H2Error, exceptions.Http2ProtocolException): - self.log(traceback.format_exc(), "debug") + self.log("Failed to send error response to client: {}".format(message), "debug") def change_upstream_proxy_server(self, address) -> None: # Make set_upstream_proxy_server always available,
Traceback when client disconnects before error message is sent. `send_error_response` does not catch all kinds of errors: ``` 127.0.0.1:52651: Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\net\tcp.py", line 763, in connect connection.connect(self.address()) TimeoutError: [WinError 10060] Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\base.py", line 180, in connect self.server_conn.connect() File "c:\users\user\git\mitmproxy\mitmproxy\connections.py", line 206, in connect tcp.TCPClient.connect(self) File "c:\users\user\git\mitmproxy\mitmproxy\net\tcp.py", line 768, in connect (self.address.host, err) mitmproxy.exceptions.TcpException: Error connecting to "baidu.com": [WinError 10060] Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 311, in _process_flow f.request.scheme File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 453, in establish_server_connection self.connect() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 397, in connect self.ctx.connect() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\tls.py", line 397, in connect self.ctx.connect() File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\base.py", line 184, in connect repr(self.server_conn.address), str(e) mitmproxy.exceptions.ProtocolException: Server connection to baidu.com:443 failed: Error connecting to "baidu.com": [WinError 10060] Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\net\tcp.py", line 188, in write return self.o.sendall(v) File "c:\python35\lib\site-packages\OpenSSL\SSL.py", line 1286, in sendall self._raise_ssl_error(self._ssl, result) File "c:\python35\lib\site-packages\OpenSSL\SSL.py", line 1166, in _raise_ssl_error raise SysCallError(errno, errorcode.get(errno)) OpenSSL.SSL.SysCallError: (10053, 'WSAECONNABORTED') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 432, in send_error_response self.send_response(response) File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http.py", line 43, in send_response self.send_response_headers(response) File "c:\users\user\git\mitmproxy\mitmproxy\proxy\protocol\http1.py", line 43, in send_response_headers self.client_conn.wfile.write(raw) File "c:\users\user\git\mitmproxy\mitmproxy\net\tcp.py", line 194, in write raise exceptions.TcpDisconnect(str(e)) mitmproxy.exceptions.TcpDisconnect: (10053, 'WSAECONNABORTED') ```
My mistake, I had verbosity all the way up. What does verbosity have to do with it? Or do you think it is ok to show a traceback for high verbosity? IMHO we should never ever show a traceback in the eventlog - most certainly not for `mitmproxy.exceptions.ProtocolException` errors. I vividly remember [this line](https://github.com/mitmproxy/mitmproxy/blob/d4298cd74728982388cb8d93f93b0e463dc67b91/mitmproxy/proxy/protocol/http.py#L434) for some very ugly socket-related debugging on Windows, where it was incredibly useful. You are right though, we should just log the error message here and not the full traceback.
2016-12-17T17:19:35
mitmproxy/mitmproxy
1,876
mitmproxy__mitmproxy-1876
[ "1858" ]
504c289ad0d670fbdc0fb0f598d2e693cda9f5f7
diff --git a/examples/complex/har_dump.py b/examples/complex/har_dump.py --- a/examples/complex/har_dump.py +++ b/examples/complex/har_dump.py @@ -136,7 +136,7 @@ def response(flow): if flow.request.method in ["POST", "PUT", "PATCH"]: params = [ - {"name": a.decode("utf8", "surrogateescape"), "value": b.decode("utf8", "surrogateescape")} + {"name": a, "value": b} for a, b in flow.request.urlencoded_form.items(multi=True) ] entry["request"]["postData"] = { diff --git a/mitmproxy/addons/serverplayback.py b/mitmproxy/addons/serverplayback.py --- a/mitmproxy/addons/serverplayback.py +++ b/mitmproxy/addons/serverplayback.py @@ -1,9 +1,10 @@ -import urllib import hashlib +import urllib +from typing import Any # noqa +from typing import List # noqa -from mitmproxy.utils import strutils -from mitmproxy import exceptions from mitmproxy import ctx +from mitmproxy import exceptions from mitmproxy import io @@ -36,17 +37,20 @@ def _hash(self, flow): _, _, path, _, query, _ = urllib.parse.urlparse(r.url) queriesArray = urllib.parse.parse_qsl(query, keep_blank_values=True) - key = [str(r.port), str(r.scheme), str(r.method), str(path)] + key = [str(r.port), str(r.scheme), str(r.method), str(path)] # type: List[Any] if not self.options.server_replay_ignore_content: - form_contents = r.urlencoded_form or r.multipart_form - if self.options.server_replay_ignore_payload_params and form_contents: - params = [ - strutils.always_bytes(i) - for i in self.options.server_replay_ignore_payload_params - ] - for p in form_contents.items(multi=True): - if p[0] not in params: - key.append(p) + if self.options.server_replay_ignore_payload_params and r.multipart_form: + key.extend( + (k, v) + for k, v in r.multipart_form.items(multi=True) + if k.decode(errors="replace") not in self.options.server_replay_ignore_payload_params + ) + elif self.options.server_replay_ignore_payload_params and r.urlencoded_form: + key.extend( + (k, v) + for k, v in r.urlencoded_form.items(multi=True) + if k not in self.options.server_replay_ignore_payload_params + ) else: key.append(str(r.raw_content)) diff --git a/mitmproxy/net/http/request.py b/mitmproxy/net/http/request.py --- a/mitmproxy/net/http/request.py +++ b/mitmproxy/net/http/request.py @@ -350,6 +350,8 @@ def urlencoded_form(self): The URL-encoded form data as an :py:class:`~mitmproxy.net.multidict.MultiDictView` object. An empty multidict.MultiDictView if the content-type indicates non-form data or the content could not be parsed. + + Starting with mitmproxy 1.0, key and value are strings. """ return multidict.MultiDictView( self._get_urlencoded_form, @@ -360,7 +362,7 @@ def _get_urlencoded_form(self): is_valid_content_type = "application/x-www-form-urlencoded" in self.headers.get("content-type", "").lower() if is_valid_content_type: try: - return tuple(mitmproxy.net.http.url.decode(self.content)) + return tuple(mitmproxy.net.http.url.decode(self.content.decode())) except ValueError: pass return () @@ -381,7 +383,10 @@ def urlencoded_form(self, value): def multipart_form(self): """ The multipart form data as an :py:class:`~mitmproxy.net.multidict.MultiDictView` object. - None if the content-type indicates non-form data. + An empty multidict.MultiDictView if the content-type indicates non-form data + or the content could not be parsed. + + Key and value are bytes. """ return multidict.MultiDictView( self._get_multipart_form,
diff --git a/test/mitmproxy/net/http/test_request.py b/test/mitmproxy/net/http/test_request.py --- a/test/mitmproxy/net/http/test_request.py +++ b/test/mitmproxy/net/http/test_request.py @@ -255,11 +255,11 @@ def test_get_urlencoded_form(self): assert not request.urlencoded_form request.headers["Content-Type"] = "application/x-www-form-urlencoded" - assert list(request.urlencoded_form.items()) == [(b"foobar", b"baz")] + assert list(request.urlencoded_form.items()) == [("foobar", "baz")] def test_set_urlencoded_form(self): request = treq() - request.urlencoded_form = [(b'foo', b'bar'), (b'rab', b'oof')] + request.urlencoded_form = [('foo', 'bar'), ('rab', 'oof')] assert request.headers["Content-Type"] == "application/x-www-form-urlencoded" assert request.content diff --git a/test/mitmproxy/test_examples.py b/test/mitmproxy/test_examples.py --- a/test/mitmproxy/test_examples.py +++ b/test/mitmproxy/test_examples.py @@ -68,11 +68,11 @@ def test_modify_form(self): f = tflow.tflow(req=tutils.treq(headers=form_header)) m.request(f) - assert f.request.urlencoded_form[b"mitmproxy"] == b"rocks" + assert f.request.urlencoded_form["mitmproxy"] == "rocks" f.request.headers["content-type"] = "" m.request(f) - assert list(f.request.urlencoded_form.items()) == [(b"foo", b"bar")] + assert list(f.request.urlencoded_form.items()) == [("foo", "bar")] def test_modify_querystring(self): m, sc = tscript("simple/modify_querystring.py")
flow.request.urlencoded_form does not work with Unicode parameters in Python 3 ##### Steps to reproduce the problem: 1. Save the following as `test_script.py`: ``` import mitmproxy import json def request(flow): if flow.request.urlencoded_form: mitmproxy.ctx.log(str(flow.request.urlencoded_form)) else: mitmproxy.ctx.log("No form parameters found") ``` 2. Launch `mitmdump` with `mitmdump -s test_script.py` 3. Point your browser to `https://secure.splitwise.com/login`, and try to log in with any username or password (don't worry, you don't need an actual account) The expected behavior is for `flow.request.urlencoded_form` to return a list of form parameters that includes `('utf8', '✓')` (or `(b'utf8', b'%E2%9C%93')`). Instead, `flow.request.urlencoded_form` returns no parameters at all, because it throws an exception trying to process the Unicode `✓` symbol that is included in the form. ##### Any other comments? What have you tried so far? A semi-working fix is to update [this line](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/request.py#L363) to the following: ``` return tuple(mitmproxy.net.http.url.decode(str(self.content))) ``` It appears that `mitmproxy.net.http.url.decode` chokes when trying to process a parameter of the `bytes` type, but it succeeds when processing a parameter of the `str` type. Unfortunately, this also changes the type of the returned tuples from `bytes` to `str`, which probably isn't backwards-compatible with existing usage of mitmproxy. Not sure if there's an easy way to fix that – I plan to keep investigating, but if anyone has suggestions or expertise, I'd appreciate the help! ##### System information ``` Mitmproxy version: 0.19 Python version: 3.5.2 Platform: Darwin-16.1.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.1 ('', '', '') x86_64 ``` /cc @jhottenstein
Thanks for the excellent report! The root cause of this is the following: ```python3 >>> import urrlib >>> urllib.parse.parse_qsl("foo=bar&baz=%E2%9C%93", keep_blank_values=True, errors='surrogateescape') [('foo', 'bar'), ('baz', '✓')] >>> urllib.parse.parse_qsl(b"foo=bar&baz=%E2%9C%93", keep_blank_values=True, errors='surrogateescape') Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> urllib.parse.parse_qsl(b"foo=bar&baz=%E2%9C%93", keep_blank_values=True, errors='surrogateescape') File "C:\Python35\lib\urllib\parse.py", line 628, in parse_qsl value = _coerce_result(value) File "C:\Python35\lib\urllib\parse.py", line 94, in _encode_result return obj.encode(encoding, errors) UnicodeEncodeError: 'ascii' codec can't encode character '\u2713' in position 0: ordinal not in range(128) ``` This seems surprising to me, but who am I to judge. :-) After looking around a bit, your proposal of returning text instead of bytes seems to be the way to go (see: http://stackoverflow.com/a/4073451/934719). While we could implement our own parse_qsl that just works on bytes, browsers apparently always use mutipart/form-data for binary files (see linked SO page), so text is the more elegant API anyway. If you want to send a PR that changes the default behaviour, briefly notes this in the doc string and dass a quick test, I'd be happy to merge that right away! :smiley: Minor nitpick: If you send a PR: please use `self.content.decode()` instead of `str(self.content)` - that makes clear that there always is a strict ascii decode operation. Thanks again! I'll quickly take this over to have it in 1.0!
2016-12-19T00:15:36
mitmproxy/mitmproxy
1,880
mitmproxy__mitmproxy-1880
[ "1877", "1877" ]
cbc0d3fd410f50508fdd7b4cb05bac8f6a18a3a4
diff --git a/mitmproxy/net/http/message.py b/mitmproxy/net/http/message.py --- a/mitmproxy/net/http/message.py +++ b/mitmproxy/net/http/message.py @@ -103,7 +103,11 @@ def get_content(self, strict: bool=True) -> bytes: ce = self.headers.get("content-encoding") if ce: try: - return encoding.decode(self.raw_content, ce) + content = encoding.decode(self.raw_content, ce) + # A client may illegally specify a byte -> str encoding here (e.g. utf8) + if isinstance(content, str): + raise ValueError("Invalid Content-Encoding: {}".format(ce)) + return content except ValueError: if strict: raise
diff --git a/test/mitmproxy/net/http/test_message.py b/test/mitmproxy/net/http/test_message.py --- a/test/mitmproxy/net/http/test_message.py +++ b/test/mitmproxy/net/http/test_message.py @@ -141,6 +141,15 @@ def test_unknown_ce(self): assert r.headers["content-encoding"] assert r.get_content(strict=False) == b"foo" + def test_utf8_as_ce(self): + r = tutils.tresp() + r.headers["content-encoding"] = "utf8" + r.raw_content = b"foo" + with tutils.raises(ValueError): + assert r.content + assert r.headers["content-encoding"] + assert r.get_content(strict=False) == b"foo" + def test_cannot_decode(self): r = tutils.tresp() r.encode("gzip")
Crash when opening specific flows ##### Steps to reproduce the problem: 1. Record a flow with `mitmproxy -T --host` from a specific application 2. Open one of the flows (I can mail you an example) 3. Whole program closes with the following error message ##### Any other comments? What have you tried so far? ``` Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 657, in get_content_view ret = viewmode(data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 138, in __call__ return content_types_map[ct][0](data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 228, in __call__ pj = pretty_json(data) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 55, in pretty_json p = json.loads(s.decode('utf-8')) AttributeError: 'str' object has no attribute 'decode' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/mitmproxy/console/master.py", line 482, in run self.loop.run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/lib/python3.5/site-packages/mitmproxy/console/window.py", line 86, in keypress k = super(self.__class__, self).keypress(size, k) File "/usr/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowlist.py", line 385, in keypress return urwid.ListBox.keypress(self, size, key) File "/usr/lib/python3.5/site-packages/urwid/listbox.py", line 985, in keypress key = focus_widget.keypress((maxcol,),key) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowlist.py", line 238, in keypress self.master.view_flow(self.flow) File "/usr/lib/python3.5/site-packages/mitmproxy/console/master.py", line 576, in view_flow flowview.FlowView(self, self.state, flow, tab_offset), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 143, in __init__ tab_offset File "/usr/lib/python3.5/site-packages/mitmproxy/console/tabs.py", line 31, in __init__ self.show() File "/usr/lib/python3.5/site-packages/mitmproxy/console/tabs.py", line 69, in show body = self.tabs[self.tab_offset][1](), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 166, in view_request return self.conn_text(self.flow.request) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 260, in conn_text msg, body = self.content_view(viewmode, conn) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 203, in content_view flow_modify_cache_invalidation File "/usr/lib/python3.5/site-packages/mitmproxy/utils.py", line 32, in get ret = gen(*args) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 200, in <lambda> lambda *args: self._get_content_view(message, *args), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 208, in _get_content_view viewmode, message File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 635, in get_message_content_view viewmode, content, headers=headers, query=query File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 665, in get_content_view _, content = get("Raw")(data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 156, in __call__ return "Raw", format_text(strutils.bytes_to_escaped_str(data, True)) File "/usr/lib/python3.5/site-packages/netlib/strutils.py", line 88, in bytes_to_escaped_str raise ValueError("data must be bytes, but is {}".format(data.__class__.__name__)) ValueError: data must be bytes, but is str mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` Only some of the Request/Response-pairs causes the crash. It also crashes when loading a saved version of the flow. ##### System information Mitmproxy version: 0.18.2 Python version: 3.5.2 Platform: Linux-4.7.2-1-ARCH-x86_64-with-arch SSL version: OpenSSL 1.0.2h 3 May 2016 Linux distro: arch <!-- Cut and paste the output of "mitmdump --sysinfo". If you're using an older version if mitmproxy, please specify the version and OS. --> Crash when opening specific flows ##### Steps to reproduce the problem: 1. Record a flow with `mitmproxy -T --host` from a specific application 2. Open one of the flows (I can mail you an example) 3. Whole program closes with the following error message ##### Any other comments? What have you tried so far? ``` Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 657, in get_content_view ret = viewmode(data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 138, in __call__ return content_types_map[ct][0](data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 228, in __call__ pj = pretty_json(data) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 55, in pretty_json p = json.loads(s.decode('utf-8')) AttributeError: 'str' object has no attribute 'decode' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/mitmproxy/console/master.py", line 482, in run self.loop.run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/lib/python3.5/site-packages/mitmproxy/console/window.py", line 86, in keypress k = super(self.__class__, self).keypress(size, k) File "/usr/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowlist.py", line 385, in keypress return urwid.ListBox.keypress(self, size, key) File "/usr/lib/python3.5/site-packages/urwid/listbox.py", line 985, in keypress key = focus_widget.keypress((maxcol,),key) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowlist.py", line 238, in keypress self.master.view_flow(self.flow) File "/usr/lib/python3.5/site-packages/mitmproxy/console/master.py", line 576, in view_flow flowview.FlowView(self, self.state, flow, tab_offset), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 143, in __init__ tab_offset File "/usr/lib/python3.5/site-packages/mitmproxy/console/tabs.py", line 31, in __init__ self.show() File "/usr/lib/python3.5/site-packages/mitmproxy/console/tabs.py", line 69, in show body = self.tabs[self.tab_offset][1](), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 166, in view_request return self.conn_text(self.flow.request) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 260, in conn_text msg, body = self.content_view(viewmode, conn) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 203, in content_view flow_modify_cache_invalidation File "/usr/lib/python3.5/site-packages/mitmproxy/utils.py", line 32, in get ret = gen(*args) File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 200, in <lambda> lambda *args: self._get_content_view(message, *args), File "/usr/lib/python3.5/site-packages/mitmproxy/console/flowview.py", line 208, in _get_content_view viewmode, message File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 635, in get_message_content_view viewmode, content, headers=headers, query=query File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 665, in get_content_view _, content = get("Raw")(data, **metadata) File "/usr/lib/python3.5/site-packages/mitmproxy/contentviews.py", line 156, in __call__ return "Raw", format_text(strutils.bytes_to_escaped_str(data, True)) File "/usr/lib/python3.5/site-packages/netlib/strutils.py", line 88, in bytes_to_escaped_str raise ValueError("data must be bytes, but is {}".format(data.__class__.__name__)) ValueError: data must be bytes, but is str mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` Only some of the Request/Response-pairs causes the crash. It also crashes when loading a saved version of the flow. ##### System information Mitmproxy version: 0.18.2 Python version: 3.5.2 Platform: Linux-4.7.2-1-ARCH-x86_64-with-arch SSL version: OpenSSL 1.0.2h 3 May 2016 Linux distro: arch <!-- Cut and paste the output of "mitmdump --sysinfo". If you're using an older version if mitmproxy, please specify the version and OS. -->
For some reason it seems like the data of the request was stored in a string instead of a bytestring, which made the pretty printing functions crash. Adding the following to the top of get_content_view is a workaround (but not a fix): ``` --- /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.old 2016-12-19 14:09:36.816351044 +0100 +++ /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.new 2016-12-19 14:10:34.841016211 +0100 @@ -654,6 +654,8 @@ In contrast to calling the views directly, text is always safe-to-print unicode. """ try: + if isinstance(data, str): + data = data.encode('utf-8') ret = viewmode(data, **metadata) if ret is None: ret = "Couldn't parse: falling back to Raw", get("Raw")(data, **metadata)[1] ``` Could it be possible that you recorded this with Python2/3 but opened it with the other Python version? On Mon, 19 Dec 2016, 14:12 Andreas Källberg, <[email protected]> wrote: > For some reason it seems like the data of the request was stored in a > string instead of a bytestring, which made the pretty printing functions > crash. Adding the following to the top of get_content_view is a workaround > (but not a fix): > > --- /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.old 2016-12-19 14:09:36.816351044 +0100 > +++ /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.new 2016-12-19 14:10:34.841016211 +0100 > @@ -654,6 +654,8 @@ > In contrast to calling the views directly, text is always safe-to-print unicode. > """ > try: > + if isinstance(data, str): > + data = data.encode('utf-8') > ret = viewmode(data, **metadata) > if ret is None: > ret = "Couldn't parse: falling back to Raw", get("Raw")(data, **metadata)[1] > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/1877#issuecomment-267960735>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AA-NPn_BTEa9EOuiz7_5IBsywcj8MdFVks5rJoKegaJpZM4LQfdz> > . > Nope. I got the error even without saving and loading the flows. Just recording (with mitmproxy) and opening (in the same process) while recording is sufficient. For some reason it seems like the data of the request was stored in a string instead of a bytestring, which made the pretty printing functions crash. Adding the following to the top of get_content_view is a workaround (but not a fix): ``` --- /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.old 2016-12-19 14:09:36.816351044 +0100 +++ /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.new 2016-12-19 14:10:34.841016211 +0100 @@ -654,6 +654,8 @@ In contrast to calling the views directly, text is always safe-to-print unicode. """ try: + if isinstance(data, str): + data = data.encode('utf-8') ret = viewmode(data, **metadata) if ret is None: ret = "Couldn't parse: falling back to Raw", get("Raw")(data, **metadata)[1] ``` Could it be possible that you recorded this with Python2/3 but opened it with the other Python version? On Mon, 19 Dec 2016, 14:12 Andreas Källberg, <[email protected]> wrote: > For some reason it seems like the data of the request was stored in a > string instead of a bytestring, which made the pretty printing functions > crash. Adding the following to the top of get_content_view is a workaround > (but not a fix): > > --- /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.old 2016-12-19 14:09:36.816351044 +0100 > +++ /usr/lib/python3.5/site-packages/mitmproxy/contentviews.py.new 2016-12-19 14:10:34.841016211 +0100 > @@ -654,6 +654,8 @@ > In contrast to calling the views directly, text is always safe-to-print unicode. > """ > try: > + if isinstance(data, str): > + data = data.encode('utf-8') > ret = viewmode(data, **metadata) > if ret is None: > ret = "Couldn't parse: falling back to Raw", get("Raw")(data, **metadata)[1] > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/1877#issuecomment-267960735>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AA-NPn_BTEa9EOuiz7_5IBsywcj8MdFVks5rJoKegaJpZM4LQfdz> > . > Nope. I got the error even without saving and loading the flows. Just recording (with mitmproxy) and opening (in the same process) while recording is sufficient.
2016-12-19T15:11:35
mitmproxy/mitmproxy
1,896
mitmproxy__mitmproxy-1896
[ "1894" ]
8185cf27243a7c982ff4c3151045b3d494396740
diff --git a/mitmproxy/utils/typecheck.py b/mitmproxy/utils/typecheck.py --- a/mitmproxy/utils/typecheck.py +++ b/mitmproxy/utils/typecheck.py @@ -1,5 +1,4 @@ import typing -import sys def check_type(attr_name: str, value: typing.Any, typeinfo: type) -> None: @@ -25,10 +24,11 @@ def check_type(attr_name: str, value: typing.Any, typeinfo: type) -> None: typename = str(typeinfo) if typename.startswith("typing.Union"): - if sys.version_info < (3, 6): - types = typeinfo.__union_params__ - else: + try: types = typeinfo.__args__ + except AttributeError: + # Python 3.5.x + types = typeinfo.__union_params__ for T in types: try: @@ -39,10 +39,11 @@ def check_type(attr_name: str, value: typing.Any, typeinfo: type) -> None: return raise e elif typename.startswith("typing.Tuple"): - if sys.version_info < (3, 6): - types = typeinfo.__tuple_params__ - else: + try: types = typeinfo.__args__ + except AttributeError: + # Python 3.5.x + types = typeinfo.__tuple_params__ if not isinstance(value, (tuple, list)): raise e @@ -52,7 +53,11 @@ def check_type(attr_name: str, value: typing.Any, typeinfo: type) -> None: check_type("{}[{}]".format(attr_name, i), x, T) return elif typename.startswith("typing.Sequence"): - T = typeinfo.__args__[0] + try: + T = typeinfo.__args__[0] + except AttributeError: + # Python 3.5.0 + T = typeinfo.__parameters__[0] if not isinstance(value, (tuple, list)): raise e for v in value: @@ -60,6 +65,8 @@ def check_type(attr_name: str, value: typing.Any, typeinfo: type) -> None: elif typename.startswith("typing.IO"): if hasattr(value, "read"): return + else: + raise e elif not isinstance(value, typeinfo): raise e
diff --git a/test/mitmproxy/utils/test_typecheck.py b/test/mitmproxy/utils/test_typecheck.py --- a/test/mitmproxy/utils/test_typecheck.py +++ b/test/mitmproxy/utils/test_typecheck.py @@ -1,6 +1,9 @@ +import io import typing +import mock import pytest + from mitmproxy.utils import typecheck @@ -57,3 +60,17 @@ def test_check_sequence(): typecheck.check_type("foo", [10, "foo"], typing.Sequence[int]) with pytest.raises(TypeError): typecheck.check_type("foo", [b"foo"], typing.Sequence[str]) + with pytest.raises(TypeError): + typecheck.check_type("foo", "foo", typing.Sequence[str]) + + # Python 3.5.0 only defines __parameters__ + m = mock.Mock() + m.__str__ = lambda self: "typing.Sequence" + m.__parameters__ = (int,) + typecheck.check_type("foo", [10], m) + + +def test_check_io(): + typecheck.check_type("foo", io.StringIO(), typing.IO[str]) + with pytest.raises(TypeError): + typecheck.check_type("foo", "foo", typing.IO[str])
type object 'Sequence' has no attribute '__args__' using python3.5.0 ##### Steps to reproduce the problem: 1.pyenv global 3.5.0 2.pip3.5 install mitmproxy 3.mitmproxy -b 10.19.84.140 -p 9999 --no-upstream-cert ##### Any other comments? What have you tried so far? trying to install from brew, and problem still by raising the py3.6.0 problem. 0.15 runs perfectly under python2.7.10 ##### System information Traceback (most recent call last): File "/usr/local/var/pyenv/versions/3.5.0/bin/mitmproxy", line 11, in <module> sys.exit(mitmproxy()) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/tools/main.py", line 67, in mitmproxy console_options = options.Options() File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/options.py", line 117, in __init__ self.client_replay = client_replay File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 111, in __setattr__ self._typecheck(attr, value) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 122, in _typecheck typecheck.check_type(attr, value, expected_type) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/utils/typecheck.py", line 55, in check_type T = typeinfo.__args__[0] AttributeError: type object 'Sequence' has no attribute '__args__' <!-- Traceback (most recent call last): File "/usr/local/var/pyenv/versions/3.5.0/bin/mitmproxy", line 11, in <module> sys.exit(mitmproxy()) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/tools/main.py", line 67, in mitmproxy console_options = options.Options() File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/options.py", line 117, in __init__ self.client_replay = client_replay File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 111, in __setattr__ self._typecheck(attr, value) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 122, in _typecheck typecheck.check_type(attr, value, expected_type) File "/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/site-packages/mitmproxy/utils/typecheck.py", line 55, in check_type T = typeinfo.__args__[0] AttributeError: type object 'Sequence' has no attribute '__args__' -->
I have a similar error, trying to use it on Kali Linux (Debian based distro). Traceback (most recent call last): File "/usr/local/bin/mitmproxy", line 11, in <module> sys.exit(mitmproxy()) File "/usr/local/lib/python3.5/dist-packages/mitmproxy/tools/main.py", line 67, in mitmproxy console_options = options.Options() File "/usr/local/lib/python3.5/dist-packages/mitmproxy/options.py", line 123, in __init__ self.rfile = rfile File "/usr/local/lib/python3.5/dist-packages/mitmproxy/optmanager.py", line 111, in __setattr__ self._typecheck(attr, value) File "/usr/local/lib/python3.5/dist-packages/mitmproxy/optmanager.py", line 122, in _typecheck typecheck.check_type(attr, value, expected_type) File "/usr/local/lib/python3.5/dist-packages/mitmproxy/utils/typecheck.py", line 29, in check_type types = typeinfo.__union_params__ AttributeError: '_Union' object has no attribute '__union_params__' What's your output of `python --version`? mine: ``` ~ » python --version Python 3.5.0 ``` Thanks. Looks like 3.5.2 works, but 3.5.0 doesn't. @CapitanShinChan: What's your output of `pip freeze`?
2016-12-28T12:41:01
mitmproxy/mitmproxy
1,904
mitmproxy__mitmproxy-1904
[ "1901" ]
e83083b64e8293fbd82d6625757d459664306bfc
diff --git a/mitmproxy/tools/console/grideditor/editors.py b/mitmproxy/tools/console/grideditor/editors.py --- a/mitmproxy/tools/console/grideditor/editors.py +++ b/mitmproxy/tools/console/grideditor/editors.py @@ -65,8 +65,8 @@ def handle_key(self, key): class URLEncodedFormEditor(base.GridEditor): title = "Editing URL-encoded form" columns = [ - col_bytes.Column("Key"), - col_bytes.Column("Value") + col_text.Column("Key"), + col_text.Column("Value") ]
ValueError: data must be bytes, but is str Hi , When i use 'e' to edit form , sometimes i get this . ``` ➜ ~ mitmproxy -b 192.168.1.2 -p 8080 Traceback (most recent call last): File "mitmproxy/tools/console/master.py", line 292, in run File "site-packages/urwid/main_loop.py", line 278, in run File "site-packages/urwid/main_loop.py", line 376, in _run File "site-packages/urwid/main_loop.py", line 682, in run File "site-packages/urwid/main_loop.py", line 719, in _loop File "site-packages/urwid/raw_display.py", line 393, in <lambda> File "site-packages/urwid/raw_display.py", line 493, in parse_input File "site-packages/urwid/main_loop.py", line 403, in _update File "site-packages/urwid/main_loop.py", line 503, in process_input File "mitmproxy/tools/console/window.py", line 84, in keypress File "site-packages/urwid/container.py", line 1116, in keypress File "mitmproxy/tools/console/statusbar.py", line 155, in keypress File "mitmproxy/tools/console/statusbar.py", line 108, in keypress File "mitmproxy/tools/console/statusbar.py", line 133, in prompt_execute File "mitmproxy/tools/console/statusbar.py", line 31, in __call__ File "mitmproxy/tools/console/flowview.py", line 415, in edit File "mitmproxy/tools/console/flowview.py", line 351, in edit_form File "mitmproxy/tools/console/master.py", line 352, in view_grideditor File "site-packages/blinker/base.py", line 267, in send File "site-packages/blinker/base.py", line 267, in <listcomp> File "mitmproxy/tools/console/master.py", line 144, in sig_push_view_state File "site-packages/urwid/main_loop.py", line 578, in draw_screen File "site-packages/urwid/widget.py", line 141, in cached_render File "site-packages/urwid/container.py", line 1083, in render File "site-packages/urwid/widget.py", line 141, in cached_render File "site-packages/urwid/decoration.py", line 225, in render File "site-packages/urwid/widget.py", line 141, in cached_render File "site-packages/urwid/widget.py", line 1750, in render File "site-packages/urwid/widget.py", line 141, in cached_render File "site-packages/urwid/container.py", line 1083, in render File "site-packages/urwid/widget.py", line 141, in cached_render File "site-packages/urwid/listbox.py", line 455, in render File "site-packages/urwid/listbox.py", line 337, in calculate_visible File "site-packages/urwid/listbox.py", line 702, in _set_focus_complete File "site-packages/urwid/listbox.py", line 672, in _set_focus_first_selectable File "site-packages/urwid/listbox.py", line 340, in calculate_visible File "mitmproxy/tools/console/grideditor/base.py", line 223, in get_focus File "mitmproxy/tools/console/grideditor/base.py", line 77, in __init__ File "mitmproxy/tools/console/grideditor/col_bytes.py", line 33, in Display File "mitmproxy/tools/console/grideditor/col_bytes.py", line 73, in __init__ File "mitmproxy/utils/strutils.py", line 72, in bytes_to_escaped_str ValueError: data must be bytes, but is str mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` systeminfo: Mitmproxy version: 1.0.0 Python version: 3.5.2 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.11.6 ('', '', '') x86_64
2016-12-30T12:32:03
mitmproxy/mitmproxy
1,905
mitmproxy__mitmproxy-1905
[ "1529" ]
973406f327ceb488d4fa269b57d1e4f342e59d2c
diff --git a/mitmproxy/net/check.py b/mitmproxy/net/check.py --- a/mitmproxy/net/check.py +++ b/mitmproxy/net/check.py @@ -1,6 +1,7 @@ import re -_label_valid = re.compile(b"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) +# Allow underscore in host name +_label_valid = re.compile(b"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE) def is_valid_host(host: bytes) -> bool:
diff --git a/test/mitmproxy/net/test_check.py b/test/mitmproxy/net/test_check.py --- a/test/mitmproxy/net/test_check.py +++ b/test/mitmproxy/net/test_check.py @@ -8,3 +8,5 @@ def test_is_valid_host(): assert check.is_valid_host(b"one.two") assert not check.is_valid_host(b"one" * 255) assert check.is_valid_host(b"one.two.") + # Allow underscore + assert check.is_valid_host(b"one_two")
Gracefully handle underscores in hostnames We need to handle invalid hostnames more gracefully. See the discussion here: https://discourse.mitmproxy.org/t/mitmproxy-not-working-with-urls-which-have-under-scores/ ##### Steps to reproduce the problem: 1. mitmdump -vv 2. env http_proxy=http://localhost:8080 curl "http://foo_bar.com" My inclination here is to make the host matching more liberal, and pass this sort of error upstream. Basically, if I'm using mitmproxy in an analysis situation, and the client is exhibiting this behaviour, I want to see what the server does with it rather than see an error. Either way, we certainly shouldn't be spewing a user-visible traceback to the logs for this kind of protocol error.
2016-12-30T13:07:48
mitmproxy/mitmproxy
1,982
mitmproxy__mitmproxy-1982
[ "1960" ]
79aa99427550e738007e8b87d41e5c097cd06c46
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -230,6 +230,17 @@ def clear(self): self.sig_view_refresh.send(self) self.sig_store_refresh.send(self) + def clear_not_marked(self): + """ + Clears only the unmarked flows. + """ + for flow in self._store.copy().values(): + if not flow.marked: + self._store.pop(flow.id) + + self._refilter() + self.sig_store_refresh.send(self) + def add(self, f: mitmproxy.flow.Flow) -> bool: """ Adds a flow to the state. If the flow already exists, it is diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -35,6 +35,7 @@ def _mkhelp(): ("W", "stream flows to file"), ("X", "kill and delete flow, even if it's mid-intercept"), ("z", "clear flow list or eventlog"), + ("Z", "clear unmarked flows"), ("tab", "tab between eventlog and flow list"), ("enter", "view flow"), ("|", "run script on this flow"), @@ -354,6 +355,8 @@ def keypress(self, size, key): self.master.view.update(f) elif key == "z": self.master.view.clear() + elif key == "Z": + self.master.view.clear_not_marked() elif key == "e": self.master.toggle_eventlog() elif key == "g":
diff --git a/test/mitmproxy/addons/test_view.py b/test/mitmproxy/addons/test_view.py --- a/test/mitmproxy/addons/test_view.py +++ b/test/mitmproxy/addons/test_view.py @@ -108,6 +108,13 @@ def test_simple(): assert list(v) == [f, f3, f2] assert len(v._store) == 3 + f.marked = not f.marked + f2.marked = not f2.marked + v.clear_not_marked() + assert list(v) == [f, f2] + assert len(v) == 2 + assert len(v._store) == 2 + v.clear() assert len(v) == 0 assert len(v._store) == 0
Feature request: Preserve marked flows when clearing flow list When I'm busy in mitmproxy, I often mark an important flow using `m` to preserve it for easy access; my flow list grows pretty quickly even when I'm using a filter, so I often clear the list using `z` to tidy up. Up until very recently clearing the list preserved my marked flows, this was very convenient because I could "clean up" my window and keep what's important (my marked flows) around and continue working. I've installed the latest version (mitmproxy 1.0.2) and I've just noticed that clearing the flow list also removes the marked flows. Could I request this be added as a feature if what I've described was occurring by coincidence, or to be fixed if this is a regression. It is a super handy feature for myself, and hopefully others too. Thanks
This sounds like a reasonable request to me. Maybe we can add this under `Z`? There is also another issue with the flow list. The marked flows can get randomly rearranged whenever `M` or `Z` is pressed, as it iterates through `view._store` which is a dictionary, to refresh the view. @lymanZerga11: Yes, good catch - needs to be replaced with OrderedDict I believe. Can you open a separate issue (or PR 😛) for this please? Yeah okay!
2017-02-02T20:08:50
mitmproxy/mitmproxy
1,984
mitmproxy__mitmproxy-1984
[ "1978" ]
2316c0fb74efefd76970c685b8f77f45834f1490
diff --git a/examples/complex/har_dump.py b/examples/complex/har_dump.py --- a/examples/complex/har_dump.py +++ b/examples/complex/har_dump.py @@ -7,6 +7,7 @@ import sys import base64 import zlib +import os from datetime import datetime import pytz @@ -166,7 +167,7 @@ def done(): if dump_file.endswith('.zhar'): raw = zlib.compress(raw, 9) - with open(dump_file, "wb") as f: + with open(os.path.expanduser(dump_file), "wb") as f: f.write(raw) mitmproxy.ctx.log("HAR dump finished (wrote %s bytes to file)" % len(json_dump)) diff --git a/mitmproxy/net/http/encoding.py b/mitmproxy/net/http/encoding.py --- a/mitmproxy/net/http/encoding.py +++ b/mitmproxy/net/http/encoding.py @@ -31,8 +31,8 @@ def decode(encoded: Union[str, bytes], encoding: str, errors: str='strict') -> U Raises: ValueError, if decoding fails. """ - if len(encoded) == 0: - return encoded + if encoded is None: + return None global _cache cached = ( @@ -72,8 +72,8 @@ def encode(decoded: Union[str, bytes], encoding: str, errors: str='strict') -> U Raises: ValueError, if encoding fails. """ - if len(decoded) == 0: - return decoded + if decoded is None: + return None global _cache cached = ( @@ -86,10 +86,7 @@ def encode(decoded: Union[str, bytes], encoding: str, errors: str='strict') -> U return _cache.encoded try: try: - value = decoded - if isinstance(value, str): - value = decoded.encode() - encoded = custom_encode[encoding](value) + encoded = custom_encode[encoding](decoded) except KeyError: encoded = codecs.encode(decoded, encoding, errors) if encoding in ("gzip", "deflate", "br"): @@ -114,12 +111,14 @@ def identity(content): return content -def decode_gzip(content): +def decode_gzip(content: bytes) -> bytes: + if not content: + return b"" gfile = gzip.GzipFile(fileobj=BytesIO(content)) return gfile.read() -def encode_gzip(content): +def encode_gzip(content: bytes) -> bytes: s = BytesIO() gf = gzip.GzipFile(fileobj=s, mode='wb') gf.write(content) @@ -127,15 +126,17 @@ def encode_gzip(content): return s.getvalue() -def decode_brotli(content): +def decode_brotli(content: bytes) -> bytes: + if not content: + return b"" return brotli.decompress(content) -def encode_brotli(content): +def encode_brotli(content: bytes) -> bytes: return brotli.compress(content) -def decode_deflate(content): +def decode_deflate(content: bytes) -> bytes: """ Returns decompressed data for DEFLATE. Some servers may respond with compressed data without a zlib header or checksum. An undocumented @@ -144,13 +145,15 @@ def decode_deflate(content): http://bugs.python.org/issue5784 """ + if not content: + return b"" try: return zlib.decompress(content) except zlib.error: return zlib.decompress(content, -15) -def encode_deflate(content): +def encode_deflate(content: bytes) -> bytes: """ Returns compressed content, always including zlib header and checksum. """
diff --git a/test/mitmproxy/net/http/test_encoding.py b/test/mitmproxy/net/http/test_encoding.py --- a/test/mitmproxy/net/http/test_encoding.py +++ b/test/mitmproxy/net/http/test_encoding.py @@ -21,26 +21,55 @@ def test_identity(encoder): 'deflate', ]) def test_encoders(encoder): - assert "" == encoding.decode("", encoder) + """ + This test is for testing byte->byte encoding/decoding + """ + assert encoding.decode(None, encoder) is None + assert encoding.encode(None, encoder) is None + assert b"" == encoding.decode(b"", encoder) - assert "string" == encoding.decode( + assert b"string" == encoding.decode( encoding.encode( - "string", + b"string", encoder ), encoder ) - assert b"string" == encoding.decode( + + with pytest.raises(TypeError): + encoding.encode("string", encoder) + + with pytest.raises(TypeError): + encoding.decode("string", encoder) + with pytest.raises(ValueError): + encoding.decode(b"foobar", encoder) + + [email protected]("encoder", [ + 'utf8', + 'latin-1' +]) +def test_encoders_strings(encoder): + """ + This test is for testing byte->str decoding + and str->byte encoding + """ + assert "" == encoding.decode(b"", encoder) + + assert "string" == encoding.decode( encoding.encode( - b"string", + "string", encoder ), encoder ) - with pytest.raises(ValueError): - encoding.decode(b"foobar", encoder) + with pytest.raises(TypeError): + encoding.encode(b"string", encoder) + + with pytest.raises(TypeError): + encoding.decode("foobar", encoder) def test_cache():
Crash of har_dump.py I sometimes get either `b'' is not JSON serializable` or `Object of type 'bytes' is not JSON serializable` I used mitmproxy to extract such a flow and uploaded it [here](https://gist.github.com/Junkern/495d4c7c1b572d7749f0291adfb0dd15) ##### Steps to reproduce the problem: 1. 2. 3. ##### Any other comments? What have you tried so far? It seems, that the error mostly occurs for `POST` and `HEAD` requests. Sometimes with an empty response body, sometimes not. Seldomly a `GET` requests triggers this error ##### System information mitmproxy 1.0.2 macOs Sierra 10.12.3 Edit: Updated the Gist link to point to a working binary gist
Thanks. Could you please upload the flow somewhere else? Gists don't work with binary data, the file is corrupted. I now used <https://github.com/mbostock/gistup> to upload binary data as a gist. [Link](https://gist.github.com/Junkern/495d4c7c1b572d7749f0291adfb0dd15) That works, thanks! A short update from my side: I used the fix from https://github.com/mitmproxy/mitmproxy/pull/1650/files to address this issue. Seems to work as well. @Junkern Does that work in case of an empty response? I implemented the fix in the har_dump and tested it on the flow with an empty response (the one I posted above). No error was thrown
2017-02-03T21:01:58
mitmproxy/mitmproxy
1,988
mitmproxy__mitmproxy-1988
[ "1977" ]
53f298ac41ff812ca69a8220862746f55c1505b8
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -102,7 +102,7 @@ def generate(self, f: mitmproxy.flow.Flow) -> int: class View(collections.Sequence): def __init__(self): super().__init__() - self._store = {} + self._store = collections.OrderedDict() self.filter = matchall # Should we show only marked flows? self.show_marked = False
Change view._store from dictionary to OrderedDict ##### Steps to reproduce the problem: 1. Mark multiple flows in the flow list using `m` key 2. Toggle to show-marked-only view using `M` 3. mitmproxy rearranges flow list when `M` is toggled ##### Any other comments? What have you tried so far? This is an issue with the flow list mentioned earlier in #1960. The marked flows can get randomly rearranged whenever M or Z is pressed, as it iterates through `view._store` which is a dictionary, to refresh the view. ##### System information Mitmproxy version: 2.0.0 (v1.0.1-45-g0022c81) Python version: 3.5.3 Platform: Linux-4.8.2-c9-x86_64-with-debian-jessie-sid SSL version: OpenSSL 1.0.1f 6 Jan 2014 Linux distro: debian jessie/sid <!-- Cut and paste the output of "mitmproxy --version". If you're using an older version if mitmproxy, please specify the version and OS. -->
2017-02-04T12:26:50
mitmproxy/mitmproxy
1,996
mitmproxy__mitmproxy-1996
[ "1580" ]
da8444b11f8bebbb0e0495e4d4d896e2c60e3f02
diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -131,7 +131,7 @@ class HTTPMode(enum.Enum): # At this point, we see only a subset of the proxy modes MODE_REQUEST_FORMS = { HTTPMode.regular: ("authority", "absolute"), - HTTPMode.transparent: ("relative"), + HTTPMode.transparent: ("relative",), HTTPMode.upstream: ("authority", "absolute"), } @@ -143,9 +143,16 @@ def validate_request_form(mode, request): ) allowed_request_forms = MODE_REQUEST_FORMS[mode] if request.first_line_format not in allowed_request_forms: - err_message = "Invalid HTTP request form (expected: %s, got: %s)" % ( - " or ".join(allowed_request_forms), request.first_line_format - ) + if mode == HTTPMode.transparent: + err_message = ( + "Mitmproxy received an {} request even though it is not running in regular mode. " + "This usually indicates a misconfiguration, please see " + "http://docs.mitmproxy.org/en/stable/modes.html for details." + ).format("HTTP CONNECT" if request.first_line_format == "authority" else "absolute-form") + else: + err_message = "Invalid HTTP request form (expected: %s, got: %s)" % ( + " or ".join(allowed_request_forms), request.first_line_format + ) raise exceptions.HttpException(err_message)
diff --git a/test/mitmproxy/protocol/test_http1.py b/test/mitmproxy/protocol/test_http1.py --- a/test/mitmproxy/protocol/test_http1.py +++ b/test/mitmproxy/protocol/test_http1.py @@ -30,6 +30,16 @@ def test_relative_request(self): assert b"Invalid HTTP request form" in r.content +class TestProxyMisconfiguration(tservers.TransparentProxyTest): + + def test_absolute_request(self): + p = self.pathoc() + with p.connect(): + r = p.request("get:'http://localhost:%d/p/200'" % self.server.port) + assert r.status_code == 400 + assert b"misconfiguration" in r.content + + class TestExpectHeader(tservers.HTTPProxyTest): def test_simple(self):
Provide a better error message for proxy mode misconfigurations ##### Steps to reproduce the problem: 1. `mitmproxy -T` 2. `curl -x localhost:8080 example.com` ##### What is the expected behavior? mitmproxy should provide a warning that you want to run either transparent mode or configure an explicit proxy. ##### What went wrong? mitmproxy complains about "Invalid HTTP request form (expected: relative, got: authority)" ##### Any other comments? What have you tried so far? We should just detect this very specific case (expected: relative, got: authority) and provide a better error message for it. See #1579 for a confused user. :stuck_out_tongue: --- Mitmproxy Version: master Operating System: Ubuntu 16.04
Seems like one just needs to throw in another "if" check and raise with a more appropriate exception? If so, I can take care of this. I would like to work on this issue.
2017-02-05T22:53:38
mitmproxy/mitmproxy
2,005
mitmproxy__mitmproxy-2005
[ "1828", "1828" ]
d4264cb719016e02527ce0a2cad533787798266f
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -110,11 +110,16 @@ def __init__(self, callback): self.callback = callback def filter(self, event): + """ + Returns True only when .py file is changed + """ if event.is_directory: return False if os.path.basename(event.src_path).startswith("."): return False - return True + if event.src_path.endswith(".py"): + return True + return False def on_modified(self, event): if self.filter(event):
diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py --- a/test/mitmproxy/addons/test_script.py +++ b/test/mitmproxy/addons/test_script.py @@ -44,14 +44,19 @@ def test_reloadhandler(): rh = script.ReloadHandler(Called()) assert not rh.filter(watchdog.events.DirCreatedEvent("path")) assert not rh.filter(watchdog.events.FileModifiedEvent("/foo/.bar")) - assert rh.filter(watchdog.events.FileModifiedEvent("/foo/bar")) + assert not rh.filter(watchdog.events.FileModifiedEvent("/foo/bar")) + assert rh.filter(watchdog.events.FileModifiedEvent("/foo/bar.py")) assert not rh.callback.called rh.on_modified(watchdog.events.FileModifiedEvent("/foo/bar")) + assert not rh.callback.called + rh.on_modified(watchdog.events.FileModifiedEvent("/foo/bar.py")) assert rh.callback.called rh.callback.called = False rh.on_created(watchdog.events.FileCreatedEvent("foo")) + assert not rh.callback.called + rh.on_created(watchdog.events.FileCreatedEvent("foo.py")) assert rh.callback.called
How to configure file system watchdog (away) for attached scripts Hi folks, I upgraded my local mitmproxy using pip from 0.17 to 0.18.2 and now my script does not work anymore. The mitmproxy is used to connect a local machine with a corporate proxy and measure the traffic in between. The mitmproxy (to be exact, the mitmdump program) is called like this: /usr/local/bin/mitmdump -p 9090 -U 'http://proxy:8080' -s 'tracer.py argument' The `tracer.py` has three functions implemented as described in the [Events Documentation](http://docs.mitmproxy.org/en/latest/scripting/events.html): def start(): # should be called once on startup # so do some initialization here def response(flow): # track the response information def done(): # called at script shutdown In the stdout I see a lot of lines telling me `Reloading script: tracer.py` and if I add a print('hello from start()') to the `start()` function I also see this message in stdout, which means that `start()` gets executed more than once. My search for `Reloading script` pointed me to [the function `tick` in addons/script.py](https://github.com/mitmproxy/mitmproxy/blob/6792cc1de90b02b89da9ae80704ea237c5486e66/mitmproxy/addons/script.py#L185), which seems to be running in a certain interval. The problem I can address so far here is that what happens when `self.should_reload.is_set()` returns `True` while the proxy is running. `should_reload`s internal state is set to `False` by `clear()` in line 187, but it could be set to `True` again by `reload()` in line 175. `reload` is passed as callback to a `ReloadHandler` in line 204, which is connected to a file system watchdog. This sounds similar to the [Scripting Overview](http://docs.mitmproxy.org/en/latest/scripting/overview.html#developing-scripts), > Mitmprxoy monitors scripts for modifications, and reloads them on change. When this happens, the script is shut down (the done event is called), and the new instance is started up as if the script had just been loaded (the start and configure events are called). with the exception, that the `ReloadHandler` reloads the script if _anything_ in the observed directory is changed. So I propose not only to filter directories and files starting with a `.`, but to watch _only_ for files ending with `.py`. ##### System information The output of "mitmdump --sysinfo": Mitmproxy version: 0.18.2 Python version: 2.7.12 Platform: Linux-4.4.0-42-generic-x86_64-with-LinuxMint-18-sarah SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: LinuxMint 18 sarah How to configure file system watchdog (away) for attached scripts Hi folks, I upgraded my local mitmproxy using pip from 0.17 to 0.18.2 and now my script does not work anymore. The mitmproxy is used to connect a local machine with a corporate proxy and measure the traffic in between. The mitmproxy (to be exact, the mitmdump program) is called like this: /usr/local/bin/mitmdump -p 9090 -U 'http://proxy:8080' -s 'tracer.py argument' The `tracer.py` has three functions implemented as described in the [Events Documentation](http://docs.mitmproxy.org/en/latest/scripting/events.html): def start(): # should be called once on startup # so do some initialization here def response(flow): # track the response information def done(): # called at script shutdown In the stdout I see a lot of lines telling me `Reloading script: tracer.py` and if I add a print('hello from start()') to the `start()` function I also see this message in stdout, which means that `start()` gets executed more than once. My search for `Reloading script` pointed me to [the function `tick` in addons/script.py](https://github.com/mitmproxy/mitmproxy/blob/6792cc1de90b02b89da9ae80704ea237c5486e66/mitmproxy/addons/script.py#L185), which seems to be running in a certain interval. The problem I can address so far here is that what happens when `self.should_reload.is_set()` returns `True` while the proxy is running. `should_reload`s internal state is set to `False` by `clear()` in line 187, but it could be set to `True` again by `reload()` in line 175. `reload` is passed as callback to a `ReloadHandler` in line 204, which is connected to a file system watchdog. This sounds similar to the [Scripting Overview](http://docs.mitmproxy.org/en/latest/scripting/overview.html#developing-scripts), > Mitmprxoy monitors scripts for modifications, and reloads them on change. When this happens, the script is shut down (the done event is called), and the new instance is started up as if the script had just been loaded (the start and configure events are called). with the exception, that the `ReloadHandler` reloads the script if _anything_ in the observed directory is changed. So I propose not only to filter directories and files starting with a `.`, but to watch _only_ for files ending with `.py`. ##### System information The output of "mitmdump --sysinfo": Mitmproxy version: 0.18.2 Python version: 2.7.12 Platform: Linux-4.4.0-42-generic-x86_64-with-LinuxMint-18-sarah SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: LinuxMint 18 sarah
Thanks for the report! While there are cases where always-reload is useful, only reloading on *.py files seems to be a reasonable default to me. Judging from bug reports, this seems to be a common annoyance right now. If we want to have the always-reload functioanlity again, we could make that configurable at some point. @cortesi, IIRC you championed the "always-reload" paradigm - would you be okay with having *.py-reload only by default? I think we have to accept that we can never cater perfectly for all use-cases here, and that someone is always going to be surprised whatever behaviour is chosen. I am OK with either strategy, as long as it's clearly documented. I also have a strawman proposal - maybe mitmproxy shouldn't be doing this at all. Instead, we can provide a script-reload function through a web API, and let users use a tool like [modd](https://github.com/cortesi/modd) instead to get precisely the behaviour they expect. This would also remove one of our trickier dependencies. The idea of auto-reloading is not so bad (you can reload by simply `touch`ing), but the current implementation is somehow surprising, as it observes the whole directory, while the documentation only mentions the actual script. @RobbBienert: If @cortesi is fine with either behaviour, I think we'd be more than happy to accept a PR that changes the implementation (and updates the docs)! :smiley: You've probably seen this already, the place to fix this is [`mitmproxy/addons/script.py#L124`](https://github.com/mitmproxy/mitmproxy/blob/6792cc1de90b02b89da9ae80704ea237c5486e66/mitmproxy/addons/script.py#L124)! 😊 I'm back again and working on the fix -- see pull request #1911 Thanks for the report! While there are cases where always-reload is useful, only reloading on *.py files seems to be a reasonable default to me. Judging from bug reports, this seems to be a common annoyance right now. If we want to have the always-reload functioanlity again, we could make that configurable at some point. @cortesi, IIRC you championed the "always-reload" paradigm - would you be okay with having *.py-reload only by default? I think we have to accept that we can never cater perfectly for all use-cases here, and that someone is always going to be surprised whatever behaviour is chosen. I am OK with either strategy, as long as it's clearly documented. I also have a strawman proposal - maybe mitmproxy shouldn't be doing this at all. Instead, we can provide a script-reload function through a web API, and let users use a tool like [modd](https://github.com/cortesi/modd) instead to get precisely the behaviour they expect. This would also remove one of our trickier dependencies. The idea of auto-reloading is not so bad (you can reload by simply `touch`ing), but the current implementation is somehow surprising, as it observes the whole directory, while the documentation only mentions the actual script. @RobbBienert: If @cortesi is fine with either behaviour, I think we'd be more than happy to accept a PR that changes the implementation (and updates the docs)! :smiley: You've probably seen this already, the place to fix this is [`mitmproxy/addons/script.py#L124`](https://github.com/mitmproxy/mitmproxy/blob/6792cc1de90b02b89da9ae80704ea237c5486e66/mitmproxy/addons/script.py#L124)! 😊 I'm back again and working on the fix -- see pull request #1911
2017-02-10T15:33:20
mitmproxy/mitmproxy
2,015
mitmproxy__mitmproxy-2015
[ "2014" ]
f77cf03543d89a9503cd86fb48fe4d9d32b57190
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -37,7 +37,6 @@ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security", "Topic :: Internet", "Topic :: Internet :: WWW/HTTP",
Remove pypy support Officially mitmproxy still claims to support pypy. However, I can't remember seeing any test runs - let alone successful ones. mitmproxy requires Python 3.5+, but pypy currently only offers a Python3.3 compatible release. We should therefore remove pypy-related things from `setup.py` and `.travis.yml`.
2017-02-12T11:32:59
mitmproxy/mitmproxy
2,029
mitmproxy__mitmproxy-2029
[ "1722", "1734" ]
4aa656f2a6a2791d5fd78fa5ac40ad35b2044fb9
diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py --- a/mitmproxy/addons/proxyauth.py +++ b/mitmproxy/addons/proxyauth.py @@ -1,35 +1,43 @@ import binascii +import weakref +from typing import Optional +from typing import Set # noqa +from typing import Tuple import passlib.apache +import mitmproxy.net.http +from mitmproxy import connections # noqa from mitmproxy import exceptions from mitmproxy import http -import mitmproxy.net.http - +from mitmproxy.net.http import status_codes REALM = "mitmproxy" -def mkauth(username, password, scheme="basic"): +def mkauth(username: str, password: str, scheme: str = "basic") -> str: + """ + Craft a basic auth string + """ v = binascii.b2a_base64( (username + ":" + password).encode("utf8") ).decode("ascii") return scheme + " " + v -def parse_http_basic_auth(s): - words = s.split() - if len(words) != 2: - return None - scheme = words[0] +def parse_http_basic_auth(s: str) -> Tuple[str, str, str]: + """ + Parse a basic auth header. + Raises a ValueError if the input is invalid. + """ + scheme, authinfo = s.split() + if scheme.lower() != "basic": + raise ValueError("Unknown scheme") try: - user = binascii.a2b_base64(words[1]).decode("utf8", "replace") - except binascii.Error: - return None - parts = user.split(':') - if len(parts) != 2: - return None - return scheme, parts[0], parts[1] + user, password = binascii.a2b_base64(authinfo.encode()).decode("utf8", "replace").split(":") + except binascii.Error as e: + raise ValueError(str(e)) + return scheme, user, password class ProxyAuth: @@ -37,67 +45,72 @@ def __init__(self): self.nonanonymous = False self.htpasswd = None self.singleuser = None + self.mode = None + self.authenticated = weakref.WeakSet() # type: Set[connections.ClientConnection] + """Contains all connections that are permanently authenticated after an HTTP CONNECT""" - def enabled(self): + def enabled(self) -> bool: return any([self.nonanonymous, self.htpasswd, self.singleuser]) - def which_auth_header(self, f): - if f.mode == "regular": + def is_proxy_auth(self) -> bool: + """ + Returns: + - True, if authentication is done as if mitmproxy is a proxy + - False, if authentication is done as if mitmproxy is a HTTP server + """ + return self.mode in ("regular", "upstream") + + def which_auth_header(self) -> str: + if self.is_proxy_auth(): return 'Proxy-Authorization' else: return 'Authorization' - def auth_required_response(self, f): - if f.mode == "regular": - hdrname = 'Proxy-Authenticate' - else: - hdrname = 'WWW-Authenticate' - - headers = mitmproxy.net.http.Headers() - headers[hdrname] = 'Basic realm="%s"' % REALM - - if f.mode == "transparent": + def auth_required_response(self) -> http.HTTPResponse: + if self.is_proxy_auth(): return http.make_error_response( - 401, - "Authentication Required", - headers + status_codes.PROXY_AUTH_REQUIRED, + headers=mitmproxy.net.http.Headers(Proxy_Authenticate='Basic realm="{}"'.format(REALM)), ) else: return http.make_error_response( - 407, - "Proxy Authentication Required", - headers, + status_codes.UNAUTHORIZED, + headers=mitmproxy.net.http.Headers(WWW_Authenticate='Basic realm="{}"'.format(REALM)), ) - def check(self, f): - auth_value = f.request.headers.get(self.which_auth_header(f), None) - if not auth_value: - return False - parts = parse_http_basic_auth(auth_value) - if not parts: - return False - scheme, username, password = parts - if scheme.lower() != 'basic': - return False + def check(self, f: http.HTTPFlow) -> Optional[Tuple[str, str]]: + """ + Check if a request is correctly authenticated. + Returns: + - a (username, password) tuple if successful, + - None, otherwise. + """ + auth_value = f.request.headers.get(self.which_auth_header(), "") + try: + scheme, username, password = parse_http_basic_auth(auth_value) + except ValueError: + return None if self.nonanonymous: - pass + return username, password elif self.singleuser: - if [username, password] != self.singleuser: - return False + if self.singleuser == [username, password]: + return username, password elif self.htpasswd: - if not self.htpasswd.check_password(username, password): - return False - else: - raise NotImplementedError("Should never happen.") + if self.htpasswd.check_password(username, password): + return username, password - return True + return None - def authenticate(self, f): - if self.check(f): - del f.request.headers[self.which_auth_header(f)] + def authenticate(self, f: http.HTTPFlow) -> bool: + valid_credentials = self.check(f) + if valid_credentials: + f.metadata["proxyauth"] = valid_credentials + del f.request.headers[self.which_auth_header()] + return True else: - f.response = self.auth_required_response(f) + f.response = self.auth_required_response() + return False # Handlers def configure(self, options, updated): @@ -125,24 +138,28 @@ def configure(self, options, updated): ) else: self.htpasswd = None + if "mode" in updated: + self.mode = options.mode if self.enabled(): if options.mode == "transparent": raise exceptions.OptionsError( "Proxy Authentication not supported in transparent mode." ) - elif options.mode == "socks5": + if options.mode == "socks5": raise exceptions.OptionsError( "Proxy Authentication not supported in SOCKS mode. " "https://github.com/mitmproxy/mitmproxy/issues/738" ) - # TODO: check for multiple auth options + # TODO: check for multiple auth options - def http_connect(self, f): - if self.enabled() and f.mode == "regular": - self.authenticate(f) + def http_connect(self, f: http.HTTPFlow) -> None: + if self.enabled(): + if self.authenticate(f): + self.authenticated.add(f.client_conn) - def requestheaders(self, f): + def requestheaders(self, f: http.HTTPFlow) -> None: if self.enabled(): - # Are we already authenticated in CONNECT? - if not (f.mode == "regular" and f.server_conn.via): - self.authenticate(f) + # Is this connection authenticated by a previous HTTP CONNECT? + if f.client_conn in self.authenticated: + return + self.authenticate(f) diff --git a/mitmproxy/http.py b/mitmproxy/http.py --- a/mitmproxy/http.py +++ b/mitmproxy/http.py @@ -1,4 +1,5 @@ -import cgi +import html +from typing import Optional from mitmproxy import flow @@ -203,16 +204,27 @@ def replace(self, pattern, repl, *args, **kwargs): return c -def make_error_response(status_code, message, headers=None): - response = http.status_codes.RESPONSES.get(status_code, "Unknown") +def make_error_response( + status_code: int, + message: str="", + headers: Optional[http.Headers]=None, +) -> HTTPResponse: + reason = http.status_codes.RESPONSES.get(status_code, "Unknown") body = """ <html> <head> - <title>%d %s</title> + <title>{status_code} {reason}</title> </head> - <body>%s</body> + <body> + <h1>{status_code} {reason}</h1> + <p>{message}</p> + </body> </html> - """.strip() % (status_code, response, cgi.escape(message)) + """.strip().format( + status_code=status_code, + reason=reason, + message=html.escape(message), + ) body = body.encode("utf8", "replace") if not headers: @@ -226,7 +238,7 @@ def make_error_response(status_code, message, headers=None): return HTTPResponse( b"HTTP/1.1", status_code, - response, + reason, headers, body, )
diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py --- a/test/mitmproxy/addons/test_proxyauth.py +++ b/test/mitmproxy/addons/test_proxyauth.py @@ -1,21 +1,27 @@ import binascii + import pytest from mitmproxy import exceptions +from mitmproxy.addons import proxyauth from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy.test import tutils -from mitmproxy.addons import proxyauth def test_parse_http_basic_auth(): assert proxyauth.parse_http_basic_auth( proxyauth.mkauth("test", "test") ) == ("basic", "test", "test") - assert not proxyauth.parse_http_basic_auth("") - assert not proxyauth.parse_http_basic_auth("foo bar") - v = "basic " + binascii.b2a_base64(b"foo").decode("ascii") - assert not proxyauth.parse_http_basic_auth(v) + with pytest.raises(ValueError): + proxyauth.parse_http_basic_auth("") + with pytest.raises(ValueError): + proxyauth.parse_http_basic_auth("foo bar") + with pytest.raises(ValueError): + proxyauth.parse_http_basic_auth("basic abc") + with pytest.raises(ValueError): + v = "basic " + binascii.b2a_base64(b"foo").decode("ascii") + proxyauth.parse_http_basic_auth(v) def test_configure(): @@ -42,14 +48,14 @@ def test_configure(): ctx.configure( up, - auth_htpasswd = tutils.test_data.path( + auth_htpasswd=tutils.test_data.path( "mitmproxy/net/data/htpasswd" ) ) assert up.htpasswd assert up.htpasswd.check_password("test", "test") assert not up.htpasswd.check_password("test", "foo") - ctx.configure(up, auth_htpasswd = None) + ctx.configure(up, auth_htpasswd=None) assert not up.htpasswd with pytest.raises(exceptions.OptionsError): @@ -57,11 +63,14 @@ def test_configure(): with pytest.raises(exceptions.OptionsError): ctx.configure(up, auth_nonanonymous=True, mode="socks5") + ctx.configure(up, mode="regular") + assert up.mode == "regular" + def test_check(): up = proxyauth.ProxyAuth() with taddons.context() as ctx: - ctx.configure(up, auth_nonanonymous=True) + ctx.configure(up, auth_nonanonymous=True, mode="regular") f = tflow.tflow() assert not up.check(f) f.request.headers["Proxy-Authorization"] = proxyauth.mkauth( @@ -73,7 +82,7 @@ def test_check(): assert not up.check(f) f.request.headers["Proxy-Authorization"] = proxyauth.mkauth( - "test", "test", scheme = "unknown" + "test", "test", scheme="unknown" ) assert not up.check(f) @@ -87,8 +96,8 @@ def test_check(): ctx.configure( up, - auth_singleuser = None, - auth_htpasswd = tutils.test_data.path( + auth_singleuser=None, + auth_htpasswd=tutils.test_data.path( "mitmproxy/net/data/htpasswd" ) ) @@ -105,7 +114,7 @@ def test_check(): def test_authenticate(): up = proxyauth.ProxyAuth() with taddons.context() as ctx: - ctx.configure(up, auth_nonanonymous=True) + ctx.configure(up, auth_nonanonymous=True, mode="regular") f = tflow.tflow() assert not f.response @@ -121,13 +130,12 @@ def test_authenticate(): assert not f.request.headers.get("Proxy-Authorization") f = tflow.tflow() - f.mode = "transparent" + ctx.configure(up, mode="reverse") assert not f.response up.authenticate(f) assert f.response.status_code == 401 f = tflow.tflow() - f.mode = "transparent" f.request.headers["Authorization"] = proxyauth.mkauth( "test", "test" ) @@ -139,7 +147,7 @@ def test_authenticate(): def test_handlers(): up = proxyauth.ProxyAuth() with taddons.context() as ctx: - ctx.configure(up, auth_nonanonymous=True) + ctx.configure(up, auth_nonanonymous=True, mode="regular") f = tflow.tflow() assert not f.response @@ -151,3 +159,15 @@ def test_handlers(): assert not f.response up.http_connect(f) assert f.response.status_code == 407 + + f = tflow.tflow() + f.request.method = "CONNECT" + f.request.headers["Proxy-Authorization"] = proxyauth.mkauth( + "test", "test" + ) + up.http_connect(f) + assert not f.response + + f2 = tflow.tflow(client_conn=f.client_conn) + up.requestheaders(f2) + assert not f2.response
Proxy-Authentication does not work with HTTPS sites ##### Steps to reproduce the problem: 1. `mitmdump --nonanonymous` 2. `curl -x localhost:8080 -k -U foo:bar http://example.com` (works) 3. `curl -x localhost:8080 -k -U foo:bar https://example.com` (doesn't) ##### Any other comments? What have you tried so far? The problem is an invalid handling of `http_authenticated`. Ensure that addons can access auth credentials from clients See #1732 by @martyn-w for the motivation and discussion.
This is still an issue after the latest changes. Just to note that we have experienced exactly the same issue with MITMProxy 0.18.2, but not with 0.17.1. The problem seems to be the use of "transparent mode" in the low-level http interaction between the proxy and the upstream server; even when non-transparent mode is selected. For example: # MITMProxy 0.17.1 $ mitmdump --version mitmdump 0.17.1 $ mitmdump --cadir ~/path/to/certificates --nonanonymous (another terminal) $ curl -x "http://foo:[email protected]:8080" "https://www.google.co.uk/" 127.0.0.1:45260: clientconnect 127.0.0.1 GET https://www.google.co.uk/ << 200 OK 10.1kB 127.0.0.1:45260: clientdisconnect Compared with: $ mitmdump --version mitmdump 0.18.2 $ mitmdump --cadir ~/path/to/certificates --nonanonymous Proxy server listening at http://0.0.0.0:8080 (another terminal) $ curl -x "http://foo:[email protected]:8080" "https://www.google.co.uk/" <html> <head> <title>401 Unauthorized</title> </head> <body>Authentication Required</body> </html>Zippy:~ martyn$ 127.0.0.1:45262: clientconnect 127.0.0.1:45262: clientdisconnect
2017-02-15T00:50:46
mitmproxy/mitmproxy
2,035
mitmproxy__mitmproxy-2035
[ "1916" ]
4cec88fc7fcf8a5c16c0639961c27792cd73af13
diff --git a/mitmproxy/net/http/http1/read.py b/mitmproxy/net/http/http1/read.py --- a/mitmproxy/net/http/http1/read.py +++ b/mitmproxy/net/http/http1/read.py @@ -227,7 +227,7 @@ def _get_first_line(rfile): if line == b"\r\n" or line == b"\n": # Possible leftover from previous message line = rfile.readline() - except exceptions.TcpDisconnect: + except (exceptions.TcpDisconnect, exceptions.TlsException): raise exceptions.HttpReadDisconnect("Remote disconnected") if not line: raise exceptions.HttpReadDisconnect("Remote disconnected")
mitmproxy has crashed: ETIMEDOUT Hi, I've been analysing an android app's traffic for a few weeks now without any problem and today mitmdump started crashing with the following stacktrace: ``` mitmdump -T --host -s analysis.py 192.168.0.103:49825: clientconnect 192.168.0.103:36334: Traceback (most recent call last): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 211, in read data = self.o.read(rlen) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1304, in recv self._raise_ssl_error(self._ssl, result) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1166, in _raise_ssl_error raise SysCallError(errno, errorcode.get(errno)) OpenSSL.SSL.SysCallError: (60, 'ETIMEDOUT') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/server.py", line 119, in handle root_layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/modes/transparent_proxy.py", line 19, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/tls.py", line 383, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http.py", line 176, in __call__ if not self._process_flow(flow): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http.py", line 227, in _process_flow request = self.read_request_headers(f) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http1.py", line 14, in read_request_headers http1.read_request_head(self.client_conn.rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 52, in read_request_head form, method, scheme, host, port, path, http_version = _read_request_line(rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 240, in _read_request_line line = _get_first_line(rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 227, in _get_first_line line = rfile.readline() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 251, in readline ch = self.read(1) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 233, in read raise exceptions.TlsException(str(e)) mitmproxy.exceptions.TlsException: (60, 'ETIMEDOUT') Traceback (most recent call last): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 211, in read data = self.o.read(rlen) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1304, in recv self._raise_ssl_error(self._ssl, result) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/OpenSSL/SSL.py", line 1166, in _raise_ssl_error raise SysCallError(errno, errorcode.get(errno)) OpenSSL.SSL.SysCallError: (60, 'ETIMEDOUT') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/server.py", line 119, in handle root_layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/modes/transparent_proxy.py", line 19, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/tls.py", line 383, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http1.py", line 72, in __call__ layer() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http.py", line 176, in __call__ if not self._process_flow(flow): File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http.py", line 227, in _process_flow request = self.read_request_headers(f) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/proxy/protocol/http1.py", line 14, in read_request_headers http1.read_request_head(self.client_conn.rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 52, in read_request_head form, method, scheme, host, port, path, http_version = _read_request_line(rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 240, in _read_request_line line = _get_first_line(rfile) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/http/http1/read.py", line 227, in _get_first_line line = rfile.readline() File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 251, in readline ch = self.read(1) File "/Users/mycomputer/development/python/analysis/.venv/lib/python3.5/site-packages/mitmproxy/net/tcp.py", line 233, in read raise exceptions.TlsException(str(e)) mitmproxy.exceptions.TlsException: (60, 'ETIMEDOUT') mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` Since it nicely asked ti lodge a report, here I am. I was running v0.18.2 but after this I've tried the latest build (v1.0.2) and still experiencing the same issue. ##### Steps to reproduce the problem: 1. `mitmdump -T --host -s analysis.py` ##### Any other comments? What have you tried so far? Tried to run `mitmproxy -T --host` instead, same result. ##### System information $ mitmdump --sysinfo Mitmproxy version: 1.0.2 Python version: 3.5.1 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.11.6 ('', '', '') x86_64
Thanks! ETIMEDOUT is weird. How do you connect your Android app to mitmproxy? Hey! I changed the wifi settings to use my computer as the gateway. I'm also using ip forwarding by following the instructions in [docs > OSX](http://docs.mitmproxy.org/en/stable/transparent/osx.html?highlight=pfctl). Update: for the last 2 days I haven't seen the issue. At the time I was experiencing it coincided with an app update, where lots of downloads were happening from their servers. I'm now thinking this issue may have some correlation with latency from app's servers. Thanks for reporting back, happy to hear it works again. This certainly was an issue with your network, as it seems between client and mitmproxy. Nonetheless, we should not crash, so this remains open. 😃
2017-02-17T21:43:03
mitmproxy/mitmproxy
2,041
mitmproxy__mitmproxy-2041
[ "2033" ]
6a1e03ac6f5fbbfda70200d465cfb2f7cc01d253
diff --git a/mitmproxy/utils/debug.py b/mitmproxy/utils/debug.py --- a/mitmproxy/utils/debug.py +++ b/mitmproxy/utils/debug.py @@ -37,8 +37,12 @@ def dump_system_info(): except: pass + bin_indicator = "" # PyInstaller builds indicator, if using precompiled binary + if getattr(sys, 'frozen', False): + bin_indicator = "Precompiled Binary" + data = [ - "Mitmproxy version: {} ({})".format(version.VERSION, git_describe), + "Mitmproxy version: {} ({}) {}".format(version.VERSION, git_describe, bin_indicator), "Python version: {}".format(platform.python_version()), "Platform: {}".format(platform.platform()), "SSL version: {}".format(SSL.SSLeay_version(SSL.SSLEAY_VERSION).decode()),
diff --git a/test/mitmproxy/utils/test_debug.py b/test/mitmproxy/utils/test_debug.py --- a/test/mitmproxy/utils/test_debug.py +++ b/test/mitmproxy/utils/test_debug.py @@ -1,11 +1,13 @@ import io import subprocess +import sys from unittest import mock from mitmproxy.utils import debug def test_dump_system_info(): + setattr(sys, 'frozen', True) assert debug.dump_system_info() with mock.patch('subprocess.check_output') as m:
Add PyInstaller indicator to `mitmproxy --version` We currently cannot distinguish if users use our precompiled binaries or if they installed mitmproxy using pip/brew/$packagemanager. It would be very useful to output if we are running the precompiled PyInstaller binary. https://pythonhosted.org/PyInstaller/runtime-information.html
Use of precompiled binaries can be detected (I'll send a PR by tomorrow) but how would it distinguish between the other cases (system package / pip / source), or it just wouldn't be necessary? As first step, identifying pyinstaller builds is good enough. We already distinguish between release versions and git-based installations based on `git describe` and tags. Sure, thanks!
2017-02-18T01:08:53
mitmproxy/mitmproxy
2,048
mitmproxy__mitmproxy-2048
[ "1938" ]
18401dda8f293434410fba066afe9235740be98b
diff --git a/mitmproxy/net/check.py b/mitmproxy/net/check.py --- a/mitmproxy/net/check.py +++ b/mitmproxy/net/check.py @@ -1,3 +1,4 @@ +import ipaddress import re # Allow underscore in host name @@ -6,17 +7,26 @@ def is_valid_host(host: bytes) -> bool: """ - Checks if a hostname is valid. + Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address. """ try: host.decode("idna") except ValueError: return False + # RFC1035: 255 bytes or less. if len(host) > 255: return False if host and host[-1:] == b".": host = host[:-1] - return all(_label_valid.match(x) for x in host.split(b".")) + # DNS hostname + if all(_label_valid.match(x) for x in host.split(b".")): + return True + # IPv4/IPv6 address + try: + ipaddress.ip_address(host.decode('idna')) + return True + except ValueError: + return False def is_valid_port(port):
diff --git a/test/mitmproxy/net/test_check.py b/test/mitmproxy/net/test_check.py --- a/test/mitmproxy/net/test_check.py +++ b/test/mitmproxy/net/test_check.py @@ -11,3 +11,4 @@ def test_is_valid_host(): assert check.is_valid_host(b"one.two.") # Allow underscore assert check.is_valid_host(b"one_two") + assert check.is_valid_host(b"::1")
Support absolute-form HTTP requests with IPv6 addresses ##### Steps to reproduce the problem: 1. MITMDump proxy IPv6 flow 2. Log ``` 172.17.15.1:53074: HTTP protocol error in client request: Bad HTTP request line: b'GET http://[::ffff:180.97.8.37]/mmsns/9KavCVwReibwDKBMmibrWUdVZZbHCQ0bV3R89mboKO6QDls7Sxcl4tfbHvLIHFbj3NASftTH2VAGw/150?tp=wxpc&length=2208&width=1242&idx=1&token=WSEN6qDsKwV8A02w3onOGQYfxnkibdqSOkmHhZGNB4DGicdGyTltMQXCTF7lr4IJR8Jz4lKQBBW47EV1CP33SGjg HTTP/1.1' 172.17.15.1:53075: HTTP protocol error in client request: Bad HTTP request line: b'GET http://[::ffff:b461:819]/mmcrhead/Q3auHgzwzM606QEH0kXoF60vMh5Iiay7B3DiauET3kCpbBwEfgzhNqOSeJ6y4geORGPxEcKf36Totd4sHQcwvBEg/0 HTTP/1.1' ``` ##### Any other comments? What have you tried so far? No ##### System information ``` Mitmproxy version: 1.0.2 Python version: 3.6.0 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.11.6 ('', '', '') x86_6 ```
Thanks for the report!
2017-02-20T14:41:39
mitmproxy/mitmproxy
2,051
mitmproxy__mitmproxy-2051
[ "1928", "1928" ]
18401dda8f293434410fba066afe9235740be98b
diff --git a/mitmproxy/script/concurrent.py b/mitmproxy/script/concurrent.py --- a/mitmproxy/script/concurrent.py +++ b/mitmproxy/script/concurrent.py @@ -29,4 +29,8 @@ def run(): "script.concurrent (%s)" % fn.__name__, target=run ).start() - return _concurrent + # Support @concurrent for class-based addons + if "." in fn.__qualname__: + return staticmethod(_concurrent) + else: + return _concurrent
diff --git a/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py b/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py @@ -0,0 +1,13 @@ +import time +from mitmproxy.script import concurrent + + +class ConcurrentClass: + + @concurrent + def request(flow): + time.sleep(0.1) + + +def start(): + return ConcurrentClass() diff --git a/test/mitmproxy/script/test_concurrent.py b/test/mitmproxy/script/test_concurrent.py --- a/test/mitmproxy/script/test_concurrent.py +++ b/test/mitmproxy/script/test_concurrent.py @@ -44,3 +44,21 @@ def test_concurrent_err(self): ) sc.start() assert "decorator not supported" in tctx.master.event_log[0][1] + + def test_concurrent_class(self): + with taddons.context() as tctx: + sc = script.Script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/concurrent_decorator_class.py" + ) + ) + sc.start() + + f1, f2 = tflow.tflow(), tflow.tflow() + tctx.cycle(sc, f1) + tctx.cycle(sc, f2) + start = time.time() + while time.time() - start < 5: + if f1.reply.state == f2.reply.state == "committed": + return + raise ValueError("Script never acked")
@concurrent annotation doesn't work in the OOP script method I.E: ``` class SomeClass: @concurrent [doesn't work, 2 args] def request(self, flow): pass ``` @concurrent annotation doesn't work in the OOP script method I.E: ``` class SomeClass: @concurrent [doesn't work, 2 args] def request(self, flow): pass ```
Good catch - thanks! Good catch - thanks!
2017-02-21T07:23:00
mitmproxy/mitmproxy
2,067
mitmproxy__mitmproxy-2067
[ "2065" ]
19b2208c27ac0d1240462377d34a727c3fada53d
diff --git a/mitmproxy/tools/console/flowview.py b/mitmproxy/tools/console/flowview.py --- a/mitmproxy/tools/console/flowview.py +++ b/mitmproxy/tools/console/flowview.py @@ -681,7 +681,7 @@ def encode_callback(self, key, conn): encoding_map = { "z": "gzip", "d": "deflate", - "b": "brotli", + "b": "br", } conn.encode(encoding_map[key]) signals.flow_change.send(self, flow = self.flow)
brotli encode/decode crash ##### Steps to reproduce the problem: 1. load google.com in browser 2. press `enter` on `GET https://www.google.com/ HTTP/2.0` 3. press `z` to select encoding in either `Request` or `Response` 4. press `b` to select brotli ##### Any other comments? What have you tried so far? ``` Traceback (most recent call last): File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/master.py", line 281, in run self.loop.run() File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/home/whackashoe/code/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1116, in keypress return self.footer.keypress((maxcol,),key) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 155, in keypress return self.master.ab.keypress(*args, **kwargs) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 108, in keypress self.prompt_execute(k) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 133, in prompt_execute msg = p(txt) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/statusbar.py", line 31, in __call__ return self.callback(txt, *self.args) File "/home/whackashoe/code/mitmproxy/mitmproxy/tools/console/flowview.py", line 686, in encode_callback conn.encode(encoding_map[key]) File "/home/whackashoe/code/mitmproxy/mitmproxy/net/http/message.py", line 245, in encode raise ValueError("Invalid content encoding {}".format(repr(e))) ValueError: Invalid content encoding 'brotli' ``` Here is a patch which suppresses the error: ``` diff --git a/mitmproxy/tools/console/flowview.py b/mitmproxy/tools/console/flowview.py index a97a9b3..650ef42 100644 --- a/mitmproxy/tools/console/flowview.py +++ b/mitmproxy/tools/console/flowview.py @@ -683,5 +683,9 @@ class FlowView(tabs.Tabs): "d": "deflate", "b": "brotli", } - conn.encode(encoding_map[key]) + try: + conn.encode(encoding_map[key]) + except ValueError: + pass + signals.flow_change.send(self, flow = self.flow) ``` ##### System information ``` $ mitmproxy --version Mitmproxy version: 3.0.0 (2.0.0dev0020-0x2aecffd) Python version: 3.5.0 Platform: Linux-3.13.0-107-generic-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2k 26 Jan 2017 Linux distro: Ubuntu 14.04 trusty ```
Thanks. I think the actual bug here is that we should invoke the encoding with "br", not "brotli".
2017-02-26T20:51:45
mitmproxy/mitmproxy
2,069
mitmproxy__mitmproxy-2069
[ "2068" ]
0fdf2c0f4be5c6522ff3d5dd586e1e23b9f545ad
diff --git a/mitmproxy/tools/console/palettepicker.py b/mitmproxy/tools/console/palettepicker.py --- a/mitmproxy/tools/console/palettepicker.py +++ b/mitmproxy/tools/console/palettepicker.py @@ -43,7 +43,7 @@ def mkopt(name): i, None, lambda: self.master.options.console_palette == name, - lambda: setattr(self.master.options, "palette", name) + lambda: setattr(self.master.options, "console_palette", name) ) for i in high: @@ -59,7 +59,7 @@ def mkopt(name): "Transparent", "T", lambda: master.options.console_palette_transparent, - master.options.toggler("palette_transparent") + master.options.toggler("console_palette_transparent") ) ] )
Entering Palette options crashes mitmproxy ##### Steps to reproduce the problem: 1. Press 'O' for options 2. Select 'Palette' 3. mitmproxy will crash ##### Any other comments? What have you tried so far? ``` Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/master.py", line 281, in run self.loop.run() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/select.py", line 114, in keypress self.get_focus()[0].option.activate() File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/palettepicker.py", line 46, in <lambda> lambda: setattr(self.master.options, "palette", name) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/optmanager.py", line 114, in __setattr__ self.update(**{attr: value}) File "/usr/local/Cellar/mitmproxy/2.0.0/libexec/lib/python3.6/site-packages/mitmproxy/optmanager.py", line 141, in update raise KeyError("No such option: %s" % k) KeyError: 'No such option: palette' ``` The option names in mitmproxy/options.py were prefixed with 'console_', but line 46 and line 62 of mitmproxy/tools/console/palettepicker.py were not updated to include this prefix. This appears to have been broken by commit [35aff3b](https://github.com/mitmproxy/mitmproxy/commit/35aff3b7838f8df718cc574d2643f1355849fa8e) ##### System information Mitmproxy version: 2.0.0 (release version) Python version: 3.6.0 Platform: Darwin-16.4.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.12.3 ('', '', '') x86_64
2017-02-27T00:18:08
mitmproxy/mitmproxy
2,072
mitmproxy__mitmproxy-2072
[ "2071" ]
2b3093fa1c11758b0e03f5ea5dcda0c9545c1cc5
diff --git a/mitmproxy/tools/web/app.py b/mitmproxy/tools/web/app.py --- a/mitmproxy/tools/web/app.py +++ b/mitmproxy/tools/web/app.py @@ -85,6 +85,7 @@ def flow_to_json(flow: mitmproxy.flow.Flow) -> dict: "is_replay": flow.response.is_replay, } f.get("server_conn", {}).pop("cert", None) + f.get("client_conn", {}).pop("mitmcert", None) return f
[web] Failed to dump flows into json when visiting https website. ##### Steps to reproduce the problem: 1. start mitmweb and set the correct proxy configuration in the browser. 2. visit [github](https://github.com), or any other website with https 3. mitmweb stuck and throw an exception: ```python ERROR:tornado.application:Exception in callback <function WebMaster.run.<locals>.<lambda> at 0x7f8871ebb378> Traceback (most recent call last): File "/home/matthew/Hack/mitmproxy/venv3.5/lib/python3.5/site-packages/tornado/ioloop.py", line 1041, in _run return self.callback() File "/home/matthew/Hack/mitmproxy/mitmproxy/tools/web/master.py", line 109, in <lambda> tornado.ioloop.PeriodicCallback(lambda: self.tick(timeout=0), 5).start() File "/home/matthew/Hack/mitmproxy/mitmproxy/master.py", line 109, in tick handle_func(obj) File "/home/matthew/Hack/mitmproxy/mitmproxy/controller.py", line 70, in wrapper master.addons(f.__name__, message) File "/home/matthew/Hack/mitmproxy/mitmproxy/addonmanager.py", line 90, in __call__ self.invoke(i, name, *args, **kwargs) File "/home/matthew/Hack/mitmproxy/mitmproxy/addonmanager.py", line 85, in invoke func(*args, **kwargs) File "/home/matthew/Hack/mitmproxy/mitmproxy/addons/view.py", line 327, in request self.add(f) File "/home/matthew/Hack/mitmproxy/mitmproxy/addons/view.py", line 255, in add self.sig_view_add.send(self, flow=f) File "/home/matthew/Hack/mitmproxy/venv3.5/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/matthew/Hack/mitmproxy/venv3.5/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/home/matthew/Hack/mitmproxy/mitmproxy/tools/web/master.py", line 58, in _sig_view_add data=app.flow_to_json(flow) File "/home/matthew/Hack/mitmproxy/mitmproxy/tools/web/app.py", line 197, in broadcast message = json.dumps(kwargs, ensure_ascii=False).encode("utf8", "surrogateescape") File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/usr/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.5/json/encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: b'-----BEGIN CERTIFICATE-----\nMIIC5jCCAc6gAwIBAgIGDYj0HL5MMA0GCSqGSIb3DQEBCwUAMCgxEjAQBgNVBAMM\nCW1pdG1wcm94eTESMBAGA1UECgwJbWl0bXByb3h5MB4XDTE3MDIyNTA5MDM0M1oX\nDTIwMDIyNzA5MDM0M1owFTETMBEGA1UEAwwKZ2l0aHViLmNvbTCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAMTLqdlVNA4h2xzkX5XhLO1wtqZX0X0JpsXC\nHUO+KE3Pf2IBHWFAzeB3SVuaTSIa55UvRUDgZm+gYpl/qswf3MpPB8rkosLtwSJt\ns7ziAYF0JlrwYW+ZBaH/baQZ4JmgpY3qFzrkNhXwrVW+Wg3uO47w/9GaIuUNVv5t\nElfbCDBO0wvWt9tgEuaFNLVwOnibN4LEioQw/xnnUZu4JU6u+16rWasARxU7vlGs\no+CB6wgoK62W4VnSK7aQv6PMAOR49tyzhLXO6LKHQtZA4DG34zXWTYfXhuTC7rnA\nQ6haZ9qyVyeYclIXpJkmf10q2eJTjQbj8ff4Cj3LYlVmBtC2qbsCAwEAAaMpMCcw\nJQYDVR0RBB4wHIIKZ2l0aHViLmNvbYIOd3d3LmdpdGh1Yi5jb20wDQYJKoZIhvcN\nAQELBQADggEBABRJcH+lDB6ec343S+tNYDtr+wWgSiGw7WggKcUpMawBuqY61K4L\nLoxous98ie5XFfLbZI2rW/sIbMEuhjjamEMNmt83ZmZxo/YzMTXO/HlmHZYm+Vjw\nTdhGxe5cGTxjCwXhygRHX+IupDjanniwmh2jfg/0SlW7S4YE/MQJ1mcbGyzppwkg\n4hZ6sEcGe+RC7Sn1tJWlVpA3V8a6udZE8ejlaZV0/PYbJUWyRxAl00PlvRG2sPu5\nEJM7Xbd0TxtqVX7oagImBhqlhf0CyJfRMq0DU34j0oeUqtV/0FaapMumOODcnloI\nJeldz1QeX2hHksE1hYeVjZNFNKQLtzvEpgg=\n-----END CERTIFICATE-----\n' is not JSON serializable ``` ##### Any other comments? What have you tried so far? `Flow.client_conn.mitmcert`is in the type of `bytes`, so `json.dumps()` could not handle it and throw an exception saying that it is not JSON serializable. I noticed that in `flow_to_json()` function, there is a comment say: > Remove flow message content and cert to save transmission space. And we indeed remove the `server_conn.cert` from the returning dict, but left `client_conn.mitmcert`. I have tried to add one more line of code to remove `client_conn.mitmcert` from the returning dict and it solve this exception. However, I am not sure whether it is appropriate to remove this item. Or should we convert it into a string and keep it in the returning dict? ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0028-0x0fdf2c0) Python version: 3.5.2 Platform: Linux-4.4.0-63-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial
2017-02-27T13:49:42
mitmproxy/mitmproxy
2,081
mitmproxy__mitmproxy-2081
[ "1888" ]
bae4cdf8d5cc434938c74a041f762075513dd8e4
diff --git a/mitmproxy/tools/web/app.py b/mitmproxy/tools/web/app.py --- a/mitmproxy/tools/web/app.py +++ b/mitmproxy/tools/web/app.py @@ -65,6 +65,7 @@ def flow_to_json(flow: mitmproxy.flow.Flow) -> dict: "timestamp_start": flow.request.timestamp_start, "timestamp_end": flow.request.timestamp_end, "is_replay": flow.request.is_replay, + "pretty_host": flow.request.pretty_host, } if flow.response: if flow.response.raw_content:
mitmweb: --host Not Working ##### Steps to reproduce the problem: mitmweb is not respecting --host. All hosts are ips, never domain names. "showhost" is displayed at bottom of mitmweb web page. ##### Any other comments? What have you tried so far? I had reported this long ago. The issue was switches weren't implemented. Now they are but --host isn't working anyway. ##### System information Mitmproxy version: 1.0.0 Python version: 3.5.2 Platform: Windows-10-10.0.14393 SSL version: OpenSSL 1.0.2j 26 Sep 2016 Windows version: 10 10.0.14393 Multiprocessor Free
As always, thanks for the great report. We really appreciate having someone who consistently reports good Windows and mitmweb issues 😊 Regarding the actual issue: This needs to be implemented [here](https://github.com/mitmproxy/mitmproxy/blob/27353388157adda3d22000fcf146fe599f4f9a6f/web/src/js/flow/utils.js#L58). Hi, I'd like to work on this. I'm still going through the source code though so some more time would be appreciated. Thanks!
2017-03-01T11:23:54
mitmproxy/mitmproxy
2,104
mitmproxy__mitmproxy-2104
[ "2102" ]
22154dee5c4ecec5eb9ef0fb1a2ce98fd0d39ecd
diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -68,7 +68,7 @@ def keypress(self, size, key): self.set_focus(0) elif key == "F": o = self.master.options - o.focus_follow = not o.focus_follow + o.console_focus_follow = not o.console_focus_follow return urwid.ListBox.keypress(self, size, key)
Crash when pressing F with eventlog focused ##### Steps to reproduce the problem: 1. Start mitmproxy (console UI). 2. Press E to show the eventlog. 3. Press Tab to focus the eventlog. 4. Press F. ``` Traceback (most recent call last): File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/master.py", line 281, in run self.loop.run() File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/flowlist.py", line 116, in keypress return self.focus_item.keypress(tsize, key) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/tools/console/flowlist.py", line 71, in keypress o.focus_follow = not o.focus_follow File "/home/vasiliy/tmp/env4/lib/python3.5/site-packages/mitmproxy/optmanager.py", line 107, in __getattr__ raise AttributeError("No such option: %s" % attr) AttributeError: No such option: focus_follow mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` ##### System information (this is mitmproxy from master) Mitmproxy version: 3.0.0 (release version) Python version: 3.5.2 Platform: Linux-4.4.0-64-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial
I'm looking into it On first look, it seems like `o.focus_follow = not o.focus_follow` should be `o.console_focus_follow = not o.console_focus_follow`
2017-03-06T15:21:14
mitmproxy/mitmproxy
2,118
mitmproxy__mitmproxy-2118
[ "2111" ]
cb6240974d16e9f2923543fe28c201d39a63f60f
diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py --- a/mitmproxy/addons/proxyauth.py +++ b/mitmproxy/addons/proxyauth.py @@ -1,7 +1,7 @@ import binascii import weakref from typing import Optional -from typing import Set # noqa +from typing import MutableMapping # noqa from typing import Tuple import passlib.apache @@ -46,7 +46,7 @@ def __init__(self): self.htpasswd = None self.singleuser = None self.mode = None - self.authenticated = weakref.WeakSet() # type: Set[connections.ClientConnection] + self.authenticated = weakref.WeakKeyDictionary() # type: MutableMapping[connections.ClientConnection, Tuple[str, str]] """Contains all connections that are permanently authenticated after an HTTP CONNECT""" def enabled(self) -> bool: @@ -155,11 +155,12 @@ def configure(self, options, updated): def http_connect(self, f: http.HTTPFlow) -> None: if self.enabled(): if self.authenticate(f): - self.authenticated.add(f.client_conn) + self.authenticated[f.client_conn] = f.metadata["proxyauth"] def requestheaders(self, f: http.HTTPFlow) -> None: if self.enabled(): # Is this connection authenticated by a previous HTTP CONNECT? if f.client_conn in self.authenticated: + f.metadata["proxyauth"] = self.authenticated[f.client_conn] return self.authenticate(f)
diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py --- a/test/mitmproxy/addons/test_proxyauth.py +++ b/test/mitmproxy/addons/test_proxyauth.py @@ -171,3 +171,4 @@ def test_handlers(): f2 = tflow.tflow(client_conn=f.client_conn) up.requestheaders(f2) assert not f2.response + assert f2.metadata["proxyauth"] == ('test', 'test')
Proxyauth metadata not present for HTTPS requests ##### Steps to reproduce the problem: 1. Run `mitmproxy --nonanonymous` 2. Set up the proxy in `System Preferences`. Enter a username and password (here I used `laura` and `pass` respectively). 3. Navigate to a HTTP site. Verify that you can see the proxyauth credentials in the `Detail` tab when viewing the request in mitmproxy. See image below: <img width="1440" alt="screen shot 2017-03-07 at 11 18 52" src="https://cloud.githubusercontent.com/assets/9434500/23654470/b927f98e-0328-11e7-832c-b008a37943de.png"> 4. Navigate to a HTTPS site. Verify that the proxyauth credentials are not visible in the `Detail` tab. Example: <img width="1440" alt="screen shot 2017-03-07 at 11 19 18" src="https://cloud.githubusercontent.com/assets/9434500/23654556/1e8a0704-0329-11e7-8aa9-0e576a1e341d.png"> ##### Any other comments? What have you tried so far? The proxyauth metadata is not present in the `request` method of inline scripts either. It is present when the request is HTTP. I have not checked other events. Adding ```python mitmproxy.ctx.log(f.request.pretty_host + "- Adding credientials to metadata") ``` to [line 109 of the proxyauth addon](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/proxyauth.py#L109), and using a simple inline script: ```python def request(self, flow): ctx.log("Request recieved: " + flow.request.pretty_host + ". Metadata: " + str(flow.metadata)) ``` I get the following output in the event log: <img width="1440" alt="screen shot 2017-03-07 at 11 42 39" src="https://cloud.githubusercontent.com/assets/9434500/23655118/a88d2010-032b-11e7-86fd-78fa45cdc83b.png"> <img width="1440" alt="screen shot 2017-03-07 at 11 42 34" src="https://cloud.githubusercontent.com/assets/9434500/23655119/a88e4ef4-032b-11e7-8115-ef853d8e31fa.png"> ##### System information Mitmproxy version: 3.0.0 (1.0.1dev0299-0x37c1c55) Python version: 3.6.0 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2k 26 Jan 2017 Mac version: 10.11.6 ('', '', '') x86_64
Side note: I previously added ```python f.metadata['user'] = username ``` to [line 91 of the proxyauth addon](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/proxyauth.py#L91) and I was always able to access that metadata from the `request` method of my inline script. That is no longer present for HTTPS requests either, and I'm not sure at when it broke since I have been away for a couple of weeks (and pulled when I got back). Just letting you know in case it helps you trace down the issue, but I shouldn't need to do this anymore if the proxyauth metadata is added correctly 😄 Thanks for the extensive report! The issue here is that the client won't send authentication headers anymore after it has issued a `CONNECT` request to establish a TLS connection. If we detect this [here](https://github.com/mitmproxy/mitmproxy/blob/cb6240974d16e9f2923543fe28c201d39a63f60f/mitmproxy/addons/proxyauth.py#L163) we should still add the credentials as metadata to the flow. I think the correct approach is to use a `weakref.WeakKeyDictionary` for `.authenticated` instead of a `WeakSet`, so that we can look up the credentials belonging to a client connection there.
2017-03-08T03:38:42
mitmproxy/mitmproxy
2,142
mitmproxy__mitmproxy-2142
[ "2140", "2140" ]
ee65894d40f5a9f73125a8d3e73ba50540939e5b
diff --git a/mitmproxy/options.py b/mitmproxy/options.py --- a/mitmproxy/options.py +++ b/mitmproxy/options.py @@ -78,7 +78,7 @@ def __init__(self, **kwargs) -> None: "Kill extra requests during replay." ) self.add_option( - "keepserving", bool, True, + "keepserving", bool, False, "Continue serving after client playback or file read." ) self.add_option(
mitmdump -nr does not exit automatically ##### Steps to reproduce the problem: 1. Use `mitmdump -nr foo.mitm` to print some flows. 2. Mitmdump should exit automatically after printing, but it doesn't. ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0136-0x05e1154) Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty mitmdump -nr does not exit automatically ##### Steps to reproduce the problem: 1. Use `mitmdump -nr foo.mitm` to print some flows. 2. Mitmdump should exit automatically after printing, but it doesn't. ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0136-0x05e1154) Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty
2017-03-13T17:41:04
mitmproxy/mitmproxy
2,150
mitmproxy__mitmproxy-2150
[ "2146" ]
1f377435495a7db9c888dd5ce10a51b6f3c3f8ad
diff --git a/mitmproxy/flowfilter.py b/mitmproxy/flowfilter.py --- a/mitmproxy/flowfilter.py +++ b/mitmproxy/flowfilter.py @@ -319,10 +319,14 @@ class FDomain(_Rex): code = "d" help = "Domain" flags = re.IGNORECASE + is_binary = False @only(http.HTTPFlow) def __call__(self, f): - return bool(self.re.search(f.request.data.host)) + return bool( + self.re.search(f.request.host) or + self.re.search(f.request.pretty_host) + ) class FUrl(_Rex): @@ -339,7 +343,7 @@ def make(klass, s, loc, toks): @only(http.HTTPFlow) def __call__(self, f): - return self.re.search(f.request.url) + return self.re.search(f.request.pretty_url) class FSrc(_Rex):
Can't filter by hostname when --host is used ##### Steps to reproduce the problem: 1. mitmproxy -T --host 2. Capture something 3. Press f and filter by something like `~d domain.com` or `~u domain com` ##### Any other comments? What have you tried so far? Going to detail view to get the resolved IP address and using it for the filter works, but it's uncomfortable when you want to match things like "google.com" (lots of IP ranges, lots of unrelated domains, but many mentioning google) ##### System information Mitmproxy version: 2.0.0 (release version) Python version: 3.6.0 Platform: Linux-4.9.11-1-ARCH-x86_64-with-arch SSL version: OpenSSL 1.0.2k 26 Jan 2017 Linux distro: arch
Thanks for the report. It's probably a good idea to also iterate over the host headers for `~d`. This needs to be fixed in flowfilter.py and filt.peg.
2017-03-14T04:59:29
mitmproxy/mitmproxy
2,155
mitmproxy__mitmproxy-2155
[ "2154" ]
eba6d4359cdf147b378ffa5eb66b12fc9249bc69
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ "click>=6.2, <7", "certifi>=2015.11.20.1", # no semver here - this should always be on the last release! "construct>=2.8, <2.9", - "cryptography>=1.3, <1.8", + "cryptography>=1.3, <1.9", "cssutils>=1.0.1, <1.1", "h2>=2.5.1, <3", "html2text>=2016.1.8, <=2016.9.19",
cryptography dependency update? The template here wasn't relevant so I cut it, apologies. `mitmproxy` currently mandates `cryptography <1.8` which when built from source on macOS/OS X El Capitan (10.11) using Xcode 8 results in `Symbol not found: _getentropy` errors. Reported and explained in more detail [here](https://github.com/pyca/cryptography/issues/3332), hence my short summary. These issues were fixed in https://github.com/pyca/cryptography/pull/3354, which was released in the 1.8 branch. This is also currently causing some "fun" for downstream package managers having to carry their own somewhat hacky patches like [this](https://github.com/Homebrew/homebrew-core/blob/37abcfc55099f635d0e187657a55a1eed36b5ccf/Formula/mitmproxy.rb#L193-L202). The gist of my request is whether `mitmproxy` has plans to/would consider update/updating [cryptography](https://github.com/mitmproxy/mitmproxy/blob/e723a58af5dc4fc7a46958aa9ce8c386a7387450/setup.py#L67) to use the latest release without these issues.
2017-03-15T09:03:36
mitmproxy/mitmproxy
2,187
mitmproxy__mitmproxy-2187
[ "2184" ]
92e33589159ee94df831fc0f0b2084854a6c44ae
diff --git a/mitmproxy/tools/web/app.py b/mitmproxy/tools/web/app.py --- a/mitmproxy/tools/web/app.py +++ b/mitmproxy/tools/web/app.py @@ -421,6 +421,7 @@ def get(self): contentViews=[v.name.replace(' ', '_') for v in contentviews.views], listen_host=self.master.options.listen_host, listen_port=self.master.options.listen_port, + server=self.master.options.server, )) def put(self): diff --git a/mitmproxy/tools/web/master.py b/mitmproxy/tools/web/master.py --- a/mitmproxy/tools/web/master.py +++ b/mitmproxy/tools/web/master.py @@ -9,6 +9,7 @@ from mitmproxy.addons import intercept from mitmproxy.addons import termlog from mitmproxy.addons import view +from mitmproxy.addons import termstatus from mitmproxy.options import Options # noqa from mitmproxy.tools.web import app @@ -35,7 +36,7 @@ def __init__(self, options, server, with_termlog=True): self.events, ) if with_termlog: - self.addons.add(termlog.TermLog()) + self.addons.add(termlog.TermLog(), termstatus.TermStatus()) self.app = app.Application( self, self.options.web_debug ) @@ -99,11 +100,6 @@ def run(self): # pragma: no cover iol.add_callback(self.start) tornado.ioloop.PeriodicCallback(lambda: self.tick(timeout=0), 5).start() - self.add_log( - "Proxy server listening at http://{}:{}/".format(self.server.address[0], self.server.address[1]), - "info" - ) - web_url = "http://{}:{}/".format(self.options.web_iface, self.options.web_port) self.add_log( "Web server listening at {}".format(web_url),
mitmweb -n: Proxy server listening at http://d:u/ ##### Steps to reproduce the problem: 1. `mitmweb -n` 2. Incorrect information is displayed on the console: "Proxy server listening at http://d:u/" ##### Any other comments? What have you tried so far? mitmweb should use the termstatus addon for printing this as well. ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0203-0xc088249) Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty
2017-03-19T02:01:06
mitmproxy/mitmproxy
2,191
mitmproxy__mitmproxy-2191
[ "2139" ]
0c0c0d38cc65b4b1cecbe82d8d2b558ed3c62994
diff --git a/mitmproxy/options.py b/mitmproxy/options.py --- a/mitmproxy/options.py +++ b/mitmproxy/options.py @@ -433,7 +433,13 @@ def __init__(self, **kwargs) -> None: ) self.add_option( "flow_detail", int, 1, - "Flow detail display level." + """ + The display detail level for flows in mitmdump: 0 (almost quiet) to 3 (very verbose). + 0: shortened request URL, response status code, WebSocket and TCP message notifications. + 1: full request URL with response status code + 2: 1 + HTTP headers + 3: 2 + full response content, content of WebSocket and TCP messages. + """ ) self.update(**kwargs)
mitmdump: unrecognized arguments: -dd ##### Steps to reproduce the problem: 1. `mitmdump -d -nr foo.mitm` ``` mitmdump: error: unrecognized arguments: -d ``` ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0136-0x05e1154) Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty
This is apparently `--flow-detail` now. `mitmdump --help` explains that I should use `--flow-detail LEVEL`, but does not indicate what a valid value for LEVEL would be.
2017-03-20T08:59:24
mitmproxy/mitmproxy
2,207
mitmproxy__mitmproxy-2207
[ "1530" ]
439c113989feb193972b83ffcd0823ea4d2218df
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -65,14 +65,28 @@ def cut_traceback(tb, func_name): return tb +class StreamLog: + """ + A class for redirecting output using contextlib. + """ + def __init__(self, log): + self.log = log + + def write(self, buf): + if buf.strip(): + self.log(buf) + + @contextlib.contextmanager def scriptenv(path, args): oldargs = sys.argv sys.argv = [path] + args script_dir = os.path.dirname(os.path.abspath(path)) sys.path.append(script_dir) + stdout_replacement = StreamLog(ctx.log.warn) try: - yield + with contextlib.redirect_stdout(stdout_replacement): + yield except SystemExit as v: ctx.log.error("Script exited with code %s" % v.code) except Exception:
diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py --- a/test/mitmproxy/addons/test_script.py +++ b/test/mitmproxy/addons/test_script.py @@ -5,6 +5,7 @@ import watchdog.events import pytest +from unittest import mock from mitmproxy.test import tflow from mitmproxy.test import tutils from mitmproxy.test import taddons @@ -97,12 +98,26 @@ def test_parse_windows(self): def test_load_script(): - ns = script.load_script( - tutils.test_data.path( - "mitmproxy/data/addonscripts/recorder.py" - ), [] - ) - assert ns.start + with taddons.context(): + ns = script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/recorder.py" + ), [] + ) + assert ns.start + + +def test_script_print_stdout(): + with taddons.context() as tctx: + with mock.patch('mitmproxy.ctx.log.warn') as mock_warn: + with script.scriptenv("path", []): + ns = script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/print.py" + ), [] + ) + ns.start(tctx.options) + mock_warn.assert_called_once_with("stdoutprint") class TestScript: diff --git a/test/mitmproxy/data/addonscripts/print.py b/test/mitmproxy/data/addonscripts/print.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/data/addonscripts/print.py @@ -0,0 +1,2 @@ +def start(opts): + print("stdoutprint")
Handle print() statements for inline scripts print() statements in inline scripts should be suppressed, and produce into ctx.log.warn() calls instead.
Doing a simple search at github of `print(` a lot of candidates appear. To understand what you propose to do, tell me, Is [this](https://github.com/mitmproxy/mitmproxy/blob/6792cc1de90b02b89da9ae80704ea237c5486e66/mitmproxy/tools/main.py#L6) a good candidate? It is a `print` to `sys.stderr`. And what about [this](https://github.com/mitmproxy/mitmproxy/blob/711078ba3f63257df745bb3edd80a85717e94b20/mitmproxy/utils/version_check.py#L19)? It seems a legit use of print, although it could be write as a file write, given the file object is an argument. I think a better question I could ask is: Which are those inline scripts? If I may, I could add another suggestion/question here. Why not use python's built-in logger instead of print? That way the log level can be changed as well How about something like http://stackoverflow.com/questions/19425736/how-to-redirect-stdout-and-stderr-to-logger-in-py :question: I think this issue is about redirecting anything that gets sent to `sys.stdout` to `ctx.log.warn`. This would probably look roughly like to this: ```python class StreamLog: def __init__(self, log: Callable): self.log = log def write(self, buf): self.log(buf) stdout_replacement = StreamLog(ctx.log.warn) with contextlib.redirect_stdout(stdout_replacement): # invoke addon ``` A possible integration between Python's built-in logger and `ctx.log` is out of scope for this issue.
2017-03-23T23:19:08
mitmproxy/mitmproxy
2,213
mitmproxy__mitmproxy-2213
[ "2201" ]
c6a16e95e856c859b147e72a484feefe96c37ad9
diff --git a/mitmproxy/proxy/protocol/http2.py b/mitmproxy/proxy/protocol/http2.py --- a/mitmproxy/proxy/protocol/http2.py +++ b/mitmproxy/proxy/protocol/http2.py @@ -62,7 +62,7 @@ def safe_send_body(self, raise_zombie: Callable, stream_id: int, chunks: List[by raise_zombie(self.lock.release) max_outbound_frame_size = self.max_outbound_frame_size frame_chunk = chunk[position:position + max_outbound_frame_size] - if self.local_flow_control_window(stream_id) < len(frame_chunk): + if self.local_flow_control_window(stream_id) < len(frame_chunk): # pragma: no cover self.lock.release() time.sleep(0.1) continue @@ -362,7 +362,7 @@ def __call__(self): self._kill_all_streams() -def detect_zombie_stream(func): +def detect_zombie_stream(func): # pragma: no cover @functools.wraps(func) def wrapper(self, *args, **kwargs): self.raise_zombie() @@ -454,7 +454,7 @@ def data_finished(self): else: return self.request_data_finished - def raise_zombie(self, pre_command=None): + def raise_zombie(self, pre_command=None): # pragma: no cover connection_closed = self.h2_connection.state_machine.state == h2.connection.ConnectionState.CLOSED if self.zombie is not None or connection_closed: if pre_command is not None: @@ -626,7 +626,7 @@ def run(self): self.log(repr(e), "info") except exceptions.SetServerNotAllowedException as e: # pragma: no cover self.log("Changing the Host server for HTTP/2 connections not allowed: {}".format(e), "info") - except exceptions.Kill: + except exceptions.Kill: # pragma: no cover self.log("Connection killed", "info") self.kill()
Flaky Coverage for http2.py See [codecov](https://codecov.io/gh/mitmproxy/mitmproxy/compare/ab2fcbef8dceb5abc97f7e73638629ded606daa6...82ecc5448d4e3eb53a947154f49d431148f6508a/src/mitmproxy/proxy/protocol/http2.py) for https://github.com/mitmproxy/mitmproxy/pull/2200. Apparently that line is not triggered consistently in tests.
Here's another one: https://codecov.io/gh/mitmproxy/mitmproxy/compare/c6a16e95e856c859b147e72a484feefe96c37ad9...4201fc3073d2e683ff1471a1aedc18aea923cf38/src/mitmproxy/proxy/protocol/http2.py
2017-03-25T15:42:35
mitmproxy/mitmproxy
2,259
mitmproxy__mitmproxy-2259
[ "2228" ]
07cb83597b05b1355a6038d2b1ef96d7e7eb26d3
diff --git a/mitmproxy/addons/stickycookie.py b/mitmproxy/addons/stickycookie.py --- a/mitmproxy/addons/stickycookie.py +++ b/mitmproxy/addons/stickycookie.py @@ -1,14 +1,14 @@ import collections from http import cookiejar +from typing import List, Tuple, Dict, Optional # noqa +from mitmproxy import http, flowfilter, ctx, exceptions from mitmproxy.net.http import cookies -from mitmproxy import exceptions -from mitmproxy import flowfilter -from mitmproxy import ctx +TOrigin = Tuple[str, int, str] -def ckey(attrs, f): +def ckey(attrs: Dict[str, str], f: http.HTTPFlow) -> TOrigin: """ Returns a (domain, port, path) tuple. """ @@ -21,18 +21,18 @@ def ckey(attrs, f): return (domain, f.request.port, path) -def domain_match(a, b): - if cookiejar.domain_match(a, b): +def domain_match(a: str, b: str) -> bool: + if cookiejar.domain_match(a, b): # type: ignore return True - elif cookiejar.domain_match(a, b.strip(".")): + elif cookiejar.domain_match(a, b.strip(".")): # type: ignore return True return False class StickyCookie: def __init__(self): - self.jar = collections.defaultdict(dict) - self.flt = None + self.jar = collections.defaultdict(dict) # type: Dict[TOrigin, Dict[str, str]] + self.flt = None # type: Optional[flowfilter.TFilter] def configure(self, updated): if "stickycookie" in updated: @@ -46,7 +46,7 @@ def configure(self, updated): else: self.flt = None - def response(self, flow): + def response(self, flow: http.HTTPFlow): if self.flt: for name, (value, attrs) in flow.response.cookies.items(multi=True): # FIXME: We now know that Cookie.py screws up some cookies with @@ -63,24 +63,21 @@ def response(self, flow): if not self.jar[dom_port_path]: self.jar.pop(dom_port_path, None) else: - b = attrs.copy() - b.insert(0, name, value) - self.jar[dom_port_path][name] = b + self.jar[dom_port_path][name] = value - def request(self, flow): + def request(self, flow: http.HTTPFlow): if self.flt: - l = [] + cookie_list = [] # type: List[Tuple[str,str]] if flowfilter.match(self.flt, flow): - for domain, port, path in self.jar.keys(): + for (domain, port, path), c in self.jar.items(): match = [ domain_match(flow.request.host, domain), flow.request.port == port, flow.request.path.startswith(path) ] if all(match): - c = self.jar[(domain, port, path)] - l.extend([cookies.format_cookie_header(c[name].items(multi=True)) for name in c.keys()]) - if l: + cookie_list.extend(c.items()) + if cookie_list: # FIXME: we need to formalise this... - flow.request.stickycookie = True - flow.request.headers["cookie"] = "; ".join(l) + flow.metadata["stickycookie"] = True + flow.request.headers["cookie"] = cookies.format_cookie_header(cookie_list)
diff --git a/test/mitmproxy/addons/test_dumper.py b/test/mitmproxy/addons/test_dumper.py --- a/test/mitmproxy/addons/test_dumper.py +++ b/test/mitmproxy/addons/test_dumper.py @@ -68,7 +68,6 @@ def test_simple(): ctx.configure(d, flow_detail=4) flow = tflow.tflow() flow.request = tutils.treq() - flow.request.stickycookie = True flow.client_conn = mock.MagicMock() flow.client_conn.address[0] = "foo" flow.response = tutils.tresp(content=None) diff --git a/test/mitmproxy/addons/test_stickycookie.py b/test/mitmproxy/addons/test_stickycookie.py --- a/test/mitmproxy/addons/test_stickycookie.py +++ b/test/mitmproxy/addons/test_stickycookie.py @@ -110,8 +110,8 @@ def test_response_overwrite(self): f.response.headers["Set-Cookie"] = c2 sc.response(f) googlekey = list(sc.jar.keys())[0] - assert len(sc.jar[googlekey].keys()) == 1 - assert list(sc.jar[googlekey]["somecookie"].items())[0][1] == "newvalue" + assert len(sc.jar[googlekey]) == 1 + assert sc.jar[googlekey]["somecookie"] == "newvalue" def test_response_delete(self): sc = stickycookie.StickyCookie()
Sticky cookies are improperly formatted. ##### Steps to reproduce the problem: 1. Go to http://www.html-kit.com/tools/cookietester/ 2. Click 'Set Test Cookie' 3. Observe that one cookie is sent to the server. 4. Remove the cookie. 5. launch mitmproxy with `mitmproxy -t html-kit\.com` and tell your browser to use it as a proxy 6. Reload the page. 7. Click 'Set Test Cookie' 8. Observe that two 'cookies' are sent to the server. ##### Any other comments? What have you tried so far? There appears to be a comma in the output of mitmproxy, even though it is surrounded by quotes. It's possible, then that this is a parsing fail on the tool's end caused by a difference in what's sent back for the format of the date. Still, should it really be changing that? ##### System information Arch Linux, freshly updated. Mitmproxy version: 2.0.1 (release version) Python version: 3.6.0 Platform: Linux-4.10.6-1-ARCH-x86_64-with-glibc2.3.4 SSL version: OpenSSL 1.0.2k 26 Jan 2017
Thanks for the report. It looks like we parse it correctly: ```python >>> from mitmproxy.net.http import cookies >>> cookies.parse_set_cookie_header("TestCookie_Name_201704075049=TestCookie_Value_035049; Domain=www.html-kit.com; Expires=Sun, 09-Apr-2017 08:50:54 GMT; Path=/") [ ('TestCookie_Name_201704075049', 'TestCookie_Value_035049', CookieAttrs[ ('Domain', 'www.html-kit.com'), ('Expires', 'Sun, 09-Apr-2017 08:50:54 GMT'), ('Path', '/') ]) ] ``` But for some reason [stickycookie.py](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/stickycookie.py) includes the attributes in the `Cookie` header. My understanding is that this is very wrong. We definitely should catch that in our tests. So, I've got a hack that seems to fix it. If you replace: `l.extend([cookies.format_cookie_header(c[name].items(multi=True)) for name in c.keys()])` with `l.extend([cookies.format_cookie_header([c[name].items(multi=True)[0]]) for name in c.keys()])` I don't like this solution, though. The issue appears to be with how the cookies are stored in the sticky cookie implementation, as well as, to an extent, the `format_cookie_header()` implementation. Sticky cookies stores them as a list of `(key, value)` tuple lists, instead of a list of `(key, value, CookieAttrs[(k,v),(k,v)])` tuples as seems to be used elsewhere. `format_cookie_header()` expects a list of `(key, value)` tuples for each cookie. It is noteworthy that this seems broken at the moment, because the way it should work as currently implemented should give me cookies for every attribute. The changes I would reccomend would be to have `format_cookie_header()` take a list `(key, value, CookieAttrs[(k,v),(k,v)])` tuples, same as `format_set_cookie_header()` and change the cookie jar in sticky cookies to store cookies in this same format. If there are big issues with this, the hack I mentioned above can be applied. I'm going to go ahead and submit the hack in a pull request, for now.
2017-04-24T14:28:38
mitmproxy/mitmproxy
2,268
mitmproxy__mitmproxy-2268
[ "2257" ]
7607240c30a319f37494baeca07ff735289d0315
diff --git a/mitmproxy/export.py b/mitmproxy/export.py --- a/mitmproxy/export.py +++ b/mitmproxy/export.py @@ -6,19 +6,7 @@ from typing import Any from mitmproxy import http - - -def _native(s): - if isinstance(s, bytes): - return s.decode() - return s - - -def dictstr(items, indent: str) -> str: - lines = [] - for k, v in items: - lines.append(indent + "%s: %s,\n" % (repr(_native(k)), repr(_native(v)))) - return "{\n%s}\n" % "".join(lines) +from mitmproxy.utils import strutils def curl_command(flow: http.HTTPFlow) -> str: @@ -36,7 +24,10 @@ def curl_command(flow: http.HTTPFlow) -> str: data += "'%s'" % request.url if request.content: - data += " --data-binary '%s'" % _native(request.content) + data += " --data-binary '%s'" % strutils.bytes_to_escaped_str( + request.content, + escape_single_quotes=True + ) return data @@ -127,10 +118,14 @@ class WebsiteUser(HttpLocust): args = "" headers = "" + + def conv(x): + return strutils.bytes_to_escaped_str(x, escape_single_quotes=True) + if flow.request.headers: lines = [ - (_native(k), _native(v)) for k, v in flow.request.headers.fields - if _native(k).lower() not in [":authority", "host", "cookie"] + (conv(k), conv(v)) for k, v in flow.request.headers.fields + if conv(k).lower() not in [":authority", "host", "cookie"] ] lines = [" '%s': '%s',\n" % (k, v) for k, v in lines] headers += "\n headers = {\n%s }\n" % "".join(lines) @@ -148,7 +143,7 @@ class WebsiteUser(HttpLocust): data = "" if flow.request.content: - data = "\n data = '''%s'''\n" % _native(flow.request.content) + data = "\n data = '''%s'''\n" % conv(flow.request.content) args += "\n data=data," code = code.format(
diff --git a/test/mitmproxy/data/test_flow_export/locust_task_post.py b/test/mitmproxy/data/test_flow_export/locust_task_post.py --- a/test/mitmproxy/data/test_flow_export/locust_task_post.py +++ b/test/mitmproxy/data/test_flow_export/locust_task_post.py @@ -2,7 +2,7 @@ def path(self): url = self.locust.host + '/path' - data = '''content''' + data = '''\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff''' self.response = self.client.request( method='POST', diff --git a/test/mitmproxy/data/test_flow_export/python_post.py b/test/mitmproxy/data/test_flow_export/python_post.py --- a/test/mitmproxy/data/test_flow_export/python_post.py +++ b/test/mitmproxy/data/test_flow_export/python_post.py @@ -2,7 +2,16 @@ response = requests.post( 'http://address:22/path', - data=b'content' + data=(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13' + b'\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./01234567' + b'89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f' + b'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f' + b'\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f' + b'\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf' + b'\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf' + b'\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf' + b'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf' + b'\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef' + b'\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff') ) - print(response.text) diff --git a/test/mitmproxy/test_export.py b/test/mitmproxy/test_export.py --- a/test/mitmproxy/test_export.py +++ b/test/mitmproxy/test_export.py @@ -1,13 +1,15 @@ -from mitmproxy.test import tflow import re -from mitmproxy.net.http import Headers +import pytest + from mitmproxy import export # heh +from mitmproxy.net.http import Headers +from mitmproxy.test import tflow from mitmproxy.test import tutils def clean_blanks(s): - return re.sub(r"^(\s+)$", "", s, flags=re.MULTILINE) + return re.sub(r"^\s+", "", s, flags=re.MULTILINE) def python_equals(testdata, text): @@ -19,85 +21,110 @@ def python_equals(testdata, text): assert clean_blanks(text).rstrip() == clean_blanks(d).rstrip() -def req_get(): - return tutils.treq(method=b'GET', content=b'', path=b"/path?a=foo&a=bar&b=baz") [email protected] +def get_request(): + return tflow.tflow( + req=tutils.treq( + method=b'GET', + content=b'', + path=b"/path?a=foo&a=bar&b=baz" + ) + ) + + [email protected] +def post_request(): + return tflow.tflow( + req=tutils.treq( + method=b'POST', + headers=(), + content=bytes(range(256)) + ) + ) + + [email protected] +def patch_request(): + return tflow.tflow( + req=tutils.treq(method=b'PATCH', path=b"/path?query=param") + ) -def req_post(): - return tutils.treq(method=b'POST', headers=()) +class TExport: + def test_get(self, get_request): + raise NotImplementedError() + def test_post(self, post_request): + raise NotImplementedError() -def req_patch(): - return tutils.treq(method=b'PATCH', path=b"/path?query=param") + def test_patch(self, patch_request): + raise NotImplementedError() -class TestExportCurlCommand: - def test_get(self): - flow = tflow.tflow(req=req_get()) +class TestExportCurlCommand(TExport): + def test_get(self, get_request): result = """curl -H 'header:qvalue' -H 'content-length:7' 'http://address:22/path?a=foo&a=bar&b=baz'""" - assert export.curl_command(flow) == result + assert export.curl_command(get_request) == result - def test_post(self): - flow = tflow.tflow(req=req_post()) - result = """curl -X POST 'http://address:22/path' --data-binary 'content'""" - assert export.curl_command(flow) == result + def test_post(self, post_request): + result = "curl -X POST 'http://address:22/path' --data-binary '{}'".format( + str(bytes(range(256)))[2:-1] + ) + assert export.curl_command(post_request) == result - def test_patch(self): - flow = tflow.tflow(req=req_patch()) + def test_patch(self, patch_request): result = """curl -H 'header:qvalue' -H 'content-length:7' -X PATCH 'http://address:22/path?query=param' --data-binary 'content'""" - assert export.curl_command(flow) == result + assert export.curl_command(patch_request) == result -class TestExportPythonCode: - def test_get(self): - flow = tflow.tflow(req=req_get()) - python_equals("mitmproxy/data/test_flow_export/python_get.py", export.python_code(flow)) +class TestExportPythonCode(TExport): + def test_get(self, get_request): + python_equals("mitmproxy/data/test_flow_export/python_get.py", + export.python_code(get_request)) - def test_post(self): - flow = tflow.tflow(req=req_post()) - python_equals("mitmproxy/data/test_flow_export/python_post.py", export.python_code(flow)) + def test_post(self, post_request): + python_equals("mitmproxy/data/test_flow_export/python_post.py", + export.python_code(post_request)) - def test_post_json(self): - p = req_post() - p.content = b'{"name": "example", "email": "[email protected]"}' - p.headers = Headers(content_type="application/json") - flow = tflow.tflow(req=p) - python_equals("mitmproxy/data/test_flow_export/python_post_json.py", export.python_code(flow)) + def test_post_json(self, post_request): + post_request.request.content = b'{"name": "example", "email": "[email protected]"}' + post_request.request.headers = Headers(content_type="application/json") + python_equals("mitmproxy/data/test_flow_export/python_post_json.py", + export.python_code(post_request)) - def test_patch(self): - flow = tflow.tflow(req=req_patch()) - python_equals("mitmproxy/data/test_flow_export/python_patch.py", export.python_code(flow)) + def test_patch(self, patch_request): + python_equals("mitmproxy/data/test_flow_export/python_patch.py", + export.python_code(patch_request)) -class TestExportLocustCode: - def test_get(self): - flow = tflow.tflow(req=req_get()) - python_equals("mitmproxy/data/test_flow_export/locust_get.py", export.locust_code(flow)) +class TestExportLocustCode(TExport): + def test_get(self, get_request): + python_equals("mitmproxy/data/test_flow_export/locust_get.py", + export.locust_code(get_request)) - def test_post(self): - p = req_post() - p.content = b'content' - p.headers = '' - flow = tflow.tflow(req=p) - python_equals("mitmproxy/data/test_flow_export/locust_post.py", export.locust_code(flow)) + def test_post(self, post_request): + post_request.request.content = b'content' + post_request.request.headers.clear() + python_equals("mitmproxy/data/test_flow_export/locust_post.py", + export.locust_code(post_request)) - def test_patch(self): - flow = tflow.tflow(req=req_patch()) - python_equals("mitmproxy/data/test_flow_export/locust_patch.py", export.locust_code(flow)) + def test_patch(self, patch_request): + python_equals("mitmproxy/data/test_flow_export/locust_patch.py", + export.locust_code(patch_request)) -class TestExportLocustTask: - def test_get(self): - flow = tflow.tflow(req=req_get()) - python_equals("mitmproxy/data/test_flow_export/locust_task_get.py", export.locust_task(flow)) +class TestExportLocustTask(TExport): + def test_get(self, get_request): + python_equals("mitmproxy/data/test_flow_export/locust_task_get.py", + export.locust_task(get_request)) - def test_post(self): - flow = tflow.tflow(req=req_post()) - python_equals("mitmproxy/data/test_flow_export/locust_task_post.py", export.locust_task(flow)) + def test_post(self, post_request): + python_equals("mitmproxy/data/test_flow_export/locust_task_post.py", + export.locust_task(post_request)) - def test_patch(self): - flow = tflow.tflow(req=req_patch()) - python_equals("mitmproxy/data/test_flow_export/locust_task_patch.py", export.locust_task(flow)) + def test_patch(self, patch_request): + python_equals("mitmproxy/data/test_flow_export/locust_task_patch.py", + export.locust_task(patch_request)) class TestURL:
crash when export flow to 'r' curl ##### Steps to reproduce the problem: 1. enter a flow view 2. press E and choose r 3. crash ##### Any other comments? What have you tried so far? ##### System information Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/master.py", line 281, in run self.loop.run() File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/window.py", line 84, in keypress k = super().keypress(size, k) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/urwid/container.py", line 1116, in keypress return self.footer.keypress((maxcol,),key) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/statusbar.py", line 155, in keypress return self.master.ab.keypress(*args, **kwargs) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/statusbar.py", line 108, in keypress self.prompt_execute(k) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/statusbar.py", line 133, in prompt_execute msg = p(txt) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/statusbar.py", line 31, in __call__ return self.callback(txt, *self.args) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/common.py", line 328, in export_to_clip_or_file writer(exporter(flow)) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/export.py", line 39, in curl_command data += " --data-binary '%s'" % _native(request.content) File "/usr/local/Cellar/mitmproxy/2.0.1/libexec/lib/python3.6/site-packages/mitmproxy/export.py", line 13, in _native return s.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 188: invalid start byte <!-- Cut and paste the output of "mitmproxy --version". If you're using an older version if mitmproxy, please specify the version and OS. --> Mitmproxy version: 2.0.1 (release version) Python version: 3.6.1 Platform: Darwin-16.1.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.12.1 ('', '', '') x86_64
Thanks. Can you share the flow for which this is happening? [export_python.py.zip](https://github.com/mitmproxy/mitmproxy/files/950252/export_python.py.zip) accidently closed~ the file is exported with python, i modify a little to hide the domain
2017-04-26T10:10:17
mitmproxy/mitmproxy
2,269
mitmproxy__mitmproxy-2269
[ "2250" ]
d5ea08db6244e4957f9134a4313a90d3efb8dde9
diff --git a/examples/complex/har_dump.py b/examples/complex/har_dump.py --- a/examples/complex/har_dump.py +++ b/examples/complex/har_dump.py @@ -206,7 +206,7 @@ def format_request_cookies(fields): def format_response_cookies(fields): - return format_cookies((c[0], c[1].value, c[1].attrs) for c in fields) + return format_cookies((c[0], c[1][0], c[1][1]) for c in fields) def name_value(obj): diff --git a/mitmproxy/net/http/cookies.py b/mitmproxy/net/http/cookies.py --- a/mitmproxy/net/http/cookies.py +++ b/mitmproxy/net/http/cookies.py @@ -1,7 +1,7 @@ -import collections import email.utils import re import time +from typing import Tuple, List, Iterable from mitmproxy.types import multidict @@ -23,10 +23,7 @@ http://tools.ietf.org/html/rfc2965 """ -_cookie_params = set(( - 'expires', 'path', 'comment', 'max-age', - 'secure', 'httponly', 'version', -)) +_cookie_params = {'expires', 'path', 'comment', 'max-age', 'secure', 'httponly', 'version'} ESCAPE = re.compile(r"([\"\\])") @@ -43,7 +40,8 @@ def _reduce_values(values): return values[-1] -SetCookie = collections.namedtuple("SetCookie", ["value", "attrs"]) +TSetCookie = Tuple[str, str, CookieAttrs] +TPairs = List[List[str]] # TODO: Should be List[Tuple[str,str]]? def _read_until(s, start, term): @@ -131,15 +129,15 @@ def _read_cookie_pairs(s, off=0): return pairs, off -def _read_set_cookie_pairs(s, off=0): +def _read_set_cookie_pairs(s: str, off=0) -> Tuple[List[TPairs], int]: """ Read pairs of lhs=rhs values from SetCookie headers while handling multiple cookies. off: start offset specials: attributes that are treated specially """ - cookies = [] - pairs = [] + cookies = [] # type: List[TPairs] + pairs = [] # type: TPairs while True: lhs, off = _read_key(s, off, ";=,") @@ -182,7 +180,7 @@ def _read_set_cookie_pairs(s, off=0): return cookies, off -def _has_special(s): +def _has_special(s: str) -> bool: for i in s: if i in '",;\\': return True @@ -238,41 +236,44 @@ def format_cookie_header(lst): return _format_pairs(lst) -def parse_set_cookie_header(line): +def parse_set_cookie_header(line: str) -> List[TSetCookie]: """ - Parse a Set-Cookie header value + Parse a Set-Cookie header value - Returns a list of (name, value, attrs) tuples, where attrs is a + Returns: + A list of (name, value, attrs) tuples, where attrs is a CookieAttrs dict of attributes. No attempt is made to parse attribute values - they are treated purely as strings. """ cookie_pairs, off = _read_set_cookie_pairs(line) - cookies = [ - (pairs[0][0], pairs[0][1], CookieAttrs(tuple(x) for x in pairs[1:])) - for pairs in cookie_pairs if pairs - ] + cookies = [] + for pairs in cookie_pairs: + if pairs: + cookie, *attrs = pairs + cookies.append(( + cookie[0], + cookie[1], + CookieAttrs(attrs) + )) return cookies -def parse_set_cookie_headers(headers): +def parse_set_cookie_headers(headers: Iterable[str]) -> List[TSetCookie]: rv = [] for header in headers: cookies = parse_set_cookie_header(header) - if cookies: - for name, value, attrs in cookies: - rv.append((name, SetCookie(value, attrs))) + rv.extend(cookies) return rv -def format_set_cookie_header(set_cookies): +def format_set_cookie_header(set_cookies: List[TSetCookie]) -> str: """ Formats a Set-Cookie header value. """ rv = [] - for set_cookie in set_cookies: - name, value, attrs = set_cookie + for name, value, attrs in set_cookies: pairs = [(name, value)] pairs.extend( @@ -284,37 +285,36 @@ def format_set_cookie_header(set_cookies): return ", ".join(rv) -def refresh_set_cookie_header(c, delta): +def refresh_set_cookie_header(c: str, delta: int) -> str: """ Args: c: A Set-Cookie string delta: Time delta in seconds Returns: A refreshed Set-Cookie string + Raises: + ValueError, if the cookie is invalid. """ - - name, value, attrs = parse_set_cookie_header(c)[0] - if not name or not value: - raise ValueError("Invalid Cookie") - - if "expires" in attrs: - e = email.utils.parsedate_tz(attrs["expires"]) - if e: - f = email.utils.mktime_tz(e) + delta - attrs.set_all("expires", [email.utils.formatdate(f)]) - else: - # This can happen when the expires tag is invalid. - # reddit.com sends a an expires tag like this: "Thu, 31 Dec - # 2037 23:59:59 GMT", which is valid RFC 1123, but not - # strictly correct according to the cookie spec. Browsers - # appear to parse this tolerantly - maybe we should too. - # For now, we just ignore this. - del attrs["expires"] - - rv = format_set_cookie_header([(name, value, attrs)]) - if not rv: - raise ValueError("Invalid Cookie") - return rv + cookies = parse_set_cookie_header(c) + for cookie in cookies: + name, value, attrs = cookie + if not name or not value: + raise ValueError("Invalid Cookie") + + if "expires" in attrs: + e = email.utils.parsedate_tz(attrs["expires"]) + if e: + f = email.utils.mktime_tz(e) + delta + attrs.set_all("expires", [email.utils.formatdate(f)]) + else: + # This can happen when the expires tag is invalid. + # reddit.com sends a an expires tag like this: "Thu, 31 Dec + # 2037 23:59:59 GMT", which is valid RFC 1123, but not + # strictly correct according to the cookie spec. Browsers + # appear to parse this tolerantly - maybe we should too. + # For now, we just ignore this. + del attrs["expires"] + return format_set_cookie_header(cookies) def get_expiration_ts(cookie_attrs): diff --git a/mitmproxy/net/http/response.py b/mitmproxy/net/http/response.py --- a/mitmproxy/net/http/response.py +++ b/mitmproxy/net/http/response.py @@ -131,7 +131,11 @@ def reason(self, reason): def _get_cookies(self): h = self.headers.get_all("set-cookie") - return tuple(cookies.parse_set_cookie_headers(h)) + all_cookies = cookies.parse_set_cookie_headers(h) + return tuple( + (name, (value, attrs)) + for name, value, attrs in all_cookies + ) def _set_cookies(self, value): cookie_headers = []
diff --git a/test/mitmproxy/net/http/test_cookies.py b/test/mitmproxy/net/http/test_cookies.py --- a/test/mitmproxy/net/http/test_cookies.py +++ b/test/mitmproxy/net/http/test_cookies.py @@ -283,6 +283,10 @@ def test_refresh_cookie(): c = "foo/bar=bla" assert cookies.refresh_set_cookie_header(c, 0) + # https://github.com/mitmproxy/mitmproxy/issues/2250 + c = "" + assert cookies.refresh_set_cookie_header(c, 60) == "" + @mock.patch('time.time') def test_get_expiration_ts(*args):
`refresh_set_cookie_header` raises an IndexError ##### Steps to reproduce the problem: 1. `refresh_set_cookie_header("", 42)` ``` File "C:\Users\user\git\mitmproxy\mitmproxy\net\http\response.py", line 189, in refresh refreshed = cookies.refresh_set_cookie_header(set_cookie_header, delta) File "C:\Users\user\git\mitmproxy\mitmproxy\net\http\cookies.py", line 296, in refresh_set_cookie_header name, value, attrs = parse_set_cookie_header(c)[0] IndexError: list index out of range ``` ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0283-0x3d7cde0) Python version: 3.5.2 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial
2017-04-26T12:17:49
mitmproxy/mitmproxy
2,311
mitmproxy__mitmproxy-2311
[ "2310" ]
822797c7e0588695ecf318b7e7c424eda393405c
diff --git a/mitmproxy/net/http/message.py b/mitmproxy/net/http/message.py --- a/mitmproxy/net/http/message.py +++ b/mitmproxy/net/http/message.py @@ -226,8 +226,9 @@ def decode(self, strict=True): Raises: ValueError, when the content-encoding is invalid and strict is True. """ - self.raw_content = self.get_content(strict) + decoded = self.get_content(strict) self.headers.pop("content-encoding", None) + self.content = decoded def encode(self, e): """
diff --git a/test/mitmproxy/addons/test_export.py b/test/mitmproxy/addons/test_export.py --- a/test/mitmproxy/addons/test_export.py +++ b/test/mitmproxy/addons/test_export.py @@ -45,11 +45,11 @@ def tcp_flow(): class TestExportCurlCommand: def test_get(self, get_request): - result = """curl -H 'header:qvalue' -H 'content-length:7' 'http://address:22/path?a=foo&a=bar&b=baz'""" + result = """curl -H 'header:qvalue' -H 'content-length:0' 'http://address:22/path?a=foo&a=bar&b=baz'""" assert export.curl_command(get_request) == result def test_post(self, post_request): - result = "curl -X POST 'http://address:22/path' --data-binary '{}'".format( + result = "curl -H 'content-length:256' -X POST 'http://address:22/path' --data-binary '{}'".format( str(bytes(range(256)))[2:-1] ) assert export.curl_command(post_request) == result diff --git a/test/mitmproxy/net/http/test_message.py b/test/mitmproxy/net/http/test_message.py --- a/test/mitmproxy/net/http/test_message.py +++ b/test/mitmproxy/net/http/test_message.py @@ -117,6 +117,14 @@ def test_simple(self): assert r.content == b"message" assert r.raw_content != b"message" + def test_update_content_length_header(self): + r = tutils.tresp() + assert int(r.headers["content-length"]) == 7 + r.encode("gzip") + assert int(r.headers["content-length"]) == 27 + r.decode() + assert int(r.headers["content-length"]) == 7 + def test_modify(self): r = tutils.tresp() assert "content-encoding" not in r.headers
Unpacking request body (gzip) doesn't automatically update the Content-Length header ##### Steps to reproduce the problem: 1. Send a request with the body packed as gzip. 2. Enter into the request in mitmproxy and notice Content-Length shows the packed length. 3. Unpack the body (the z key) - notice the Content-Length header doesn't change, although the unpacked content length must be known at this point. Replying the request fails in my case as the server complains about the stream having more data than expected (the un-gzipped data has more bytes than gzipped). When the users goes into raw body edit mode ('e', than 'r') and just quits the editor, the Content-Length header is updated correctly. ##### System information Mitmproxy version: 2.0.2 (release version) Python version: 3.6.1 Platform: Darwin-14.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.10.5 ('', '', '') x86_64 The same behavior observed on an up-to-date Arch linux.
2017-05-03T15:28:14
mitmproxy/mitmproxy
2,325
mitmproxy__mitmproxy-2325
[ "2324", "2324", "2324" ]
81d68aa564d640a64c5394c0fcd648433e100090
diff --git a/mitmproxy/addons/onboardingapp/app.py b/mitmproxy/addons/onboardingapp/app.py --- a/mitmproxy/addons/onboardingapp/app.py +++ b/mitmproxy/addons/onboardingapp/app.py @@ -44,6 +44,18 @@ class PEM(tornado.web.RequestHandler): def filename(self): return config.CONF_BASENAME + "-ca-cert.pem" + def head(self): + p = os.path.join(self.request.master.options.cadir, self.filename) + p = os.path.expanduser(p) + content_length = os.path.getsize(p) + + self.set_header("Content-Type", "application/x-x509-ca-cert") + self.set_header( + "Content-Disposition", + "inline; filename={}".format( + self.filename)) + self.set_header("Content-Length", content_length) + def get(self): p = os.path.join(self.request.master.options.cadir, self.filename) p = os.path.expanduser(p) @@ -63,6 +75,19 @@ class P12(tornado.web.RequestHandler): def filename(self): return config.CONF_BASENAME + "-ca-cert.p12" + def head(self): + p = os.path.join(self.request.master.options.cadir, self.filename) + p = os.path.expanduser(p) + content_length = os.path.getsize(p) + + self.set_header("Content-Type", "application/x-pkcs12") + self.set_header( + "Content-Disposition", + "inline; filename={}".format( + self.filename)) + + self.set_header("Content-Length", content_length) + def get(self): p = os.path.join(self.request.master.options.cadir, self.filename) p = os.path.expanduser(p)
diff --git a/test/mitmproxy/addons/test_onboarding.py b/test/mitmproxy/addons/test_onboarding.py --- a/test/mitmproxy/addons/test_onboarding.py +++ b/test/mitmproxy/addons/test_onboarding.py @@ -1,5 +1,8 @@ +import pytest + from mitmproxy.addons import onboarding from mitmproxy.test import taddons +from mitmproxy import options from .. import tservers @@ -12,10 +15,21 @@ def test_basic(self): tctx.configure(self.addons()[0]) assert self.app("/").status_code == 200 - def test_cert(self): + @pytest.mark.parametrize("ext", ["pem", "p12"]) + def test_cert(self, ext): + with taddons.context() as tctx: + tctx.configure(self.addons()[0]) + resp = self.app("/cert/%s" % ext) + assert resp.status_code == 200 + assert resp.content + + @pytest.mark.parametrize("ext", ["pem", "p12"]) + def test_head(self, ext): with taddons.context() as tctx: tctx.configure(self.addons()[0]) - for ext in ["pem", "p12"]: - resp = self.app("/cert/%s" % ext) + p = self.pathoc() + with p.connect(): + resp = p.request("head:'http://%s/cert/%s'" % (options.APP_HOST, ext)) assert resp.status_code == 200 - assert resp.content + assert "Content-Length" in resp.headers + assert not resp.content
HEAD method not allowed to access mitm.it ##### Steps to reproduce the problem: 1. Using mitmdump in transparent mode, with on-boarding port on 6969 (did not test on 80) /mitmdump -T --host --insecure --onboarding-port 6969 2. On iPad + Chrome + Transparent mode, access to http://mitm.it:6969 3. An HEAD /cert/pem is sent, receive an "405 Method Not Allowed" Any idea of any workaround? ##### Any other comments? What have you tried so far? Exact packet: Hypertext Transfer Protocol HEAD /cert/pem HTTP/1.1\r\n Host: mitm.it:6969\r\n Connection: keep-alive\r\n User-Agent: Mozilla/5.0 (iPad; CPU OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/55.0.2883.79 Mobile/13C75 Safari/601.1.46\r\n Accept-Encoding: gzip, deflate, sdch\r\n Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4\r\n \r\n Answer: Hypertext Transfer Protocol HTTP/1.1 405 Method Not Allowed\r\n Server: TornadoServer/4.4.2\r\n Content-Length: 87\r\n Date: Tue, 09 May 2017 13:35:38 GMT\r\n Content-Type: text/html; charset=UTF-8\r\n \r\n ##### System information mitmdump --version Mitmproxy version: 2.0.1 (release version) Precompiled Binary Python version: 3.5.2 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.4 ('', '', '') x86_64 HEAD method not allowed to access mitm.it ##### Steps to reproduce the problem: 1. Using mitmdump in transparent mode, with on-boarding port on 6969 (did not test on 80) /mitmdump -T --host --insecure --onboarding-port 6969 2. On iPad + Chrome + Transparent mode, access to http://mitm.it:6969 3. An HEAD /cert/pem is sent, receive an "405 Method Not Allowed" Any idea of any workaround? ##### Any other comments? What have you tried so far? Exact packet: Hypertext Transfer Protocol HEAD /cert/pem HTTP/1.1\r\n Host: mitm.it:6969\r\n Connection: keep-alive\r\n User-Agent: Mozilla/5.0 (iPad; CPU OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/55.0.2883.79 Mobile/13C75 Safari/601.1.46\r\n Accept-Encoding: gzip, deflate, sdch\r\n Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4\r\n \r\n Answer: Hypertext Transfer Protocol HTTP/1.1 405 Method Not Allowed\r\n Server: TornadoServer/4.4.2\r\n Content-Length: 87\r\n Date: Tue, 09 May 2017 13:35:38 GMT\r\n Content-Type: text/html; charset=UTF-8\r\n \r\n ##### System information mitmdump --version Mitmproxy version: 2.0.1 (release version) Precompiled Binary Python version: 3.5.2 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.4 ('', '', '') x86_64 HEAD method not allowed to access mitm.it ##### Steps to reproduce the problem: 1. Using mitmdump in transparent mode, with on-boarding port on 6969 (did not test on 80) /mitmdump -T --host --insecure --onboarding-port 6969 2. On iPad + Chrome + Transparent mode, access to http://mitm.it:6969 3. An HEAD /cert/pem is sent, receive an "405 Method Not Allowed" Any idea of any workaround? ##### Any other comments? What have you tried so far? Exact packet: Hypertext Transfer Protocol HEAD /cert/pem HTTP/1.1\r\n Host: mitm.it:6969\r\n Connection: keep-alive\r\n User-Agent: Mozilla/5.0 (iPad; CPU OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/55.0.2883.79 Mobile/13C75 Safari/601.1.46\r\n Accept-Encoding: gzip, deflate, sdch\r\n Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4\r\n \r\n Answer: Hypertext Transfer Protocol HTTP/1.1 405 Method Not Allowed\r\n Server: TornadoServer/4.4.2\r\n Content-Length: 87\r\n Date: Tue, 09 May 2017 13:35:38 GMT\r\n Content-Type: text/html; charset=UTF-8\r\n \r\n ##### System information mitmdump --version Mitmproxy version: 2.0.1 (release version) Precompiled Binary Python version: 3.5.2 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.4 ('', '', '') x86_64
AFAIK the mitm.it just implements enough to serve the page. Any specific reason why you want to use a HEAD request? Or is this an intrinsic behaviour of Chrome for iOS? Why are they doing it? Actually it makes both requests in a row: GET, I receive a 400 HEAD, I receive 405 <img width="1173" alt="screenshot" src="https://cloud.githubusercontent.com/assets/15690818/25855704/422c2d22-34d4-11e7-9392-7255eafd38cf.png"> It works well on Safari on iPad Ok - thanks for the wireshark trace. Looks like the regular GET still works ok. Not sure now why you are seeing a HEAD request as well. But I guess there is no harm in implementing it here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L41-L57 and here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L60-L76 PRs are welcome! You mean something like `def head(self): ...` with exact same definition as def get(self)? Or it's not simple as that? More or less. The important bit is probably `self.set_header("Content-Length", "7")` AFAIK the mitm.it just implements enough to serve the page. Any specific reason why you want to use a HEAD request? Or is this an intrinsic behaviour of Chrome for iOS? Why are they doing it? Actually it makes both requests in a row: GET, I receive a 400 HEAD, I receive 405 <img width="1173" alt="screenshot" src="https://cloud.githubusercontent.com/assets/15690818/25855704/422c2d22-34d4-11e7-9392-7255eafd38cf.png"> It works well on Safari on iPad Ok - thanks for the wireshark trace. Looks like the regular GET still works ok. Not sure now why you are seeing a HEAD request as well. But I guess there is no harm in implementing it here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L41-L57 and here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L60-L76 PRs are welcome! You mean something like `def head(self): ...` with exact same definition as def get(self)? Or it's not simple as that? More or less. The important bit is probably `self.set_header("Content-Length", "7")` AFAIK the mitm.it just implements enough to serve the page. Any specific reason why you want to use a HEAD request? Or is this an intrinsic behaviour of Chrome for iOS? Why are they doing it? Actually it makes both requests in a row: GET, I receive a 400 HEAD, I receive 405 <img width="1173" alt="screenshot" src="https://cloud.githubusercontent.com/assets/15690818/25855704/422c2d22-34d4-11e7-9392-7255eafd38cf.png"> It works well on Safari on iPad Ok - thanks for the wireshark trace. Looks like the regular GET still works ok. Not sure now why you are seeing a HEAD request as well. But I guess there is no harm in implementing it here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L41-L57 and here https://github.com/mitmproxy/mitmproxy/blob/81d68aa564d640a64c5394c0fcd648433e100090/mitmproxy/addons/onboardingapp/app.py#L60-L76 PRs are welcome! You mean something like `def head(self): ...` with exact same definition as def get(self)? Or it's not simple as that? More or less. The important bit is probably `self.set_header("Content-Length", "7")`
2017-05-09T16:55:03
mitmproxy/mitmproxy
2,361
mitmproxy__mitmproxy-2361
[ "2230", "2245" ]
f4567bc9c879d3b3b87196bbf9243a4c894bd5ed
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -634,7 +634,12 @@ def convert_to_ssl(self, sni=None, alpn_protos=None, **sslctx_kwargs): if self.cert.cn: crt["subject"] = [[["commonName", self.cert.cn.decode("ascii", "strict")]]] if sni: - hostname = sni + # SNI hostnames allow support of IDN by using ASCII-Compatible Encoding + # Conversion algorithm is in RFC 3490 which is implemented by idna codec + # https://docs.python.org/3/library/codecs.html#text-encodings + # https://tools.ietf.org/html/rfc6066#section-3 + # https://tools.ietf.org/html/rfc4985#section-3 + hostname = sni.encode("idna").decode("ascii") else: hostname = "no-hostname" match_hostname(crt, hostname)
diff --git a/test/mitmproxy/net/data/server.crt b/test/mitmproxy/net/data/server.crt --- a/test/mitmproxy/net/data/server.crt +++ b/test/mitmproxy/net/data/server.crt @@ -1,14 +1,23 @@ -----BEGIN CERTIFICATE----- -MIICOzCCAaQCCQDC7f5GsEpo9jANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJO -WjEOMAwGA1UECBMFT3RhZ28xEDAOBgNVBAcTB0R1bmVkaW4xDzANBgNVBAoTBm5l -dGxpYjEPMA0GA1UECxMGbmV0bGliMQ8wDQYDVQQDEwZuZXRsaWIwHhcNMTIwNjI0 -MjI0MTU0WhcNMjIwNjIyMjI0MTU0WjBiMQswCQYDVQQGEwJOWjEOMAwGA1UECBMF -T3RhZ28xEDAOBgNVBAcTB0R1bmVkaW4xDzANBgNVBAoTBm5ldGxpYjEPMA0GA1UE -CxMGbmV0bGliMQ8wDQYDVQQDEwZuZXRsaWIwgZ8wDQYJKoZIhvcNAQEBBQADgY0A -MIGJAoGBALJSVEl9y3QUSYuXTH0UjBOPQgS0nHmNWej9hjqnA0KWvEnGY+c6yQeP -/rmwswlKw1iVV5o8kRK9Wej88YWQl/hl/xruyeJgGic0+yqY/FcueZxRudwBcWu2 -7+46aEftwLLRF0GwHZxX/HwWME+TcCXGpXGSG2qs921M4iVeBn5hAgMBAAEwDQYJ -KoZIhvcNAQEFBQADgYEAODZCihEv2yr8zmmQZDrfqg2ChxAoOXWF5+W2F/0LAUBf -2bHP+K4XE6BJWmadX1xKngj7SWrhmmTDp1gBAvXURoDaScOkB1iOCOHoIyalscTR -0FvSHKqFF8fgSlfqS6eYaSbXU3zQolvwP+URzIVnGDqgQCWPtjMqLD3Kd5tuwos= +MIID3zCCAsegAwIBAgIJAKA4XJuTgjSHMA0GCSqGSIb3DQEBCwUAMIGFMQswCQYD +VQQGEwJOWjEOMAwGA1UECAwFT3RhZ28xEDAOBgNVBAcMB0R1bmVkaW4xEjAQBgNV +BAoMCU1pdG1wcm94eTESMBAGA1UECwwJTWl0bXByb3h5MSwwKgYDVQQDDCN4bi0t +bWl0bXByb3h5c3MtdDhhOHU0Yy5leGFtcGxlLmNvbTAeFw0xNzA2MDExMTM4MTha +Fw0yNzA1MzAxMTM4MThaMIGFMQswCQYDVQQGEwJOWjEOMAwGA1UECAwFT3RhZ28x +EDAOBgNVBAcMB0R1bmVkaW4xEjAQBgNVBAoMCU1pdG1wcm94eTESMBAGA1UECwwJ +TWl0bXByb3h5MSwwKgYDVQQDDCN4bi0tbWl0bXByb3h5c3MtdDhhOHU0Yy5leGFt +cGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALkECdLZFqH8 +7JRpfdkUMew4qrric4WGM3UiLyQ8sgpCqeqK4m7Df2CAXGRze8JKjfIWSsva+y18 +xC2CCIBUFvvBgXxkvrBML+NddYNxPeV2zCjBMgjrhtKUqbHeV5Fz0WtGUoUds955 +uXeNK0d5wa4QmaRcPARTpW2UFvMrxlivI0/MQ8x3YfejAvUZaho8FvWKmB0kI6um +396xtsrYqjevofSFwi+LYx6q4mYsQke6Ubglasv9naTHEiZmrKBrtBmxuMJQjh8Q +aikeM6X/NyUC0zS6eEimjW1IPRI7hyeVPYcIBccSdkDuP5iJeuUdVa/Qx0vUp0U7 +YJoPTCyUn+ECAwEAAaNQME4wHQYDVR0OBBYEFHrTiFx1z6RP+EFK4I064u+3Jtd4 +MB8GA1UdIwQYMBaAFHrTiFx1z6RP+EFK4I064u+3Jtd4MAwGA1UdEwQFMAMBAf8w +DQYJKoZIhvcNAQELBQADggEBAIYX5dEvO44idRwFJPoleOh+mjJVeIeW0qOEf14q +pRRm3l7s+xTaxu0TnIZ2PZRmajFlmSAqoeUyowrmjMQWb63CWTz/aqDLxdS0ciD9 +/T26xYHGV5QtPsLY/O5r0LtmBXHWDIaON4vDbH72NVNUMeZAI0Mayewd6uWXgwOo +2azncUS2PO89vgX1Xjxq45bVMauwOTq2j5/1ZLb1VJ8IwfsNsvvTXJyv5iSXnuJ5 +ACIwY3auSHqRL+3fjNRgfp/YuQfZ0rZJKvVujPSig9AMoWlQ+J0K5wHptGe76O/v +PWWNho52eLHtAquwXfcyZ7RqD2qsosIJ++MnLEk+gHwmqn0= -----END CERTIFICATE----- diff --git a/test/mitmproxy/net/data/server.key b/test/mitmproxy/net/data/server.key --- a/test/mitmproxy/net/data/server.key +++ b/test/mitmproxy/net/data/server.key @@ -1,15 +1,28 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXAIBAAKBgQCyUlRJfct0FEmLl0x9FIwTj0IEtJx5jVno/YY6pwNClrxJxmPn -OskHj/65sLMJSsNYlVeaPJESvVno/PGFkJf4Zf8a7sniYBonNPsqmPxXLnmcUbnc -AXFrtu/uOmhH7cCy0RdBsB2cV/x8FjBPk3AlxqVxkhtqrPdtTOIlXgZ+YQIDAQAB -AoGAQEpGcSiVTYhy64zk2sOprPOdTa0ALSK1I7cjycmk90D5KXAJXLho+f0ETVZT -dioqO6m8J7NmamcyHznyqcDzyNRqD2hEBDGVRJWmpOjIER/JwWLNNbpeVjsMHV8I -40P5rZMOhBPYlwECSC5NtMwaN472fyGNNze8u37IZKiER/ECQQDe1iY5AG3CgkP3 -tEZB3Vtzcn4PoOr3Utyn1YER34lPqAmeAsWUhmAVEfR3N1HDe1VFD9s2BidhBn1a -/Bgqxz4DAkEAzNw0m+uO0WkD7aEYRBW7SbXCX+3xsbVToIWC1jXFG+XDzSWn++c1 -DMXEElzEJxPDA+FzQUvRTml4P92bTAbGywJAS9H7wWtm7Ubbj33UZfbGdhqfz/uF -109naufXedhgZS0c0JnK1oV+Tc0FLEczV9swIUaK5O/lGDtYDcw3AN84NwJBAIw5 -/1jrOOtm8uVp6+5O4dBmthJsEZEPCZtLSG/Qhoe+EvUN3Zq0fL+tb7USAsKs6ERz -wizj9PWzhDhTPMYhrVkCQGIponZHx6VqiFyLgYUH9+gDTjBhYyI+6yMTYzcRweyL -9Suc2NkS3X2Lp+wCjvVZdwGtStp6Vo8z02b3giIsAIY= ------END RSA PRIVATE KEY----- +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5BAnS2Rah/OyU +aX3ZFDHsOKq64nOFhjN1Ii8kPLIKQqnqiuJuw39ggFxkc3vCSo3yFkrL2vstfMQt +ggiAVBb7wYF8ZL6wTC/jXXWDcT3ldswowTII64bSlKmx3leRc9FrRlKFHbPeebl3 +jStHecGuEJmkXDwEU6VtlBbzK8ZYryNPzEPMd2H3owL1GWoaPBb1ipgdJCOrpt/e +sbbK2Ko3r6H0hcIvi2MequJmLEJHulG4JWrL/Z2kxxImZqyga7QZsbjCUI4fEGop +HjOl/zclAtM0unhIpo1tSD0SO4cnlT2HCAXHEnZA7j+YiXrlHVWv0MdL1KdFO2Ca +D0wslJ/hAgMBAAECggEARcfeJKY4QRRx7m/zRUK2qY+d5Sqvw3agRdeEzDgQNop6 +J7oGORyHGFCRiFl+HgOckegSgdyvy7I5E6jtp+kPWhjby5z7xuaVUT3YqqC1Zaxu +yBhF1NNwYFAtyKZBhNyX6cv2J7rSMmDasNqPrj+f6xTbvgADquYZiMDH/yNNhfiz +Hq6E2ojO0jjFBh/gooLo8ADk1bnpc/b5x6+DdYtjDOqioSujJbAxHTcZLpeBGBHm ++WBnxnSNpJHJQvscpry8eBMG8HSKNMgG3o5kHKdyOiJkWL5luz2xkmEnHBUBTZTI +lB5v2J2SC+XGP4R1jbbfeLIx2P+zaDkzXeaiwr/2AQKBgQD0tJZmYLmZwZHWUcya +01wJ07+K+zr8uKItI22TtjQ74svqtbP/Xg8GBjtRunf9evPEJ2tRuBqMR+3iwZXe +wB/gn+llHkSjQguLuKhlVGfreURMchTS4dvLSy+BRGKTqjryFJnUPUeqaQbijFV9 +mSbXXWGmyJkW9VSZebFg2uC20QKBgQDBjiogBmnmAeoTJp2Aj5sEtno9GU6N0IaT +TVNO66Qn0baV4LGcMb+8ogjM813FlMFtCBsrwKKrBo+slERJX1wtZ+69c5T+V1n2 +1X0B4odreH4E5Qty4nqrwv4kf7GUsqszWQEYVuzs7beTWHFVCbdYkMPRydRX6N2Q +g4s2jre8EQKBgFcSy1GyqVhk4Jf6k2ukOePlTQsPSnYS3OJi8OLWus90bEsgTORZ +e88Q+JqkV34C+iqaPD3f3NJ95dACQmn4w18Sh+JLWvEc1y7ojkNAPZo0lHD/Rxmi +9KrqHgVJaCpTMJZjbjlvdMjWhnSmquT+UivgNpc6Wf8pXOkfvFZSjBOBAoGAPodi +7H2l8Hxl1lH/R+0cs2UQEHUAf6gCEcxFQZW2rnZ9eeXg+wjHXHUsSqnEfXQVGNgp +jvTomD/CYopzlRCNgs20vtd8Jr6pfahyfg1kmj+O1p34GOE5qAuSdtAZ2mPuEuSK +Cgbq+4/AYoWL92DwLlh2Kmv9gXjlOy6D5tgsW0ECgYEAvr14NW1D+NTIEw41VWPj +gzr1hsrWoTSXQs4oDJ1ng2yrRclEpVgzytGConfxiWOFwApxOfngRYz0VZKTShQx +c6eA/948VBdveGWZcRnkD3iDyIzjXCCapHQMn8w3CxIyve4p1177WA8cPOdHfZrm +BYSkZMxKTfrmGPULj5+De+E= +-----END PRIVATE KEY----- diff --git a/test/mitmproxy/net/test_tcp.py b/test/mitmproxy/net/test_tcp.py --- a/test/mitmproxy/net/test_tcp.py +++ b/test/mitmproxy/net/test_tcp.py @@ -387,6 +387,13 @@ def test_echo(self): assert c.sni == "foo.com" assert c.rfile.readline() == b"foo.com" + def test_idn(self): + c = tcp.TCPClient(("127.0.0.1", self.port)) + with c.connect(): + c.convert_to_ssl(sni="mitmproxyäöüß.example.com") + assert c.ssl_established + assert "doesn't match" not in str(c.ssl_verification_error) + class TestServerCipherList(tservers.ServerTestBase): handler = ClientCipherListHandler
Cyrillic domains https problem ##### Steps to reproduce the problem: 1. Start http proxy 2. Go to https://фонд-достоинство.рф 3. See the problem Certificate Verification Error for фонд-достоинство.рф: hostname 'фонд-достоинство.рф' doesn't match 'xn----dtbebu0aecead5adket.xn--p1ai' ##### Any other comments? What have you tried so far? ##### System information Mitmproxy version: 2.0.1 (release version) Python version: 3.6.1 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.11.6 ('', '', '') x86_64 compare IDN hostnames without 'Certificate Verification Error' fixes #2230
Thanks for the report! This very much looks like a bug. As a short-term workaround, you can pass `--ssl-insecure` to disable upstream certificate verification. The certificate we generate seems to be okay. I want to take this. I think a message/warning like this > invalid certificate closing connection , pass `--ssl-insecure `(short = `k `) to disable certification could be a fix to this. what say @mhils @Kriechi Definitely no. If the certificate is accepted by all major browsers, it should also be accepted by mitmproxy without turning off all security. If you (or anyone else) wants to tackle this, start here: - Figure out & document the specified encoding for Subject Alternative Names - Figure out & document the specified encoding for Server Name Indication - Figure out & document why they don't match right now. - Create a test case Can you please add a testcase for this? Thanks!
2017-05-30T20:09:41
mitmproxy/mitmproxy
2,367
mitmproxy__mitmproxy-2367
[ "2329", "2329" ]
7fef4efd81495eea203af8a938d0ba89432813e2
diff --git a/mitmproxy/log.py b/mitmproxy/log.py --- a/mitmproxy/log.py +++ b/mitmproxy/log.py @@ -4,6 +4,9 @@ def __init__(self, msg, level): self.msg = msg self.level = level + def __repr__(self): + return "LogEntry({}, {})".format(self.msg, self.level) + class Log: """ diff --git a/mitmproxy/proxy/root_context.py b/mitmproxy/proxy/root_context.py --- a/mitmproxy/proxy/root_context.py +++ b/mitmproxy/proxy/root_context.py @@ -70,8 +70,16 @@ def _next_layer(self, top_layer): top_layer.server_tls, top_layer.server_conn.address[0] ) - if isinstance(top_layer, protocol.ServerConnectionMixin) or isinstance(top_layer, protocol.UpstreamConnectLayer): + if isinstance(top_layer, protocol.ServerConnectionMixin): return protocol.TlsLayer(top_layer, client_tls, client_tls) + if isinstance(top_layer, protocol.UpstreamConnectLayer): + # if the user manually sets a scheme for connect requests, we use this to decide if we + # want TLS or not. + if top_layer.connect_request.scheme: + tls = top_layer.connect_request.scheme == "https" + else: + tls = client_tls + return protocol.TlsLayer(top_layer, client_tls, tls) # 3. In Http Proxy mode and Upstream Proxy mode, the next layer is fixed. if isinstance(top_layer, protocol.TlsLayer):
diff --git a/mitmproxy/test/taddons.py b/mitmproxy/test/taddons.py --- a/mitmproxy/test/taddons.py +++ b/mitmproxy/test/taddons.py @@ -17,6 +17,8 @@ def __init__(self, master): def trigger(self, event, *args, **kwargs): if event == "log": self.master.logs.append(args[0]) + elif event == "tick" and not args and not kwargs: + pass else: self.master.events.append((event, args, kwargs)) super().trigger(event, *args, **kwargs) diff --git a/test/mitmproxy/proxy/test_server.py b/test/mitmproxy/proxy/test_server.py --- a/test/mitmproxy/proxy/test_server.py +++ b/test/mitmproxy/proxy/test_server.py @@ -1,28 +1,27 @@ import os import socket import time -import pytest from unittest import mock -from mitmproxy.test import tutils -from mitmproxy import options -from mitmproxy.addons import script -from mitmproxy.addons import proxyauth -from mitmproxy import http -from mitmproxy.proxy.config import HostMatcher +import pytest + import mitmproxy.net.http -from mitmproxy.net import tcp -from mitmproxy.net import socks from mitmproxy import certs from mitmproxy import exceptions +from mitmproxy import http +from mitmproxy import options +from mitmproxy.addons import proxyauth +from mitmproxy.addons import script +from mitmproxy.net import socks +from mitmproxy.net import tcp from mitmproxy.net.http import http1 +from mitmproxy.proxy.config import HostMatcher +from mitmproxy.test import tutils from pathod import pathoc from pathod import pathod - from .. import tservers from ...conftest import skip_appveyor - """ Note that the choice of response code in these tests matters more than you might think. libcurl treats a 304 response code differently from, say, a @@ -1009,6 +1008,40 @@ def test_change_upstream_proxy_connect(self): assert len(self.chain[0].tmaster.state.flows) == 0 assert len(self.chain[1].tmaster.state.flows) == 1 + def test_connect_https_to_http(self): + """ + https://github.com/mitmproxy/mitmproxy/issues/2329 + + Client <- HTTPS -> Proxy <- HTTP -> Proxy <- HTTPS -> Server + """ + self.proxy.tmaster.addons.add(RewriteToHttp()) + self.chain[1].tmaster.addons.add(RewriteToHttps()) + p = self.pathoc() + with p.connect(): + resp = p.request("get:'/p/418'") + + assert self.proxy.tmaster.state.flows[0].client_conn.tls_established + assert not self.proxy.tmaster.state.flows[0].server_conn.tls_established + assert not self.chain[1].tmaster.state.flows[0].client_conn.tls_established + assert self.chain[1].tmaster.state.flows[0].server_conn.tls_established + assert resp.status_code == 418 + + +class RewriteToHttp: + def http_connect(self, f): + f.request.scheme = "http" + + def request(self, f): + f.request.scheme = "http" + + +class RewriteToHttps: + def http_connect(self, f): + f.request.scheme = "https" + + def request(self, f): + f.request.scheme = "https" + class UpstreamProxyChanger: def __init__(self, addr): diff --git a/test/mitmproxy/test_log.py b/test/mitmproxy/test_log.py --- a/test/mitmproxy/test_log.py +++ b/test/mitmproxy/test_log.py @@ -1 +1,6 @@ -# TODO: write tests +from mitmproxy import log + + +def test_logentry(): + e = log.LogEntry("foo", "info") + assert repr(e) == "LogEntry(foo, info)"
Support removing SSL/TLS from upstream https connection I'm trying to use an upstream proxy that expects plain HTTP bytes instead of TLS-encapsulated HTTP for HTTPS URLs. I've tried to modify the scheme and other things but mitmproxy still continues to send a TLS client hello after the initial upstream CONNECT. It appears that this is currently unsupported in mitmproxy? ##### Steps to reproduce the problem: uplink.py: ``` from mitmproxy import ctx def http_connect(flow): flow.request.scheme = 'http' flow.request.port = 80 ctx.log.info('script: connect '+repr(flow)) def request(flow): flow.request.scheme = 'http' flow.request.port = 80 ctx.log.info('script: request '+repr(flow)) ``` 1. socat -v tcp-listen:8082,reuseaddr,fork TCP:upstreamproxy:999 2. mitmproxy -p 8081 -s uplink.py -U http://localhost:8082 --insecure --no-upstream-cert 3. curl -v -k -x http://127.0.0.1:8081 https://www.google.com The output of socat is: ``` > 2017/05/11 10:11:56.527763 length=119 from=0 to=118 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com:443\r User-Agent: curl/7.51.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 10:11:56.720058 length=116 from=0 to=115 HTTP/1.1 200 OK\r Content-Length: 0\r Date: Thu, 11 May 2017 08:11:56 GMT\r Content-Type: text/plain; charset=utf-8\r \r > 2017/05/11 10:11:56.753419 length=164 from=119 to=282 ............i..RF+,Q..2.=....... oA5T].Lt....2.,.+.$.#. . .0./.(.'.........k.g.9.3.....=.<.5./.....@.\v....... .......#...\r. ........................................< 2017/05/11 10:11:56.753987 length=82 from=116 to=197 HTTP/1.1 502 Uplink Bad Gateway\r Content-Length: 131\r Content-Type: text/plain\r \r < 2017/05/11 10:11:56.754159 length=131 from=198 to=328 malformed HTTP request "\\x16\\x03\\x01\\x00\\x9f\\x01\\x00\\x00\\x9b\\x03\\x03\\xd2i\\xe3\\xacRF+,Q\\xa4\\xec2\\xfe=\\x11\\x11\\xf1\\xfe\\xcf\\x0e\\u007f"^C⏎ ``` As you can see above, the TLS client hello `\\x16\\x03\\x01\\x00` is sent. The upstream proxy doesn't like it and replies with error 502. ##### Expected behavior If configured/scripted, mitmproxy should send upstream HTTP bytes for a HTTPS URL. ##### Any other comments? What have you tried so far? I also tried some variants of uplink.py, also the script from issue #1731 for example. I also tried switching off `--insecure` or `--no-upstream-cert`. I'm currently using those flags because Burp (which I actually intend to use instead of curl) apparently doesn't send SNI [properly](https://support.portswigger.net/customer/portal/questions/16827939-burp-does-not-set-sni-on-the-outgoing-connection-to-an-ssl-enabled-web-server). ##### System information ``` Mitmproxy version: 2.0.2 (1.2.0dev0000-0x8cba0352e) Python version: 3.6.1 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.12.4 ('', '', '') x86_64 ``` Support removing SSL/TLS from upstream https connection I'm trying to use an upstream proxy that expects plain HTTP bytes instead of TLS-encapsulated HTTP for HTTPS URLs. I've tried to modify the scheme and other things but mitmproxy still continues to send a TLS client hello after the initial upstream CONNECT. It appears that this is currently unsupported in mitmproxy? ##### Steps to reproduce the problem: uplink.py: ``` from mitmproxy import ctx def http_connect(flow): flow.request.scheme = 'http' flow.request.port = 80 ctx.log.info('script: connect '+repr(flow)) def request(flow): flow.request.scheme = 'http' flow.request.port = 80 ctx.log.info('script: request '+repr(flow)) ``` 1. socat -v tcp-listen:8082,reuseaddr,fork TCP:upstreamproxy:999 2. mitmproxy -p 8081 -s uplink.py -U http://localhost:8082 --insecure --no-upstream-cert 3. curl -v -k -x http://127.0.0.1:8081 https://www.google.com The output of socat is: ``` > 2017/05/11 10:11:56.527763 length=119 from=0 to=118 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com:443\r User-Agent: curl/7.51.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 10:11:56.720058 length=116 from=0 to=115 HTTP/1.1 200 OK\r Content-Length: 0\r Date: Thu, 11 May 2017 08:11:56 GMT\r Content-Type: text/plain; charset=utf-8\r \r > 2017/05/11 10:11:56.753419 length=164 from=119 to=282 ............i..RF+,Q..2.=....... oA5T].Lt....2.,.+.$.#. . .0./.(.'.........k.g.9.3.....=.<.5./.....@.\v....... .......#...\r. ........................................< 2017/05/11 10:11:56.753987 length=82 from=116 to=197 HTTP/1.1 502 Uplink Bad Gateway\r Content-Length: 131\r Content-Type: text/plain\r \r < 2017/05/11 10:11:56.754159 length=131 from=198 to=328 malformed HTTP request "\\x16\\x03\\x01\\x00\\x9f\\x01\\x00\\x00\\x9b\\x03\\x03\\xd2i\\xe3\\xacRF+,Q\\xa4\\xec2\\xfe=\\x11\\x11\\xf1\\xfe\\xcf\\x0e\\u007f"^C⏎ ``` As you can see above, the TLS client hello `\\x16\\x03\\x01\\x00` is sent. The upstream proxy doesn't like it and replies with error 502. ##### Expected behavior If configured/scripted, mitmproxy should send upstream HTTP bytes for a HTTPS URL. ##### Any other comments? What have you tried so far? I also tried some variants of uplink.py, also the script from issue #1731 for example. I also tried switching off `--insecure` or `--no-upstream-cert`. I'm currently using those flags because Burp (which I actually intend to use instead of curl) apparently doesn't send SNI [properly](https://support.portswigger.net/customer/portal/questions/16827939-burp-does-not-set-sni-on-the-outgoing-connection-to-an-ssl-enabled-web-server). ##### System information ``` Mitmproxy version: 2.0.2 (1.2.0dev0000-0x8cba0352e) Python version: 3.6.1 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0e 16 Feb 2017 Mac version: 10.12.4 ('', '', '') x86_64 ```
Thanks for the fantastic bug report! 😃 This seems to be a bug. Here is the socat output on master with another mitmproxy instance running on port 999: ``` mitmproxy -p 8081 -s uplink.py --mode upstream:http://localhost:8082 --ssl-insecure --set upstream_cert=false ``` ``` > 2017/05/11 13:12:03.064050 length=119 from=0 to=118 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com:443\r User-Agent: curl/7.47.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 13:12:03.120659 length=39 from=0 to=38 HTTP/1.1 200 Connection established\r \r > 2017/05/11 13:12:03.426827 length=239 from=119 to=357 ...........2...?6n.dm*w`]..qm.{.|.u...q..]<..B.+.,. .#. .$.\b./.0...'...(......./.<.5.=.A... .....3.g.9.k.E.........{.........www.google.com.\v....... <snip> socat[1498] E write(6, 0x15294a0, 31): Broken pipe > 2017/05/11 13:12:03.762322 length=115 from=0 to=114 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com\r User-Agent: curl/7.47.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 13:12:03.846242 length=39 from=0 to=38 HTTP/1.1 200 Connection established\r \r > 2017/05/11 13:12:03.849285 length=78 from=115 to=192 GET / HTTP/1.1\r Host: www.google.com\r User-Agent: curl/7.47.0\r Accept: */*\r \r < 2017/05/11 13:12:03.988207 length=243 from=39 to=281 HTTP/1.1 302 Found\r <snip> ``` This looks like we initially establish a TLS connection, but then immediately disconnect and open a new (plaintext) connection. Looking at the code, we always establish a connection [here](https://github.com/mitmproxy/mitmproxy/blob/6af72160bf98b58682b8f9fc5aabf51928d2b1d3/mitmproxy/proxy/protocol/http.py#L220). I'm not exactly sure why that is the case, maybe we just need to call `self.set_server(address)` at this point instead. @Kriechi @ujjwal96: Can one of you verify if that works? I'm moving this weekend, so I won't get to this before the end of next week. Need this feature too. Like the post I send: https://discourse.mitmproxy.org/t/upstream-mode-always-send-connect-to-upstream-server-when-using-https/412 The issue, which @icese7en linked, is the same I'm having. Thanks for the fantastic bug report! 😃 This seems to be a bug. Here is the socat output on master with another mitmproxy instance running on port 999: ``` mitmproxy -p 8081 -s uplink.py --mode upstream:http://localhost:8082 --ssl-insecure --set upstream_cert=false ``` ``` > 2017/05/11 13:12:03.064050 length=119 from=0 to=118 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com:443\r User-Agent: curl/7.47.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 13:12:03.120659 length=39 from=0 to=38 HTTP/1.1 200 Connection established\r \r > 2017/05/11 13:12:03.426827 length=239 from=119 to=357 ...........2...?6n.dm*w`]..qm.{.|.u...q..]<..B.+.,. .#. .$.\b./.0...'...(......./.<.5.=.A... .....3.g.9.k.E.........{.........www.google.com.\v....... <snip> socat[1498] E write(6, 0x15294a0, 31): Broken pipe > 2017/05/11 13:12:03.762322 length=115 from=0 to=114 CONNECT www.google.com:80 HTTP/1.1\r Host: www.google.com\r User-Agent: curl/7.47.0\r Proxy-Connection: Keep-Alive\r \r < 2017/05/11 13:12:03.846242 length=39 from=0 to=38 HTTP/1.1 200 Connection established\r \r > 2017/05/11 13:12:03.849285 length=78 from=115 to=192 GET / HTTP/1.1\r Host: www.google.com\r User-Agent: curl/7.47.0\r Accept: */*\r \r < 2017/05/11 13:12:03.988207 length=243 from=39 to=281 HTTP/1.1 302 Found\r <snip> ``` This looks like we initially establish a TLS connection, but then immediately disconnect and open a new (plaintext) connection. Looking at the code, we always establish a connection [here](https://github.com/mitmproxy/mitmproxy/blob/6af72160bf98b58682b8f9fc5aabf51928d2b1d3/mitmproxy/proxy/protocol/http.py#L220). I'm not exactly sure why that is the case, maybe we just need to call `self.set_server(address)` at this point instead. @Kriechi @ujjwal96: Can one of you verify if that works? I'm moving this weekend, so I won't get to this before the end of next week. Need this feature too. Like the post I send: https://discourse.mitmproxy.org/t/upstream-mode-always-send-connect-to-upstream-server-when-using-https/412 The issue, which @icese7en linked, is the same I'm having.
2017-06-01T21:38:05
mitmproxy/mitmproxy
2,378
mitmproxy__mitmproxy-2378
[ "2377", "2323" ]
387235b5809bc1b86f748f5da56d03eb946d1c44
diff --git a/mitmproxy/tools/console/eventlog.py b/mitmproxy/tools/console/eventlog.py --- a/mitmproxy/tools/console/eventlog.py +++ b/mitmproxy/tools/console/eventlog.py @@ -23,7 +23,7 @@ def set_focus(self, index): def keypress(self, size, key): if key == "z": - self.master.clear_events() + self.clear_events() key = None elif key == "m_end": self.set_focus(len(self.walker) - 1) diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py --- a/mitmproxy/tools/console/flowlist.py +++ b/mitmproxy/tools/console/flowlist.py @@ -69,7 +69,7 @@ def selectable(self): def mouse_event(self, size, event, button, col, row, focus): if event == "mouse press" and button == 1: if self.flow.request: - self.master.view_flow(self.flow) + self.master.commands.call("console.view.flow @focus") return True def keypress(self, xxx_todo_changeme, key):
Crash when clearing event log ##### Steps to reproduce the problem: 1. Press `E` 2. Press `z` ``` ... File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/home/ujjwal/Github/mitmproxy/mitmproxy/tools/console/window.py", line 226, in keypress k = fs.keypress(size, k) File "/home/ujjwal/Github/mitmproxy/mitmproxy/tools/console/eventlog.py", line 26, in keypress self.master.clear_events() AttributeError: 'ConsoleMaster' object has no attribute 'clear_events' ``` ##### Any other comments? What have you tried so far? Caused by: https://github.com/mitmproxy/mitmproxy/commit/0f4d94b31c02171c1cc39bf90426b61e5c2a05e1 ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0564-0x0d7b718) Python version: 3.5.2 Platform: Linux-4.9.0-040900-generic-x86_64-with-elementary-0.4.1-loki SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: "elementary" 0.4.1 loki <!-- Cut and paste the output of "mitmproxy --version". If you're using an older version if mitmproxy, please specify the version and OS. --> Crash when using mouse in mitmproxy ##### Steps to reproduce the problem: 1.Open mitmproxy 2.Click on any flow for flow details 3. ``` ... File "/home/ujjwal/Github/mitmproxy/mitmproxy/tools/console/window.py", line 206, in mouse_event k = super().mouse_event(*args, **kwargs) File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1169, in mouse_event event, button, col, row-htrim, focus ) File "/home/ujjwal/Github/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 1566, in mouse_event focus) File "/home/ujjwal/Github/mitmproxy/mitmproxy/tools/console/flowlist.py", line 72, in mouse_event self.master.view_flow(self.flow) AttributeError: 'ConsoleMaster' object has no attribute 'view_flow' ``` ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0424-0x81d68aa) Python version: 3.5.2 Platform: Linux-4.9.0-040900-generic-x86_64-with-elementary-0.4-loki SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: "elementary" 0.4 loki <!-- Cut and paste the output of "mitmproxy --version". If you're using an older version if mitmproxy, please specify the version and OS. -->
https://github.com/mitmproxy/mitmproxy/commit/0f4d94b31c02171c1cc39bf90426b61e5c2a05e1#diff-7905b817459f7672d33cc35b365d34eaR26 Change `self.master.clear_events()` to `self.clear_events()` Yes, this is a reproducible crash!
2017-06-05T21:48:05
mitmproxy/mitmproxy
2,390
mitmproxy__mitmproxy-2390
[ "2349" ]
93d37e29c382240c688c574c2369d8a947a1e8f9
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -264,6 +264,12 @@ def create_store(path, basename, o=None, cn=None, expiry=DEFAULT_EXP): # Dump the certificate in PKCS12 format for Windows devices with open(os.path.join(path, basename + "-ca-cert.p12"), "wb") as f: + p12 = OpenSSL.crypto.PKCS12() + p12.set_certificate(ca) + f.write(p12.export()) + + # Dump the certificate and key in a PKCS12 format for Windows devices + with open(os.path.join(path, basename + "-ca.p12"), "wb") as f: p12 = OpenSSL.crypto.PKCS12() p12.set_certificate(ca) p12.set_privatekey(key)
Private key is present in mitmproxy-ca-cert.p12 ##### Steps to reproduce the problem: Private key is inserted in .p12 file, although filename says "mitmproxy-ca-**cert**.p12" Output can be verified with: openssl pkcs12 -in mitmproxy-ca-cert.p12 -nocerts -nodes I don't have a Windows machine to test if a .p12 file would work without the private key inside. We can generate a .p12 file without key with: openssl pkcs12 -export -nokeys -in mitmproxy-ca-cert.pem -out mitmproxy-ca-cert.p12 -> If private key is needed, file could be renamed "mitmproxy-ca.p12" for better understanding -> If private key is not needed, .p12 generation should be modified ##### System information Mitmproxy version: 2.0.1 (release version) Precompiled Binary Python version: 3.5.2 Platform: Darwin-16.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2j 26 Sep 2016 Mac version: 10.12.5 ('', '', '') x86_64
Thanks for the useful report. I just tested this and found that the private key is not needed. Fixing this in [certs.py](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py) should be quite easy, so I'll leave this open for new contributors! :)
2017-06-12T07:45:33
mitmproxy/mitmproxy
2,402
mitmproxy__mitmproxy-2402
[ "2197" ]
646f26b0e288109f0c975d616a242d17442792eb
diff --git a/mitmproxy/master.py b/mitmproxy/master.py --- a/mitmproxy/master.py +++ b/mitmproxy/master.py @@ -162,6 +162,11 @@ def replay_request( f.response = None f.error = None + if f.request.http_version == "HTTP/2.0": # https://github.com/mitmproxy/mitmproxy/issues/2197 + f.request.http_version = "HTTP/1.1" + host = f.request.headers.pop(":authority") + f.request.headers.insert(0, "host", host) + rt = http_replay.RequestReplayThread( self.server.config, f,
diff --git a/test/mitmproxy/test_flow.py b/test/mitmproxy/test_flow.py --- a/test/mitmproxy/test_flow.py +++ b/test/mitmproxy/test_flow.py @@ -1,7 +1,8 @@ import io +from unittest import mock import pytest -from mitmproxy.test import tflow +from mitmproxy.test import tflow, tutils import mitmproxy.io from mitmproxy import flowfilter from mitmproxy import options @@ -10,6 +11,7 @@ from mitmproxy.exceptions import FlowReadException, ReplayException, ControlException from mitmproxy import flow from mitmproxy import http +from mitmproxy.net import http as net_http from mitmproxy.proxy.server import DummyServer from mitmproxy import master from . import tservers @@ -99,7 +101,9 @@ def test_load_flow_reverse(self): assert s.flows[0].request.host == "use-this-domain" def test_replay(self): - fm = master.Master(None, DummyServer()) + opts = options.Options() + conf = config.ProxyConfig(opts) + fm = master.Master(opts, DummyServer(conf)) f = tflow.tflow(resp=True) f.request.content = None with pytest.raises(ReplayException, match="missing"): @@ -117,6 +121,14 @@ def test_replay(self): with pytest.raises(ReplayException, match="live"): fm.replay_request(f) + req = tutils.treq(headers=net_http.Headers(((b":authority", b"foo"), (b"header", b"qvalue"), (b"content-length", b"7")))) + f = tflow.tflow(req=req) + f.request.http_version = "HTTP/2.0" + with mock.patch('mitmproxy.proxy.protocol.http_replay.RequestReplayThread.run'): + rt = fm.replay_request(f) + assert rt.f.request.http_version == "HTTP/1.1" + assert ":authority" not in rt.f.request.headers + def test_all(self): s = tservers.TestState() fm = master.Master(None, DummyServer())
Replay does not work with HTTP/2 flows. ##### Steps to reproduce the problem: 1. Replay a HTTP/2 flow. 2. Notice that the server fails because it expects a `host` header, but we only send an `:authority` header. ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0229-0x0c0c0d3) Python version: 3.5.2 Platform: Linux-3.4.0+-x86_64-with-Ubuntu-14.04-trusty SSL version: OpenSSL 1.0.2g-fips 1 Mar 2016 Linux distro: Ubuntu 14.04 trusty
Are you trying to replay an HTTP/2 request against a HTTP/1 server? If we would want to support this mixed-protocol-proxying, I guess we have to emulate/set that header (and possible others as well?) Not trying intentionally, but that's what currently happens if you press `r` on a HTTP/2.0 flow. So I'm not necessarily saying we have to translate headers, we could also do the replay using HTTP/2.0. Not sure what's best, but we should do one of those things. :) As discussed, the way to fix this is by always replaying via a fresh HTTP/1 connection and setting the correct headers: renaming `:authority` to `Host` (value should be the same), and changing `http_version` of the request.
2017-06-18T21:50:52
mitmproxy/mitmproxy
2,411
mitmproxy__mitmproxy-2411
[ "2407", "2407" ]
ba38a120e410f47e85387fc50f25d93f5f0fd503
diff --git a/mitmproxy/contentviews/image/image_parser.py b/mitmproxy/contentviews/image/image_parser.py --- a/mitmproxy/contentviews/image/image_parser.py +++ b/mitmproxy/contentviews/image/image_parser.py @@ -6,6 +6,7 @@ from mitmproxy.contrib.kaitaistruct import png from mitmproxy.contrib.kaitaistruct import gif from mitmproxy.contrib.kaitaistruct import jpeg +from mitmproxy.contrib.kaitaistruct import ico Metadata = typing.List[typing.Tuple[str, str]] @@ -78,3 +79,25 @@ def parse_jpeg(data: bytes) -> Metadata: if field.data is not None: parts.append((field.tag._name_, field.data.decode('UTF-8').strip('\x00'))) return parts + + +def parse_ico(data: bytes) -> Metadata: + img = ico.Ico(KaitaiStream(io.BytesIO(data))) + parts = [ + ('Format', 'ICO'), + ('Number of images', str(img.num_images)), + ] + + for i, image in enumerate(img.images): + parts.append( + ( + 'Image {}'.format(i + 1), "Size: {} x {}\n" + "{: >18}Bits per pixel: {}\n" + "{: >18}PNG: {}".format(256 if not image.width else image.width, + 256 if not image.height else image.height, + '', image.bpp, + '', image.is_png) + ) + ) + + return parts diff --git a/mitmproxy/contentviews/image/view.py b/mitmproxy/contentviews/image/view.py --- a/mitmproxy/contentviews/image/view.py +++ b/mitmproxy/contentviews/image/view.py @@ -5,6 +5,14 @@ from . import image_parser +def test_ico(h, f): + if h.startswith(b"\x00\x00\x01\x00"): + return "ico" + + +imghdr.tests.append(test_ico) + + class ViewImage(base.View): name = "Image" prompt = ("image", "i") @@ -27,6 +35,8 @@ def __call__(self, data, **metadata): image_metadata = image_parser.parse_gif(data) elif image_type == 'jpeg': image_metadata = image_parser.parse_jpeg(data) + elif image_type == 'ico': + image_metadata = image_parser.parse_ico(data) else: image_metadata = [ ("Image Format", image_type or "unknown") diff --git a/mitmproxy/contrib/kaitaistruct/ico.py b/mitmproxy/contrib/kaitaistruct/ico.py new file mode 100644 --- /dev/null +++ b/mitmproxy/contrib/kaitaistruct/ico.py @@ -0,0 +1,90 @@ +# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild + +from pkg_resources import parse_version +from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO +import struct + + +if parse_version(ks_version) < parse_version('0.7'): + raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version)) + +class Ico(KaitaiStruct): + """Microsoft Windows uses specific file format to store applications + icons - ICO. This is a container that contains one or more image + files (effectively, DIB parts of BMP files or full PNG files are + contained inside). + + .. seealso:: + Source - https://msdn.microsoft.com/en-us/library/ms997538.aspx + """ + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.magic = self._io.ensure_fixed_contents(struct.pack('4b', 0, 0, 1, 0)) + self.num_images = self._io.read_u2le() + self.images = [None] * (self.num_images) + for i in range(self.num_images): + self.images[i] = self._root.IconDirEntry(self._io, self, self._root) + + + class IconDirEntry(KaitaiStruct): + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.width = self._io.read_u1() + self.height = self._io.read_u1() + self.num_colors = self._io.read_u1() + self.reserved = self._io.ensure_fixed_contents(struct.pack('1b', 0)) + self.num_planes = self._io.read_u2le() + self.bpp = self._io.read_u2le() + self.len_img = self._io.read_u4le() + self.ofs_img = self._io.read_u4le() + + @property + def img(self): + """Raw image data. Use `is_png` to determine whether this is an + embedded PNG file (true) or a DIB bitmap (false) and call a + relevant parser, if needed to parse image data further. + """ + if hasattr(self, '_m_img'): + return self._m_img if hasattr(self, '_m_img') else None + + _pos = self._io.pos() + self._io.seek(self.ofs_img) + self._m_img = self._io.read_bytes(self.len_img) + self._io.seek(_pos) + return self._m_img if hasattr(self, '_m_img') else None + + @property + def png_header(self): + """Pre-reads first 8 bytes of the image to determine if it's an + embedded PNG file. + """ + if hasattr(self, '_m_png_header'): + return self._m_png_header if hasattr(self, '_m_png_header') else None + + _pos = self._io.pos() + self._io.seek(self.ofs_img) + self._m_png_header = self._io.read_bytes(8) + self._io.seek(_pos) + return self._m_png_header if hasattr(self, '_m_png_header') else None + + @property + def is_png(self): + """True if this image is in PNG format.""" + if hasattr(self, '_m_is_png'): + return self._m_is_png if hasattr(self, '_m_is_png') else None + + self._m_is_png = self.png_header == struct.pack('8b', -119, 80, 78, 71, 13, 10, 26, 10) + return self._m_is_png if hasattr(self, '_m_is_png') else None + + +
diff --git a/test/mitmproxy/contentviews/image/test_image_parser.py b/test/mitmproxy/contentviews/image/test_image_parser.py --- a/test/mitmproxy/contentviews/image/test_image_parser.py +++ b/test/mitmproxy/contentviews/image/test_image_parser.py @@ -167,3 +167,26 @@ def test_parse_gif(filename, metadata): def test_parse_jpeg(filename, metadata): with open(tutils.test_data.path(filename), 'rb') as f: assert metadata == image_parser.parse_jpeg(f.read()) + + [email protected]("filename, metadata", { + "mitmproxy/data/image.ico": [ + ('Format', 'ICO'), + ('Number of images', '3'), + ('Image 1', "Size: {} x {}\n" + "{: >18}Bits per pixel: {}\n" + "{: >18}PNG: {}".format(48, 48, '', 24, '', False) + ), + ('Image 2', "Size: {} x {}\n" + "{: >18}Bits per pixel: {}\n" + "{: >18}PNG: {}".format(32, 32, '', 24, '', False) + ), + ('Image 3', "Size: {} x {}\n" + "{: >18}Bits per pixel: {}\n" + "{: >18}PNG: {}".format(16, 16, '', 24, '', False) + ) + ] +}.items()) +def test_ico(filename, metadata): + with open(tutils.test_data.path(filename), 'rb') as f: + assert metadata == image_parser.parse_ico(f.read()) diff --git a/test/mitmproxy/contentviews/image/test_view.py b/test/mitmproxy/contentviews/image/test_view.py --- a/test/mitmproxy/contentviews/image/test_view.py +++ b/test/mitmproxy/contentviews/image/test_view.py @@ -9,8 +9,7 @@ def test_view_image(): "mitmproxy/data/image.png", "mitmproxy/data/image.gif", "mitmproxy/data/all.jpeg", - # https://bugs.python.org/issue21574 - # "mitmproxy/data/image.ico", + "mitmproxy/data/image.ico", ]: with open(tutils.test_data.path(img), "rb") as f: viewname, lines = v(f.read())
Add .ico content view @GreyCat added a kaitai-struct parser for ICO files in https://github.com/kaitai-io/kaitai_struct_formats/commit/22ecfbf7759c3e575bba092b27ddcc1e8f1aff9e. :tada: Given that favicons are quite common in mitmproxy, adding this would be a fantastic addition to the project! Add .ico content view @GreyCat added a kaitai-struct parser for ICO files in https://github.com/kaitai-io/kaitai_struct_formats/commit/22ecfbf7759c3e575bba092b27ddcc1e8f1aff9e. :tada: Given that favicons are quite common in mitmproxy, adding this would be a fantastic addition to the project!
2017-06-23T21:57:36
mitmproxy/mitmproxy
2,418
mitmproxy__mitmproxy-2418
[ "2315" ]
d58abc9200812a165cfc6c4f67ac2a713236d6ad
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -52,11 +52,19 @@ def addons(self): def tick(self): if time.time() - self.last_load > self.ReloadInterval: - mtime = os.stat(self.fullpath).st_mtime + try: + mtime = os.stat(self.fullpath).st_mtime + except FileNotFoundError: + scripts = ctx.options.scripts + scripts.remove(self.path) + ctx.options.update(scripts=scripts) + return + if mtime > self.last_mtime: ctx.log.info("Loading script: %s" % self.path) if self.ns: ctx.master.addons.remove(self.ns) + del sys.modules[self.ns.__name__] self.ns = load_script(ctx, self.fullpath) if self.ns: # We're already running, so we have to explicitly register and
diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py --- a/test/mitmproxy/addons/test_script.py +++ b/test/mitmproxy/addons/test_script.py @@ -1,6 +1,7 @@ import traceback import sys import time +import os import pytest from unittest import mock @@ -183,6 +184,20 @@ def test_dupes(self): scripts = ["one", "one"] ) + def test_script_deletion(self): + tdir = tutils.test_data.path("mitmproxy/data/addonscripts/") + with open(tdir + "/dummy.py", 'w') as f: + f.write("\n") + with taddons.context() as tctx: + sl = script.ScriptLoader() + tctx.master.addons.add(sl) + tctx.configure(sl, scripts=[tutils.test_data.path("mitmproxy/data/addonscripts/dummy.py")]) + + os.remove(tutils.test_data.path("mitmproxy/data/addonscripts/dummy.py")) + tctx.invoke(sl, "tick") + assert not tctx.options.scripts + assert not sl.addons + def test_order(self): rec = tutils.test_data.path("mitmproxy/data/addonscripts/recorder") sc = script.ScriptLoader()
Script Reloader does not unload old script ##### Steps to reproduce the problem: 1. mitmdump -s script.py 2. Modify script on disk. ##### System information Mitmproxy version: 3.0.0 (2.0.0dev0407-0x315daa0) Python version: 3.5.2 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial
Also: We fail badly if the script is deleted during execution.
2017-06-28T07:23:43
mitmproxy/mitmproxy
2,427
mitmproxy__mitmproxy-2427
[ "2021" ]
b115c25dcc07186e1012f57d60766625926c1d56
diff --git a/mitmproxy/contentviews/protobuf.py b/mitmproxy/contentviews/protobuf.py --- a/mitmproxy/contentviews/protobuf.py +++ b/mitmproxy/contentviews/protobuf.py @@ -1,6 +1,63 @@ -import subprocess +import io +from kaitaistruct import KaitaiStream from . import base +from mitmproxy.contrib.kaitaistruct import google_protobuf + + +def write_buf(out, field_tag, body, indent_level): + if body is not None: + out.write("{: <{level}}{}: {}\n".format('', field_tag, body if isinstance(body, int) else str(body, 'utf-8'), + level=indent_level)) + elif field_tag is not None: + out.write(' ' * indent_level + str(field_tag) + " {\n") + else: + out.write(' ' * indent_level + "}\n") + + +def format_pbuf(raw): + out = io.StringIO() + stack = [] + + try: + buf = google_protobuf.GoogleProtobuf(KaitaiStream(io.BytesIO(raw))) + except: + return False + stack.extend([(pair, 0) for pair in buf.pairs[::-1]]) + + while len(stack): + pair, indent_level = stack.pop() + + if pair.wire_type == pair.WireTypes.group_start: + body = None + elif pair.wire_type == pair.WireTypes.group_end: + body = None + pair._m_field_tag = None + elif pair.wire_type == pair.WireTypes.len_delimited: + body = pair.value.body + elif pair.wire_type == pair.WireTypes.varint: + body = pair.value.value + else: + body = pair.value + + try: + next_buf = google_protobuf.GoogleProtobuf(KaitaiStream(io.BytesIO(body))) + stack.extend([(pair, indent_level + 2) for pair in next_buf.pairs[::-1]]) + write_buf(out, pair.field_tag, None, indent_level) + except: + write_buf(out, pair.field_tag, body, indent_level) + + if stack: + prev_level = stack[-1][1] + else: + prev_level = 0 + + if prev_level < indent_level: + levels = int((indent_level - prev_level) / 2) + for i in range(1, levels + 1): + write_buf(out, None, None, indent_level - i * 2) + + return out.getvalue() class ViewProtobuf(base.View): @@ -15,28 +72,9 @@ class ViewProtobuf(base.View): "application/x-protobuffer", ] - def is_available(self): - try: - p = subprocess.Popen( - ["protoc", "--version"], - stdout=subprocess.PIPE - ) - out, _ = p.communicate() - return out.startswith(b"libprotoc") - except: - return False - def __call__(self, data, **metadata): - if not self.is_available(): - raise NotImplementedError("protoc not found. Please make sure 'protoc' is available in $PATH.") - - # if Popen raises OSError, it will be caught in - # get_content_view and fall back to Raw - p = subprocess.Popen(['protoc', '--decode_raw'], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - decoded, _ = p.communicate(input=data) + decoded = format_pbuf(data) if not decoded: raise ValueError("Failed to parse input.") + return "Protobuf", base.format_text(decoded) diff --git a/mitmproxy/contrib/kaitaistruct/google_protobuf.py b/mitmproxy/contrib/kaitaistruct/google_protobuf.py new file mode 100644 --- /dev/null +++ b/mitmproxy/contrib/kaitaistruct/google_protobuf.py @@ -0,0 +1,124 @@ +# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild + +from pkg_resources import parse_version +from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO +from enum import Enum + + +if parse_version(ks_version) < parse_version('0.7'): + raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version)) + +from .vlq_base128_le import VlqBase128Le +class GoogleProtobuf(KaitaiStruct): + """Google Protocol Buffers (AKA protobuf) is a popular data + serialization scheme used for communication protocols, data storage, + etc. There are implementations are available for almost every + popular language. The focus points of this scheme are brevity (data + is encoded in a very size-efficient manner) and extensibility (one + can add keys to the structure, while keeping it readable in previous + version of software). + + Protobuf uses semi-self-describing encoding scheme for its + messages. It means that it is possible to parse overall structure of + the message (skipping over fields one can't understand), but to + fully understand the message, one needs a protocol definition file + (`.proto`). To be specific: + + * "Keys" in key-value pairs provided in the message are identified + only with an integer "field tag". `.proto` file provides info on + which symbolic field names these field tags map to. + * "Keys" also provide something called "wire type". It's not a data + type in its common sense (i.e. you can't, for example, distinguish + `sint32` vs `uint32` vs some enum, or `string` from `bytes`), but + it's enough information to determine how many bytes to + parse. Interpretation of the value should be done according to the + type specified in `.proto` file. + * There's no direct information on which fields are optional / + required, which fields may be repeated or constitute a map, what + restrictions are placed on fields usage in a single message, what + are the fields' default values, etc, etc. + + .. seealso:: + Source - https://developers.google.com/protocol-buffers/docs/encoding + """ + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.pairs = [] + while not self._io.is_eof(): + self.pairs.append(self._root.Pair(self._io, self, self._root)) + + + class Pair(KaitaiStruct): + """Key-value pair.""" + + class WireTypes(Enum): + varint = 0 + bit_64 = 1 + len_delimited = 2 + group_start = 3 + group_end = 4 + bit_32 = 5 + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.key = VlqBase128Le(self._io) + _on = self.wire_type + if _on == self._root.Pair.WireTypes.varint: + self.value = VlqBase128Le(self._io) + elif _on == self._root.Pair.WireTypes.len_delimited: + self.value = self._root.DelimitedBytes(self._io, self, self._root) + elif _on == self._root.Pair.WireTypes.bit_64: + self.value = self._io.read_u8le() + elif _on == self._root.Pair.WireTypes.bit_32: + self.value = self._io.read_u4le() + + @property + def wire_type(self): + """"Wire type" is a part of the "key" that carries enough + information to parse value from the wire, i.e. read correct + amount of bytes, but there's not enough informaton to + interprete in unambiguously. For example, one can't clearly + distinguish 64-bit fixed-sized integers from 64-bit floats, + signed zigzag-encoded varints from regular unsigned varints, + arbitrary bytes from UTF-8 encoded strings, etc. + """ + if hasattr(self, '_m_wire_type'): + return self._m_wire_type if hasattr(self, '_m_wire_type') else None + + self._m_wire_type = self._root.Pair.WireTypes((self.key.value & 7)) + return self._m_wire_type if hasattr(self, '_m_wire_type') else None + + @property + def field_tag(self): + """Identifies a field of protocol. One can look up symbolic + field name in a `.proto` file by this field tag. + """ + if hasattr(self, '_m_field_tag'): + return self._m_field_tag if hasattr(self, '_m_field_tag') else None + + self._m_field_tag = (self.key.value >> 3) + return self._m_field_tag if hasattr(self, '_m_field_tag') else None + + + class DelimitedBytes(KaitaiStruct): + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.len = VlqBase128Le(self._io) + self.body = self._io.read_bytes(self.len.value) + + + diff --git a/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py b/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py new file mode 100644 --- /dev/null +++ b/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py @@ -0,0 +1,94 @@ +# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild + +from pkg_resources import parse_version +from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO + + +if parse_version(ks_version) < parse_version('0.7'): + raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version)) + +class VlqBase128Le(KaitaiStruct): + """A variable-length unsigned integer using base128 encoding. 1-byte groups + consists of 1-bit flag of continuation and 7-bit value, and are ordered + "least significant group first", i.e. in "little-endian" manner. + + This particular encoding is specified and used in: + + * DWARF debug file format, where it's dubbed "unsigned LEB128" or "ULEB128". + http://dwarfstd.org/doc/dwarf-2.0.0.pdf - page 139 + * Google Protocol Buffers, where it's called "Base 128 Varints". + https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints + * Apache Lucene, where it's called "VInt" + http://lucene.apache.org/core/3_5_0/fileformats.html#VInt + * Apache Avro uses this as a basis for integer encoding, adding ZigZag on + top of it for signed ints + http://avro.apache.org/docs/current/spec.html#binary_encode_primitive + + More information on this encoding is available at https://en.wikipedia.org/wiki/LEB128 + + This particular implementation supports serialized values to up 8 bytes long. + """ + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.groups = [] + while True: + _ = self._root.Group(self._io, self, self._root) + self.groups.append(_) + if not (_.has_next): + break + + class Group(KaitaiStruct): + """One byte group, clearly divided into 7-bit "value" and 1-bit "has continuation + in the next byte" flag. + """ + def __init__(self, _io, _parent=None, _root=None): + self._io = _io + self._parent = _parent + self._root = _root if _root else self + self._read() + + def _read(self): + self.b = self._io.read_u1() + + @property + def has_next(self): + """If true, then we have more bytes to read.""" + if hasattr(self, '_m_has_next'): + return self._m_has_next if hasattr(self, '_m_has_next') else None + + self._m_has_next = (self.b & 128) != 0 + return self._m_has_next if hasattr(self, '_m_has_next') else None + + @property + def value(self): + """The 7-bit (base128) numeric value of this group.""" + if hasattr(self, '_m_value'): + return self._m_value if hasattr(self, '_m_value') else None + + self._m_value = (self.b & 127) + return self._m_value if hasattr(self, '_m_value') else None + + + @property + def len(self): + if hasattr(self, '_m_len'): + return self._m_len if hasattr(self, '_m_len') else None + + self._m_len = len(self.groups) + return self._m_len if hasattr(self, '_m_len') else None + + @property + def value(self): + """Resulting value as normal integer.""" + if hasattr(self, '_m_value'): + return self._m_value if hasattr(self, '_m_value') else None + + self._m_value = (((((((self.groups[0].value + ((self.groups[1].value << 7) if self.len >= 2 else 0)) + ((self.groups[2].value << 14) if self.len >= 3 else 0)) + ((self.groups[3].value << 21) if self.len >= 4 else 0)) + ((self.groups[4].value << 28) if self.len >= 5 else 0)) + ((self.groups[5].value << 35) if self.len >= 6 else 0)) + ((self.groups[6].value << 42) if self.len >= 7 else 0)) + ((self.groups[7].value << 49) if self.len >= 8 else 0)) + return self._m_value if hasattr(self, '_m_value') else None + +
diff --git a/test/mitmproxy/contentviews/test_protobuf.py b/test/mitmproxy/contentviews/test_protobuf.py --- a/test/mitmproxy/contentviews/test_protobuf.py +++ b/test/mitmproxy/contentviews/test_protobuf.py @@ -1,52 +1,31 @@ -from unittest import mock import pytest from mitmproxy.contentviews import protobuf from mitmproxy.test import tutils from . import full_eval +data = tutils.test_data.push("mitmproxy/contentviews/test_protobuf_data/") + def test_view_protobuf_request(): v = full_eval(protobuf.ViewProtobuf()) - p = tutils.test_data.path("mitmproxy/data/protobuf01") - - with mock.patch('mitmproxy.contentviews.protobuf.ViewProtobuf.is_available'): - with mock.patch('subprocess.Popen') as n: - m = mock.Mock() - attrs = {'communicate.return_value': (b'1: "3bbc333c-e61c-433b-819a-0b9a8cc103b8"', True)} - m.configure_mock(**attrs) - n.return_value = m - - with open(p, "rb") as f: - data = f.read() - content_type, output = v(data) - assert content_type == "Protobuf" - assert output[0] == [('text', b'1: "3bbc333c-e61c-433b-819a-0b9a8cc103b8"')] - - m.communicate = mock.MagicMock() - m.communicate.return_value = (None, None) - with pytest.raises(ValueError, matches="Failed to parse input."): - v(b'foobar') - - -def test_view_protobuf_availability(): - with mock.patch('subprocess.Popen') as n: - m = mock.Mock() - attrs = {'communicate.return_value': (b'libprotoc fake version', True)} - m.configure_mock(**attrs) - n.return_value = m - assert protobuf.ViewProtobuf().is_available() - - m = mock.Mock() - attrs = {'communicate.return_value': (b'command not found', True)} - m.configure_mock(**attrs) - n.return_value = m - assert not protobuf.ViewProtobuf().is_available() - - -def test_view_protobuf_fallback(): - with mock.patch('subprocess.Popen.communicate') as m: - m.side_effect = OSError() - v = full_eval(protobuf.ViewProtobuf()) - with pytest.raises(NotImplementedError, matches='protoc not found'): - v(b'foobar') + p = data.path("protobuf01") + + with open(p, "rb") as f: + raw = f.read() + content_type, output = v(raw) + assert content_type == "Protobuf" + assert output == [[('text', '1: 3bbc333c-e61c-433b-819a-0b9a8cc103b8')]] + with pytest.raises(ValueError, matches="Failed to parse input."): + v(b'foobar') + + [email protected]("filename", ["protobuf02", "protobuf03"]) +def test_format_pbuf(filename): + path = data.path(filename) + with open(path, "rb") as f: + input = f.read() + with open(path + "-decoded") as f: + expected = f.read() + + assert protobuf.format_pbuf(input) == expected diff --git a/test/mitmproxy/data/protobuf01 b/test/mitmproxy/contentviews/test_protobuf_data/protobuf01 similarity index 100% rename from test/mitmproxy/data/protobuf01 rename to test/mitmproxy/contentviews/test_protobuf_data/protobuf01 diff --git a/test/mitmproxy/contentviews/test_protobuf_data/protobuf02 b/test/mitmproxy/contentviews/test_protobuf_data/protobuf02 new file mode 100644 Binary files /dev/null and b/test/mitmproxy/contentviews/test_protobuf_data/protobuf02 differ diff --git a/test/mitmproxy/contentviews/test_protobuf_data/protobuf02-decoded b/test/mitmproxy/contentviews/test_protobuf_data/protobuf02-decoded new file mode 100644 --- /dev/null +++ b/test/mitmproxy/contentviews/test_protobuf_data/protobuf02-decoded @@ -0,0 +1,65 @@ +1 { + 1: tpbuf + 4 { + 1: Person + 2 { + 1: name + 3: 1 + 4: 2 + 5: 9 + } + 2 { + 1: id + 3: 2 + 4: 2 + 5: 5 + } + 2 { + 1 { + 12: 1818845549 + } + 3: 3 + 4: 1 + 5: 9 + } + 2 { + 1: phone + 3: 4 + 4: 3 + 5: 11 + 6: .Person.PhoneNumber + } + 3 { + 1: PhoneNumber + 2 { + 1: number + 3: 1 + 4: 2 + 5: 9 + } + 2 { + 1: type + 3: 2 + 4: 1 + 5: 14 + 6: .Person.PhoneType + 7: HOME + } + } + 4 { + 1: PhoneType + 2 { + 1: MOBILE + 2: 0 + } + 2 { + 1: HOME + 2: 1 + } + 2 { + 1: WORK + 2: 2 + } + } + } +} diff --git a/test/mitmproxy/contentviews/test_protobuf_data/protobuf03 b/test/mitmproxy/contentviews/test_protobuf_data/protobuf03 new file mode 100644 --- /dev/null +++ b/test/mitmproxy/contentviews/test_protobuf_data/protobuf03 @@ -0,0 +1 @@ +� � \ No newline at end of file diff --git a/test/mitmproxy/contentviews/test_protobuf_data/protobuf03-decoded b/test/mitmproxy/contentviews/test_protobuf_data/protobuf03-decoded new file mode 100644 --- /dev/null +++ b/test/mitmproxy/contentviews/test_protobuf_data/protobuf03-decoded @@ -0,0 +1,4 @@ +2 { +3: 3840 +4: 2160 +}
refactor protobuf contentview Currently the protobuf contentview relies on the `protoc` compiler to be available as shell command (in `$PATH`). https://github.com/mitmproxy/mitmproxy/blob/75a0a4c09276ef2aa479c9ae9feab97f7803ed6d/mitmproxy/contentviews/protobuf.py However, it would be much cleaner to directly use the Python API provided by https://github.com/google/protobuf https://developers.google.com/protocol-buffers/docs/pythontutorial We already have that package as dependency, so why not use it?
I will like to fix this issue. I will start working on it now. It looks like the Python API from google-protobuf has a some severe limitations and is not capable of decoding serialized messages without the `.proto` file. From the official docs: > The current Python implementation does not track unknown fields. So the only output we really can get our hands on is the one from `protoc` CLI tool, and even this only gives us key-value pairs with raw field IDs. I believe that this could also be done with a simple construct or kaitai decoder to parse the on-the-wire representation into their (nested) key-value tuples. https://developers.google.com/protocol-buffers/docs/encoding kaitai just got protobuf support! https://github.com/kaitai-io/kaitai_struct_formats/commit/d4f066eacb4132807bec3fc8ddf9f6e7e690ae34 Yes, implementing this with kaitaistruct is the way to go. @saganshul, did you start working on this? Otherwise this is free for pick up again. @mhils I started looking for support for raw decoding in google prototype python module. I got same thing as @Kriechi said. I will take a look at kaitai_struct_format and try to resolve this issue. @mhils @Kriechi **Error on compiling google_protobuf.ksy using kaitai-struct-compiler** Exception in thread "main" io.kaitai.struct.translators.TypeMismatchError: called invalid attribute 'size' on expression of type ArrayType(UserTypeInstream(List(group))) at io.kaitai.struct.translators.BaseTranslator.detectType(BaseTranslator.scala:337) at io.kaitai.struct.TypeProcessor$$anonfun$deriveValueType$1.apply(TypeProcessor.scala:63) at io.kaitai.struct.TypeProcessor$$anonfun$deriveValueType$1.apply(TypeProcessor.scala:56) at scala.collection.immutable.Map$Map2.foreach(Map.scala:137) at io.kaitai.struct.TypeProcessor$.deriveValueType(TypeProcessor.scala:56) at io.kaitai.struct.TypeProcessor$$anonfun$deriveValueType$2.apply(TypeProcessor.scala:83) at io.kaitai.struct.TypeProcessor$$anonfun$deriveValueType$2.apply(TypeProcessor.scala:81) at scala.collection.immutable.Map$Map3.foreach(Map.scala:161) at io.kaitai.struct.TypeProcessor$.deriveValueType(TypeProcessor.scala:81) at io.kaitai.struct.TypeProcessor$.deriveValueTypes(TypeProcessor.scala:44) at io.kaitai.struct.TypeProcessor$.processTypes(TypeProcessor.scala:16) at io.kaitai.struct.formats.JavaKSYParser$.localFileToSpec(JavaKSYParser.scala:17) at io.kaitai.struct.Main$.compileOne(Main.scala:83) at io.kaitai.struct.Main$$anonfun$main$1.apply(Main.scala:120) at io.kaitai.struct.Main$$anonfun$main$1.apply(Main.scala:115) at scala.collection.immutable.List.foreach(List.scala:381) at io.kaitai.struct.Main$.main(Main.scala:115) at io.kaitai.struct.Main.main(Main.scala) Do you guys know how to fix this? I am working on this. As of now, we're waiting for KS 0.7 to be released as the `.ksy` file uses `size` which is unsupported for KS < 0.7. Upgrading to 0.7 will also involve recompiling the files used for image parsing in `mitmproxy/contrib/kaitaistruct`. @s4chin any update on this? I asked the KS team about the release date. KS 0.7 was supposed to released this Monday, but was delayed. Now it's 50% done, shouldn't be too long. Thanks! :)
2017-07-05T09:25:32
mitmproxy/mitmproxy
2,473
mitmproxy__mitmproxy-2473
[ "2464" ]
d409a6c09a873c8131c5e6938aea496904f324c3
diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -217,16 +217,19 @@ def handle_regular_connect(self, f): return False def handle_upstream_connect(self, f): - self.establish_server_connection( - f.request.host, - f.request.port, - f.request.scheme - ) - self.send_request(f.request) - f.response = self.read_response_headers() - f.response.data.content = b"".join( - self.read_response_body(f.request, f.response) - ) + # if the user specifies a response in the http_connect hook, we do not connect upstream here. + # https://github.com/mitmproxy/mitmproxy/pull/2473 + if not f.response: + self.establish_server_connection( + f.request.host, + f.request.port, + f.request.scheme + ) + self.send_request(f.request) + f.response = self.read_response_headers() + f.response.data.content = b"".join( + self.read_response_body(f.request, f.response) + ) self.send_response(f.response) if is_ok(f.response.status_code): layer = UpstreamConnectLayer(self, f.request)
Postpone establishing connection with server Hi, I use mitmproxy in upstream mode as a flow replayer by loading a couple scripts and resource files. It's never intended to deliver a request to remote server. Everything is ok except that, although each of the canned responses (loaded from a file on the disk) is correctly returned to the client, it actually makes connection to remote server on each of the flow via the upstream proxy server I configured in the cmd line, which is totally unnecessary and time-wasting in my senario. Would it be possible to postpone the establishing of connection with server (after the request() hook has been revoked) so that my upstream mitmproxy server can run with a dummy -U flag, which don't have to be a real proxy server at all, as it never should really forward a request/establish a connection to remote server?
Thanks for raising this. As you never intend to send a request upstream, have you tried just using mitmproxy in regular mode instead? That should give you the desired behaviour. In any case, we need to make the strategy for upstream connections user-decidable. I tracked this in #1775. Interesting, yes, as you suggested, it works in regular mode, even if machine the mitmproxy resides on does not have internet connection at all. However, most of my other client apps would require features of upstream forwarding. Would it be possible for me to server both client apps with one single mitmproxy instance (as they require shared features that are implemented as inline scripts already)? I'm not sure if I get your question correctly. You can only run one proxy mode at the same time. If you need to mitmproxy instances, I would suggest to just run them on different ports.
2017-07-26T10:20:36
mitmproxy/mitmproxy
2,490
mitmproxy__mitmproxy-2490
[ "2334" ]
e8f836425a64a786f0d68c6b2a0b682e7cf6e00a
diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py --- a/mitmproxy/addons/proxyauth.py +++ b/mitmproxy/addons/proxyauth.py @@ -61,7 +61,7 @@ def is_proxy_auth(self) -> bool: - True, if authentication is done as if mitmproxy is a proxy - False, if authentication is done as if mitmproxy is a HTTP server """ - return ctx.options.mode in ("regular", "upstream") + return ctx.options.mode == "regular" or ctx.options.mode.startswith("upstream:") def which_auth_header(self) -> str: if self.is_proxy_auth():
Unable to use upstream proxy and proxy authentification ##### Steps to reproduce the problem: 1. git clone https://github.com/mitmproxy/mitmproxy.git 2. cd mitmproxy 3. ./dev.sh 4. . venv/bin/activate 5. mitmdump --proxyauth test:test -m upstream:http://10.7.0.225:8080/ --ssl-insecure On 10.7.0.225, I have a VM that runs mitmproxy : 6. mitmdump --insecure ##### Any other comments? What have you tried so far? It seems that each time you have a clientdisconnect/clientconnect, you get a new prompt to login (proxyauth). Basically for each domain you have to login to the proxyauth, here test/test. I wild guess would be that the information in the header to pass by the upstreamproxy somehow is not compatible with the header auth information ##### System information HOST : ``` Mitmproxy version: 3.0.0 (2.0.0dev0435-0x1c6b33f) Python version: 3.6.0 Platform: Linux-4.9.0-0.bpo.2-amd64-x86_64-with-debian-8.7 SSL version: OpenSSL 1.1.0e 16 Feb 2017 Linux distro: debian 8.7 ``` VM (10.7.0.225): ``` Mitmproxy version : 2.0.0 (release version) Python version : 3.5.2 Platform : Linux-4.4.0-75-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial ```
Thanks for the report. [This](https://github.com/mitmproxy/mitmproxy/blob/69c5a0b6993f70340a0a4b99159086c638d77103/mitmproxy/addons/proxyauth.py#L64) is faulty, because the mode is now `upstream:...`, not just `upstream`. I fixed it with just a minor change, show I create a pull request ? ``` - return ctx.options.mode in ("regular", "upstream") + if ctx.options.mode == "regular" or "upstream" in ctx.options.mode: + return True + else: + return False ``` Go ahead please!
2017-08-01T19:48:15
mitmproxy/mitmproxy
2,509
mitmproxy__mitmproxy-2509
[ "2495" ]
802e8cb34105ac7464838fc57ba2294428f9d3c2
diff --git a/mitmproxy/io/compat.py b/mitmproxy/io/compat.py --- a/mitmproxy/io/compat.py +++ b/mitmproxy/io/compat.py @@ -58,7 +58,7 @@ def convert_017_018(data): # convert_unicode needs to be called for every dual release and the first py3-only release data = convert_unicode(data) - data["server_conn"]["ip_address"] = data["server_conn"].pop("peer_address") + data["server_conn"]["ip_address"] = data["server_conn"].pop("peer_address", None) data["marked"] = False data["version"] = (0, 18) return data
Keyerror in compat 0.17 - peer_address I get this error when loading an old 0.17 dump file: ``` Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/2.0.2/bin/mitmdump", line 11, in <module> load_entry_point('mitmproxy==2.0.2', 'console_scripts', 'mitmdump')() File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/tools/main.py", line 120, in mitmdump master = dump.DumpMaster(dump_options, server) File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/tools/dump.py", line 55, in __init__ self.load_flows_file(options.rfile) File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/master.py", line 182, in load_flows_file return self.load_flows(freader) File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/master.py", line 164, in load_flows for i in fr.stream(): File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/io.py", line 42, in stream data = io_compat.migrate_flow(data) File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/io_compat.py", line 152, in migrate_flow flow_data = converters[flow_version[:2]](flow_data) File "/usr/local/Cellar/mitmproxy/2.0.2/libexec/lib/python3.6/site-packages/mitmproxy/io_compat.py", line 61, in convert_017_018 data["server_conn"]["ip_address"] = data["server_conn"].pop("peer_address") KeyError: 'peer_address' ``` ##### Steps to reproduce the problem: 1. Create an outfile with mitmproxy 0.17 2. Open with mitmdump 2.0.2 3. Get a keyerror on "peer_address" ##### Any other comments? What have you tried so far? Was told on slack to create an issue, however I can't supply the test files because they contain sensitive data. ##### System information $ /usr/local/Cellar/mitmproxy/2.0.2/bin/mitmdump --version Mitmproxy version: 2.0.2 (release version) Python version: 3.6.2 Platform: Darwin-16.7.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0f 25 May 2017 Mac version: 10.12.6 ('', '', '') x86_64
Commenting from my actual account to keep track of it - accidentally created the issue on the wrong account. 0.17 is old enough that we won't maintain this ourselves anymore, but I'd certainly accept a PR that fixes this, which should be easy.
2017-08-09T21:05:56
mitmproxy/mitmproxy
2,556
mitmproxy__mitmproxy-2556
[ "2477" ]
7bd930693e809af7c0fc89aa0edb28975f30e44a
diff --git a/examples/complex/xss_scanner.py b/examples/complex/xss_scanner.py --- a/examples/complex/xss_scanner.py +++ b/examples/complex/xss_scanner.py @@ -198,7 +198,7 @@ def get_SQLi_data(new_body: str, original_body: str, request_URL: str, injection } for dbms, regexes in DBMS_ERRORS.items(): for regex in regexes: - if re.search(regex, new_body) and not re.search(regex, original_body): + if re.search(regex, new_body, re.IGNORECASE) and not re.search(regex, original_body, re.IGNORECASE): return SQLiData(request_URL, injection_point, regex,
xss_scanner.py issue hi in the function test_query_injection the body is converted to lower case (line 153) but in the get_SQLi_data function it is compared with upper case words (line 187) that results in no match ##### System information
Thanks for the report! Would you mind sending a pull request that fixes this? 😃 sure, also there are issuse with "decode" in log_SQLi_data function(line 176-179) that causes to error. Im working on a new sqli example that also test post data for sqli and save vulnerable hosts to file.
2017-09-01T07:57:31
mitmproxy/mitmproxy
2,573
mitmproxy__mitmproxy-2573
[ "2572" ]
9716b3dab57735099e4c2ac27aebe87b61896087
diff --git a/mitmproxy/contentviews/__init__.py b/mitmproxy/contentviews/__init__.py --- a/mitmproxy/contentviews/__init__.py +++ b/mitmproxy/contentviews/__init__.py @@ -22,7 +22,7 @@ from mitmproxy.net import http from mitmproxy.utils import strutils from . import ( - auto, raw, hex, json, xml_html, html_outline, wbxml, javascript, css, + auto, raw, hex, json, xml_html, wbxml, javascript, css, urlencoded, multipart, image, query, protobuf ) from .base import View, VIEW_CUTOFF, KEY_MAX, format_text, format_dict, TViewResult @@ -168,7 +168,6 @@ def get_content_view(viewmode: View, data: bytes, **metadata): add(json.ViewJSON()) add(xml_html.ViewXmlHtml()) add(wbxml.ViewWBXML()) -add(html_outline.ViewHTMLOutline()) add(javascript.ViewJavaScript()) add(css.ViewCSS()) add(urlencoded.ViewURLEncoded()) diff --git a/mitmproxy/contentviews/html_outline.py b/mitmproxy/contentviews/html_outline.py deleted file mode 100644 --- a/mitmproxy/contentviews/html_outline.py +++ /dev/null @@ -1,17 +0,0 @@ -import html2text - -from mitmproxy.contentviews import base - - -class ViewHTMLOutline(base.View): - name = "HTML Outline" - prompt = ("html outline", "o") - content_types = ["text/html"] - - def __call__(self, data, **metadata): - data = data.decode("utf-8", "replace") - h = html2text.HTML2Text(baseurl="") - h.ignore_images = True - h.body_width = 0 - outline = h.handle(data) - return "HTML Outline", base.format_text(outline) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -66,7 +66,6 @@ "click>=6.2, <7", "cryptography>=2.0,<2.1", "h2>=3.0, <4", - "html2text>=2016.1.8, <=2016.9.19", "hyperframe>=5.0, <6", "kaitaistruct>=0.7, <0.8", "ldap3>=2.2.0, <2.4",
diff --git a/test/mitmproxy/contentviews/test_html_outline.py b/test/mitmproxy/contentviews/test_html_outline.py deleted file mode 100644 --- a/test/mitmproxy/contentviews/test_html_outline.py +++ /dev/null @@ -1,9 +0,0 @@ -from mitmproxy.contentviews import html_outline -from test.mitmproxy.contentviews import full_eval - - -def test_view_html_outline(): - v = full_eval(html_outline.ViewHTMLOutline()) - s = b"<html><br><br></br><p>one</p></html>" - assert v(s) - assert v(b'\xfe')
MIT incompatible with GPL3 I was pleased to see mitmproxy is licensed under MIT. At least one dependency, html2text, is licensed under GPL3. This is a problem as per https://opensource.stackexchange.com/questions/1640/if-im-using-a-gpl-3-library-in-my-project-can-i-license-my-project-under-mit-l. Can we resolve this incompatible licensing issue? html2text is barely used. I think it could be removed.
2017-09-14T22:12:30
mitmproxy/mitmproxy
2,606
mitmproxy__mitmproxy-2606
[ "2563", "2563" ]
45145ed08b7623add9a96bfcdcd02a746e44124a
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -4,6 +4,7 @@ import datetime import ipaddress import sys +import typing from pyasn1.type import univ, constraint, char, namedtype, tag from pyasn1.codec.der.decoder import decode @@ -114,46 +115,6 @@ def dummy_cert(privkey, cacert, commonname, sans): return SSLCert(cert) -# DNTree did not pass TestCertStore.test_sans_change and is temporarily replaced by a simple dict. -# -# class _Node(UserDict.UserDict): -# def __init__(self): -# UserDict.UserDict.__init__(self) -# self.value = None -# -# -# class DNTree: -# """ -# Domain store that knows about wildcards. DNS wildcards are very -# restricted - the only valid variety is an asterisk on the left-most -# domain component, i.e.: -# -# *.foo.com -# """ -# def __init__(self): -# self.d = _Node() -# -# def add(self, dn, cert): -# parts = dn.split(".") -# parts.reverse() -# current = self.d -# for i in parts: -# current = current.setdefault(i, _Node()) -# current.value = cert -# -# def get(self, dn): -# parts = dn.split(".") -# current = self.d -# for i in reversed(parts): -# if i in current: -# current = current[i] -# elif "*" in current: -# return current["*"].value -# else: -# return None -# return current.value - - class CertStoreEntry: def __init__(self, cert, privatekey, chain_file): @@ -162,6 +123,11 @@ def __init__(self, cert, privatekey, chain_file): self.chain_file = chain_file +TCustomCertId = bytes # manually provided certs (e.g. mitmproxy's --certs) +TGeneratedCertId = typing.Tuple[typing.Optional[bytes], typing.Tuple[bytes, ...]] # (common_name, sans) +TCertId = typing.Union[TCustomCertId, TGeneratedCertId] + + class CertStore: """ @@ -179,7 +145,7 @@ def __init__( self.default_ca = default_ca self.default_chain_file = default_chain_file self.dhparams = dhparams - self.certs = dict() + self.certs = {} # type: typing.Dict[TCertId, CertStoreEntry] self.expire_queue = [] def expire(self, entry): @@ -280,7 +246,7 @@ def create_store(path, basename, o=None, cn=None, expiry=DEFAULT_EXP): return key, ca - def add_cert_file(self, spec, path): + def add_cert_file(self, spec: str, path: str) -> None: with open(path, "rb") as f: raw = f.read() cert = SSLCert( @@ -295,10 +261,10 @@ def add_cert_file(self, spec, path): privatekey = self.default_privatekey self.add_cert( CertStoreEntry(cert, privatekey, path), - spec + spec.encode("idna") ) - def add_cert(self, entry, *names): + def add_cert(self, entry: CertStoreEntry, *names: bytes): """ Adds a cert to the certstore. We register the CN in the cert plus any SANs, and also the list of names provided as an argument. @@ -311,21 +277,18 @@ def add_cert(self, entry, *names): self.certs[i] = entry @staticmethod - def asterisk_forms(dn): - if dn is None: - return [] + def asterisk_forms(dn: bytes) -> typing.List[bytes]: + """ + Return all asterisk forms for a domain. For example, for www.example.com this will return + [b"www.example.com", b"*.example.com", b"*.com"]. The single wildcard "*" is omitted. + """ parts = dn.split(b".") - parts.reverse() - curr_dn = b"" - dn_forms = [b"*"] - for part in parts[:-1]: - curr_dn = b"." + part + curr_dn # .example.com - dn_forms.append(b"*" + curr_dn) # *.example.com - if parts[-1] != b"*": - dn_forms.append(parts[-1] + curr_dn) - return dn_forms - - def get_cert(self, commonname, sans): + ret = [dn] + for i in range(1, len(parts)): + ret.append(b"*." + b".".join(parts[i:])) + return ret + + def get_cert(self, commonname: typing.Optional[bytes], sans: typing.List[bytes]): """ Returns an (cert, privkey, cert_chain) tuple. @@ -335,9 +298,12 @@ def get_cert(self, commonname, sans): sans: A list of Subject Alternate Names. """ - potential_keys = self.asterisk_forms(commonname) + potential_keys = [] # type: typing.List[TCertId] + if commonname: + potential_keys.extend(self.asterisk_forms(commonname)) for s in sans: potential_keys.extend(self.asterisk_forms(s)) + potential_keys.append(b"*") potential_keys.append((commonname, tuple(sans))) name = next(
diff --git a/test/mitmproxy/proxy/test_server.py b/test/mitmproxy/proxy/test_server.py --- a/test/mitmproxy/proxy/test_server.py +++ b/test/mitmproxy/proxy/test_server.py @@ -479,7 +479,7 @@ class TestHTTPSNoCommonName(tservers.HTTPProxyTest): ssl = True ssloptions = pathod.SSLOptions( certs=[ - (b"*", tutils.test_data.path("mitmproxy/data/no_common_name.pem")) + ("*", tutils.test_data.path("mitmproxy/data/no_common_name.pem")) ] ) @@ -1142,7 +1142,7 @@ class AddUpstreamCertsToClientChainMixin: ssloptions = pathod.SSLOptions( cn=b"example.mitmproxy.org", certs=[ - (b"example.mitmproxy.org", servercert) + ("example.mitmproxy.org", servercert) ] ) diff --git a/test/mitmproxy/test_certs.py b/test/mitmproxy/test_certs.py --- a/test/mitmproxy/test_certs.py +++ b/test/mitmproxy/test_certs.py @@ -102,7 +102,7 @@ def test_overrides(self, tmpdir): dc = ca2.get_cert(b"foo.com", [b"sans.example.com"]) dcp = tmpdir.join("dc") dcp.write(dc[0].to_pem()) - ca1.add_cert_file(b"foo.com", str(dcp)) + ca1.add_cert_file("foo.com", str(dcp)) ret = ca1.get_cert(b"foo.com", []) assert ret[0].serial == dc[0].serial diff --git a/test/pathod/test_pathod.py b/test/pathod/test_pathod.py --- a/test/pathod/test_pathod.py +++ b/test/pathod/test_pathod.py @@ -57,7 +57,7 @@ def test_connect(self): class TestCustomCert(tservers.DaemonTests): ssl = True ssloptions = dict( - certs=[(b"*", tutils.test_data.path("pathod/data/testkey.pem"))], + certs=[("*", tutils.test_data.path("pathod/data/testkey.pem"))], ) def test_connect(self):
Custom certificate is ignored in reverse proxy mode https://github.com/mitmproxy/mitmproxy/blob/master/docs/certinstall.rst#using-a-custom-certificate Following the documentation, mitmproxy fails to use the provided custom certificate. ##### Steps to reproduce the problem: 1. `openssl genrsa -out cert.key 2048` `openssl req -new -x509 -key cert.key -out cert.crt` `... <specify CSR>` `cat cert.key cert.crt > cert.pem` 2. `mitmproxy -e -v --cert ./cert.pem -p 8000 -R https://www.google.com:443` 3. `echo | openssl s_client -connect 127.0.0.1:8000` > ... > Certificate chain > 0 s:/CN=www.google.com > i:/CN=mitmproxy/O=mitmproxy > 1 s:/CN=mitmproxy/O=mitmproxy > i:/CN=mitmproxy/O=mitmproxy (the self-signed CSR just created should appear here, rather than the default mitmproxy cert) Custom certificate is ignored in reverse proxy mode https://github.com/mitmproxy/mitmproxy/blob/master/docs/certinstall.rst#using-a-custom-certificate Following the documentation, mitmproxy fails to use the provided custom certificate. ##### Steps to reproduce the problem: 1. `openssl genrsa -out cert.key 2048` `openssl req -new -x509 -key cert.key -out cert.crt` `... <specify CSR>` `cat cert.key cert.crt > cert.pem` 2. `mitmproxy -e -v --cert ./cert.pem -p 8000 -R https://www.google.com:443` 3. `echo | openssl s_client -connect 127.0.0.1:8000` > ... > Certificate chain > 0 s:/CN=www.google.com > i:/CN=mitmproxy/O=mitmproxy > 1 s:/CN=mitmproxy/O=mitmproxy > i:/CN=mitmproxy/O=mitmproxy (the self-signed CSR just created should appear here, rather than the default mitmproxy cert)
Thanks for the detailed steps. Which mitmproxy version is this? On Thu, 7 Sep 2017, 08:25 chorner <[email protected]> wrote: > > https://github.com/mitmproxy/mitmproxy/blob/master/docs/certinstall.rst#using-a-custom-certificate > Following the documentation, mitmproxy fails to use the provided custom > certificate. > Steps to reproduce the problem: > > 1. openssl genrsa -out cert.key 2048 > openssl req -new -x509 -key cert.key -out cert.crt > ... <specify CSR> > cat cert.key cert.crt > cert.pem > 2. mitmproxy -e -v --cert ./cert.pem -p 8000 -R > https://www.google.com:443 > 3. echo | openssl s_client -connect 127.0.0.1:8000 > > ... > Certificate chain > 0 s:/CN=www.google.com > i:/CN=mitmproxy/O=mitmproxy > 1 s:/CN=mitmproxy/O=mitmproxy > i:/CN=mitmproxy/O=mitmproxy > > (the self-signed CSR just created should appear here, rather than the > default mitmproxy cert) > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/2563>, or mute the thread > <https://github.com/notifications/unsubscribe-auth/AA-NPiv7_P3M6drKpfsPyxX_jaoFmULLks5sf4xwgaJpZM4PPWAj> > . > mitmproxy --version > Mitmproxy version: 2.0.2 (release version) > Python version: 3.6.2 > Platform: Darwin-16.7.0-x86_64-i386-64bit > SSL version: OpenSSL 1.1.0f 25 May 2017 > Mac version: 10.12.6 ('', '', '') x86_64 Thanks for the detailed steps. Which mitmproxy version is this? On Thu, 7 Sep 2017, 08:25 chorner <[email protected]> wrote: > > https://github.com/mitmproxy/mitmproxy/blob/master/docs/certinstall.rst#using-a-custom-certificate > Following the documentation, mitmproxy fails to use the provided custom > certificate. > Steps to reproduce the problem: > > 1. openssl genrsa -out cert.key 2048 > openssl req -new -x509 -key cert.key -out cert.crt > ... <specify CSR> > cat cert.key cert.crt > cert.pem > 2. mitmproxy -e -v --cert ./cert.pem -p 8000 -R > https://www.google.com:443 > 3. echo | openssl s_client -connect 127.0.0.1:8000 > > ... > Certificate chain > 0 s:/CN=www.google.com > i:/CN=mitmproxy/O=mitmproxy > 1 s:/CN=mitmproxy/O=mitmproxy > i:/CN=mitmproxy/O=mitmproxy > > (the self-signed CSR just created should appear here, rather than the > default mitmproxy cert) > > — > You are receiving this because you are subscribed to this thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/2563>, or mute the thread > <https://github.com/notifications/unsubscribe-auth/AA-NPiv7_P3M6drKpfsPyxX_jaoFmULLks5sf4xwgaJpZM4PPWAj> > . > mitmproxy --version > Mitmproxy version: 2.0.2 (release version) > Python version: 3.6.2 > Platform: Darwin-16.7.0-x86_64-i386-64bit > SSL version: OpenSSL 1.1.0f 25 May 2017 > Mac version: 10.12.6 ('', '', '') x86_64
2017-10-24T19:14:20
mitmproxy/mitmproxy
2,615
mitmproxy__mitmproxy-2615
[ "2601" ]
731b40ce0f31e64e9bff87e00d7bfbee12138d47
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -85,7 +85,7 @@ "pydivert>=2.0.3,<2.2", ], 'dev': [ - "flake8>=3.2.1, <3.5", + "flake8>=3.5, <3.6", "Flask>=0.10.1, <0.13", "mypy>=0.530,<0.541", "pytest-cov>=2.2.1, <3",
[requires.io] dependency update on master branch
2017-10-31T09:58:55
mitmproxy/mitmproxy
2,619
mitmproxy__mitmproxy-2619
[ "2617", "2617" ]
1d55d241f8f3c3c49a67777de42c9636a39c93db
diff --git a/mitmproxy/proxy/protocol/base.py b/mitmproxy/proxy/protocol/base.py --- a/mitmproxy/proxy/protocol/base.py +++ b/mitmproxy/proxy/protocol/base.py @@ -96,15 +96,7 @@ def __call__(self): def __init__(self, server_address=None): super().__init__() - self.server_conn = None - if self.config.options.spoof_source_address and self.config.options.upstream_bind_address == '': - self.server_conn = connections.ServerConnection( - server_address, (self.ctx.client_conn.address[0], 0), True) - else: - self.server_conn = connections.ServerConnection( - server_address, (self.config.options.upstream_bind_address, 0), - self.config.options.spoof_source_address - ) + self.server_conn = self.__make_server_conn(server_address) self.__check_self_connect() @@ -125,6 +117,16 @@ def __check_self_connect(self): "The proxy shall not connect to itself.".format(repr(address)) ) + def __make_server_conn(self, server_address): + if self.config.options.spoof_source_address and self.config.options.upstream_bind_address == '': + return connections.ServerConnection( + server_address, (self.ctx.client_conn.address[0], 0), True) + else: + return connections.ServerConnection( + server_address, (self.config.options.upstream_bind_address, 0), + self.config.options.spoof_source_address + ) + def set_server(self, address): """ Sets a new server address. If there is an existing connection, it will be closed. @@ -146,11 +148,7 @@ def disconnect(self): self.server_conn.close() self.channel.tell("serverdisconnect", self.server_conn) - self.server_conn = connections.ServerConnection( - address, - (self.server_conn.source_address[0], 0), - self.config.options.spoof_source_address - ) + self.server_conn = self.__make_server_conn(address) def connect(self): """ diff --git a/mitmproxy/proxy/protocol/http.py b/mitmproxy/proxy/protocol/http.py --- a/mitmproxy/proxy/protocol/http.py +++ b/mitmproxy/proxy/protocol/http.py @@ -165,7 +165,7 @@ class HttpLayer(base.Layer): def __init__(self, ctx, mode): super().__init__(ctx) self.mode = mode - self.__initial_server_conn = None + self.__initial_server_address = None # type: tuple "Contains the original destination in transparent mode, which needs to be restored" "if an inline script modified the target server for a single http request" # We cannot rely on server_conn.tls_established, @@ -177,7 +177,7 @@ def __init__(self, ctx, mode): def __call__(self): if self.mode == HTTPMode.transparent: self.__initial_server_tls = self.server_tls - self.__initial_server_conn = self.server_conn + self.__initial_server_address = self.server_conn.address while True: flow = http.HTTPFlow( self.client_conn, @@ -313,8 +313,8 @@ def _process_flow(self, f): # Setting request.host also updates the host header, which we want # to preserve host_header = f.request.host_header - f.request.host = self.__initial_server_conn.address[0] - f.request.port = self.__initial_server_conn.address[1] + f.request.host = self.__initial_server_address[0] + f.request.port = self.__initial_server_address[1] f.request.host_header = host_header # set again as .host overwrites this. f.request.scheme = "https" if self.__initial_server_tls else "http" self.channel.ask("request", f)
Wrong value for flow address on successive requests Hi, I encountered a problem which I think is similar to #2567. I could easily reproduce it with my client (Alamofire on iOS), although it took me some time to reproduce it with `curl`. When my client tries to access `https://my.api.com` through `mitmproxy`, I want requests to be transferred to my server running on `http://localhost:8080`. To do so, I have the following script: ```python from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_host == "my.api.com": original_host = flow.request.pretty_host original_scheme = flow.request.scheme flow.request.scheme = "http" flow.request.host = "localhost" flow.request.port = 8080 flow.request.headers["Host"] = original_host flow.request.headers["X-Forwarded-Proto"] = original_scheme if flow.request.pretty_host == "localhost": print("bad!") ``` Now, what I started to observe, is that for successive requests (made on the same socket), the first request was correctly transferred to `http://localhost:8080`, but when my script is called during the second one, its scheme, host and port are oddly `https://localhost:8080`, and I eventually see in the logs the following error: ``` << Cannot establish TLS with localhost:8080 (sni: localhost): TlsException("SSL handshake error: Error([('SSL routines', 'ssl3_get_record', 'wrong version number')],)",) ``` By digging a bit more, I found out that in `protocol/http.py`, on line 305 `f.request.host = self.__initial_server_conn.address.host`, `__initial_server_conn` was set to `localhost:8080` for the second request, which I imagine is wrong. Now, I can only reproduce the problem when `_client_tls and establish_server_tls_now` is set to `False` in `tls.py`. I thought about setting this manually after having a look at the logs: verbose logs excerpt (happens with my client). Error ! ``` 192.168.0.162:63994: clientconnect 192.168.0.162:63994: Set new server address: ('my.api.com', 443) 192.168.0.162:63994: Establish TLS with client 192.168.0.162:63994: request 192.168.0.162:63994: Set new server address: localhost:8080 192.168.0.162:63994: serverconnect 192.168.0.162:63994: response 192.168.0.162:63994: GET http://localhost:8080/path 192.168.0.162:63994: request 192.168.0.162:63994: serverdisconnect 192.168.0.162:63994: Set new server address: localhost:8080 192.168.0.162:63994: serverconnect 192.168.0.162:63994: Establish TLS with server 192.168.0.162:63994: GET https://localhost:8080/path << Cannot establish TLS with localhost:8080 (sni: localhost): TlsException("SSL handshake error: Error([('SSL routines', 'ssl3_get_record', 'wrong version number')],)",) 192.168.0.162:63994: serverdisconnect 192.168.0.162:63994: clientdisconnect ``` verbose logs excerpt (happens when I use curl). No Error ``` 127.0.0.1:56369: clientconnect 127.0.0.1:56369: Set new server address: ('my.api.com', 443) 127.0.0.1:56369: serverconnect 127.0.0.1:56369: Establish TLS with server 127.0.0.1:56369: ALPN selected by server: http/1.1 127.0.0.1:56369: Establish TLS with client 127.0.0.1:56369: ALPN for client: b'http/1.1' 127.0.0.1:56369: request 127.0.0.1:56369: serverdisconnect 127.0.0.1:56369: Set new server address: localhost:8080 127.0.0.1:56369: serverconnect 127.0.0.1:56369: response 127.0.0.1:56369: GET http://localhost:8080/path 127.0.0.1:56369: request 127.0.0.1:56369: response 127.0.0.1:56369: GET http://localhost:8080/path 127.0.0.1:56369: serverdisconnect 127.0.0.1:56369: clientdisconnect ``` ##### Steps to reproduce the problem: 1. Set `establish_server_tls_now` to `False` in `tls.py`, e.g.: ```python # ... # if self._client_tls and establish_server_tls_now: if False: self._establish_tls_with_client_and_server() # ... ``` 2. run a dummy server on `localhost:8080` 3. run mitmdump with the script (e.g. replacing `my.api.com` with `google.com`) ``` mitmdump -v -p 9999 --no-http2 -s ./redirect_host.py ``` 4. make 2 requests on the same connection with curl ``` curl --cacert ~/.mitmproxy/mitmproxy-ca.pem --proxy http://localhost:9999 https://google.com https://google.com ``` 5. observe error on second request ``` 404 page not found # <- first request, this is expected <html> <head> <title>502 Bad Gateway</title> </head> <body> <h1>502 Bad Gateway</h1> <p>TlsProtocolException(&#x27;Cannot establish TLS with localhost:8080 (sni: localhost): TlsException(&quot;SSL handshake error: Error([(\&#x27;SSL routines\&#x27;, \&#x27;ssl3_get_record\&#x27;, \&#x27;wrong version number\&#x27;)],)&quot;,)&#x27;,)</p> </body> </html> ``` ------ Do you have any idea where this can come from? Let me know if you need more info! ##### System information ``` $ mitmdump --version Mitmproxy version: 2.0.2 (release version) Python version: 3.6.3 Platform: Darwin-17.0.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0f 25 May 2017 Mac version: 10.13 ('', '', '') x86_64 ``` Wrong value for flow address on successive requests Hi, I encountered a problem which I think is similar to #2567. I could easily reproduce it with my client (Alamofire on iOS), although it took me some time to reproduce it with `curl`. When my client tries to access `https://my.api.com` through `mitmproxy`, I want requests to be transferred to my server running on `http://localhost:8080`. To do so, I have the following script: ```python from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_host == "my.api.com": original_host = flow.request.pretty_host original_scheme = flow.request.scheme flow.request.scheme = "http" flow.request.host = "localhost" flow.request.port = 8080 flow.request.headers["Host"] = original_host flow.request.headers["X-Forwarded-Proto"] = original_scheme if flow.request.pretty_host == "localhost": print("bad!") ``` Now, what I started to observe, is that for successive requests (made on the same socket), the first request was correctly transferred to `http://localhost:8080`, but when my script is called during the second one, its scheme, host and port are oddly `https://localhost:8080`, and I eventually see in the logs the following error: ``` << Cannot establish TLS with localhost:8080 (sni: localhost): TlsException("SSL handshake error: Error([('SSL routines', 'ssl3_get_record', 'wrong version number')],)",) ``` By digging a bit more, I found out that in `protocol/http.py`, on line 305 `f.request.host = self.__initial_server_conn.address.host`, `__initial_server_conn` was set to `localhost:8080` for the second request, which I imagine is wrong. Now, I can only reproduce the problem when `_client_tls and establish_server_tls_now` is set to `False` in `tls.py`. I thought about setting this manually after having a look at the logs: verbose logs excerpt (happens with my client). Error ! ``` 192.168.0.162:63994: clientconnect 192.168.0.162:63994: Set new server address: ('my.api.com', 443) 192.168.0.162:63994: Establish TLS with client 192.168.0.162:63994: request 192.168.0.162:63994: Set new server address: localhost:8080 192.168.0.162:63994: serverconnect 192.168.0.162:63994: response 192.168.0.162:63994: GET http://localhost:8080/path 192.168.0.162:63994: request 192.168.0.162:63994: serverdisconnect 192.168.0.162:63994: Set new server address: localhost:8080 192.168.0.162:63994: serverconnect 192.168.0.162:63994: Establish TLS with server 192.168.0.162:63994: GET https://localhost:8080/path << Cannot establish TLS with localhost:8080 (sni: localhost): TlsException("SSL handshake error: Error([('SSL routines', 'ssl3_get_record', 'wrong version number')],)",) 192.168.0.162:63994: serverdisconnect 192.168.0.162:63994: clientdisconnect ``` verbose logs excerpt (happens when I use curl). No Error ``` 127.0.0.1:56369: clientconnect 127.0.0.1:56369: Set new server address: ('my.api.com', 443) 127.0.0.1:56369: serverconnect 127.0.0.1:56369: Establish TLS with server 127.0.0.1:56369: ALPN selected by server: http/1.1 127.0.0.1:56369: Establish TLS with client 127.0.0.1:56369: ALPN for client: b'http/1.1' 127.0.0.1:56369: request 127.0.0.1:56369: serverdisconnect 127.0.0.1:56369: Set new server address: localhost:8080 127.0.0.1:56369: serverconnect 127.0.0.1:56369: response 127.0.0.1:56369: GET http://localhost:8080/path 127.0.0.1:56369: request 127.0.0.1:56369: response 127.0.0.1:56369: GET http://localhost:8080/path 127.0.0.1:56369: serverdisconnect 127.0.0.1:56369: clientdisconnect ``` ##### Steps to reproduce the problem: 1. Set `establish_server_tls_now` to `False` in `tls.py`, e.g.: ```python # ... # if self._client_tls and establish_server_tls_now: if False: self._establish_tls_with_client_and_server() # ... ``` 2. run a dummy server on `localhost:8080` 3. run mitmdump with the script (e.g. replacing `my.api.com` with `google.com`) ``` mitmdump -v -p 9999 --no-http2 -s ./redirect_host.py ``` 4. make 2 requests on the same connection with curl ``` curl --cacert ~/.mitmproxy/mitmproxy-ca.pem --proxy http://localhost:9999 https://google.com https://google.com ``` 5. observe error on second request ``` 404 page not found # <- first request, this is expected <html> <head> <title>502 Bad Gateway</title> </head> <body> <h1>502 Bad Gateway</h1> <p>TlsProtocolException(&#x27;Cannot establish TLS with localhost:8080 (sni: localhost): TlsException(&quot;SSL handshake error: Error([(\&#x27;SSL routines\&#x27;, \&#x27;ssl3_get_record\&#x27;, \&#x27;wrong version number\&#x27;)],)&quot;,)&#x27;,)</p> </body> </html> ``` ------ Do you have any idea where this can come from? Let me know if you need more info! ##### System information ``` $ mitmdump --version Mitmproxy version: 2.0.2 (release version) Python version: 3.6.3 Platform: Darwin-17.0.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0f 25 May 2017 Mac version: 10.13 ('', '', '') x86_64 ```
Thanks for tracking this down and submitting such a detailed report! :smiley: I'm quite busy this week, but will try to take a look as soon as possible. Thanks for tracking this down and submitting such a detailed report! :smiley: I'm quite busy this week, but will try to take a look as soon as possible.
2017-11-03T15:52:16
mitmproxy/mitmproxy
2,636
mitmproxy__mitmproxy-2636
[ "2635" ]
168c72a55f82d24c1dc332cb44a9fe4a0d57f8ce
diff --git a/mitmproxy/addons/save.py b/mitmproxy/addons/save.py --- a/mitmproxy/addons/save.py +++ b/mitmproxy/addons/save.py @@ -42,7 +42,7 @@ def configure(self, updated): ) else: self.filt = None - if "save_stream_file" in updated: + if "save_stream_file" in updated or "save_stream_filter" in updated: if self.stream: self.done() if ctx.options.save_stream_file:
mitmdump does not apply filter to saved data ##### Steps to reproduce the problem: 1. I captured some traffic, and ran the following to filter it: ``` $ mitmdump -r traffic.mitm -w out.mitm '~u main.css' Proxy server listening at http://[::]:8080 172.16.122.1:51049: GET https://www.sjoerdlangkemper.nl/css/main.css << 304 Not Modified 0b $ ``` It displays only the matched URL, but it saves all traffic. When done, out.mitm contains the same requests and responses as traffic.mitm. I.e. `mitmproxy -r out.mitm` shows a lot of requests, where I would expect only the request for main.css. ##### Any other comments? What have you tried so far? I tried this with release 2.0.2, and there it worked as expected. This issue seems to be similar to #1089. ##### System information ``` $ mitmdump --version Mitmproxy version: 3.0.0 (2.0.0dev0965-0x168c72a) Python version: 3.5.2 Platform: Linux-4.4.0-98-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.1.0f 25 May 2017 Linux distro: Ubuntu 16.04 xenial ```
2017-11-21T02:58:39
mitmproxy/mitmproxy
2,642
mitmproxy__mitmproxy-2642
[ "2618" ]
46901d1d55cb5bad86e17e093b85ade8111315aa
diff --git a/mitmproxy/net/http/http1/read.py b/mitmproxy/net/http/http1/read.py --- a/mitmproxy/net/http/http1/read.py +++ b/mitmproxy/net/http/http1/read.py @@ -210,7 +210,11 @@ def expected_http_body_size(request, response=None): return None if "content-length" in headers: try: - size = int(headers["content-length"]) + sizes = headers.get_all("content-length") + different_content_length_headers = any(x != sizes[0] for x in sizes) + if different_content_length_headers: + raise exceptions.HttpSyntaxException("Conflicting Content Length Headers") + size = int(sizes[0]) if size < 0: raise ValueError() return size
diff --git a/test/mitmproxy/net/http/http1/test_read.py b/test/mitmproxy/net/http/http1/test_read.py --- a/test/mitmproxy/net/http/http1/test_read.py +++ b/test/mitmproxy/net/http/http1/test_read.py @@ -194,6 +194,17 @@ def test_expected_http_body_size(): treq(headers=Headers(content_length="42")) ) == 42 + # more than 1 content-length headers with same value + assert expected_http_body_size( + treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'42')])) + ) == 42 + + # more than 1 content-length headers with conflicting value + with pytest.raises(exceptions.HttpSyntaxException): + expected_http_body_size( + treq(headers=Headers([(b'content-length', b'42'), (b'content-length', b'45')])) + ) + # no length assert expected_http_body_size( treq(headers=Headers())
Bug in expected_http_body_size ##### Steps to reproduce the problem: 1. Any response with more than one content-length header ##### Any other comments? What have you tried so far? headers is MultiDict so this: size = int(headers["content-length"]) can be change to: size = int(headers.get_all("content-length")[0])
Thanks. Would you like to file a PR that fixes that? We should use `get_all` and verify that all returned values are equal as per https://tools.ietf.org/html/rfc7230#section-3.3.2. Maybe like that: ```python # Handle multiple content-length headers as per https://tools.ietf.org/html/rfc7230#section-3.3.2 sizes = headers.get_all("content-length") different_content_length_headers = any(x != sizes[0] for x in sizes) if different_content_length_headers: raise exceptions.HttpSyntaxException("Conflicting Content Length Headers") size = int(sizes[0]) ``` Yes, i'll do it today.
2017-11-27T06:47:59
mitmproxy/mitmproxy
2,643
mitmproxy__mitmproxy-2643
[ "2594" ]
472d122c12c22f6cc5ebd2e139a2132c77267526
diff --git a/mitmproxy/platform/pf.py b/mitmproxy/platform/pf.py --- a/mitmproxy/platform/pf.py +++ b/mitmproxy/platform/pf.py @@ -1,3 +1,4 @@ +import re import sys @@ -8,6 +9,9 @@ def lookup(address, port, s): Returns an (address, port) tuple, or None. """ + # We may get an ipv4-mapped ipv6 address here, e.g. ::ffff:127.0.0.1. + # Those still appear as "127.0.0.1" in the table, so we need to strip the prefix. + address = re.sub("^::ffff:(?=\d+.\d+.\d+.\d+$)", "", address) s = s.decode() spec = "%s:%s" % (address, port) for i in s.split("\n"):
diff --git a/test/mitmproxy/platform/test_pf.py b/test/mitmproxy/platform/test_pf.py --- a/test/mitmproxy/platform/test_pf.py +++ b/test/mitmproxy/platform/test_pf.py @@ -15,6 +15,7 @@ def test_simple(self): d = f.read() assert pf.lookup("192.168.1.111", 40000, d) == ("5.5.5.5", 80) + assert pf.lookup("::ffff:192.168.1.111", 40000, d) == ("5.5.5.5", 80) with pytest.raises(Exception, match="Could not resolve original destination"): pf.lookup("192.168.1.112", 40000, d) with pytest.raises(Exception, match="Could not resolve original destination"):
Transparent mode fail with looking up failure. ##### Steps to reproduce the problem: 1. Launch Wifi Access Point(OS X) 2. Setup pfctl configuration so that http packet will be forwarded. 3. Launch mitmproxy ( `sudo mitmproxy -p 8080 -m transparent --showhost` ) 4. Access web page after connecting to AP which launched before. 5. See event log. ##### Any other comments? What have you tried so far? When I tried to use transparent mode with OS X(10.11.6). RuntimeError("Could not resolve original destination.") raised. I investigated this bug. And I found that this is caused by difference between AF_INET's and AF_INET6's peername. https://github.com/mitmproxy/mitmproxy/blob/de006ea8adc08b9a8a6aa94eda2b30468727c307/mitmproxy/net/tcp.py#L567 If we use AF_INET, getpeername() return string like `"192.168.2.5:45670"`. But if we use AF_INET6, getpeername() return string like `"::ffff:192.168.2.5:45670"`. `pfctl -s state` 's result is like below. `ALL tcp 192.168.2.5:45670 -> xx.xx.xx.xx:33291 -> xx.xx.xx.xx:443 ESTABLISHED:ESTABLISHED` As you see, `::ffff:` doesn't exist. So [lookup](https://github.com/mitmproxy/mitmproxy/blob/f17c0fdac636f7269f4885294e2a8d2c52c23590/mitmproxy/platform/pf.py#L4) function raises RuntimeError() because `spec in i` condition won't become true. ##### System information Mitmproxy version: 3.0.0 (release version) Python version: 3.6.2 Platform: Darwin-15.6.0-x86_64-i386-64bit SSL version: OpenSSL 1.0.2l 25 May 2017 Mac version: 10.11.6 ('', '', '') x86_64
Thanks for the awesome report! :smiley: 🍰
2017-11-29T08:21:42
mitmproxy/mitmproxy
2,659
mitmproxy__mitmproxy-2659
[ "2652" ]
472a74044024bad63099b113c07fc7190682115b
diff --git a/mitmproxy/command.py b/mitmproxy/command.py --- a/mitmproxy/command.py +++ b/mitmproxy/command.py @@ -190,10 +190,19 @@ def parsearg(manager: CommandManager, spec: str, argtype: type) -> typing.Any: raise exceptions.CommandError("Unsupported argument type: %s" % argtype) +def verify_arg_signature(f: typing.Callable, args: list, kwargs: dict) -> None: + sig = inspect.signature(f) + try: + sig.bind(*args, **kwargs) + except TypeError as v: + raise exceptions.CommandError("Argument mismatch: %s" % v.args[0]) + + def command(path): def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): + verify_arg_signature(function, args, kwargs) return function(*args, **kwargs) wrapper.__dict__["command_path"] = path return wrapper
diff --git a/test/mitmproxy/test_command.py b/test/mitmproxy/test_command.py --- a/test/mitmproxy/test_command.py +++ b/test/mitmproxy/test_command.py @@ -163,3 +163,10 @@ def test_decorator(): with taddons.context() as tctx: tctx.master.addons.add(a) assert tctx.master.commands.call("cmd1 bar") == "ret bar" + + +def test_verify_arg_signature(): + with pytest.raises(exceptions.CommandError): + command.verify_arg_signature(lambda: None, [1, 2], {}) + print('hello there') + command.verify_arg_signature(lambda a, b: None, [1, 2], {}) \ No newline at end of file
command console.choose.cmd crashes when given no arguments Enter mitmproxy console, issue a command like: console.choose.cmd ... and press return.
2017-12-10T20:13:45
mitmproxy/mitmproxy
2,663
mitmproxy__mitmproxy-2663
[ "2651", "2651" ]
472d122c12c22f6cc5ebd2e139a2132c77267526
diff --git a/mitmproxy/tools/console/consoleaddons.py b/mitmproxy/tools/console/consoleaddons.py --- a/mitmproxy/tools/console/consoleaddons.py +++ b/mitmproxy/tools/console/consoleaddons.py @@ -329,9 +329,9 @@ def bodyview(self, f: flow.Flow, part: str) -> None: correct viewier, and fall back to the programs in $PAGER or $EDITOR if necessary. """ - fpart = getattr(f, part) + fpart = getattr(f, part, None) if not fpart: - raise exceptions.CommandError("Could not view part %s." % part) + raise exceptions.CommandError("Part must be either request or response, not %s." % part) t = fpart.headers.get("content-type") content = fpart.get_content(strict=False) if not content:
command "console.bodyview" crashes when given an invalid argument Triggered by entering a command like: console.bodyview @focus foo command "console.bodyview" crashes when given an invalid argument Triggered by entering a command like: console.bodyview @focus foo
2017-12-12T12:14:55
mitmproxy/mitmproxy
2,665
mitmproxy__mitmproxy-2665
[ "2529", "2529" ]
472d122c12c22f6cc5ebd2e139a2132c77267526
diff --git a/mitmproxy/flow.py b/mitmproxy/flow.py --- a/mitmproxy/flow.py +++ b/mitmproxy/flow.py @@ -179,5 +179,7 @@ def resume(self): if not self.intercepted: return self.intercepted = False - self.reply.ack() - self.reply.commit() + # If a flow is intercepted and then duplicated, the duplicated one is not taken. + if self.reply.state == "taken": + self.reply.ack() + self.reply.commit()
diff --git a/test/mitmproxy/test_http.py b/test/mitmproxy/test_http.py --- a/test/mitmproxy/test_http.py +++ b/test/mitmproxy/test_http.py @@ -203,6 +203,15 @@ def test_resume(self): f.resume() assert f.reply.state == "committed" + def test_resume_duplicated(self): + f = tflow.tflow() + f.intercept() + f2 = f.copy() + assert f.intercepted is f2.intercepted is True + f.resume() + f2.resume() + assert f.intercepted is f2.intercepted is False + def test_replace_unicode(self): f = tflow.tflow(resp=True) f.response.content = b"\xc2foo"
crached when resumeall after duplicate flow ##### Steps to reproduce the problem: 1.mitmproxy -p 7778 2.chrome use proxy switchysharp to charge to 127.0.0.1:7778 3.Intercept filter:~q 4.Intercept a resquest,click into it,press `shirt+d` to duplicate one or more flow,press `shift+a`to resume all 5.carsh and show this ```shell Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/master.py", line 200, in run self.loop.run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/window.py", line 276, in keypress return self.master.keymap.handle(fs.keyctx, k) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/keymap.py", line 123, in handle return self.executor(b.command) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/commandeditor.py", line 24, in __call__ ret = self.master.commands.call(cmd) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 144, in call return self.call_args(parts[0], parts[1:]) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 135, in call_args return self.commands[path].call(args) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 106, in call ret = self.func(*pargs) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 197, in wrapper return function(*args, **kwargs) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/addons/core.py", line 34, in resume f.resume() File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/flow.py", line 182, in resume self.reply.commit() File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/controller.py", line 100, in commit "Reply is {}, but expected it to be taken.".format(self.state) mitmproxy.exceptions.ControlException: Reply is start, but expected it to be taken. mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` ##### Any other comments? What have you tried so far? searched but not help ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ```shell Mitmproxy version: 3.0.0 (release version) Python version: 3.6.2 Platform: Linux-4.12.6-1-ARCH-x86_64-with-arch-Arch-Linux SSL version: OpenSSL 1.1.0f 25 May 2017 Linux distro: arch Arch Linux ``` crached when resumeall after duplicate flow ##### Steps to reproduce the problem: 1.mitmproxy -p 7778 2.chrome use proxy switchysharp to charge to 127.0.0.1:7778 3.Intercept filter:~q 4.Intercept a resquest,click into it,press `shirt+d` to duplicate one or more flow,press `shift+a`to resume all 5.carsh and show this ```shell Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/master.py", line 200, in run self.loop.run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/usr/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/usr/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/window.py", line 276, in keypress return self.master.keymap.handle(fs.keyctx, k) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/keymap.py", line 123, in handle return self.executor(b.command) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/tools/console/commandeditor.py", line 24, in __call__ ret = self.master.commands.call(cmd) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 144, in call return self.call_args(parts[0], parts[1:]) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 135, in call_args return self.commands[path].call(args) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 106, in call ret = self.func(*pargs) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/command.py", line 197, in wrapper return function(*args, **kwargs) File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/addons/core.py", line 34, in resume f.resume() File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/flow.py", line 182, in resume self.reply.commit() File "/usr/lib/python3.6/site-packages/mitmproxy-3.0.0-py3.6.egg/mitmproxy/controller.py", line 100, in commit "Reply is {}, but expected it to be taken.".format(self.state) mitmproxy.exceptions.ControlException: Reply is start, but expected it to be taken. mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ``` ##### Any other comments? What have you tried so far? searched but not help ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ```shell Mitmproxy version: 3.0.0 (release version) Python version: 3.6.2 Platform: Linux-4.12.6-1-ARCH-x86_64-with-arch-Arch-Linux SSL version: OpenSSL 1.1.0f 25 May 2017 Linux distro: arch Arch Linux ```
Thanks! This is a recent 3.0 snapshot from master? @mhils Yes, this is a still a problem on master (1d55d241f8f3c3c49a67777de42c9636a39c93db). Looking into this, there's a more general issue. When we duplicate a flow, it still has `flow.intercepted` set to True. This is a bit confusing as there is no corresponding connection that we could "resume". Do we want to 1. Make "resume" a no-op in these cases, which just sets `intercepted = False` 2. Set `.intercepted = False` on duplication *and file save* (where we have the same issue)? @cortesi, @Kriechi, any opinion? Thanks! This is a recent 3.0 snapshot from master? @mhils Yes, this is a still a problem on master (1d55d241f8f3c3c49a67777de42c9636a39c93db). Looking into this, there's a more general issue. When we duplicate a flow, it still has `flow.intercepted` set to True. This is a bit confusing as there is no corresponding connection that we could "resume". Do we want to 1. Make "resume" a no-op in these cases, which just sets `intercepted = False` 2. Set `.intercepted = False` on duplication *and file save* (where we have the same issue)? @cortesi, @Kriechi, any opinion?
2017-12-12T13:42:32
mitmproxy/mitmproxy
2,674
mitmproxy__mitmproxy-2674
[ "2620", "2620" ]
b725e40b128c5a14b040b9bff2d3c404eff39f64
diff --git a/mitmproxy/tools/console/window.py b/mitmproxy/tools/console/window.py --- a/mitmproxy/tools/console/window.py +++ b/mitmproxy/tools/console/window.py @@ -156,12 +156,14 @@ def wrapped(idx): w = urwid.Pile( [ wrapped(i) for i, s in enumerate(self.stacks) - ] + ], + focus_item=self.pane ) else: w = urwid.Columns( [wrapped(i) for i, s in enumerate(self.stacks)], - dividechars=1 + dividechars=1, + focus_column=self.pane ) self.body = urwid.AttrWrap(w, "background") @@ -270,13 +272,12 @@ def mouse_event(self, *args, **kwargs): return True def keypress(self, size, k): - if self.focus_part == "footer": - return super().keypress(size, k) - else: - fs = self.focus_stack().top_widget() - k = fs.keypress(size, k) - if k: - return self.master.keymap.handle(fs.keyctx, k) + k = super().keypress(size, k) + if k: + return self.master.keymap.handle( + self.focus_stack().top_widget().keyctx, + k + ) class Screen(urwid.raw_display.Screen):
Mitmproxy odd UI behaviour ##### Steps to reproduce the problem: 1. Run `mitmproxy` and start intercepting flows. 2. Let the UI fill with flows and then goto the last flow. ![m1](https://user-images.githubusercontent.com/20314742/32436238-62843d80-c309-11e7-9c28-df97ff8b4688.png) 3. Press up key to go one flow above. 4. The UI shifts one flow downwards instead of marker going one flow upwards. ![m2](https://user-images.githubusercontent.com/20314742/32436228-5d7a0df6-c309-11e7-85ca-16f5438d6adf.png) ##### Any other comments? What have you tried so far? This is not a deal breaker or anything but a bit annoying. This seems to happen only with the last flow in UI. ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ``` Mitmproxy: 3.0.0 Python: 3.6.2 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.8.0-53-generic-x86_64-with-debian-stretch-sid ``` <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) --> Mitmproxy odd UI behaviour ##### Steps to reproduce the problem: 1. Run `mitmproxy` and start intercepting flows. 2. Let the UI fill with flows and then goto the last flow. ![m1](https://user-images.githubusercontent.com/20314742/32436238-62843d80-c309-11e7-9c28-df97ff8b4688.png) 3. Press up key to go one flow above. 4. The UI shifts one flow downwards instead of marker going one flow upwards. ![m2](https://user-images.githubusercontent.com/20314742/32436228-5d7a0df6-c309-11e7-85ca-16f5438d6adf.png) ##### Any other comments? What have you tried so far? This is not a deal breaker or anything but a bit annoying. This seems to happen only with the last flow in UI. ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ``` Mitmproxy: 3.0.0 Python: 3.6.2 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.8.0-53-generic-x86_64-with-debian-stretch-sid ``` <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Good catch. Thanks! 😃 Are you comfortable taking a stab at this and attempt a PR? ☺️ Yeah, sure! I'll make a PR as soon as I make any progress. Thanks! Please feel free to hop on our Slack chat if you have any questions. :-) @mhils Is this still open ? I would like to give it a try. @akash612 Yeah, I am a bit busy at the moment. Feel free to take this. Is this issue open? I would like to give it a try. This might be an urwid issue - if I resize my terminal to an odd number of rows, the issue disappears. More concretely, urwid's focus_pos may be confused here. Persisting from Slack: **mhils [22:29]** https://github.com/mitmproxy/mitmproxy/blame/master/mitmproxy/tools/console/window.py#L276-L279 <- this makes sure that keypresses are relayed to the currently active window, right? **cortesi [22:30]** yep **mhils [22:30]** I'm looking into https://github.com/mitmproxy/mitmproxy/issues/2620 at the moment. in a nutshell, the problem is that we just pass down `size` in the code I just linked. this breaks some internal urwid calculations as the size of the flowlist is smaller than the size of the window. so we kind of have to mimic this: https://github.com/urwid/urwid/blob/master/urwid/container.py#L1119-L1124 **cortesi [22:34]** @mhils yes, i’ve come across this type of issue with urwid before, and unfortunately the solution is never nice: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/options.py#L273-L280 Good catch. Thanks! 😃 Are you comfortable taking a stab at this and attempt a PR? ☺️ Yeah, sure! I'll make a PR as soon as I make any progress. Thanks! Please feel free to hop on our Slack chat if you have any questions. :-) @mhils Is this still open ? I would like to give it a try. @akash612 Yeah, I am a bit busy at the moment. Feel free to take this. Is this issue open? I would like to give it a try. This might be an urwid issue - if I resize my terminal to an odd number of rows, the issue disappears. More concretely, urwid's focus_pos may be confused here. Persisting from Slack: **mhils [22:29]** https://github.com/mitmproxy/mitmproxy/blame/master/mitmproxy/tools/console/window.py#L276-L279 <- this makes sure that keypresses are relayed to the currently active window, right? **cortesi [22:30]** yep **mhils [22:30]** I'm looking into https://github.com/mitmproxy/mitmproxy/issues/2620 at the moment. in a nutshell, the problem is that we just pass down `size` in the code I just linked. this breaks some internal urwid calculations as the size of the flowlist is smaller than the size of the window. so we kind of have to mimic this: https://github.com/urwid/urwid/blob/master/urwid/container.py#L1119-L1124 **cortesi [22:34]** @mhils yes, i’ve come across this type of issue with urwid before, and unfortunately the solution is never nice: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/options.py#L273-L280
2017-12-14T14:03:15
mitmproxy/mitmproxy
2,675
mitmproxy__mitmproxy-2675
[ "2673", "2673" ]
842c9f72f751ebc941090a78ea60cca6a8501937
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -406,8 +406,11 @@ def remove(self, flows: typing.Sequence[mitmproxy.flow.Flow]) -> None: if f.killable: f.kill() if f in self._view: + # We manually pass the index here because multiple flows may have the same + # sorting key, and we cannot reconstruct the index from that. + idx = self._view.index(f) self._view.remove(f) - self.sig_view_remove.send(self, flow=f) + self.sig_view_remove.send(self, flow=f, index=idx) del self._store[f.id] self.sig_store_remove.send(self, flow=f) if len(flows) > 1: @@ -507,11 +510,12 @@ def update(self, flows: typing.Sequence[mitmproxy.flow.Flow]) -> None: self.sig_view_update.send(self, flow=f) else: try: - self._view.remove(f) - self.sig_view_remove.send(self, flow=f) + idx = self._view.index(f) except ValueError: - # The value was not in the view - pass + pass # The value was not in the view + else: + self._view.remove(f) + self.sig_view_remove.send(self, flow=f, index=idx) class Focus: @@ -554,11 +558,11 @@ def index(self, idx): def _nearest(self, f, v): return min(v._bisect(f), len(v) - 1) - def _sig_view_remove(self, view, flow): + def _sig_view_remove(self, view, flow, index): if len(view) == 0: self.flow = None elif flow is self.flow: - self.flow = view[self._nearest(self.flow, view)] + self.index = min(index, len(self.view) - 1) def _sig_view_refresh(self, view): if len(view) == 0: diff --git a/mitmproxy/tools/web/master.py b/mitmproxy/tools/web/master.py --- a/mitmproxy/tools/web/master.py +++ b/mitmproxy/tools/web/master.py @@ -60,7 +60,7 @@ def _sig_view_update(self, view, flow): data=app.flow_to_json(flow) ) - def _sig_view_remove(self, view, flow): + def _sig_view_remove(self, view, flow, index): app.ClientConnection.broadcast( resource="flows", cmd="remove",
Flowlist: Focus jumps to bottom of list when deleting flow ##### Steps to reproduce the problem: 1. Create a flow in mitmproxy, duplicate it ten times. 2. Delete flow number 5. 3. Cursor jumps to the last flow, instead to what previously was flow 6. ##### System information Mitmproxy: 3.0.0dev0989 (62561ed) Python: 3.5.2 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial Flowlist: Focus jumps to bottom of list when deleting flow ##### Steps to reproduce the problem: 1. Create a flow in mitmproxy, duplicate it ten times. 2. Delete flow number 5. 3. Cursor jumps to the last flow, instead to what previously was flow 6. ##### System information Mitmproxy: 3.0.0dev0989 (62561ed) Python: 3.5.2 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial
2017-12-14T17:06:17
mitmproxy/mitmproxy
2,700
mitmproxy__mitmproxy-2700
[ "2697", "2697" ]
9e4a443d4234149119e196ada3dbf2306173122e
diff --git a/mitmproxy/tools/console/window.py b/mitmproxy/tools/console/window.py --- a/mitmproxy/tools/console/window.py +++ b/mitmproxy/tools/console/window.py @@ -15,16 +15,30 @@ from mitmproxy.tools.console import eventlog -class Header(urwid.Frame): +class StackWidget(urwid.Frame): def __init__(self, widget, title, focus): - super().__init__( - widget, + if title: header = urwid.AttrWrap( urwid.Text(title), "heading" if focus else "heading_inactive" ) + else: + header = None + super().__init__( + widget, + header=header ) + def keypress(self, size, key): + # Make sure that we don't propagate cursor events outside of the widget. + # Otherwise, in a horizontal layout, urwid's Pile would change the focused widget + # if we cannot scroll any further. + ret = super().keypress(size, key) + command = self._command_map[ret] # awkward as they don't implement a full dict api + if command and command.startswith("cursor"): + return None + return ret + class WindowStack: def __init__(self, master, base): @@ -142,12 +156,16 @@ def refresh(self): self.pane = 0 def wrapped(idx): - window = self.stacks[idx].top_window() widget = self.stacks[idx].top_widget() - if self.master.options.console_layout_headers and window.title: - return Header(widget, window.title, self.pane == idx) + if self.master.options.console_layout_headers: + title = self.stacks[idx].top_window().title else: - return widget + title = None + return StackWidget( + widget, + title, + self.pane == idx + ) w = None if c == "single":
Horizontal view: Pressing up/down modifies non-focused pane. As the title says - we just need to patch that out of urwid.Pile, and take a look at the situation with urwid.Columns. Horizontal view: Pressing up/down modifies non-focused pane. As the title says - we just need to patch that out of urwid.Pile, and take a look at the situation with urwid.Columns.
2017-12-17T16:54:34
mitmproxy/mitmproxy
2,705
mitmproxy__mitmproxy-2705
[ "2694" ]
6ef6286d8e53a0a9045fa41956e65dae2e41ab6d
diff --git a/mitmproxy/tools/console/consoleaddons.py b/mitmproxy/tools/console/consoleaddons.py --- a/mitmproxy/tools/console/consoleaddons.py +++ b/mitmproxy/tools/console/consoleaddons.py @@ -348,6 +348,8 @@ def edit_focus_options(self) -> typing.Sequence[str]: "reason", "request-headers", "response-headers", + "request-body", + "response-body", "status_code", "set-cookies", "url", @@ -359,6 +361,11 @@ def edit_focus(self, part: str) -> None: """ Edit a component of the currently focused flow. """ + flow = self.master.view.focus.flow + # This shouldn't be necessary once this command is "console.edit @focus", + # but for now it is. + if not flow: + raise exceptions.CommandError("No flow selected.") if part == "cookies": self.master.switch_view("edit_focus_cookies") elif part == "form": @@ -371,6 +378,21 @@ def edit_focus(self, part: str) -> None: self.master.switch_view("edit_focus_request_headers") elif part == "response-headers": self.master.switch_view("edit_focus_response_headers") + elif part in ("request-body", "response-body"): + if part == "request-body": + message = flow.request + else: + message = flow.response + if not message: + raise exceptions.CommandError("Flow has no {}.".format(part.split("-")[0])) + c = self.master.spawn_editor(message.get_content(strict=False) or b"") + # Fix an issue caused by some editors when editing a + # request/response body. Many editors make it hard to save a + # file without a terminating newline on the last line. When + # editing message bodies, this can cause problems. For now, I + # just strip the newlines off the end of the body when we return + # from an editor. + message.content = c.rstrip(b"\n") elif part == "set-cookies": self.master.switch_view("edit_focus_setcookies") elif part in ["url", "method", "status_code", "reason"]:
Add command to edit flow body. `console.edit.focus.options` currently provides no option to edit the flow body. I then tried the bodyview feature, but that is read-only. In general, there seems to be no option to edit a flow body?
2017-12-17T18:18:25
mitmproxy/mitmproxy
2,728
mitmproxy__mitmproxy-2728
[ "2724" ]
ddb8f43b87306437a8eb720072857bde1f2dcf9b
diff --git a/mitmproxy/proxy/protocol/websocket.py b/mitmproxy/proxy/protocol/websocket.py --- a/mitmproxy/proxy/protocol/websocket.py +++ b/mitmproxy/proxy/protocol/websocket.py @@ -109,7 +109,7 @@ def _handle_data_received(self, event, source_conn, other_conn, is_server): self.flow.messages.append(websocket_message) self.channel.ask("websocket_message", self.flow) - if not self.flow.stream: + if not self.flow.stream and not websocket_message.killed: def get_chunk(payload): if len(payload) == length: # message has the same length, we can reuse the same sizes @@ -129,14 +129,9 @@ def get_chunk(payload): self.connections[other_conn].send_data(chunk, final) other_conn.send(self.connections[other_conn].bytes_to_send()) - else: - self.connections[other_conn].send_data(event.data, event.message_finished) - other_conn.send(self.connections[other_conn].bytes_to_send()) - - elif self.flow.stream: + if self.flow.stream: self.connections[other_conn].send_data(event.data, event.message_finished) other_conn.send(self.connections[other_conn].bytes_to_send()) - return True def _handle_ping_received(self, event, source_conn, other_conn, is_server): diff --git a/mitmproxy/websocket.py b/mitmproxy/websocket.py --- a/mitmproxy/websocket.py +++ b/mitmproxy/websocket.py @@ -10,23 +10,33 @@ class WebSocketMessage(serializable.Serializable): + """ + A WebSocket message sent from one endpoint to the other. + """ + def __init__( - self, type: int, from_client: bool, content: bytes, timestamp: Optional[int]=None + self, type: int, from_client: bool, content: bytes, timestamp: Optional[int]=None, killed: bool=False ) -> None: self.type = wsproto.frame_protocol.Opcode(type) # type: ignore + """indicates either TEXT or BINARY (from wsproto.frame_protocol.Opcode).""" self.from_client = from_client + """True if this messages was sent by the client.""" self.content = content + """A byte-string representing the content of this message.""" self.timestamp = timestamp or int(time.time()) # type: int + """Timestamp of when this message was received or created.""" + self.killed = killed + """True if this messages was killed and should not be sent to the other endpoint.""" @classmethod def from_state(cls, state): return cls(*state) def get_state(self): - return int(self.type), self.from_client, self.content, self.timestamp + return int(self.type), self.from_client, self.content, self.timestamp, self.killed def set_state(self, state): - self.type, self.from_client, self.content, self.timestamp = state + self.type, self.from_client, self.content, self.timestamp, self.killed = state self.type = wsproto.frame_protocol.Opcode(self.type) # replace enum with bare int def __repr__(self): @@ -35,20 +45,37 @@ def __repr__(self): else: return "binary message: {}".format(strutils.bytes_to_escaped_str(self.content)) + def kill(self): + """ + Kill this message. + + It will not be sent to the other endpoint. This has no effect in streaming mode. + """ + self.killed = True + class WebSocketFlow(flow.Flow): """ - A WebsocketFlow is a simplified representation of a Websocket session. + A WebsocketFlow is a simplified representation of a Websocket connection. """ def __init__(self, client_conn, server_conn, handshake_flow, live=None): super().__init__("websocket", client_conn, server_conn, live) + self.messages = [] # type: List[WebSocketMessage] + """A list containing all WebSocketMessage's.""" self.close_sender = 'client' + """'client' if the client initiated connection closing.""" self.close_code = wsproto.frame_protocol.CloseReason.NORMAL_CLOSURE + """WebSocket close code.""" self.close_message = '(message missing)' + """WebSocket close message.""" self.close_reason = 'unknown status code' + """WebSocket close reason.""" self.stream = False + """True of this connection is streaming directly to the other endpoint.""" + self.handshake_flow = handshake_flow + """The HTTP flow containing the initial WebSocket handshake.""" if handshake_flow: self.client_key = websockets.get_client_key(handshake_flow.request.headers) @@ -65,8 +92,6 @@ def __init__(self, client_conn, server_conn, handshake_flow, live=None): self.server_protocol = '' self.server_extensions = '' - self.handshake_flow = handshake_flow - _stateobject_attributes = flow.Flow._stateobject_attributes.copy() # mypy doesn't support update with kwargs _stateobject_attributes.update(dict(
diff --git a/test/mitmproxy/test_websocket.py b/test/mitmproxy/test_websocket.py --- a/test/mitmproxy/test_websocket.py +++ b/test/mitmproxy/test_websocket.py @@ -3,6 +3,7 @@ from mitmproxy.io import tnetstring from mitmproxy import flowfilter +from mitmproxy.exceptions import Kill, ControlException from mitmproxy.test import tflow @@ -42,6 +43,20 @@ def test_copy(self): assert f.error.get_state() == f2.error.get_state() assert f.error is not f2.error + def test_kill(self): + f = tflow.twebsocketflow() + with pytest.raises(ControlException): + f.intercept() + f.resume() + f.kill() + + f = tflow.twebsocketflow() + f.intercept() + assert f.killable + f.kill() + assert not f.killable + assert f.reply.value == Kill + def test_match(self): f = tflow.twebsocketflow() assert not flowfilter.match("~b nonexistent", f) @@ -71,3 +86,9 @@ def test_serialize(self): d = tflow.twebsocketflow().handshake_flow.get_state() tnetstring.dump(d, b) assert b.getvalue() + + def test_message_kill(self): + f = tflow.twebsocketflow() + assert not f.messages[-1].killed + f.messages[-1].kill() + assert f.messages[-1].killed
Proxy crashes on flow.kill() ##### Steps to reproduce the problem: 0. (Sorry if this is my own mistake, I just started poking around with mitmproxy) 1. Load the proxy with the scenario which is supposed to kill every websocket request with 50% chance ``` from mitmproxy import ctx, websocket import random def websocket_message(flow: websocket.WebSocketFlow) -> None: ctx.log.info(flow.messages[-1].content.strip()[:20]) if random.random() < 50: flow.kill() ``` 2. Start the test which opens a websocket connection through the proxy and sends several binary chunks of data. => Proxy crashes ``` Traceback (most recent call last): File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 715, in _loop alarm_callback() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 164, in cb callback(self, user_data) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/tools/console/master.py", line 175, in ticker changed = self.tick(timeout=0) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/master.py", line 109, in tick self.addons.handle_lifecycle(mtype, obj) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/addonmanager.py", line 234, in handle_lifecycle message.reply.take() File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/controller.py", line 88, in take "Reply is {}, but expected it to be start.".format(self.state) mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be start. mitmproxy has crashed! ``` ``` Mitmproxy: 3.0.0dev1075 (a6a4b1c3) Python: 3.6.3 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Darwin-17.2.0-x86_64-i386-64bit ```
Do you want to kill a websocket connection with 50% probability or prevent exchanging messages with 50%? `flow.kill` kills the whole connection - and we might have a bug here because websocket is a bit different than regular HTTP. @mhils: how should this behave? Can we kill individual websocket messages? What is the expected behaviour for TCP flows/streams? I would like to prevent message exchange at 50%. The API documentation is absent on `websocket.WebSocketFlow` so I took it for granted it could be more or less the same as `HTTPFlow` and `HTTPFlow.kill()` says it kills the request. I take it `kill_flow()` should have aborted the connection.
2017-12-27T21:01:54
mitmproxy/mitmproxy
2,732
mitmproxy__mitmproxy-2732
[ "2724" ]
43c74ff1ef72888f4d12e7c52f3dadee6499fc04
diff --git a/mitmproxy/addonmanager.py b/mitmproxy/addonmanager.py --- a/mitmproxy/addonmanager.py +++ b/mitmproxy/addonmanager.py @@ -230,7 +230,7 @@ def handle_lifecycle(self, name, message): self.trigger(name, message) - if message.reply.state != "taken": + if message.reply.state == "start": message.reply.take() if not message.reply.has_message: message.reply.ack() diff --git a/mitmproxy/controller.py b/mitmproxy/controller.py --- a/mitmproxy/controller.py +++ b/mitmproxy/controller.py @@ -105,16 +105,16 @@ def commit(self): self.q.put(self.value) def ack(self, force=False): - if self.state not in {"start", "taken"}: - raise exceptions.ControlException( - "Reply is {}, but expected it to be start or taken.".format(self.state) - ) self.send(self.obj, force) def kill(self, force=False): self.send(exceptions.Kill, force) def send(self, msg, force=False): + if self.state not in {"start", "taken"}: + raise exceptions.ControlException( + "Reply is {}, but expected it to be start or taken.".format(self.state) + ) if self.has_message and not force: raise exceptions.ControlException("There is already a reply message.") self.value = msg diff --git a/mitmproxy/flow.py b/mitmproxy/flow.py --- a/mitmproxy/flow.py +++ b/mitmproxy/flow.py @@ -1,13 +1,12 @@ import time +import typing # noqa import uuid -from mitmproxy import controller # noqa -from mitmproxy import stateobject from mitmproxy import connections +from mitmproxy import controller, exceptions # noqa +from mitmproxy import stateobject from mitmproxy import version -import typing # noqa - class Error(stateobject.StateObject): @@ -145,7 +144,11 @@ def revert(self): @property def killable(self): - return self.reply and self.reply.state == "taken" + return ( + self.reply and + self.reply.state in {"start", "taken"} and + self.reply.value != exceptions.Kill + ) def kill(self): """ @@ -153,13 +156,7 @@ def kill(self): """ self.error = Error("Connection killed") self.intercepted = False - - # reply.state should be "taken" here, or .take() will raise an - # exception. - if self.reply.state != "taken": - self.reply.take() self.reply.kill(force=True) - self.reply.commit() self.live = False def intercept(self):
diff --git a/test/mitmproxy/proxy/protocol/test_websocket.py b/test/mitmproxy/proxy/protocol/test_websocket.py --- a/test/mitmproxy/proxy/protocol/test_websocket.py +++ b/test/mitmproxy/proxy/protocol/test_websocket.py @@ -221,6 +221,25 @@ def websocket_message(self, f): assert frame.payload == b'foo' +class TestKillFlow(_WebSocketTest): + + @classmethod + def handle_websockets(cls, rfile, wfile): + wfile.write(bytes(websockets.Frame(fin=1, opcode=websockets.OPCODE.TEXT, payload=b'server-foobar'))) + wfile.flush() + + def test_kill(self): + class KillFlow: + def websocket_message(self, f): + f.kill() + + self.master.addons.add(KillFlow()) + self.setup_connection() + + with pytest.raises(exceptions.TcpDisconnect): + websockets.Frame.from_file(self.client.rfile) + + class TestSimpleTLS(_WebSocketTest): ssl = True
Proxy crashes on flow.kill() ##### Steps to reproduce the problem: 0. (Sorry if this is my own mistake, I just started poking around with mitmproxy) 1. Load the proxy with the scenario which is supposed to kill every websocket request with 50% chance ``` from mitmproxy import ctx, websocket import random def websocket_message(flow: websocket.WebSocketFlow) -> None: ctx.log.info(flow.messages[-1].content.strip()[:20]) if random.random() < 50: flow.kill() ``` 2. Start the test which opens a websocket connection through the proxy and sends several binary chunks of data. => Proxy crashes ``` Traceback (most recent call last): File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 715, in _loop alarm_callback() File "/Users/eugene/gitrepo/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 164, in cb callback(self, user_data) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/tools/console/master.py", line 175, in ticker changed = self.tick(timeout=0) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/master.py", line 109, in tick self.addons.handle_lifecycle(mtype, obj) File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/addonmanager.py", line 234, in handle_lifecycle message.reply.take() File "/Users/eugene/gitrepo/mitmproxy/mitmproxy/controller.py", line 88, in take "Reply is {}, but expected it to be start.".format(self.state) mitmproxy.exceptions.ControlException: Reply is committed, but expected it to be start. mitmproxy has crashed! ``` ``` Mitmproxy: 3.0.0dev1075 (a6a4b1c3) Python: 3.6.3 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Darwin-17.2.0-x86_64-i386-64bit ```
Do you want to kill a websocket connection with 50% probability or prevent exchanging messages with 50%? `flow.kill` kills the whole connection - and we might have a bug here because websocket is a bit different than regular HTTP. @mhils: how should this behave? Can we kill individual websocket messages? What is the expected behaviour for TCP flows/streams? I would like to prevent message exchange at 50%. The API documentation is absent on `websocket.WebSocketFlow` so I took it for granted it could be more or less the same as `HTTPFlow` and `HTTPFlow.kill()` says it kills the request. I take it `kill_flow()` should have aborted the connection. @Kriechi I'm sorry to trod on the issue, but the original reported problem about the crash on `flow.kill()` is still present in the branch where you changed the websocket API/docs. @mhils suggests to use `flow.kill()` on the [forums](https://discourse.mitmproxy.org/t/killing-tcp-connections/775/3), but I refer to this issue as a blocker. Should there be a new API for TCP killing as well? If not, then this issue is still relevant. I tried to reproduce it - but unfortunately I don't see the traceback you mentioned. I'm not sure about TCP flows, @mhils? WebSocketFlows should be killable with `flow.kill()`, and it should not result in a traceback. Killing a WebSocketFlow will terminate the entire connection (websocket session & underlying socket). Are you testing with a specific website / domain we could use to debug this? This issue reproduces on a local environment, which I am not free to share, but I can provide with both the message emitter scenario (Python 2.7): ``` from websocket import create_connection def getResponse(): ws = create_connection('ws://localhost:9000/listen', http_proxy_host="localhost", http_proxy_port=8080) listen = """{ "type":"LISTEN", "id": "42", "data":{ "lang": "en-US", "hotphrase": false, "rules": [] } }""" ws.send(listen) ws.close() print("done") if __name__ == "__main__": getResponse() ``` and the MITM script: ``` from mitmproxy import ctx, websocket import random global i def websocket_message(flow: websocket.WebSocketFlow) -> None: global i i += 1 ctx.log.info(i) flow.kill() def websocket_end(flow: websocket.WebSocketFlow) -> None: global i ctx.log.info("WebSocket messages sent in total: " + str(i)) ``` From the stacktrace, I gather that the message is in committed state too early, when it should be in the start state (if I am reading this right). Is there an entrypoint to launch MITM through an IDE? I might be able to debug it.
2017-12-29T21:51:43
mitmproxy/mitmproxy
2,754
mitmproxy__mitmproxy-2754
[ "2470" ]
00b80b33a1608624e69b33898f032b94876d317e
diff --git a/mitmproxy/version.py b/mitmproxy/version.py --- a/mitmproxy/version.py +++ b/mitmproxy/version.py @@ -60,5 +60,5 @@ def get_version(dev: bool = False, build: bool = False, refresh: bool = False) - return mitmproxy_version -if __name__ == "__main__": +if __name__ == "__main__": # pragma: no cover print(VERSION)
diff --git a/test/mitmproxy/test_version.py b/test/mitmproxy/test_version.py --- a/test/mitmproxy/test_version.py +++ b/test/mitmproxy/test_version.py @@ -1,3 +1,4 @@ +import pathlib import runpy import subprocess from unittest import mock @@ -6,7 +7,9 @@ def test_version(capsys): - runpy.run_module('mitmproxy.version', run_name='__main__') + here = pathlib.Path(__file__).absolute().parent + version_file = here / ".." / ".." / "mitmproxy" / "version.py" + runpy.run_path(str(version_file), run_name='__main__') stdout, stderr = capsys.readouterr() assert len(stdout) > 0 assert stdout.strip() == version.VERSION
Transitive import of mitmproxy.version causes warning Since #1837, we import `.script`, will imports `.flow`, which imports `.version`. This causes the following warning in pytest: ``` test/mitmproxy/test_version.py::test_version /Users/kriechi/.pyenv/versions/3.5.3/lib/python3.5/runpy.py:125: RuntimeWarning: 'mitmproxy.version' found in sys.modules after import of package 'mitmproxy', but prior to execution of 'mitmproxy.version'; this may result in unpredictable behaviour warn(RuntimeWarning(msg)) -- Docs: http://doc.pytest.org/en/latest/warnings.html ``` [Note](http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-double-import-trap) > This next trap exists in all current versions of Python, including 3.3, and can be summed up in the following general guideline: “Never add a package directory, or any directory inside a package, directly to the Python path”. > The reason this is problematic is that every module in that directory is now potentially accessible under two different names: as a top level module (since the directory is on sys.path) and as a submodule of the package (if the higher level directory containing the package itself is also on sys.path). Maybe using the approach described [here](https://stackoverflow.com/questions/27947639/how-to-properly-create-a-pyinstaller-hook-or-maybe-hidden-import) works better?
To be honest I do not quite understand what the actual issue is? Is it the import? Not sure myself, but I think the fact that `mitmproxy.version` is available (imported) BEFORE actually being imported is not "good". Maybe this is related to https://github.com/mitmproxy/mitmproxy/blob/aa8969b240310f265640c92e14a4b7d6363e464b/setup.py#L15? Someone needs to remove this and see if CI still complains. If not, we should replace it with something like this: https://github.com/ffalcinelli/pydivert/blob/724bfdc0554ed6fe966eedda3b74197519526cd4/setup.py#L26-L28 Unfortunately the `RuntimeWarning` is still there. Ah, now it's caused by the test_version execution test. Much easier to fix. :)
2018-01-04T13:22:34
mitmproxy/mitmproxy
2,755
mitmproxy__mitmproxy-2755
[ "2738", "2738" ]
d9ce4659fd38362bf548690cdfd4f570a3e8e499
diff --git a/mitmproxy/tools/console/window.py b/mitmproxy/tools/console/window.py --- a/mitmproxy/tools/console/window.py +++ b/mitmproxy/tools/console/window.py @@ -234,28 +234,34 @@ def pop(self, *args, **kwargs): self.view_changed() self.focus_changed() - def current(self, keyctx): + def stacks_sorted_by_focus(self): """ - Returns the active widget, but only the current focus or overlay has - a matching key context. + Returns: + self.stacks, with the focused stack first. """ - t = self.focus_stack().top_widget() - if t.keyctx == keyctx: - return t + stacks = self.stacks.copy() + stacks.insert(0, stacks.pop(self.pane)) + return stacks - def current_window(self, keyctx): + def current(self, keyctx): """ - Returns the active window, ignoring overlays. + Returns the active widget with a matching key context, including overlays. + If multiple stacks have an active widget with a matching key context, + the currently focused stack is preferred. """ - t = self.focus_stack().top_window() - if t.keyctx == keyctx: - return t + for s in self.stacks_sorted_by_focus(): + t = s.top_widget() + if t.keyctx == keyctx: + return t - def any(self, keyctx): + def current_window(self, keyctx): """ - Returns the top window of either stack if they match the context. + Returns the active window with a matching key context, ignoring overlays. + If multiple stacks have an active widget with a matching key context, + the currently focused stack is preferred. """ - for t in [x.top_window() for x in self.stacks]: + for s in self.stacks_sorted_by_focus(): + t = s.top_window() if t.keyctx == keyctx: return t
Mitmproxy lets us interact with other tab, when focusing on the other one. ##### Steps to reproduce the problem: 1. Open mitmproxy. 2. Press `-` to open two pane layout. 3. Start intercepting something. 4. Choose any flow to see **Flow details**. 5. Change focus on other tab by pressing `Shift+Tab`. 6. Click on "Request" or "Response" by pressing left button of mouse. ![2017-12-31 19-52-30](https://user-images.githubusercontent.com/20267977/34463805-5bb3ebd0-ee70-11e7-883b-c6dc720e4127.png) I am getting: ``` Traceback (most recent call last): File "mitmproxy/tools/console/master.py", line 216, in run File "site-packages/urwid/main_loop.py", line 278, in run File "site-packages/urwid/main_loop.py", line 376, in _run File "site-packages/urwid/main_loop.py", line 682, in run File "site-packages/urwid/main_loop.py", line 719, in _loop File "site-packages/urwid/raw_display.py", line 393, in <lambda> File "site-packages/urwid/raw_display.py", line 493, in parse_input File "site-packages/urwid/main_loop.py", line 403, in _update File "site-packages/urwid/main_loop.py", line 500, in process_input File "mitmproxy/tools/console/window.py", line 277, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1687, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1148, in mouse_event File "site-packages/urwid/container.py", line 2201, in mouse_event File "mitmproxy/tools/console/tabs.py", line 19, in mouse_event File "mitmproxy/tools/console/tabs.py", line 34, in change_tab File "mitmproxy/tools/console/tabs.py", line 73, in show File "mitmproxy/tools/console/flowview.py", line 86, in view_response File "mitmproxy/tools/console/flowview.py", line 160, in conn_text File "mitmproxy/command.py", line 221, in call File "mitmproxy/command.py", line 212, in call_args File "mitmproxy/command.py", line 101, in call File "mitmproxy/command.py", line 251, in wrapper File "mitmproxy/tools/console/consoleaddons.py", line 514, in flowview_mode mitmproxy.exceptions.CommandError: Not viewing a flow. ``` ##### Any other comments? What have you tried so far? I think the problem is mitmproxy lets us to interact with other tab, when focusing on other. So, we can click on different stuff in not focused tab by pressing left button of mouse. It is possible due to https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/tabs.py (in particular https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/tabs.py#L17). `tabs.Tabs` is the superclass for `HelpView` and `FlowDetails` classes, so the problem is relevant to "Flow details" and "Help" tabs. Continue to work on it. ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid Mitmproxy lets us interact with other tab, when focusing on the other one. ##### Steps to reproduce the problem: 1. Open mitmproxy. 2. Press `-` to open two pane layout. 3. Start intercepting something. 4. Choose any flow to see **Flow details**. 5. Change focus on other tab by pressing `Shift+Tab`. 6. Click on "Request" or "Response" by pressing left button of mouse. ![2017-12-31 19-52-30](https://user-images.githubusercontent.com/20267977/34463805-5bb3ebd0-ee70-11e7-883b-c6dc720e4127.png) I am getting: ``` Traceback (most recent call last): File "mitmproxy/tools/console/master.py", line 216, in run File "site-packages/urwid/main_loop.py", line 278, in run File "site-packages/urwid/main_loop.py", line 376, in _run File "site-packages/urwid/main_loop.py", line 682, in run File "site-packages/urwid/main_loop.py", line 719, in _loop File "site-packages/urwid/raw_display.py", line 393, in <lambda> File "site-packages/urwid/raw_display.py", line 493, in parse_input File "site-packages/urwid/main_loop.py", line 403, in _update File "site-packages/urwid/main_loop.py", line 500, in process_input File "mitmproxy/tools/console/window.py", line 277, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1687, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1169, in mouse_event File "site-packages/urwid/container.py", line 1148, in mouse_event File "site-packages/urwid/container.py", line 2201, in mouse_event File "mitmproxy/tools/console/tabs.py", line 19, in mouse_event File "mitmproxy/tools/console/tabs.py", line 34, in change_tab File "mitmproxy/tools/console/tabs.py", line 73, in show File "mitmproxy/tools/console/flowview.py", line 86, in view_response File "mitmproxy/tools/console/flowview.py", line 160, in conn_text File "mitmproxy/command.py", line 221, in call File "mitmproxy/command.py", line 212, in call_args File "mitmproxy/command.py", line 101, in call File "mitmproxy/command.py", line 251, in wrapper File "mitmproxy/tools/console/consoleaddons.py", line 514, in flowview_mode mitmproxy.exceptions.CommandError: Not viewing a flow. ``` ##### Any other comments? What have you tried so far? I think the problem is mitmproxy lets us to interact with other tab, when focusing on other. So, we can click on different stuff in not focused tab by pressing left button of mouse. It is possible due to https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/tabs.py (in particular https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/tabs.py#L17). `tabs.Tabs` is the superclass for `HelpView` and `FlowDetails` classes, so the problem is relevant to "Flow details" and "Help" tabs. Continue to work on it. ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid
2018-01-04T14:59:46
mitmproxy/mitmproxy
2,757
mitmproxy__mitmproxy-2757
[ "2720" ]
04c3079aa285bf57f1e5b59a16bf42bae1957e86
diff --git a/mitmproxy/tools/console/defaultkeys.py b/mitmproxy/tools/console/defaultkeys.py --- a/mitmproxy/tools/console/defaultkeys.py +++ b/mitmproxy/tools/console/defaultkeys.py @@ -11,6 +11,7 @@ def map(km): km.add("q", "console.view.pop", ["global"], "Exit the current view") km.add("-", "console.layout.cycle", ["global"], "Cycle to next layout") km.add("shift tab", "console.panes.next", ["global"], "Focus next layout pane") + km.add("ctrl right", "console.panes.next", ["global"], "Focus next layout pane") km.add("P", "console.view.flow @focus", ["global"], "View flow details") km.add("g", "console.nav.start", ["global"], "Go to start")
console: shift+tab is broken in WSL for some Windows terminals See https://github.com/Microsoft/WSL/issues/1770. This seems to affect some but not all Windows terminals. We use shift+tab by default to switch to the next pane in the console app. We can: - Say that this is not our problem, and wait for upstream to fix it. - Find a different binding for next pane - which would be a shame, because shit+tab is very natural. @mhils what say you?
This unfortunately affects the default terminal, which I guess the vast majority uses. I think the most pragmatic approach would be to bind to something else on Windows only as a temporary workaround, and unify to shift-tab once Microsoft has fixed it. How do you feel about this? If you dislike this approach, #2676 would provide at least a somewhat convenient way to switch between panes.
2018-01-04T15:29:16
mitmproxy/mitmproxy
2,770
mitmproxy__mitmproxy-2770
[ "2767" ]
94a173ab9c54c9f8a669c92cf77adcfbe902d565
diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py --- a/mitmproxy/addons/proxyauth.py +++ b/mitmproxy/addons/proxyauth.py @@ -146,14 +146,14 @@ def configure(self, updated): ) elif ctx.options.proxyauth.startswith("ldap"): parts = ctx.options.proxyauth.split(':') - security = parts[0] - ldap_server = parts[1] - dn_baseauth = parts[2] - password_baseauth = parts[3] if len(parts) != 5: raise exceptions.OptionsError( "Invalid ldap specification" ) + security = parts[0] + ldap_server = parts[1] + dn_baseauth = parts[2] + password_baseauth = parts[3] if security == "ldaps": server = ldap3.Server(ldap_server, use_ssl=True) elif security == "ldap":
diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py --- a/test/mitmproxy/addons/test_proxyauth.py +++ b/test/mitmproxy/addons/test_proxyauth.py @@ -190,7 +190,7 @@ def test_configure(self): with pytest.raises(exceptions.OptionsError): ctx.configure(up, proxyauth="ldap:test:test:test") - with pytest.raises(IndexError): + with pytest.raises(exceptions.OptionsError): ctx.configure(up, proxyauth="ldap:fake_serveruid=?dc=example,dc=com:person") with pytest.raises(exceptions.OptionsError):
Traceback appears in Status Bar, when trying to run Mitmproxy with --proxyauth ldap (ldaps) argument ##### Steps to reproduce the problem: Run Mitmproxy with argument: `mitmproxy --proxyauth ldap` or `mitmproxy --proxyauth ldaps` I am seeing: ![screenshot from 2018-01-06 15-41-10](https://user-images.githubusercontent.com/20267977/34640265-0d47714c-f2f8-11e7-91c6-9bfe3a0f9eb6.png) ##### Any other comments? What have you tried so far? This issue is occured, because mitmproxy doesn't control the syntax of ldap authentication argument. https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/proxyauth.py#L147-L152 ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid
Looks like the [check](https://github.com/mitmproxy/mitmproxy/blob/012b938254e1bf14d47447d5f3661d3299d8f582/mitmproxy/addons/proxyauth.py#L153-L156) needs to be moved right after the `split`. Not sure why 5 parts are expected, maybe this should be changed to 4.
2018-01-07T20:36:11
mitmproxy/mitmproxy
2,773
mitmproxy__mitmproxy-2773
[ "2760" ]
821d76df02f70ccca5623cbc65d02b80e3998704
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -441,7 +441,10 @@ def resolve(self, spec: str) -> typing.Sequence[mitmproxy.flow.Flow]: @command.command("view.create") def create(self, method: str, url: str) -> None: - req = http.HTTPRequest.make(method.upper(), url) + try: + req = http.HTTPRequest.make(method.upper(), url) + except ValueError as e: + raise exceptions.CommandError("Invalid URL: %s" % e) c = connections.ClientConnection.make_dummy(("", 0)) s = connections.ServerConnection.make_dummy((req.host, req.port)) f = http.HTTPFlow(c, s)
diff --git a/test/mitmproxy/addons/test_view.py b/test/mitmproxy/addons/test_view.py --- a/test/mitmproxy/addons/test_view.py +++ b/test/mitmproxy/addons/test_view.py @@ -147,6 +147,10 @@ def test_create(): assert v[0].request.url == "http://foo.com/" v.create("get", "http://foo.com") assert len(v) == 2 + with pytest.raises(exceptions.CommandError, match="Invalid URL"): + v.create("get", "http://foo.com\\") + with pytest.raises(exceptions.CommandError, match="Invalid URL"): + v.create("get", "http://") def test_orders():
Mitmproxy crashes, when trying to create a new flow with incorrect url ##### Steps to reproduce the problem: 1. Create a new flow by pressing `n`. 2. For getting `ValueError: Invalid Host` input `https://google.com\` as url. 3. For getting `ValueError: No hostname given` input `https://` as url. I am getting: ``` Traceback (most recent call last): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 293, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1116, in keypress return self.footer.keypress((maxcol,),key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/statusbar.py", line 149, in keypress return self.ab.keypress(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/statusbar.py", line 104, in keypress self.prompt_execute(self._w.get_value()) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/statusbar.py", line 124, in prompt_execute msg = p(txt) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/commandexecutor.py", line 17, in __call__ ret = self.master.commands.call(cmd) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/command.py", line 221, in call return self.call_args(parts[0], parts[1:]) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/command.py", line 212, in call_args return self.commands[path].call(args) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/command.py", line 101, in call ret = self.func(*pargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/command.py", line 251, in wrapper return function(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/addons/view.py", line 444, in create req = http.HTTPRequest.make(method.upper(), url) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 103, in make req.url = url File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 291, in url self.scheme, self.host, self.port, self.path = mitmproxy.net.http.url.parse(url) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/url.py", line 27, in parse raise ValueError("No hostname given") ValueError: No hostname given ``` ##### Any other comments? What have you tried so far? Raised by unhandled: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py#L50 https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py#L27 ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid
This needs to be caught and handled in the `view.create` command.
2018-01-08T13:18:43
mitmproxy/mitmproxy
2,778
mitmproxy__mitmproxy-2778
[ "2768" ]
67300fab3119f055a6cbb43b7cbc9d33e849d165
diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py --- a/mitmproxy/proxy/server.py +++ b/mitmproxy/proxy/server.py @@ -114,9 +114,9 @@ def _create_root_layer(self): def handle(self): self.log("clientconnect", "info") - root_layer = self._create_root_layer() - + root_layer = None try: + root_layer = self._create_root_layer() root_layer = self.channel.ask("clientconnect", root_layer) root_layer() except exceptions.Kill: @@ -151,7 +151,8 @@ def handle(self): print("Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy", file=sys.stderr) self.log("clientdisconnect", "info") - self.channel.tell("clientdisconnect", root_layer) + if root_layer is not None: + self.channel.tell("clientdisconnect", root_layer) self.client_conn.finish() def log(self, msg, level):
diff --git a/test/mitmproxy/proxy/test_server.py b/test/mitmproxy/proxy/test_server.py --- a/test/mitmproxy/proxy/test_server.py +++ b/test/mitmproxy/proxy/test_server.py @@ -511,6 +511,14 @@ def test_overridden_host_header(self): req = self.master.state.flows[0].request assert req.host_header == "127.0.0.1" + def test_selfconnection(self): + self.options.mode = "reverse:http://127.0.0.1:0" + + p = self.pathoc() + with p.connect(): + p.request("get:/") + assert self.master.has_log("The proxy shall not connect to itself.") + class TestReverseSSL(tservers.ReverseProxyTest, CommonMixin, TcpMixin): reverse = True
Traceback appears, when trying to set mitmproxy's address as upstream server for reverse/upstream mode ##### Steps to reproduce the problem: 1. Run mitmproxy in **reverse** or **upstream** mode, using its own address as upstream server address: `mitmproxy --mode reverse:http://127.0.0.1:8080` or `mitmproxy --mode upstream:http://127.0.0.1:8080` 2. Make a request using pathoc `pathoc 127.0.0.1:8080 "get:/"` or a browser. I am seeing: ![screenshot from 2018-01-06 23-29-35](https://user-images.githubusercontent.com/20267977/34644136-7cac6222-f339-11e7-8995-2b30c6ab5c63.png) ##### Any other comments? What have you tried so far? https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/protocol/base.py#L115 should be handled. ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid
I believe we can fix this by moving [this line](https://github.com/mitmproxy/mitmproxy/blob/821d76df02f70ccca5623cbc65d02b80e3998704/mitmproxy/proxy/server.py#L117) into the try: block right afterwards. So that should be fairly simple, but we need a test! :-)
2018-01-10T13:45:20
mitmproxy/mitmproxy
2,781
mitmproxy__mitmproxy-2781
[ "2766" ]
67300fab3119f055a6cbb43b7cbc9d33e849d165
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -35,6 +35,9 @@ def start_replay(self, flows: typing.Sequence[flow.Flow]) -> None: """ Replay requests from flows. """ + for f in flows: + if f.live: + raise exceptions.CommandError("Can't replay live flow.") self.flows = list(flows) ctx.log.alert("Replaying %s flows." % len(self.flows)) ctx.master.addons.trigger("update", [])
diff --git a/test/mitmproxy/addons/test_clientplayback.py b/test/mitmproxy/addons/test_clientplayback.py --- a/test/mitmproxy/addons/test_clientplayback.py +++ b/test/mitmproxy/addons/test_clientplayback.py @@ -52,6 +52,10 @@ def test_playback(self): cp.stop_replay() assert not cp.flows + df = tflow.DummyFlow(tflow.tclient_conn(), tflow.tserver_conn(), True) + with pytest.raises(exceptions.CommandError, match="Can't replay live flow."): + cp.start_replay([df]) + def test_load_file(self, tmpdir): cp = clientplayback.ClientPlayback() with taddons.context():
Traceback appears in Status Bar, when trying to replay live flow ##### Steps to reproduce the problem: 1. Run **pathod** : `pathod -a "/=200:p0,10"` 2. Run mitmproxy. 3. Send _get request_ to pathod through mitmproxy using **pathoc**: `pathoc -c localhost:9999 localhost:8080 'get:/'` 4. Try to replay the corresponding live flow in mitmproxy by pressing `r`. I am seeing: ![screenshot from 2018-01-06 13-40-01](https://user-images.githubusercontent.com/20267977/34639350-30f9aed6-f2e7-11e7-8920-44979218178e.png) ##### Any other comments? What have you tried so far? This issue is relevant for the situations, when server didn't have time to send a response yet, but a user tries to replay the corresponding flow. I also faced this issue, when trying to replay `mitm.it` flow from onboardingapp. ##### System information Mitmproxy: 3.0.0.dev1101 (commit d9d4d15) binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-debian-stretch-sid
We need to check in the `replay.client` command that the flow(s) we're about to replay are not live yet.
2018-01-11T01:04:00
mitmproxy/mitmproxy
2,784
mitmproxy__mitmproxy-2784
[ "2658" ]
a07d52daae96e13856f7c2feb51435ed0e64aed5
diff --git a/mitmproxy/contrib/kaitaistruct/gif.py b/mitmproxy/contrib/kaitaistruct/gif.py --- a/mitmproxy/contrib/kaitaistruct/gif.py +++ b/mitmproxy/contrib/kaitaistruct/gif.py @@ -35,9 +35,11 @@ def __init__(self, _io, _parent=None, _root=None): self.global_color_table = self._root.ColorTable(io, self, self._root) self.blocks = [] - while not self._io.is_eof(): - self.blocks.append(self._root.Block(self._io, self, self._root)) - + while True: + _ = self._root.Block(self._io, self, self._root) + self.blocks.append(_) + if ((self._io.is_eof()) or (_.block_type == self._root.BlockType.end_of_file)) : + break class ImageData(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None):
Traceback when viewing certain gifs Open the attached flow dump in mitmproxy console. When viewing the content, observe the traceback that flashes to screen. A number of issues here: - [ ] Kaitai should be able to parse this gif. It's not technically correct, but I've seen this often, especially with single-pixel tracking gifs. - *Even if Kaitai fails*, we shouldn't crash - the user should see an "invalid image" message (or something more informative). (#2698) - *Even if we crash*, the traceback shouldn't be flashed to screen and disappear. This is an issue with the way we handle super-long error events in console. (#2699) [bar.log](https://github.com/mitmproxy/mitmproxy/files/1545955/bar.log)
@ujjwal96, do you want to take a look? 😃 @mhils sure, will have a look at it soon :smiley: I see quite a few variations of this with other decoders, especially in the (very frequent) case where the content type doesn't match the content. FWIW, the problem with the image in the initial post is that there's an additional null-byte at the end of the file that shouldn't be there. This issue is now just about fragile GIF parsing, the other bullet points have their own issues or PRs now. I think it's not strictly required to be on the 3.0 milestone now, so I'll remove that here. Nonetheless, we should fix this. Ref: https://github.com/kaitai-io/kaitai_struct_formats/pull/73 @mhils The above PR handles the issue caused due to the attached GIF.
2018-01-11T13:07:56